Beispiel #1
0
def post_process_compiled_contracts(compiled_contracts):
    for contract_data in compiled_contracts:
        bytecode = contract_data.get('bytecode')

        if is_string(bytecode):
            bytecode_placeholder_locations = find_placeholder_locations(bytecode)
            bytecode_link_references = normalize_placeholder_link_references(
                bytecode_placeholder_locations,
                compiled_contracts,
            )
        else:
            bytecode_link_references = tuple()

        bytecode_runtime = contract_data.get('bytecode_runtime')
        if is_string(bytecode_runtime):
            bytecode_runtime_placeholder_locations = find_placeholder_locations(
                bytecode_runtime,
            )
            bytecode_runtime_link_references = normalize_placeholder_link_references(
                bytecode_runtime_placeholder_locations,
                compiled_contracts,
            )
        else:
            bytecode_runtime_link_references = tuple()

        yield pipe(
            contract_data,
            partial(assoc, key='linkrefs', value=bytecode_link_references),
            partial(assoc, key='linkrefs_runtime', value=bytecode_runtime_link_references),
        )
Beispiel #2
0
def is_encodable(_type, value):
    try:
        base, sub, arrlist = _type
    except ValueError:
        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(sub_type, sub_value) for sub_value in value)
    elif base == 'bool':
        return is_boolean(value)
    elif base == 'uint':
        if not is_integer(value):
            return False
        exp = int(sub)
        if value < 0 or value >= 2**exp:
            return False
        return True
    elif base == 'int':
        if not is_integer(value):
            return False
        exp = int(sub)
        if value <= -1 * 2**(exp - 1) or value >= 2**(exp - 1):
            return False
        return True
    elif base == 'string':
        if not is_string(value):
            return False
        return True
    elif base == 'bytes':
        if not is_string(value):
            return False

        if not sub:
            return True

        max_length = int(sub)
        if isinstance(value, str):
            decodable = is_hex(value) and len(value) % 2 == 0
            return decodable and len(decode_hex(value)) <= max_length
        elif isinstance(value, bytes):
            return len(value) <= max_length
        else:
            False
    elif base == 'address':
        if is_ens_name(value):
            return True
        elif is_address(value):
            return True
        else:
            return False
    else:
        raise ValueError("Unsupported type")
Beispiel #3
0
def validate_abi_value(abi_type, value):
    """
    Helper function for validating a value against the expected abi_type
    Note: abi_type 'bytes' must either be python3 'bytes' object or ''
    """
    if is_array_type(abi_type) and is_list_like(value):
        # validate length
        specified_length = length_of_array_type(abi_type)
        if specified_length is not None:
            if specified_length < 1:
                raise TypeError(
                    "Invalid abi-type: {abi_type}. Length of fixed sized arrays"
                    "must be greater than 0."
                    .format(abi_type=abi_type)
                )
            if specified_length != len(value):
                raise TypeError(
                    "The following array length does not the length specified"
                    "by the abi-type, {abi_type}: {value}"
                    .format(abi_type=abi_type, value=value)
                )

        # validate sub_types
        sub_type = sub_type_of_array_type(abi_type)
        for v in value:
            validate_abi_value(sub_type, v)
        return
    elif is_bool_type(abi_type) and is_boolean(value):
        return
    elif is_uint_type(abi_type) and is_integer(value) and value >= 0:
        return
    elif is_int_type(abi_type) and is_integer(value):
        return
    elif is_address_type(abi_type):
        validate_address(value)
        return
    elif is_bytes_type(abi_type):
        if sys.version_info.major >= 3 and is_bytes(value):
            return
        elif is_string(value):
            if is_0x_prefixed(value):
                return
            else:
                raise TypeError(
                    "ABI values of abi-type 'bytes' must be either"
                    "a python3 'bytes' object or an '0x' prefixed string."
                )
    elif is_string_type(abi_type) and is_string(value):
        return

    raise TypeError(
        "The following abi value is not a '{abi_type}': {value}"
        .format(abi_type=abi_type, value=value)
    )
