def filter(self, filter_params): if is_string(filter_params): if filter_params == "latest": filter_id = self.web3._requestManager.request_blocking( "eth_newBlockFilter", [], ) return BlockFilter(self.web3, filter_id) elif filter_params == "pending": filter_id = self.web3._requestManager.request_blocking( "eth_newPendingTransactionFilter", [], ) return TransactionFilter(self.web3, filter_id) else: raise ValueError( "The filter API only accepts the values of `pending` or " "`latest` for string based filters" ) elif isinstance(filter_params, dict): formatted_filter_params = formatters.input_filter_params_formatter(filter_params) filter_id = self.web3._requestManager.request_blocking( "eth_newFilter", [formatted_filter_params], ) return LogFilter(self.web3, filter_id) else: raise ValueError("Must provide either a string or a valid filter object")
def filter(self, filter_params): if is_string(filter_params): if filter_params == "latest": filter_id = self.web3._requestManager.request_blocking( "eth_newBlockFilter", [], ) return BlockFilter(self.web3, filter_id) elif filter_params == "pending": filter_id = self.web3._requestManager.request_blocking( "eth_newPendingTransactionFilter", [], ) return TransactionFilter(self.web3, filter_id) else: raise ValueError( "The filter API only accepts the values of `pending` or " "`latest` for string based filters") elif isinstance(filter_params, dict): formatted_filter_params = formatters.input_filter_params_formatter( filter_params) filter_id = self.web3._requestManager.request_blocking( "eth_newFilter", [formatted_filter_params], ) return LogFilter(self.web3, filter_id) else: raise ValueError( "Must provide either a string or a valid filter object")
def get_contract_data_from_most_recent_deployment_migration(migration_classes, contract_name): """ Returns the migration class in which the given contract was deployed. """ from .operations import DeployContract sorted_migration_classes = sort_migrations(migration_classes, flatten=True) for migration_class in reversed(sorted_migration_classes): for operation in reversed(migration_class.operations): if not isinstance(operation, DeployContract): continue if operation.contract_registrar_name is not None: op_contract_name = operation.contract_registrar_name else: op_contract_name = operation.contract_name if not is_string(op_contract_name): raise TypeError( "Unexpectedly encountered non-string contract name while " "parsing migraton '{0}': Got {1} of type {2}".format( migration_classes.migraton_id, op_contract_name, type(op_contract_name), ) ) if op_contract_name == contract_name: return migration_class.compiled_contracts[operation.contract_name] else: # No migrations found which deploy `contract_name` return None
def __init__(self, project, chain_name, provider=IPCProvider, **geth_kwargs): super(BaseGethChain, self).__init__(project, chain_name) if geth_kwargs is None: geth_kwargs = {} if is_string(provider): provider = import_string(provider) # context manager shenanigans self.stack = ExitStack() self.provider_class = provider self.extra_kwargs = { key: value for key, value in geth_kwargs.items() if key not in GETH_KWARGS } self.geth_kwargs = { key: value for key, value in geth_kwargs.items() if key in GETH_KWARGS } self.geth = self.get_geth_process_instance()
def get_contract_data_from_most_recent_deployment_migration( migration_classes, contract_name): """ Returns the migration class in which the given contract was deployed. """ from .operations import DeployContract sorted_migration_classes = sort_migrations(migration_classes, flatten=True) for migration_class in reversed(sorted_migration_classes): for operation in reversed(migration_class.operations): if not isinstance(operation, DeployContract): continue if operation.contract_registrar_name is not None: op_contract_name = operation.contract_registrar_name else: op_contract_name = operation.contract_name if not is_string(op_contract_name): raise TypeError( "Unexpectedly encountered non-string contract name while " "parsing migraton '{0}': Got {1} of type {2}".format( migration_classes.migraton_id, op_contract_name, type(op_contract_name), )) if op_contract_name == contract_name: return migration_class.compiled_contracts[ operation.contract_name] else: # No migrations found which deploy `contract_name` return None
def is_primitive_type(value): return any(( value is None, is_boolean(value), is_string(value), is_integer(value), isinstance(value, float), ))
def validate(iban_address): if not is_string(iban_address): return False if re.match(r"^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$", iban_address) and \ mod9710(iso13616Prepare(iban_address)) == 1: return True return False
def request_blocking(self, method, params): """ Make a synchronous request using the provider """ response_raw = self.provider.make_request(method, params) if is_string(response_raw): response = json.loads(force_text(response_raw)) elif is_object(response_raw): response = response_raw if "error" in response: raise ValueError(response["error"]) return response['result']
def extract_ecdsa_signer(msg_hash, signature): msg_hash_bytes = decode_hex(msg_hash) if msg_hash.startswith(b'0x') else msg_hash signature_bytes = decode_hex(signature) if signature.startswith(b'0x') else signature pk = PublicKey(flags=ALL_FLAGS) rec_id = signature_bytes[64] if is_string(rec_id): rec_id = ord(rec_id) pk.public_key = pk.ecdsa_recover( msg_hash_bytes, pk.ecdsa_recoverable_deserialize( signature_bytes[:64], rec_id, ), raw=True, ) pk_serialized = pk.serialize(compressed=False) address = add_0x_prefix(sha3(encode_pubkey(pk_serialized, 'bin')[1:])[-40:]) return address
def generate_registrar_value_setters(receipt, prefix=None): if prefix is None: prefix = [] if is_string(prefix): prefix = [prefix] if isinstance(receipt, RegistrarValue): raise ValueError("Receipt should not be instantiated at this point") elif is_hex_address(receipt): # Special case for addresses return [ Address.defer(key='/'.join(prefix), value=receipt) ] elif is_hex_transaction_hash(receipt): # Special case for transaction hashes and addresses. return [ Bytes32.defer(key='/'.join(prefix), value=decode_hex(receipt)) ] elif isinstance(receipt, type) and issubclass(receipt, RegistrarValue): return [ receipt.defer( key=receipt.key or '/'.join(prefix), value_type=receipt.value_type, value=receipt.value, ) ] elif isinstance(receipt, dict): return list(itertools.chain.from_iterable([ generate_registrar_value_setters(value, prefix + [key]) for key, value in receipt.items() ])) elif isinstance(receipt, (list, tuple)): return list(itertools.chain.from_iterable([ generate_registrar_value_setters(value, prefix + [str(index)]) for index, value in enumerate(receipt) ])) else: raise ValueError( "Invalid type. Must be one of transaction hash, address, " "ReceiptValue, dict, or list" )
def outputBlockFormatter(block): """ Formats the output of a block to its proper values """ # Transform to number block["gasLimit"] = to_decimal(block["gasLimit"]) block["gasUsed"] = to_decimal(block["gasUsed"]) block["size"] = to_decimal(block["size"]) block["timestamp"] = to_decimal(block["timestamp"]) if block.get("number"): block["number"] = to_decimal(block["number"]) block["difficulty"] = to_decimal(block["difficulty"]) block["totalDifficulty"] = to_decimal(block["totalDifficulty"]) if is_array(block.get("transactions")): for item in block["transactions"]: if not is_string(item): item = outputTransactionFormatter(item) return block
def set(self, value=None, timeout=120): if value is None: if self.value is not None: value = self.value else: raise ValueError("No value provided") if not is_string(self.key): raise ValueError("Invalid key type. Expected string, got: {0!r}".format( type(self.key) )) transactor = self.chain.registrar.transact() if self.value_type == 'string': set_txn_hash = transactor.setString(self.key, value) elif self.value_type == 'bytes32': set_txn_hash = transactor.set(self.key, value) elif self.value_type == 'address': set_txn_hash = transactor.setAddress(self.key, value) elif self.value_type == 'uint256': set_txn_hash = transactor.setUInt(self.key, value) elif self.value_type == 'int256': set_txn_hash = transactor.setInt(self.key, value) elif self.value_type == 'bool': set_txn_hash = transactor.setBool(self.key, value) else: raise ValueError("`value_type` must be one of {0}. Got: {1}".format( ', '.join(sorted(ALLOWED_VALUE_TYPES)), self.value_type, )) if timeout is not None: self.chain.wait.for_receipt(set_txn_hash, timeout=timeout) return set_txn_hash
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 test_is_string(value, expected): assert is_string(value) == expected
def isPredefinedBlockNumber(blockNumber): if not is_string(blockNumber): return False return force_text(blockNumber) in {"latest", "pending", "earliest"}
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