Exemplo n.º 1
0
    def encodeConstructorData(cls, arguments=None):
        if arguments is None:
            arguments = []

        constructor = get_constructor_abi(cls.abi)
        if constructor:
            if constructor['inputs'] and not arguments:
                raise ValueError(
                    "This contract requires {0} constructor arguments".format(
                        len(constructor['inputs']), ))
            if arguments:
                if len(arguments) != len(constructor['inputs']):
                    raise ValueError(
                        "This contract requires {0} constructor arguments".
                        format(len(constructor['inputs']), ))

                is_encodable = check_if_arguments_can_be_encoded(
                    constructor,
                    arguments,
                    {},
                )
                if not is_encodable:
                    raise ValueError("Unable to encode provided arguments.")

            deploy_data = add_0x_prefix(
                cls._encodeABI(constructor, arguments, data=cls.code))
        else:
            deploy_data = add_0x_prefix(cls.code)

        return deploy_data
Exemplo n.º 2
0
    def encodeConstructorData(cls, arguments=None):
        if arguments is None:
            arguments = []

        constructor = get_constructor_abi(cls.abi)
        if constructor:
            if constructor['inputs'] and not arguments:
                raise ValueError(
                    "This contract requires {0} constructor arguments".format(
                        len(constructor['inputs']),
                    )
                )
            if arguments:
                if len(arguments) != len(constructor['inputs']):
                    raise ValueError(
                        "This contract requires {0} constructor arguments".format(
                            len(constructor['inputs']),
                        )
                    )

                is_encodable = check_if_arguments_can_be_encoded(
                    get_abi_input_types(constructor),
                    arguments,
                )
                if not is_encodable:
                    raise ValueError("Unable to encode provided arguments.")

            deploy_data = add_0x_prefix(cls._encodeABI(constructor, arguments, data=cls.code))
        else:
            deploy_data = add_0x_prefix(cls.code)

        return deploy_data
Exemplo n.º 3
0
def input_address_formatter(addr):
    iban = Iban(addr)
    if iban.isValid() and iban.isDirect():
        return add_0x_prefix(iban.address())
    elif is_strict_address(addr):
        return addr
    elif is_address(addr):
        return add_0x_prefix(addr)

    raise ValueError("invalid address")
Exemplo n.º 4
0
def input_address_formatter(addr):
    iban = Iban(addr)
    if iban.isValid() and iban.isDirect():
        return add_0x_prefix(iban.address())
    elif is_strict_address(addr):
        return addr
    elif is_address(addr):
        return add_0x_prefix(addr)

    raise ValueError("invalid address")
Exemplo n.º 5
0
def normalize_contract_data(contract_data, contract_meta):
    yield 'meta', contract_meta
    if 'bin' in contract_data:
        yield 'code', add_0x_prefix(contract_data['bin'])
    if 'bin-runtime' in contract_data:
        yield 'code_runtime', add_0x_prefix(contract_data['bin-runtime'])
    if 'abi' in contract_data:
        yield 'abi', contract_data['abi']
    if 'userdoc' in contract_data:
        yield 'userdoc', contract_data['userdoc']
    if 'devdoc' in contract_data:
        yield 'devdoc', contract_data['devdoc']
Exemplo n.º 6
0
    def _encode_abi(cls, 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:
            encoded_arguments = encode_abi(
                argument_types,
                force_obj_to_bytes(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 add_0x_prefix(
                force_bytes(remove_0x_prefix(data)) +
                force_bytes(remove_0x_prefix(encode_hex(encoded_arguments))))
        else:
            return encode_hex(encoded_arguments)
Exemplo n.º 7
0
    def _encode_abi(cls, 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:
            encoded_arguments = encode_abi(
                argument_types,
                force_obj_to_bytes(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 add_0x_prefix(
                force_bytes(remove_0x_prefix(data)) +
                force_bytes(remove_0x_prefix(encode_hex(encoded_arguments)))
            )
        else:
            return encode_hex(encoded_arguments)
Exemplo n.º 8
0
    def _encode_constructor_data(cls, args=None, kwargs=None):
        constructor_abi = get_constructor_abi(cls.abi)

        if constructor_abi:
            if args is None:
                args = tuple()
            if kwargs is None:
                kwargs = {}

            arguments = merge_args_and_kwargs(constructor_abi, args, kwargs)

            deploy_data = add_0x_prefix(
                cls._encode_abi(constructor_abi, arguments, data=cls.code))
        else:
            deploy_data = add_0x_prefix(cls.code)

        return deploy_data
Exemplo n.º 9
0
 def _encode_transaction_data(cls, fn_name, args=None, kwargs=None):
     fn_abi, fn_selector, fn_arguments = cls._get_function_info(
         fn_name,
         args,
         kwargs,
     )
     return add_0x_prefix(cls._encode_abi(fn_abi, fn_arguments,
                                          fn_selector))
Exemplo n.º 10
0
    def _encode_constructor_data(cls, args=None, kwargs=None):
        constructor_abi = get_constructor_abi(cls.abi)

        if constructor_abi:
            if args is None:
                args = tuple()
            if kwargs is None:
                kwargs = {}

            arguments = merge_args_and_kwargs(constructor_abi, args, kwargs)

            deploy_data = add_0x_prefix(
                cls._encode_abi(constructor_abi, arguments, data=cls.code)
            )
        else:
            deploy_data = add_0x_prefix(cls.code)

        return deploy_data
Exemplo n.º 11
0
 def _encodeABI(cls, abi, arguments, data=None):
     arguent_types = get_abi_input_types(abi)
     encoded_arguments = encode_abi(arguent_types, force_obj_to_bytes(arguments))
     if data:
         return add_0x_prefix(
             force_bytes(remove_0x_prefix(data)) +
             force_bytes(remove_0x_prefix(encode_hex(encoded_arguments)))
         )
     else:
         return encode_hex(encoded_arguments)
Exemplo n.º 12
0
 def _encodeABI(cls, abi, arguments, data=None):
     arguent_types = get_abi_input_types(abi)
     encoded_arguments = encode_abi(arguent_types,
                                    force_obj_to_bytes(arguments))
     if data:
         return add_0x_prefix(
             force_bytes(remove_0x_prefix(data)) +
             force_bytes(remove_0x_prefix(encode_hex(encoded_arguments))))
     else:
         return encode_hex(encoded_arguments)
Exemplo n.º 13
0
    def address(self):
        """
        Should be called to get client direct address

        @method address
        @returns {String} client direct address
        """
        if self.isDirect():
            base36 = self._iban[4:]
            asInt = int(base36, 36)
            return add_0x_prefix(pad_left_hex(baseN(asInt, 16), 20))

        return ""
Exemplo n.º 14
0
    def address(self):
        """
        Should be called to get client direct address

        @method address
        @returns {String} client direct address
        """
        if self.isDirect():
            base36 = self._iban[4:]
            asInt = int(base36, 36)
            return add_0x_prefix(pad_left_hex(baseN(asInt, 16), 20))

        return ""
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
Exemplo n.º 16
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
Exemplo n.º 17
0
 def _encode_transaction_data(cls, fn_name, args=None, kwargs=None):
     fn_abi, fn_selector, fn_arguments = cls._get_function_info(
         fn_name, args, kwargs,
     )
     return add_0x_prefix(cls._encode_abi(fn_abi, fn_arguments, fn_selector))
def sha3(s):
    return add_0x_prefix(sha3_256(s).hexdigest())
Exemplo n.º 19
0
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
Exemplo n.º 20
0
def sha3(s):
    return add_0x_prefix(sha3_256(s).hexdigest())
Exemplo n.º 21
0
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