Beispiel #4
0
 def filter(self, filter_params):
     if is_string(filter_params):
         if filter_params == "latest":
             filter_id = self.web3.manager.request_blocking(
                 "eth_newBlockFilter", [],
             )
             return BlockFilter(self.web3, filter_id)
         elif filter_params == "pending":
             filter_id = self.web3.manager.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):
         filter_id = self.web3.manager.request_blocking(
             "eth_newFilter",
             [filter_params],
         )
         return LogFilter(self.web3, filter_id)
     else:
         raise ValueError("Must provide either a string or a valid filter object")
Beispiel #5
0
 def filter(self, filter_params=None, filter_id=None):
     if filter_id and filter_params:
         raise TypeError(
             "Ambiguous invocation: provide either a `filter_params` or a `filter_id` argument. "
             "Both were supplied."
         )
     if is_string(filter_params):
         if filter_params == "latest":
             filter_id = self.web3.manager.request_blocking(
                 "eth_newBlockFilter", [],
             )
             return BlockFilter(self.web3, filter_id)
         elif filter_params == "pending":
             filter_id = self.web3.manager.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):
         _filter_id = self.web3.manager.request_blocking(
             "eth_newFilter",
             [filter_params],
         )
         return LogFilter(self.web3, _filter_id)
     elif filter_id and not filter_params:
         return LogFilter(self.web3, filter_id)
     else:
         raise TypeError("Must provide either filter_params as a string or "
                         "a valid filter object, or a filter_id as a string "
                         "or hex.")
Beispiel #6
0
def to_hex(value):
    """
    Auto converts any supported value into it's hex representation.
    """
    if is_boolean(value):
        return "0x1" if value else "0x0"

    if is_dict(value):
        return encode_hex(json.dumps(value, sort_keys=True))

    if is_string(value):
        if is_prefixed(value, '-0x'):
            return from_decimal(value)
        elif is_0x_prefixed(value):
            return value
        else:
            return encode_hex(value)

    if is_integer(value):
        return from_decimal(value)

    raise TypeError(
        "Unsupported type: '{0}'.  Must be one of Boolean, Dictionary, String, "
        "or Integer.".format(repr(type(value)))
    )
Beispiel #7
0
def is_by_hash(at_block):
    if is_string(at_block) and is_hex(at_block) and len(at_block) == 66:
        return True
    elif is_integer(at_block) or at_block in ('latest', 'earliest', 'pending'):
        return False
    else:
        raise ValueError("Unrecognized 'at_block' value: %r" % at_block)
Beispiel #8
0
    def sign(self, key):
        """Sign this transaction with a private key.

        A potentially already existing signature would be overridden.
        """
        if not is_bitcoin_available() or not is_secp256k1_available():
            raise ImportError(
                "In order to sign transactions the "
                "`bitcoin` and `secp256k1` packages must be installed."
            )
        from bitcoin import privtopub
        from secp256k1 import PrivateKey

        if key in (0, b'', b'\x00' * 32, b'0' * 64):
            raise ValueError("Zero privkey cannot sign")

        rawhash = keccak(rlp.encode(self, UnsignedTransaction))

        if len(key) in {64, 66}:
            # we need a binary key
            key = decode_hex(key)

        pk = PrivateKey(key, raw=True)
        sig_bytes, rec_id = pk.ecdsa_recoverable_serialize(
            pk.ecdsa_sign_recoverable(rawhash, raw=True)
        )
        signature = sig_bytes + force_bytes(chr(rec_id))
        self.v = (ord(signature[64]) if is_string(signature[64]) else signature[64]) + 27
        self.r = decode_big_endian_int(signature[0:32])
        self.s = decode_big_endian_int(signature[32:64])

        self.sender = to_normalized_address(keccak(privtopub(key)[1:])[-20:])
        return self
Beispiel #9
0
def to_hex(value=None, hexstr=None, text=None):
    """
    Auto converts any supported value into it's hex representation.

    Trims leading zeros, as defined in:
    https://github.com/ethereum/wiki/wiki/JSON-RPC#hex-value-encoding
    """
    assert_one_val(value, hexstr=hexstr, text=text)

    if hexstr is not None:
        return add_0x_prefix(hexstr.lower())

    if text is not None:
        return encode_hex(text.encode('utf-8'))

    if is_boolean(value):
        return "0x1" if value else "0x0"

    if is_dict(value):
        return encode_hex(json.dumps(value, sort_keys=True))

    if isinstance(value, bytes):
        return encode_hex(value)
    elif is_string(value):
        return to_hex(text=value)

    if is_integer(value):
        return hex(value)

    raise TypeError(
        "Unsupported type: '{0}'.  Must be one of Boolean, Dictionary, String, "
        "or Integer.".format(repr(type(value)))
    )
