def signTransaction(self, transaction_dict, private_key): ''' @param private_key in bytes, str, or int. ''' assert isinstance(transaction_dict, Mapping) account = self.privateKeyToAccount(private_key) # sign transaction ( v, r, s, rlp_encoded, ) = sign_transaction_dict(account._key_obj, transaction_dict) transaction_hash = keccak(rlp_encoded) return AttributeDict({ 'rawTransaction': HexBytes(rlp_encoded), 'hash': HexBytes(transaction_hash), 'r': r, 's': s, 'v': v, })
def signTransaction(self, transaction_dict, private_key): ''' @param private_key in bytes, str, or int. In Python 2, a bytes, unicode or str object will be interpreted as hexstr In Python 3, only a str object will be interpreted as hexstr ''' assert isinstance(transaction_dict, Mapping) account = self.privateKeyToAccount(private_key) # sign transaction ( v, r, s, rlp_encoded, ) = sign_transaction_dict(account._key_obj, transaction_dict) transaction_hash = keccak(rlp_encoded) return AttributeDict({ 'rawTransaction': HexBytes(rlp_encoded), 'hash': HexBytes(transaction_hash), 'r': HexBytes(r), 's': HexBytes(s), 'v': v, })
def to_hexbytes(num_bytes, val, variable_length=False): if isinstance(val, (str, int, bytes)): result = HexBytes(val) else: raise TypeError("Cannot convert %r to HexBytes" % val) extra_bytes = len(result) - num_bytes if extra_bytes == 0 or (variable_length and extra_bytes < 0): return result elif all(byte == 0 for byte in result[:extra_bytes]): return HexBytes(result[extra_bytes:]) else: raise ValueError("The value %r is %d bytes, but should be %d" % (result, len(result), num_bytes))
def recover(self, msghash, vrs=None, signature=None): hash_bytes = HexBytes(msghash) if vrs is not None: v, r, s = map(hexstr_if_str(to_int), vrs) v_standard = to_standard_v(v) signature_obj = self._keys.Signature(vrs=(v_standard, r, s)) elif signature is not None: signature_bytes = HexBytes(signature) signature_bytes_standard = to_standard_signature_bytes(signature_bytes) signature_obj = self._keys.Signature(signature_bytes=signature_bytes_standard) else: raise TypeError("You must supply the vrs tuple or the signature bytes") pubkey = signature_obj.recover_public_key_from_msg_hash(hash_bytes) return pubkey.to_checksum_address()
def test_eth_getTransactionReceipt_mined(self, web3, block_with_txn, mined_txn_hash): receipt = web3.eth.getTransactionReceipt(mined_txn_hash) assert is_dict(receipt) assert receipt['blockNumber'] == block_with_txn['number'] assert receipt['blockHash'] == block_with_txn['hash'] assert receipt['transactionIndex'] == 0 assert receipt['transactionHash'] == HexBytes(mined_txn_hash)
def recoverTransaction(self, serialized_transaction): txn_bytes = HexBytes(serialized_transaction) txn = Transaction.from_bytes(txn_bytes) msg_hash = hash_of_signed_transaction(txn) if sys.version_info.major < 3: msg_hash = to_hex(msg_hash) return self.recover(msg_hash, vrs=vrs_from(txn))
def encode_abi(web3, abi, arguments, data=None): argument_types = get_abi_input_types(abi) if not check_if_arguments_can_be_encoded(abi, arguments, {}): raise TypeError( "One or more arguments could not be encoded to the necessary " "ABI type. Expected types are: {0}".format( ', '.join(argument_types), )) try: normalizers = [ abi_ens_resolver(web3), abi_address_to_hex, abi_bytes_to_hex, abi_string_to_hex, hexstrs_to_bytes, ] normalized_arguments = map_abi_data( normalizers, argument_types, arguments, ) encoded_arguments = eth_abi_encode_abi( argument_types, normalized_arguments, ) except EncodingError as e: raise TypeError( "One or more arguments could not be encoded to the necessary " "ABI type: {0}".format(str(e))) if data: return to_hex(HexBytes(data) + encoded_arguments) else: return encode_hex(encoded_arguments)
def test_eth_getTransactionByBlockNumberAndIndex(self, web3, block_with_txn, mined_txn_hash): transaction = web3.eth.getTransactionFromBlock( block_with_txn['number'], 0) assert is_dict(transaction) assert transaction['hash'] == HexBytes(mined_txn_hash)
def test_eth_sendRawTransaction(self, web3, funded_account_for_raw_txn): txn_hash = web3.eth.sendRawTransaction( '0xf8648085174876e8008252089439eeed73fb1d3855e90cbd42f348b3d7b340aaa601801ba0ec1295f00936acd0c2cb90ab2cdaacb8bf5e11b3d9957833595aca9ceedb7aada05dfc8937baec0e26029057abd3a1ef8c505dca2cdc07ffacb046d090d2bea06a' # noqa: E501 ) expected = HexBytes( '0x1f80f8ab5f12a45be218f76404bda64d37270a6f4f86ededd0eb599f80548c13' ) assert txn_hash == expected
def privateKeyToAccount(self, private_key): key_bytes = HexBytes(private_key) try: key_obj = self._keys.PrivateKey(key_bytes) return LocalAccount(key_obj, self) except ValidationError as original_exception: raise ValueError( "The private key must be exactly 32 bytes long, instead of " "%d bytes." % len(key_bytes)) from original_exception
def assert_contains_log(result): assert len(result) == 1 log_entry = result[0] assert log_entry['blockNumber'] == block_with_txn_with_log['number'] assert log_entry['blockHash'] == block_with_txn_with_log['hash'] assert log_entry['logIndex'] == 0 assert is_same_address(log_entry['address'], emitter_contract.address) assert log_entry['transactionIndex'] == 0 assert log_entry['transactionHash'] == HexBytes(txn_hash_with_log)
def sign(self, message=None, private_key=None, message_hexstr=None, message_text=None): ''' @param private_key in bytes, str, or int. In Python 2, a bytes, unicode or str object will be interpreted as hexstr In Python 3, only a str object will be interpreted as hexstr ''' msg_bytes = to_bytes(message, hexstr=message_hexstr, text=message_text) msg_hash = self.hashMessage(msg_bytes) key_bytes = HexBytes(private_key) key = self._keys.PrivateKey(key_bytes) (v, r, s, eth_signature_bytes) = sign_message_hash(key, msg_hash) return AttributeDict({ 'message': HexBytes(msg_bytes), 'messageHash': msg_hash, 'r': HexBytes(r), 's': HexBytes(s), 'v': v, 'signature': HexBytes(eth_signature_bytes), })
def test_eth_getTransactionReceipt_with_log_entry(self, web3, block_with_txn_with_log, emitter_contract, txn_hash_with_log): receipt = web3.eth.getTransactionReceipt(txn_hash_with_log) assert is_dict(receipt) assert receipt['blockNumber'] == block_with_txn_with_log['number'] assert receipt['blockHash'] == block_with_txn_with_log['hash'] assert receipt['transactionIndex'] == 0 assert receipt['transactionHash'] == HexBytes(txn_hash_with_log) assert len(receipt['logs']) == 1 log_entry = receipt['logs'][0] assert log_entry['blockNumber'] == block_with_txn_with_log['number'] assert log_entry['blockHash'] == block_with_txn_with_log['hash'] assert log_entry['logIndex'] == 0 assert is_same_address(log_entry['address'], emitter_contract.address) assert log_entry['transactionIndex'] == 0 assert log_entry['transactionHash'] == HexBytes(txn_hash_with_log)
def sign(self, message=None, private_key=None, message_hexstr=None, message_text=None): ''' @param private_key in bytes, str, or int. ''' msg_bytes = to_bytes(message, hexstr=message_hexstr, text=message_text) msg_hash = self.hashMessage(msg_bytes) key_bytes = HexBytes(private_key) key = self._keys.PrivateKey(key_bytes) (v, r, s, eth_signature_bytes) = sign_message_hash(key, msg_hash) return AttributeDict({ 'message': HexBytes(msg_bytes), 'messageHash': msg_hash, 'r': r, 's': s, 'v': v, 'signature': HexBytes(eth_signature_bytes), })
def test_eth_account_sign_transaction_from_eth_test(acct, transaction): expected_raw_txn = transaction['signed'] key = transaction['key'] # validate r, in order to validate the transaction hash # There is some ambiguity about whether `r` will always be deterministically # generated from the transaction hash and private key, mostly due to code # author's ignorance. The example test fixtures and implementations seem to agree, so far. # See ecdsa_raw_sign() in /eth_keys/backends/native/ecdsa.py signed = acct.signTransaction(transaction, key) assert signed.r == HexBytes(expected_raw_txn[-130:-66]) # confirm that signed transaction can be recovered to the sender expected_sender = acct.privateKeyToAccount(key).address assert acct.recoverTransaction(signed.rawTransaction) == expected_sender
def normalize_property(cls, key, val): if key == 'abi': if isinstance(val, str): val = json.loads(val) validate_abi(val) return val elif key == 'address': validate_address(val) return to_normalized_address(val) elif key in { 'bytecode_runtime', 'bytecode', }: return HexBytes(val) else: return val
def normalize_property(cls, key, val): if key == 'abi': if isinstance(val, str): val = json.loads(val) validate_abi(val) return val elif key == 'address': if is_ens_name(val): validate_name_has_address(cls.web3.ens, val) return val else: validate_address(val) return to_checksum_address(val) elif key in { 'bytecode_runtime', 'bytecode', }: return HexBytes(val) else: return val
def test_hexbytes_equals_bytes(bytesval): assert HexBytes(bytesval) == bytesval
0, 5634810156301565519126305729385531885322755941350706789683031279718535704513, 15655399131600894366408541311673616702363115109327707006109616887384920764603, ) msg_hash = b'\xbb\r\x8a\xba\x9f\xf7\xa1<N,s{i\x81\x86r\x83{\xba\x9f\xe2\x1d\xaa\xdd\xb3\xd6\x01\xda\x00\xb7)\xa1' # noqa: E501 from_account = acct.recover(msg_hash, vrs=(v, r, s)) assert from_account == '0xFeC2079e80465cc8C687fFF9EE6386ca447aFec4' @pytest.mark.parametrize( 'message, expected', [ ( 'Message tö sign. Longer than hash!', HexBytes( '0x10c7cb57942998ab214c062e7a57220a174aacd80418cead9f90ec410eacada1' ), ), ( # Intentionally sneaky: message is a hexstr interpreted as text '0x4d6573736167652074c3b6207369676e2e204c6f6e676572207468616e206861736821', HexBytes( '0x6192785e9ad00100e7332ff585824b65eafa30bc8f1265cf86b5368aa3ab5d56' ), ), ( 'Hello World', HexBytes( '0xa1de988600a42c4b4ab089b619297c17d53cffae5d5120d82d8a92d0bb3b78f2' ), ),
def test_eth_getTransactionByHash(self, web3, mined_txn_hash): transaction = web3.eth.getTransaction(mined_txn_hash) assert is_dict(transaction) assert transaction['hash'] == HexBytes(mined_txn_hash)
# coding=utf-8 import pytest from web3 import Web3 from web3.utils.datastructures import ( HexBytes, ) @pytest.mark.parametrize( 'message, digest', [ ('cowmö', HexBytes( '0x0f355f04c0a06eebac1d219b34c598f85a1169badee164be8a30345944885fe8' )), ('', HexBytes( '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470' )), ], ) def test_sha3_text(message, digest): assert Web3.sha3(text=message) == digest @pytest.mark.parametrize( 'hexstr, digest', [ ('0x636f776dc3b6', HexBytes(
class EthModuleTest(object): def test_eth_protocolVersion(self, web3): protocol_version = web3.version.ethereum assert is_string(protocol_version) assert protocol_version.isdigit() def test_eth_syncing(self, web3): syncing = web3.eth.syncing assert is_boolean(syncing) or is_dict(syncing) if is_boolean(syncing): assert syncing is False elif is_dict(syncing): assert 'startingBlock' in syncing assert 'currentBlock' in syncing assert 'highestBlock' in syncing assert is_integer(syncing['startingBlock']) assert is_integer(syncing['currentBlock']) assert is_integer(syncing['highestBlock']) def test_eth_coinbase(self, web3): coinbase = web3.eth.coinbase assert is_checksum_address(coinbase) def test_eth_mining(self, web3): mining = web3.eth.mining assert is_boolean(mining) def test_eth_hashrate(self, web3): hashrate = web3.eth.hashrate assert is_integer(hashrate) assert hashrate >= 0 def test_eth_gasPrice(self, web3): gas_price = web3.eth.gasPrice assert is_integer(gas_price) assert gas_price > 0 def test_eth_accounts(self, web3): accounts = web3.eth.accounts assert is_list_like(accounts) assert len(accounts) != 0 assert all(( is_checksum_address(account) for account in accounts )) assert web3.eth.coinbase in accounts def test_eth_blockNumber(self, web3): block_number = web3.eth.blockNumber assert is_integer(block_number) assert block_number >= 0 def test_eth_getBalance(self, web3): coinbase = web3.eth.coinbase with pytest.raises(InvalidAddress): web3.eth.getBalance(coinbase.lower()) balance = web3.eth.getBalance(coinbase) assert is_integer(balance) assert balance >= 0 def test_eth_getStorageAt(self, web3): coinbase = web3.eth.coinbase with pytest.raises(InvalidAddress): web3.eth.getStorageAt(coinbase.lower(), 0) def test_eth_getTransactionCount(self, web3): coinbase = web3.eth.coinbase transaction_count = web3.eth.getTransactionCount(coinbase) with pytest.raises(InvalidAddress): web3.eth.getTransactionCount(coinbase.lower()) assert is_integer(transaction_count) assert transaction_count >= 0 def test_eth_getBlockTransactionCountByHash_empty_block(self, web3, empty_block): transaction_count = web3.eth.getBlockTransactionCount(empty_block['hash']) assert is_integer(transaction_count) assert transaction_count == 0 def test_eth_getBlockTransactionCountByNumber_empty_block(self, web3, empty_block): transaction_count = web3.eth.getBlockTransactionCount(empty_block['number']) assert is_integer(transaction_count) assert transaction_count == 0 def test_eth_getBlockTransactionCountByHash_block_with_txn(self, web3, block_with_txn): transaction_count = web3.eth.getBlockTransactionCount(block_with_txn['hash']) assert is_integer(transaction_count) assert transaction_count >= 1 def test_eth_getBlockTransactionCountByNumber_block_with_txn(self, web3, block_with_txn): transaction_count = web3.eth.getBlockTransactionCount(block_with_txn['number']) assert is_integer(transaction_count) assert transaction_count >= 1 def test_eth_getUncleCountByBlockHash(self, web3, empty_block): uncle_count = web3.eth.getUncleCount(empty_block['hash']) assert is_integer(uncle_count) assert uncle_count == 0 def test_eth_getUncleCountByBlockNumber(self, web3, empty_block): uncle_count = web3.eth.getUncleCount(empty_block['number']) assert is_integer(uncle_count) assert uncle_count == 0 def test_eth_getCode(self, web3, math_contract): code = web3.eth.getCode(math_contract.address) with pytest.raises(InvalidAddress): code = web3.eth.getCode(math_contract.address.lower()) assert is_string(code) assert len(code) > 2 def test_eth_sign(self, web3, unlocked_account): signature = web3.eth.sign(unlocked_account, text='Message tö sign. Longer than hash!') assert is_bytes(signature) assert len(signature) == 32 + 32 + 1 # test other formats hexsign = web3.eth.sign( unlocked_account, hexstr='0x4d6573736167652074c3b6207369676e2e204c6f6e676572207468616e206861736821' ) assert hexsign == signature intsign = web3.eth.sign( unlocked_account, 0x4d6573736167652074c3b6207369676e2e204c6f6e676572207468616e206861736821 ) assert intsign == signature bytessign = web3.eth.sign(unlocked_account, b'Message t\xc3\xb6 sign. Longer than hash!') assert bytessign == signature new_signature = web3.eth.sign(unlocked_account, text='different message is different') assert new_signature != signature def test_eth_sendTransaction_addr_checksum_required(self, web3, unlocked_account): non_checksum_addr = unlocked_account.lower() txn_params = { 'from': unlocked_account, 'to': unlocked_account, 'value': 1, 'gas': 21000, 'gas_price': web3.eth.gasPrice, } with pytest.raises(InvalidAddress): invalid_params = dict(txn_params, **{'from': non_checksum_addr}) web3.eth.sendTransaction(invalid_params) with pytest.raises(InvalidAddress): invalid_params = dict(txn_params, **{'to': non_checksum_addr}) web3.eth.sendTransaction(invalid_params) def test_eth_sendTransaction(self, web3, unlocked_account): txn_params = { 'from': unlocked_account, 'to': unlocked_account, 'value': 1, 'gas': 21000, 'gas_price': web3.eth.gasPrice, } txn_hash = web3.eth.sendTransaction(txn_params) txn = web3.eth.getTransaction(txn_hash) assert is_same_address(txn['from'], txn_params['from']) assert is_same_address(txn['to'], txn_params['to']) assert txn['value'] == 1 assert txn['gas'] == 21000 assert txn['gasPrice'] == txn_params['gas_price'] @pytest.mark.parametrize( 'raw_transaction, expected_hash', [ ( # address 0x39EEed73fb1D3855E90Cbd42f348b3D7b340aAA6 '0xf8648085174876e8008252089439eeed73fb1d3855e90cbd42f348b3d7b340aaa601801ba0ec1295f00936acd0c2cb90ab2cdaacb8bf5e11b3d9957833595aca9ceedb7aada05dfc8937baec0e26029057abd3a1ef8c505dca2cdc07ffacb046d090d2bea06a', # noqa: E501 '0x1f80f8ab5f12a45be218f76404bda64d37270a6f4f86ededd0eb599f80548c13', ), ( # private key 0x3c2ab4e8f17a7dea191b8c991522660126d681039509dc3bb31af7c9bdb63518 # This is an unfunded account, but the transaction has a 0 gas price, so is valid. # It never needs to be mined, we just want the transaction hash back to confirm. HexBytes('0xf85f808082c35094d898d5e829717c72e7438bad593076686d7d164a80801ba005c2e99ecee98a12fbf28ab9577423f42e9e88f2291b3acc8228de743884c874a077d6bc77a47ad41ec85c96aac2ad27f05a039c4787fca8a1e5ee2d8c7ec1bb6a'), # noqa: E501 '0x98eeadb99454427f6aad7b558bac13e9d225512a6f5e5c11cf48e8d4067e51b5', ), ] ) def test_eth_sendRawTransaction(self, web3, raw_transaction, funded_account_for_raw_txn, expected_hash): txn_hash = web3.eth.sendRawTransaction(raw_transaction) assert txn_hash == web3.toBytes(hexstr=expected_hash) def test_eth_call(self, web3, math_contract): coinbase = web3.eth.coinbase txn_params = math_contract._prepare_transaction( fn_name='add', fn_args=(7, 11), transaction={'from': coinbase, 'to': math_contract.address}, ) call_result = web3.eth.call(txn_params) assert is_string(call_result) result = decode_single('uint256', call_result) assert result == 18 def test_eth_call_with_0_result(self, web3, math_contract): coinbase = web3.eth.coinbase txn_params = math_contract._prepare_transaction( fn_name='add', fn_args=(0, 0), transaction={'from': coinbase, 'to': math_contract.address}, ) call_result = web3.eth.call(txn_params) assert is_string(call_result) result = decode_single('uint256', call_result) assert result == 0 def test_eth_estimateGas(self, web3): coinbase = web3.eth.coinbase gas_estimate = web3.eth.estimateGas({ 'from': coinbase, 'to': coinbase, 'value': 1, }) assert is_integer(gas_estimate) assert gas_estimate > 0 def test_eth_getBlockByHash(self, web3, empty_block): block = web3.eth.getBlock(empty_block['hash']) assert block['hash'] == empty_block['hash'] def test_eth_getBlockByHash_not_found(self, web3, empty_block): block = web3.eth.getBlock(UNKNOWN_HASH) assert block is None def test_eth_getBlockByNumber_with_integer(self, web3, empty_block): block = web3.eth.getBlock(empty_block['number']) assert block['number'] == empty_block['number'] def test_eth_getBlockByNumber_latest(self, web3, empty_block): current_block_number = web3.eth.blockNumber block = web3.eth.getBlock('latest') assert block['number'] == current_block_number def test_eth_getBlockByNumber_not_found(self, web3, empty_block): block = web3.eth.getBlock(12345) assert block is None def test_eth_getBlockByNumber_pending(self, web3, empty_block): current_block_number = web3.eth.blockNumber block = web3.eth.getBlock('pending') assert block['number'] == current_block_number + 1 def test_eth_getBlockByNumber_earliest(self, web3, empty_block): genesis_block = web3.eth.getBlock(0) block = web3.eth.getBlock('earliest') assert block['number'] == 0 assert block['hash'] == genesis_block['hash'] def test_eth_getBlockByNumber_full_transactions(self, web3, block_with_txn): block = web3.eth.getBlock(block_with_txn['number'], True) transaction = block['transactions'][0] assert transaction['hash'] == block_with_txn['transactions'][0] def test_eth_getTransactionByHash(self, web3, mined_txn_hash): transaction = web3.eth.getTransaction(mined_txn_hash) assert is_dict(transaction) assert transaction['hash'] == HexBytes(mined_txn_hash) def test_eth_getTransactionByHash_contract_creation(self, web3, math_contract_deploy_txn_hash): transaction = web3.eth.getTransaction(math_contract_deploy_txn_hash) assert is_dict(transaction) assert transaction['to'] is None def test_eth_getTransactionByBlockHashAndIndex(self, web3, block_with_txn, mined_txn_hash): transaction = web3.eth.getTransactionFromBlock(block_with_txn['hash'], 0) assert is_dict(transaction) assert transaction['hash'] == HexBytes(mined_txn_hash) def test_eth_getTransactionByBlockNumberAndIndex(self, web3, block_with_txn, mined_txn_hash): transaction = web3.eth.getTransactionFromBlock(block_with_txn['number'], 0) assert is_dict(transaction) assert transaction['hash'] == HexBytes(mined_txn_hash) def test_eth_getTransactionReceipt_mined(self, web3, block_with_txn, mined_txn_hash): receipt = web3.eth.getTransactionReceipt(mined_txn_hash) assert is_dict(receipt) assert receipt['blockNumber'] == block_with_txn['number'] assert receipt['blockHash'] == block_with_txn['hash'] assert receipt['transactionIndex'] == 0 assert receipt['transactionHash'] == HexBytes(mined_txn_hash) def test_eth_getTransactionReceipt_unmined(self, web3, unlocked_account): txn_hash = web3.eth.sendTransaction({ 'from': unlocked_account, 'to': unlocked_account, 'value': 1, 'gas': 21000, 'gas_price': web3.eth.gasPrice, }) receipt = web3.eth.getTransactionReceipt(txn_hash) assert receipt is None def test_eth_getTransactionReceipt_with_log_entry(self, web3, block_with_txn_with_log, emitter_contract, txn_hash_with_log): receipt = web3.eth.getTransactionReceipt(txn_hash_with_log) assert is_dict(receipt) assert receipt['blockNumber'] == block_with_txn_with_log['number'] assert receipt['blockHash'] == block_with_txn_with_log['hash'] assert receipt['transactionIndex'] == 0 assert receipt['transactionHash'] == HexBytes(txn_hash_with_log) assert len(receipt['logs']) == 1 log_entry = receipt['logs'][0] assert log_entry['blockNumber'] == block_with_txn_with_log['number'] assert log_entry['blockHash'] == block_with_txn_with_log['hash'] assert log_entry['logIndex'] == 0 assert is_same_address(log_entry['address'], emitter_contract.address) assert log_entry['transactionIndex'] == 0 assert log_entry['transactionHash'] == HexBytes(txn_hash_with_log) def test_eth_getUncleByBlockHashAndIndex(self, web3): # TODO: how do we make uncles.... pass def test_eth_getUncleByBlockNumberAndIndex(self, web3): # TODO: how do we make uncles.... pass def test_eth_getCompilers(self, web3): # TODO: do we want to test this? pass def test_eth_compileSolidity(self, web3): # TODO: do we want to test this? pass def test_eth_compileLLL(self, web3): # TODO: do we want to test this? pass def test_eth_compileSerpent(self, web3): # TODO: do we want to test this? pass def test_eth_newFilter(self, web3): filter = web3.eth.filter({}) changes = web3.eth.getFilterChanges(filter.filter_id) assert is_list_like(changes) assert not changes logs = web3.eth.getFilterLogs(filter.filter_id) assert is_list_like(logs) assert not logs result = web3.eth.uninstallFilter(filter.filter_id) assert result is True def test_eth_newBlockFilter(self, web3): filter = web3.eth.filter('latest') assert is_string(filter.filter_id) changes = web3.eth.getFilterChanges(filter.filter_id) assert is_list_like(changes) assert not changes # TODO: figure out why this fails in go-ethereum # logs = web3.eth.getFilterLogs(filter.filter_id) # assert is_list_like(logs) # assert not logs result = web3.eth.uninstallFilter(filter.filter_id) assert result is True def test_eth_newPendingTransactionFilter(self, web3): filter = web3.eth.filter('pending') assert is_string(filter.filter_id) changes = web3.eth.getFilterChanges(filter.filter_id) assert is_list_like(changes) assert not changes # TODO: figure out why this fails in go-ethereum # logs = web3.eth.getFilterLogs(filter.filter_id) # assert is_list_like(logs) # assert not logs result = web3.eth.uninstallFilter(filter.filter_id) assert result is True def test_eth_getLogs_without_logs(self, web3, block_with_txn_with_log): # Test with block range filter_params = { "fromBlock": 0, "toBlock": block_with_txn_with_log['number'] - 1, } result = web3.eth.getLogs(filter_params) assert len(result) == 0 # the range is wrong filter_params = { "fromBlock": block_with_txn_with_log['number'], "toBlock": block_with_txn_with_log['number'] - 1, } result = web3.eth.getLogs(filter_params) assert len(result) == 0 # Test with `address` # filter with other address filter_params = { "fromBlock": 0, "address": UNKNOWN_ADDRESS, } result = web3.eth.getLogs(filter_params) assert len(result) == 0 def test_eth_getLogs_with_logs( self, web3, block_with_txn_with_log, emitter_contract, txn_hash_with_log): def assert_contains_log(result): assert len(result) == 1 log_entry = result[0] assert log_entry['blockNumber'] == block_with_txn_with_log['number'] assert log_entry['blockHash'] == block_with_txn_with_log['hash'] assert log_entry['logIndex'] == 0 assert is_same_address(log_entry['address'], emitter_contract.address) assert log_entry['transactionIndex'] == 0 assert log_entry['transactionHash'] == HexBytes(txn_hash_with_log) # Test with block range # the range includes the block where the log resides in filter_params = { "fromBlock": block_with_txn_with_log['number'], "toBlock": block_with_txn_with_log['number'], } result = web3.eth.getLogs(filter_params) assert_contains_log(result) # specify only `from_block`. by default `to_block` should be 'latest' filter_params = { "fromBlock": 0, } result = web3.eth.getLogs(filter_params) assert_contains_log(result) # Test with `address` # filter with emitter_contract.address filter_params = { "fromBlock": 0, "address": emitter_contract.address, } result = web3.eth.getLogs(filter_params) assert_contains_log(result) def test_eth_uninstallFilter(self, web3): filter = web3.eth.filter({}) assert is_string(filter.filter_id) success = web3.eth.uninstallFilter(filter.filter_id) assert success is True failure = web3.eth.uninstallFilter(filter.filter_id) assert failure is False
class Web3ModuleTest(object): def test_web3_clientVersion(self, web3): client_version = web3.version.node self._check_web3_clientVersion(client_version) def _check_web3_clientVersion(self, client_version): raise NotImplementedError("Must be implemented by subclasses") # Contract that calculated test values can be found at # https://kovan.etherscan.io/address/0xb9be06f5b99372cf9afbccadbbb9954ccaf7f4bb#code @pytest.mark.parametrize( 'types,values,expected', ( ( ['bool'], [True], HexBytes("0x5fe7f977e71dba2ea1a68e21057beebb9be2ac30c6410aa38d4f3fbe41dcffd2"), ), ( ['uint8', 'uint8', 'uint8'], [97, 98, 99], HexBytes("0x4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45"), ), ( ['uint248'], [30], HexBytes("0x30f95d210785601eb33ae4d53d405b26f920e765dff87cca8e9a4aec99f82671"), ), ( ['bool', 'uint16'], [True, 299], HexBytes("0xed18599ccd80ee9fae9a28b0e34a5573c3233d7468f808fd659bc171cf0b43bd"), ), ( ['int256'], [-10], HexBytes("0xd6fb717f7e270a360f5093ce6a7a3752183e89c9a9afe5c0cb54b458a304d3d5"), ), ( ['int256'], [10], HexBytes("0xc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2a8"), ), ( ['int8', 'uint8'], [-10, 18], HexBytes("0x5c6ab1e634c08d9c0f4df4d789e8727943ef010dd7ca8e3c89de197a26d148be"), ), ( ['address'], ["0x49eddd3769c0712032808d86597b84ac5c2f5614"], InvalidAddress, ), ( ['address'], ["0x49EdDD3769c0712032808D86597B84ac5c2F5614"], HexBytes("0x2ff37b5607484cd4eecf6d13292e22bd6e5401eaffcc07e279583bc742c68882"), ), ( ['bytes2'], ['0x5402'], HexBytes("0x4ed9171bda52fca71ab28e7f452bd6eacc3e5a568a47e0fa53b503159a9b8910"), ), ( ['bytes3'], ['0x5402'], HexBytes("0x4ed9171bda52fca71ab28e7f452bd6eacc3e5a568a47e0fa53b503159a9b8910"), ), ( ['bytes'], [ '0x636865636b6c6f6e6762797465737472696e676167' '61696e7374736f6c6964697479736861336861736866756e6374696f6e' ], HexBytes("0xd78a84d65721b67e4011b10c99dafdedcdcd7cb30153064f773e210b4762e22f"), ), ( ['string'], ['testing a string!'], HexBytes("0xe8c275c0b4070a5ec6cfcb83f0ba394b30ddd283de785d43f2eabfb04bd96747"), ), ( ['string', 'bool', 'uint16', 'bytes2', 'address'], [ 'testing a string!', False, 299, '0x5402', "0x49eddd3769c0712032808d86597b84ac5c2f5614", ], InvalidAddress, ), ( ['string', 'bool', 'uint16', 'bytes2', 'address'], [ 'testing a string!', False, 299, '0x5402', "0x49EdDD3769c0712032808D86597B84ac5c2F5614", ], HexBytes("0x8cc6eabb25b842715e8ca39e2524ed946759aa37bfb7d4b81829cf5a7e266103"), ), ( ['bool[2][]'], [[[True, False], [False, True]]], HexBytes("0x1eef261f2eb51a8c736d52be3f91ff79e78a9ec5df2b7f50d0c6f98ed1e2bc06"), ), ( ['bool[]'], [[True, False, True]], HexBytes("0x5c6090c0461491a2941743bda5c3658bf1ea53bbd3edcde54e16205e18b45792"), ), ( ['uint24[]'], [[1, 0, 1]], HexBytes("0x5c6090c0461491a2941743bda5c3658bf1ea53bbd3edcde54e16205e18b45792"), ), ( ['uint8[2]'], [[8, 9]], HexBytes("0xc7694af312c4f286114180fd0ba6a52461fcee8a381636770b19a343af92538a"), ), ( ['uint256[2]'], [[8, 9]], HexBytes("0xc7694af312c4f286114180fd0ba6a52461fcee8a381636770b19a343af92538a"), ), ( ['uint8[]'], [[8]], HexBytes("0xf3f7a9fe364faab93b216da50a3214154f22a0a2b415b23a84c8169e8b636ee3"), ), ( ['address[]'], [[ "0x49EdDD3769c0712032808D86597B84ac5c2F5614", "0xA6b759bBbf4B59D24acf7E06e79f3a5D104fdCE5", ]], HexBytes("0xb98565c0c26a962fd54d93b0ed6fb9296e03e9da29d2281ed3e3473109ef7dde"), ), ( ['address[]'], [[ "0x49EdDD3769c0712032808D86597B84ac5c2F5614", "0xa6b759bbbf4b59d24acf7e06e79f3a5d104fdce5", ]], InvalidAddress, ), ), ) def test_soliditySha3(self, web3, types, values, expected): if isinstance(expected, type) and issubclass(expected, Exception): with pytest.raises(expected): web3.soliditySha3(types, values) return actual = web3.soliditySha3(types, values) assert actual == expected @pytest.mark.parametrize( 'types, values, expected', ( ( ['address'], ['one.eth'], HexBytes("0x2ff37b5607484cd4eecf6d13292e22bd6e5401eaffcc07e279583bc742c68882"), ), ( ['address[]'], [['one.eth', 'two.eth']], HexBytes("0xb98565c0c26a962fd54d93b0ed6fb9296e03e9da29d2281ed3e3473109ef7dde"), ), ), ) def test_soliditySha3_ens(self, web3, types, values, expected): with ens_addresses(web3, { 'one.eth': "0x49EdDD3769c0712032808D86597B84ac5c2F5614", 'two.eth': "0xA6b759bBbf4B59D24acf7E06e79f3a5D104fdCE5", }): # when called as class method, any name lookup attempt will fail with pytest.raises(InvalidAddress): Web3.soliditySha3(types, values) # when called as instance method method, ens lookups can succeed actual = web3.soliditySha3(types, values) assert actual == expected @pytest.mark.parametrize( 'types,values', ( (['address'], ['0xA6b759bBbf4B59D24acf7E06e79f3a5D104fdCE5', True]), (['address', 'bool'], ['0xA6b759bBbf4B59D24acf7E06e79f3a5D104fdCE5']), ([], ['0xA6b759bBbf4B59D24acf7E06e79f3a5D104fdCE5']), ) ) def test_soliditySha3_same_number_of_types_and_values(self, web3, types, values): with pytest.raises(ValueError): web3.soliditySha3(types, values) def test_is_connected(self, web3): assert web3.isConnected()
def encrypt(private_key, password): key_bytes = HexBytes(private_key) password_bytes = text_if_str(to_bytes, password) assert len(key_bytes) == 32 return create_keyfile_json(key_bytes, password_bytes)
5634810156301565519126305729385531885322755941350706789683031279718535704513, 15655399131600894366408541311673616702363115109327707006109616887384920764603, ) msg_hash = b'\xbb\r\x8a\xba\x9f\xf7\xa1<N,s{i\x81\x86r\x83{\xba\x9f\xe2\x1d\xaa\xdd\xb3\xd6\x01\xda\x00\xb7)\xa1' # noqa: E501 msg_hash = to_hex_if_py2(msg_hash) from_account = acct.recover(msg_hash, vrs=(v, r, s)) assert from_account == '0xFeC2079e80465cc8C687fFF9EE6386ca447aFec4' @pytest.mark.parametrize( 'message, expected', [ ( 'Message tö sign. Longer than hash!', HexBytes( '0x10c7cb57942998ab214c062e7a57220a174aacd80418cead9f90ec410eacada1' ), ), ( # Intentionally sneaky: message is a hexstr interpreted as text '0x4d6573736167652074c3b6207369676e2e204c6f6e676572207468616e206861736821', HexBytes( '0x6192785e9ad00100e7332ff585824b65eafa30bc8f1265cf86b5368aa3ab5d56' ), ), ( 'Hello World', HexBytes( '0xa1de988600a42c4b4ab089b619297c17d53cffae5d5120d82d8a92d0bb3b78f2' ), ),
def test_hexbytes_hexstr_to_bytes(hexstr): assert HexBytes(hexstr) == to_bytes(hexstr=hexstr)
def recoverTransaction(self, serialized_transaction): txn_bytes = HexBytes(serialized_transaction) txn = Transaction.from_bytes(txn_bytes) msg_hash = hash_of_signed_transaction(txn) return self.recover(msg_hash, vrs=vrs_from(txn))
return deploy(web3, WithConstructorAddressArgumentsContract, args=[ "0xd3CdA913deB6f67967B99D67aCDFa1712C293601", ]) @pytest.fixture(params=[b'\x04\x06', '0x0406', '0406']) def bytes_contract(web3, BytesContract, request): return deploy(web3, BytesContract, args=[request.param]) @pytest.fixture(params=[ '0x0406040604060406040604060406040604060406040604060406040604060406', '0406040604060406040604060406040604060406040604060406040604060406', HexBytes( '0406040604060406040604060406040604060406040604060406040604060406'), ]) def bytes32_contract(web3, Bytes32Contract, request): return deploy(web3, Bytes32Contract, args=[request.param]) @pytest.fixture() def undeployed_math_contract(web3, MathContract): empty_address = "0x000000000000000000000000000000000000dEaD" _undeployed_math_contract = MathContract(address=empty_address) return _undeployed_math_contract @pytest.fixture() def mismatched_math_contract(web3, StringContract, MathContract): deploy_txn = StringContract.deploy(args=["Caqalai"])
def normalize_bytecode(bytecode): if bytecode: bytecode = HexBytes(bytecode) return bytecode