def serialize_primitive_type(value, *args, **kwargs): if is_bytes(value): return set(), "b'{0}'".format( force_text(codecs.encode(force_text(value), 'unicode_escape'))) elif is_text(value): return set(), "'{0}'".format( force_text(codecs.encode(value, 'unicode_escape'))) else: return set(), force_text(repr(value))
def serialize_primitive_type(value, *args, **kwargs): if is_bytes(value): return set(), "b'{0}'".format( force_text(codecs.encode(force_text(value), 'unicode_escape')) ) elif is_text(value): return set(), "'{0}'".format( force_text(codecs.encode(value, 'unicode_escape')) ) else: return set(), force_text(repr(value))
def test_admin_setSolc(web3, skip_if_testrpc): skip_if_testrpc(web3) try: solc_path = subprocess.check_output(['which', 'solc']).strip() except subprocess.CalledProcessError: pytest.skip('solc binary not found') solc_version = subprocess.check_output(['solc', '--version']).strip() actual = web3.admin.setSolc(solc_path) assert force_text(solc_version) in actual assert force_text(solc_path) in actual
def test_fuzzing_uint_concatenation(chain, test_string_lib, initial_value, tail): chain.wait.for_receipt(test_string_lib.transact().reset()) if initial_value: chain.wait.for_receipt(test_string_lib.transact().set(initial_value)) assert test_string_lib.call().value() == force_text(initial_value) chain.wait.for_receipt(test_string_lib.transact().concatUInt(tail)) expected = force_text(initial_value) + str(tail) assert test_string_lib.call().value() == expected
def test_stringlib_alpha_numeric(string_lib, binary_text): text = force_text(binary_text) is_alpha_numeric = all(( c in ALPHA_NUMERIC_CHARS for c in text )) assert string_lib.call().isAlphaNumeric(text) is is_alpha_numeric
def make_request(self, method, params): request = self.encode_rpc_request(method, params) self._lock.acquire() try: with get_ipc_socket(self.ipc_path) as sock: sock.sendall(request) response_raw = b"" with gevent.Timeout(10): while True: try: response_raw += sock.recv(4096) except socket.timeout: gevent.sleep(0) continue if response_raw == b"": gevent.sleep(0) else: try: json.loads(force_text(response_raw)) except JSONDecodeError: gevent.sleep(0) continue else: break finally: self._lock.release() return response_raw
def test_dynamic_length_argument_extraction(web3, emitter, wait_for_transaction, emitter_log_topics, emitter_event_ids): string_0 = "this-is-the-first-string-which-exceeds-32-bytes-in-length" string_1 = "this-is-the-second-string-which-exceeds-32-bytes-in-length" txn_hash = emitter.transact().logDynamicArgs(string_0, string_1) txn_receipt = wait_for_transaction(web3, txn_hash) assert len(txn_receipt['logs']) == 1 log_entry = txn_receipt['logs'][0] event_abi = emitter._find_matching_event_abi('LogDynamicArgs') event_topic = emitter_log_topics.LogDynamicArgs assert event_topic in log_entry['topics'] string_0_topic = web3.sha3(string_0, encoding='utf8') assert string_0_topic in log_entry['topics'] event_data = get_event_data(event_abi, log_entry) expected_args = { "arg0": force_text(decode_hex(string_0_topic)), "arg1": string_1, } assert event_data['args'] == expected_args assert event_data['blockHash'] == txn_receipt['blockHash'] assert event_data['blockNumber'] == txn_receipt['blockNumber'] assert event_data['transactionIndex'] == txn_receipt['transactionIndex'] assert event_data['address'] == emitter.address assert event_data['event'] == 'LogDynamicArgs'
def isConnected(self): try: response_raw = self.make_request('web3_clientVersion', []) response = json.loads(force_text(response_raw)) except IOError: return False else: assert response['jsonrpc'] == '2.0' assert 'error' not in response return True assert False
def normalize_class_name(value): """ For `type()` calls: * Python 2 wants `str` * Python 3.4 wants `str` * Python 3.5 doesn't care. """ if sys.version_info.major == 2: return force_bytes(value) else: return force_text(value)
def request_blocking(self, method, params): """ Make a synchronous request using the provider """ response_raw = self.provider.make_request(method, params) response = json.loads(force_text(response_raw)) if "error" in response: raise ValueError(response["error"]) return response['result']
def test_with_locked_account(project): temp_chain = project.get_chain('temp') account = force_text( create_new_account(temp_chain.geth.data_dir, b'a-test-password')) with temp_chain: web3 = temp_chain.web3 assert account in web3.eth.accounts assert is_account_locked(web3, account) is True assert web3.personal.unlockAccount(account, 'a-test-password') assert is_account_locked(web3, account) is False
def test_with_locked_account(project): temp_chain = project.get_chain('temp') account = force_text( create_new_account(temp_chain.geth.data_dir, b'a-test-password') ) with temp_chain: web3 = temp_chain.web3 assert account in web3.eth.accounts assert is_account_locked(web3, account) is True assert web3.personal.unlockAccount(account, 'a-test-password') assert is_account_locked(web3, account) is False
def test_cannonical_signature_lib_to_string(chain, test_canonical_signature_lib, abi): init_kwargs = function_definition_to_kwargs(abi) chain.wait.for_receipt(test_canonical_signature_lib.transact().set( **init_kwargs )) assert test_canonical_signature_lib.call().isValid() expected_signature = function_definition_to_text_signature(abi) expected_selector = force_text(make_4byte_signature(expected_signature)) actual_signature = test_canonical_signature_lib.call().repr() actual_selector = test_canonical_signature_lib.call().selector() assert actual_signature == expected_signature assert actual_selector == expected_selector assert is_canonical_function_signature(actual_signature)
def test_request_account_unlock_with_bad_password(project_dir): project = Project() chain = project.get_chain('temp') # create 3 new accounts account = force_text( create_new_account(chain.geth.data_dir, b'a-test-password')) @click.command() def wrapper(): request_account_unlock(chain, account, None) with chain: assert is_account_locked(chain.web3, account) runner = CliRunner() result = runner.invoke(wrapper, [], input="bad-password\n") assert result.exit_code != 0 assert is_account_locked(chain.web3, account)
def test_chain_web3_is_preconfigured_with_default_from(project_dir, write_project_file): write_project_file('populus.ini', '[chain:local]') project = Project() chain = project.get_chain('local') default_account = force_text( create_new_account(chain.geth.data_dir, b'a-test-password')) project.config.set('chain:local', 'default_account', default_account) project.write_config() with chain: web3 = chain.web3 assert len(web3.eth.accounts) == 2 assert web3.eth.defaultAccount == default_account assert web3.eth.coinbase != default_account
def test_request_account_unlock_with_bad_password(project_dir): project = Project() chain = project.get_chain('temp') # create 3 new accounts account = force_text( create_new_account(chain.geth.data_dir, b'a-test-password') ) @click.command() def wrapper(): request_account_unlock(chain, account, None) with chain: assert is_account_locked(chain.web3, account) runner = CliRunner() result = runner.invoke(wrapper, [], input="bad-password\n") assert result.exit_code != 0 assert is_account_locked(chain.web3, account)
def test_chain_web3_is_preconfigured_with_default_from(project_dir, write_project_file): write_project_file('populus.ini', '[chain:local]') project = Project() chain = project.get_chain('local') default_account = force_text( create_new_account(chain.geth.data_dir, b'a-test-password') ) project.config.set('chain:local', 'default_account', default_account) project.write_config() with chain: web3 = chain.web3 assert len(web3.eth.accounts) == 2 assert web3.eth.defaultAccount == default_account assert web3.eth.coinbase != default_account
def test_initializing_local_chain(project_dir, write_project_file): write_project_file('populus.ini', "[chain:local_a]") project = Project() runner = CliRunner() chain = project.get_chain('local_a') deploy_from = force_text( create_new_account(chain.geth.data_dir, b'a-test-password') ) with chain: chain.wait.for_unlock(chain.web3.eth.coinbase, timeout=30) funding_txn_hash = chain.web3.eth.sendTransaction({ 'from': chain.web3.eth.coinbase, 'to': deploy_from, 'value': int(chain.web3.toWei(10, 'ether')), }) chain.wait.for_receipt(funding_txn_hash, timeout=60) result = runner.invoke( main, ['chain', 'init'], input=(( "local_a\n" # choose chain. "{0}\n" # pick deploy account. "Y\n" # set account as default "a-test-password\n" # unlock account "".format(deploy_from) )) ) assert result.exit_code == 0, result.output + str(result.exception) updated_project = Project() assert 'registrar' in updated_project.config.chains['local_a'] assert 'deploy_from' in updated_project.config.chains['local_a']
def test_initializing_local_chain(project_dir, write_project_file): write_project_file('populus.ini', "[chain:local_a]") project = Project() runner = CliRunner() chain = project.get_chain('local_a') deploy_from = force_text( create_new_account(chain.geth.data_dir, b'a-test-password')) with chain: chain.wait.for_unlock(chain.web3.eth.coinbase, timeout=30) funding_txn_hash = chain.web3.eth.sendTransaction({ 'from': chain.web3.eth.coinbase, 'to': deploy_from, 'value': int(chain.web3.toWei(10, 'ether')), }) chain.wait.for_receipt(funding_txn_hash, timeout=60) result = runner.invoke( main, ['chain', 'init'], input=(( "local_a\n" # choose chain. "{0}\n" # pick deploy account. "Y\n" # set account as default "a-test-password\n" # unlock account "".format(deploy_from)))) assert result.exit_code == 0, result.output + str(result.exception) updated_project = Project() assert 'registrar' in updated_project.config.chains['local_a'] assert 'deploy_from' in updated_project.config.chains['local_a']
def _inner_sign(account, data_to_sign): signature_hash_hex = web3.sha3(encode_hex(data_to_sign)) signature_hash_bytes = decode_hex(signature_hash_hex) private_key = tester.keys[tester.accounts.index(decode_hex(account))] priv_key = PrivateKey(flags=ALL_FLAGS) priv_key.set_raw_privkey(private_key) signature_raw = priv_key.ecdsa_sign_recoverable( signature_hash_bytes, raw=True, digest=sha3_256, ) signature_bytes, rec_id = priv_key.ecdsa_recoverable_serialize(signature_raw) signature = signature_bytes + force_bytes(chr(rec_id)) # Sanity check that the signature is valid. signer_address = force_text(extract_ecdsa_signer( signature_hash_bytes, signature, )) assert signer_address == account return signature
def is_hex_transaction_hash(value): return is_string(value) and re.match(r'^(0x)?[a-fA-F0-9]{64}$', force_text(value))
def is_hex_address(value): return is_string(value) and re.match(r'^(0x)?[a-fA-F0-9]{40}$', force_text(value))
def _convert_uint_to_token_id(token_id_as_uint): return force_text( decode_single('bytes32', encode_single('uint256', token_id_as_uint)))
def test_call_read_string_variable(string_contract): result = string_contract.call().constValue() assert force_text(result) == force_text( "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff" )
from func_sig_registry.utils.signature_db import ( function_definition_to_kwargs, ) from func_sig_registry.utils.abi import ( make_4byte_signature, function_definition_to_text_signature, ) ABI_A = { 'name': 'foo', 'inputs': [], 'type': 'function', } ABI_A_SIGNATURE = function_definition_to_text_signature(ABI_A) ABI_A_SELECTOR_BYTES = make_4byte_signature(ABI_A_SIGNATURE) ABI_A_SELECTOR = force_text(ABI_A_SELECTOR_BYTES) def test_adding_signature_to_db(chain, signature_db): assert signature_db.call().isKnownSelector(ABI_A_SELECTOR_BYTES) is False assert signature_db.call().isKnownSignature(ABI_A_SIGNATURE) is False create_kwargs = function_definition_to_kwargs(ABI_A) chain.wait.for_receipt( signature_db.transact().addSignature(**create_kwargs)) assert signature_db.call().isKnownSelector(ABI_A_SELECTOR_BYTES) is True assert signature_db.call().isKnownSignature(ABI_A_SIGNATURE) is True assert signature_db.call().numSignatures(ABI_A_SELECTOR_BYTES) == 1
def second_account(local_chain): # create a new account account = create_new_account(local_chain.geth.data_dir, b'a-test-password') return force_text(account)
def isPredefinedBlockNumber(blockNumber): if not is_string(blockNumber): return False return force_text(blockNumber) in {"latest", "pending", "earliest"}
def execute(self, chain, compiled_contracts, **kwargs): resolver = Resolver(chain) contract_name = resolver(self.contract_name) contract_registrar_name = resolver(self.contract_registrar_name) libraries = { resolver(key): resolver(value) for key, value in resolver(self.libraries).items() } transaction = { resolver(key): resolver(value) for key, value in resolver(self.transaction).items() } arguments = [ resolver(arg) for arg in self.arguments ] timeout = resolver(self.timeout) verify = resolver(self.verify) contract_data = compiled_contracts[contract_name] BaseContractFactory = chain.web3.eth.contract( abi=contract_data['abi'], code=contract_data['code'], code_runtime=contract_data['code_runtime'], source=contract_data.get('source'), ) all_known_contract_names = set(libraries.keys()).union( set(compiled_contracts.keys()) ) library_dependencies = get_contract_library_dependencies( BaseContractFactory.code, all_known_contract_names, ) registrar = chain.registrar def resolve_library_link(library_name): registrar_key = "contract/{0}".format(library_name) if library_name in libraries: return libraries[library_name] elif registrar.call().exists(registrar_key): library_address = registrar.call().getAddress(registrar_key) # TODO: implement validation that this contract address is # in fact the library we want to link against. return library_address else: raise ValueError( "Unable to find address for library '{0}'".format(library_name) ) link_dependencies = { dependency_name: resolve_library_link(dependency_name) for dependency_name in library_dependencies } deploy_transaction_hash, contract_factory = deploy_contract( chain=chain, contract_name=contract_name, contract_factory=BaseContractFactory, deploy_transaction=transaction, deploy_arguments=arguments, link_dependencies=link_dependencies, ) if timeout is not None: contract_address = chain.wait.for_contract_address( deploy_transaction_hash, timeout=timeout, ) if verify: code = force_text(chain.web3.eth.getCode(contract_address)) expected_code = force_text(contract_factory.code_runtime) if code != expected_code: raise ValueError( "Bytecode @ {0} does not match expected contract " "bytecode.\n\n" "expected : '{1}'\n" "actual : '{2}'\n".format( contract_address, expected_code, code, ), ) return { 'deploy-transaction-hash': deploy_transaction_hash, 'canonical-contract-address': Address.defer( key='contract/{name}'.format( name=contract_registrar_name or contract_name, ), value=contract_address, ), } return { 'deploy-transaction-hash': deploy_transaction_hash, }
def test_stringlib_alpha_numeric(string_lib, binary_text): text = force_text(binary_text) is_alpha_numeric = all((c in ALPHA_NUMERIC_CHARS for c in text)) assert string_lib.call().isAlphaNumeric(text) is is_alpha_numeric
def test_eth_sign(web3_empty, skip_if_testrpc): web3 = web3_empty skip_if_testrpc(web3) private_key_hex = '0x5e95384d8050109aab08c1922d3c230739bc16976553c317e5d0b87b59371f2a' private_key = decode_hex(private_key_hex) # This imports the private key into the running geth instance and unlocks # the account so that it can sign things. # `0xa5df35f30ba0ce878b1061ae086289adff3ba1e0` address = web3.personal.importRawKey(private_key, "password") web3.personal.unlockAccount(address, "password") assert add_0x_prefix(encode_hex(privtoaddr(private_key))) == add_0x_prefix(address) assert address == '0xa5df35f30ba0ce878b1061ae086289adff3ba1e0' # the data to be signed data = b'1234567890abcdefghijklmnopqrstuvwxyz' # the hash of the data `0x089c33d56ed10bd8b571a0f493cedb28db1ae0f40c6cd266243001528c06eab3` data_hash = web3.sha3(data, encoding=None) data_hash_bytes = decode_hex(data_hash) assert force_bytes(data_hash) == sha3(data) priv_key = PrivateKey(flags=ALL_FLAGS) priv_key.set_raw_privkey(private_key) # sanit check the extract_ecdsa_signer function works as expected. vector_sig = priv_key.ecdsa_sign_recoverable(data_hash_bytes, raw=True, digest=sha3_256) vector_sig_bytes, rec_id = priv_key.ecdsa_recoverable_serialize(vector_sig) vector_sig_bytes_full = vector_sig_bytes + force_bytes(chr(rec_id)) vector_address = force_text(extract_ecdsa_signer(data_hash_bytes, vector_sig_bytes_full)) assert vector_address == address # Now have geth sign some data. signature_hex = web3.eth.sign(address, data) signature_bytes = decode_hex(signature_hex) actual_signer = extract_ecdsa_signer(data_hash_bytes, signature_bytes) assert actual_signer == address # Verify the signature against the public key derived from the # original private key. It fails. rec_id = signature_bytes[64] if is_string(rec_id): rec_id = ord(rec_id) recoverable_signature = priv_key.ecdsa_recoverable_deserialize( signature_bytes[:64], rec_id, ) signature = priv_key.ecdsa_recoverable_convert(recoverable_signature) is_valid = priv_key.pubkey.ecdsa_verify( msg=data, raw_sig=signature, digest=sha3_256, ) assert is_valid
def test_eth_sign(web3_empty, skip_if_testrpc): web3 = web3_empty skip_if_testrpc(web3) private_key_hex = '0x5e95384d8050109aab08c1922d3c230739bc16976553c317e5d0b87b59371f2a' private_key = decode_hex(private_key_hex) # This imports the private key into the running geth instance and unlocks # the account so that it can sign things. # `0xa5df35f30ba0ce878b1061ae086289adff3ba1e0` address = web3.personal.importRawKey(private_key, "password") web3.personal.unlockAccount(address, "password") assert add_0x_prefix(encode_hex( privtoaddr(private_key))) == add_0x_prefix(address) assert address == '0xa5df35f30ba0ce878b1061ae086289adff3ba1e0' # the data to be signed data = b'1234567890abcdefghijklmnopqrstuvwxyz' # the hash of the data `0x089c33d56ed10bd8b571a0f493cedb28db1ae0f40c6cd266243001528c06eab3` data_hash = web3.sha3(data, encoding=None) data_hash_bytes = decode_hex(data_hash) assert force_bytes(data_hash) == sha3(data) priv_key = PrivateKey(flags=ALL_FLAGS) priv_key.set_raw_privkey(private_key) # sanit check the extract_ecdsa_signer function works as expected. vector_sig = priv_key.ecdsa_sign_recoverable(data_hash_bytes, raw=True, digest=sha3_256) vector_sig_bytes, rec_id = priv_key.ecdsa_recoverable_serialize(vector_sig) vector_sig_bytes_full = vector_sig_bytes + force_bytes(chr(rec_id)) vector_address = force_text( extract_ecdsa_signer(data_hash_bytes, vector_sig_bytes_full)) assert vector_address == address # Now have geth sign some data. signature_hex = web3.eth.sign(address, data) signature_bytes = decode_hex(signature_hex) actual_signer = extract_ecdsa_signer(data_hash_bytes, signature_bytes) assert actual_signer == address # Verify the signature against the public key derived from the # original private key. It fails. rec_id = signature_bytes[64] if is_string(rec_id): rec_id = ord(rec_id) recoverable_signature = priv_key.ecdsa_recoverable_deserialize( signature_bytes[:64], rec_id, ) signature = priv_key.ecdsa_recoverable_convert(recoverable_signature) is_valid = priv_key.pubkey.ecdsa_verify( msg=data, raw_sig=signature, digest=sha3_256, ) assert is_valid