Beispiel #10
0
def is_primitive_type(value):
    return any((
        value is None,
        is_boolean(value),
        is_string(value),
        is_number(value),
    ))
Beispiel #11
0
def test_eth_sign(web3, skip_if_testrpc):
    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
Beispiel #12
0
    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 test_eth_getBlock_by_hash(web3):
    block_1 = web3.eth.getBlock(1)
    block_1_hash = block_1['hash']

    block_1_by_hash = web3.eth.getBlock(block_1_hash)
    assert block_1_by_hash
    assert block_1_by_hash['number'] == 1
    assert block_1_by_hash['hash'] == block_1_hash
    assert all(is_string(txn) for txn in block_1['transactions'])
Beispiel #14
0
    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
Beispiel #15
0
def decint(n):
    if isinstance(n, str):
        n = to_string(n)
    if is_numeric(n) and n < 2**256 and n > -2**255:
        return n
    elif is_numeric(n):
        raise EncodingError("Number out of range: %r" % n)
    elif is_string(n) and len(n) == 40:
        return big_endian_to_int(decode_hex(n))
    elif is_string(n) and len(n) <= 32:
        return big_endian_to_int(n)
    elif is_string(n) and len(n) > 32:
        raise EncodingError("String too long: %r" % n)
    elif n is True:
        return 1
    elif n is False or n is None:
        return 0
    else:
        raise EncodingError("Cannot encode integer: %r" % n)
Beispiel #16
0
def is_hex_encoded_block_number(value):
    if not is_string(value):
        return False
    elif is_hex_encoded_block_hash(value):
        return False
    try:
        value_as_int = int(value, 16)
    except ValueError:
        return False
    return 0 <= value_as_int < 2**256
Beispiel #17
0
 def __set__(self, obj, value):
     if is_string(value):
         obj[self.key] = value
     elif isinstance(value, type):
         obj[self.key] = '.'.join([value.__module__, value.__name__])
     else:
         raise ValueError(
             "Unsupported type.  Must be either a string import path or a "
             "chain class"
         )
Beispiel #18
0
 def wrapper(*args, **kwargs):
     value = fn(*args, **kwargs)
     if is_string(value):
         return os.path.relpath(value)
     elif is_list_like(value):
         return type(value)([
             os.path.relpath(path) for path in value
         ])
     else:
         raise TypeError("Unsupported type: {0}".format(type(value)))
Beispiel #19
0
 def match(filename, pattern):
     if is_list_like(pattern):
         return any([fnmatch.fnmatch(filename, p) for p in pattern])
     elif is_string(pattern):
         return fnmatch.fnmatch(filename, pattern)
     else:
         raise TypeError(
             "Pattern must either be a string pattern or a list of patterns." +
             "  Got {0}".format(pattern)
         )
Beispiel #20
0
 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
Beispiel #21
0
def construct_event_filter_params(event_abi,
                                  contract_address=None,
                                  argument_filters=None,
                                  topics=None,
                                  fromBlock=None,
                                  toBlock=None,
                                  address=None):
    filter_params = {}
    topic_set = construct_event_topic_set(event_abi, argument_filters)

    if topics is not None:
        if len(topic_set) > 1:
            raise TypeError(
                "Merging the topics argument with topics generated "
                "from argument_filters is not supported.")
        topic_set = topics

    if len(topic_set) == 1 and is_list_like(topic_set[0]):
        filter_params['topics'] = topic_set[0]
    else:
        filter_params['topics'] = topic_set

    if address and contract_address:
        if is_list_like(address):
            filter_params['address'] = address + [contract_address]
        elif is_string(address):
            filter_params['address'] = [address, contract_address]
        else:
            raise ValueError(
                "Unsupported type for `address` parameter: {0}".format(type(address))
            )
    elif address:
        filter_params['address'] = address
    elif contract_address:
        filter_params['address'] = contract_address

    if 'address' not in filter_params:
        pass
    elif is_list_like(filter_params['address']):
        for addr in filter_params['address']:
            validate_address(addr)
    else:
        validate_address(filter_params['address'])

    if fromBlock is not None:
        filter_params['fromBlock'] = fromBlock

    if toBlock is not None:
        filter_params['toBlock'] = toBlock

    data_filters_set = construct_event_data_set(event_abi, argument_filters)

    return data_filters_set, filter_params
Beispiel #22
0
def get_solc_backend_class_for_version(solc_version):
    if is_string(solc_version):
        solc_version = Version(solc_version)

    if solc_version in Spec('<=0.4.8'):
        return SolcCombinedJSONBackend
    elif solc_version in Spec('>=0.4.11'):
        return SolcStandardJSONBackend
    else:
        raise OSError(
            "The installed solc compiler is not supported.  Supported versions "
            "of the solc compiler are <=0.4.8 and >=0.4.11"
        )
Beispiel #23
0
def to_decimal(value):
    """
    Converts value to it's decimal representation in string
    """
    if is_string(value):
        if is_0x_prefixed(value) or is_prefixed(value, '-0x'):
            value = int(value, 16)
        else:
            value = int(value)
    else:
        value = int(value)

    return value
Beispiel #24
0
def map_collection(func, collection):
    '''
    Apply func to each element of a collection, or value of a dictionary.
    If the value is not a collection, return it unmodified
    '''
    datatype = type(collection)
    if isinstance(collection, Mapping):
        return datatype((key, func(val)) for key, val in collection.items())
    if is_string(collection):
        return collection
    elif isinstance(collection, Iterable):
        return datatype(map(func, collection))
    else:
        return collection
Beispiel #25
0
def from_decimal(value):
    """
    Converts numeric value to it's hex representation
    """
    if is_string(value):
        if is_0x_prefixed(value) or is_prefixed(value, '-0x'):
            value = int(value, 16)
        else:
            value = int(value)

    # python2 longs end up with an `L` hanging off the end of their hexidecimal
    # representation.
    result = hex(value).rstrip('L')
    return result
Beispiel #26
0
    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
Beispiel #27
0
    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_dict(response_raw):
            response = response_raw

        if "error" in response:
            raise ValueError(response["error"])

        return response['result']
Beispiel #28
0
 def set_provider_class(self, provider_identifier):
     if isinstance(provider_identifier, type):
         self.provider_class = provider_identifier
     elif is_string(provider_identifier):
         if provider_identifier.lower() in PROVIDER_IDENTIFIER_MAP:
             self.provider_class = PROVIDER_IDENTIFIER_MAP[provider_identifier.lower()]
         else:
             try:
                 import_string(provider_identifier)
             except ImportError:
                 raise ValueError(
                     UNSUPPORTED_PROVIDER_IDENTIFIER_MSG.format(provider_identifier)
                 )
             else:
                 self.provider_class = provider_identifier
     else:
         raise ValueError(UNSUPPORTED_PROVIDER_IDENTIFIER_MSG.format(provider_identifier))
Beispiel #29
0
 def set_backend_class(self, backend_identifier):
     if isinstance(backend_identifier, type):
         self.backend_class = backend_identifier
     elif is_string(backend_identifier):
         if backend_identifier.lower() in BACKEND_IDENTIFIER_MAP:
             self.backend_class = BACKEND_IDENTIFIER_MAP[backend_identifier.lower()]
         else:
             try:
                 import_string(backend_identifier)
             except ImportError:
                 raise ValueError(
                     UNSUPPORTED_BACKEND_IDENTIFIER_MSG.format(backend_identifier)
                 )
             else:
                 self.backend_class = backend_identifier
     else:
         raise ValueError(UNSUPPORTED_BACKEND_IDENTIFIER_MSG.format(backend_identifier))
Beispiel #30
0
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
Beispiel #31
0
    def test_eth_protocolVersion(self, web3: "Web3") -> None:
        protocol_version = web3.eth.protocolVersion

        assert is_string(protocol_version)
        assert protocol_version.isdigit()
Beispiel #32
0
def load_json_if_string(value):
    if is_string(value):
        return json.loads(value)
    else:
        return value
    def test_eth_protocolVersion(self, web3):
        protocol_version = web3.version.ethereum

        assert is_string(protocol_version)
        assert protocol_version.isdigit()
Beispiel #34
0
def test_eth_sign(web3, skip_if_testrpc):
    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.
    # address = '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=hashlib.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)

    # geth prefix message before signing
    geth_prefix_data = eth_message_prefix_hash(web3, data.decode())

    actual_signer = extract_ecdsa_signer(force_bytes(geth_prefix_data),
                                         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=hashlib.sha3_256,
    )

    assert is_valid
Beispiel #35
0
 def test_eth_getCode(self, web3, math_contract):
     code = web3_offline_signing.eth.getCode(math_contract.address)
     assert is_string(code)
     assert len(code) > 2
Beispiel #36
0
    def test_net_version(self, web3: "Web3") -> None:
        version = web3.net.version

        assert is_string(version)
        assert version.isdigit()
Beispiel #37
0
def load_keyfile(path_or_file_obj):
    if is_string(path_or_file_obj):
        with open(path_or_file_obj) as keyfile_file:
            return json.load(keyfile_file)
    else:
        return json.load(path_or_file_obj)
    def test_eth_protocol_version(self, web3: "Web3") -> None:
        with pytest.warns(DeprecationWarning):
            protocol_version = web3.eth.protocol_version

        assert is_string(protocol_version)
        assert protocol_version.isdigit()
Beispiel #39
0
def upgrade_v5_to_v6(v5_config):
    """
    Upgrade a v5 config file to a v6 config file.
    """
    errors = get_validation_errors(v5_config, version=V5)
    if errors:
        raise ValueError(
            "Cannot upgrade invalid config.  Please ensure that your current "
            "configuration file is valid:\n\n{0}".format(
                format_errors(errors),
            )
        )

    v5_default_config = load_default_config(version=V5)
    v6_default_config = load_default_config(version=V6)

    if v5_config == v5_default_config:
        return v6_default_config

    upgraded_v5_config = copy.deepcopy(v5_config)

    # new configuration values whos keys were not present in the previous
    # configuration.
    for key_path in NEW_V6_PATHS:
        if has_nested_key(upgraded_v5_config, key_path):
            continue
        set_nested_key(
            upgraded_v5_config,
            key_path,
            get_nested_key(v6_default_config, key_path),
        )

    if has_nested_key(upgraded_v5_config, 'compilation.contracts_source_dir'):
        current_contracts_source_dir = pop_nested_key(
            upgraded_v5_config,
            'compilation.contracts_source_dir',
        )
        if is_string(current_contracts_source_dir):
            contract_source_dirs = [current_contracts_source_dir]
        else:
            contract_source_dirs = current_contracts_source_dir
        set_nested_key(
            upgraded_v5_config,
            'compilation.contract_source_dirs',
            contract_source_dirs,
        )

    # bump the version
    set_nested_key(upgraded_v5_config, 'version', V6)

    errors = get_validation_errors(upgraded_v5_config, version=V6)
    if errors:
        raise ValueError(
            "Upgraded configuration did not pass validation:\n\n"
            "\n=============Original-Configuration============\n"
            "{0}"
            "\n=============Upgraded-Configuration============\n"
            "{1}"
            "\n=============Validation-Errors============\n"
            "{2}".format(
                pprint.pformat(dict(v5_config)),
                pprint.pformat(dict(upgraded_v5_config)),
                format_errors(errors),
            )
        )

    return upgraded_v5_config
Beispiel #40
0
    def test_net_version(self, web3):
        version = web3.version.network

        assert is_string(version)
        assert version.isdigit()
Beispiel #41
0
 def test_ProtocolVersion(self, platon_connect):
     protocol_version = platon_connect.protocolVersion
     assert is_string(protocol_version)
     assert protocol_version.isdigit()
Beispiel #42
0
    def test_net_version(self, web3):
        version = web3_offline_signing.net.version

        assert is_string(version)
        assert version.isdigit()
Beispiel #43
0
def is_hexstr(value: Any) -> bool:
    return is_string(value) and is_hex(value)
Beispiel #44
0
    def test_net_version(self, webu):
        version = webu.net.version

        assert is_string(version)
        assert version.isdigit()
Beispiel #45
0
def is_hex_encoded_block_hash(value: Any) -> bool:
    if not is_string(value):
        return False
    return len(remove_0x_prefix(value)) == 64 and is_hex(value)
Beispiel #46
0
def is_array_of_strings(value):
    if not is_list_like(value):
        return False
    return all((is_string(item) for item in value))
Beispiel #47
0
def is_not_address_string(value: Any) -> bool:
    return (is_string(value) and not is_bytes(value)
            and not is_checksum_address(value) and not is_hex_address(value))
    async def test_net_version(self, async_w3: "Web3") -> None:
        version = await async_w3.async_net.version

        assert is_string(version)
        assert version.isdigit()
Beispiel #49
0
def is_predefined_block_number(block_number):
    if not is_string(block_number):
        return False
    return force_text(block_number) in {"latest", "pending", "earliest"}
Beispiel #50
0
def test_eth_getBlock_by_number(web3):
    block_1 = web3.eth.getBlock(1)
    assert block_1
    assert block_1['number'] == 1
    assert all(is_string(txn) for txn in block_1['transactions'])
Beispiel #51
0
def is_hexstr(value):
    return is_string(value) and is_hex(value)
Beispiel #52
0
def encode_single(typ, arg):
    base, sub, _ = typ
    # Unsigned integers: uint<sz>
    if base == 'uint':
        sub = int(sub)
        i = decint(arg)

        if not 0 <= i < 2**sub:
            raise ValueOutOfBounds(repr(arg))
        return zpad(encode_int(i), 32)
    # bool: int<sz>
    elif base == 'bool':
        assert isinstance(arg, bool)
        return zpad(encode_int(int(arg)), 32)
    # Signed integers: int<sz>
    elif base == 'int':
        sub = int(sub)
        i = decint(arg)  # TODO: is this OK? Does it handle <0?
        if not -2**(sub - 1) <= i < 2**sub:
            raise ValueOutOfBounds(repr(arg))
        return zpad(encode_int(i % 2**sub), 32)
    # Unsigned reals: ureal<high>x<low>
    elif base == 'ureal':
        high, low = [int(x) for x in sub.split('x')]
        if not 0 <= arg < 2**high:
            raise ValueOutOfBounds(repr(arg))
        return zpad(encode_int(arg * 2**low), 32)
    # Signed reals: real<high>x<low>
    elif base == 'real':
        high, low = [int(x) for x in sub.split('x')]
        if not -2**(high - 1) <= arg < 2**(high - 1):
            raise ValueOutOfBounds(repr(arg))
        return zpad(encode_int((arg % 2**high) * 2**low), 32)
    # Strings
    elif base == 'string' or base == 'bytes':
        if not is_string(arg):
            raise EncodingError("Expecting string: %r" % arg)
        # Fixed length: string<sz>
        if len(sub):
            assert int(sub) <= 32
            assert len(arg) <= int(sub)
            return arg + b'\x00' * (32 - len(arg))
        # Variable length: string
        else:
            return zpad(encode_int(len(arg)), 32) + \
                arg + \
                b'\x00' * (ceil32(len(arg)) - len(arg))
    # Hashes: hash<sz>
    elif base == 'hash':
        if not (int(sub) and int(sub) <= 32):
            raise EncodingError("too long: %r" % arg)
        if isnumeric(arg):
            return zpad(encode_int(arg), 32)
        elif len(arg) == len(sub):
            return zpad(arg, 32)
        elif len(arg) == len(sub) * 2:
            return zpad(decode_hex(arg), 32)
        else:
            raise EncodingError("Could not parse hash: %r" % arg)
    # Addresses: address (== hash160)
    elif base == 'address':
        assert sub == ''
        if isnumeric(arg):
            return zpad(encode_int(arg), 32)
        elif len(arg) == 20:
            return zpad(arg, 32)
        elif len(arg) == 40:
            return zpad(decode_hex(arg), 32)
        elif len(arg) == 42 and (arg[:2] == '0x' or arg[:2] == '0X'):
            return zpad(decode_hex(arg[2:]), 32)
        else:
            raise EncodingError("Could not parse address: %r" % arg)
    raise EncodingError("Unhandled type: %r %r" % (base, sub))
Beispiel #53
0
 def test_eth_getCode(self, web3, math_contract_address):
     code = web3.eth.getCode(math_contract_address)
     assert is_string(code)
     assert len(code) > 2
Beispiel #54
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
Beispiel #55
0
    def test_eth_protocolVersion(self, webu):
        protocol_version = webu.version.happyuc

        assert is_string(protocol_version)
        assert protocol_version.isdigit()