Ejemplo n.º 1
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)
Ejemplo n.º 2
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)
Ejemplo n.º 3
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)
Ejemplo n.º 4
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)
Ejemplo n.º 5
0
    def request_blocking(self, method, params):
        if method == 'eth_sendTransaction':
            base_transaction = params[0]
            # create a fully signed transaction and send through the
            # `eth_sendRawTransaction` endpoint instead.
            full_transaction = self.construct_full_transaction(base_transaction)
            raw_transaction_bytes = self.sign_and_serialize_transaction(
                full_transaction,
            )
            raw_transaction_bytes_as_hex = encode_hex(raw_transaction_bytes)
            return self.request_blocking(
                'eth_sendRawTransaction', [raw_transaction_bytes_as_hex],
            )

        result = super(BaseSendRawTransactionMixin, self).request_blocking(
            method, params,
        )
        if method in self.TXN_SENDING_METHODS:
            if method == 'eth_sendRawTransaction':
                txn = rlp.decode(decode_hex(params[0]), Transaction)
                self._known_transactions[to_address(txn.sender)].add(result)
                self._known_nonces[to_address(txn.sender)].add(txn.nonce)
            else:
                txn = params[0]
                self._known_transactions[to_address(txn['from'])].add(result)
                if 'nonce' in txn:
                    self._known_nonces[to_address(txn['from'])].add(
                        to_decimal(txn['nonce'])
                    )
        return result
Ejemplo n.º 6
0
def test_adding_signature_to_transaction(wait_for_first_block, web3,
                                         skip_if_testrpc):
    skip_if_testrpc(web3)

    transaction = {
        'nonce': hex(0),
        'to': '0xd3cda913deb6f67967b99d67acdfa1712c293601',
        'value': hex(12345),
        'gas': hex(1200300),
        'gasPrice': hex(54321),
        'data': '0x1234567890abcdef',
    }

    serialized_txn = serialize_transaction(transaction)
    signature_hex = web3.eth.sign(web3.eth.coinbase, serialized_txn)

    signed_transaction = add_signature_to_transaction(
        serialized_txn,
        decode_hex(signature_hex),
    )

    assert to_address(signed_transaction.to) == transaction['to']
    assert signed_transaction.startgas == int(transaction['gas'], 16)
    assert signed_transaction.gasprice == int(transaction['gasPrice'], 16)
    assert signed_transaction.nonce == int(transaction['nonce'], 16)
    assert signed_transaction.value == int(transaction['value'], 16)
    assert encode_hex(signed_transaction.data) == transaction['data']
    assert signed_transaction.sender == web3.eth.coinbase
def test_migrations_store_receipts_on_completion(web3, MATH, chain):
    registrar = chain.registrar

    class MockOperation(Operation):
        def execute(self, *args, **kwargs):
            return {
                'raw-address':
                web3.eth.coinbase,
                'raw-txn':
                '0xebb0f76aa6a6bb8d178ac2354de83d73a728d704bf47d135c188ca7b6d25f2e4',
                'no-key':
                Address.defer(value=web3.eth.coinbase),
                'with-key':
                String.defer(key='this-is-a-key', value='this-is-a-string'),
            }

    class TestMigration(Migration):
        migration_id = '0001_initial'
        dependencies = []

        operations = [
            MockOperation(),
        ]

    assert registrar.call().exists('migration/0001_initial') is False
    assert registrar.call().exists(
        'migration/0001_initial/operation/0') is False
    assert registrar.call().exists(
        'migration/0001_initial/operation/0/raw-address') is False
    assert registrar.call().exists(
        'migration/0001_initial/operation/0/raw-txn') is False
    assert registrar.call().exists(
        'migration/0001_initial/operation/0/no-key') is False
    assert registrar.call().exists('this-is-a-key') is False

    migration = TestMigration(chain)
    migration.execute()

    assert registrar.call().exists('migration/0001_initial') is True
    assert registrar.call().exists(
        'migration/0001_initial/operation/0') is True
    assert registrar.call().exists(
        'migration/0001_initial/operation/0/raw-address') is True
    assert registrar.call().exists(
        'migration/0001_initial/operation/0/raw-txn') is True
    assert registrar.call().exists(
        'migration/0001_initial/operation/0/no-key') is True
    assert registrar.call().exists('this-is-a-key') is True

    assert registrar.call().getBool('migration/0001_initial') is True
    assert registrar.call().getBool(
        'migration/0001_initial/operation/0') is True
    assert registrar.call().getAddress(
        'migration/0001_initial/operation/0/raw-address') == web3.eth.coinbase
    assert encode_hex(
        registrar.call().get('migration/0001_initial/operation/0/raw-txn')
    ) == '0xebb0f76aa6a6bb8d178ac2354de83d73a728d704bf47d135c188ca7b6d25f2e4'
    assert registrar.call().getAddress(
        'migration/0001_initial/operation/0/no-key') == web3.eth.coinbase
    assert registrar.call().getString('this-is-a-key') == 'this-is-a-string'
Ejemplo n.º 8
0
 def sign(self, account, data):
     data_hash = self.web3._requestManager.request_blocking(
         "web3_sha3", [encode_hex(data)],
     )
     return self.web3._requestManager.request_blocking(
         "eth_sign", [account, data_hash],
     )
def test_adding_signature_to_transaction(wait_for_first_block,
                                         web3,
                                         skip_if_testrpc):
    skip_if_testrpc(web3)

    transaction = {
        'nonce': hex(0),
        'to': '0xd3cda913deb6f67967b99d67acdfa1712c293601',
        'value': hex(12345),
        'gas': hex(1200300),
        'gasPrice': hex(54321),
        'data': '0x1234567890abcdef',
    }

    serialized_txn = serialize_transaction(transaction)
    signature_hex = web3.eth.sign(web3.eth.coinbase, serialized_txn)

    signed_transaction = add_signature_to_transaction(
        serialized_txn,
        decode_hex(signature_hex),
    )

    assert to_address(signed_transaction.to) == transaction['to']
    assert signed_transaction.startgas == int(transaction['gas'], 16)
    assert signed_transaction.gasprice == int(transaction['gasPrice'], 16)
    assert signed_transaction.nonce == int(transaction['nonce'], 16)
    assert signed_transaction.value == int(transaction['value'], 16)
    assert encode_hex(signed_transaction.data) == transaction['data']
    assert signed_transaction.sender == web3.eth.coinbase
Ejemplo n.º 10
0
    def request_blocking(self, method, params):
        if method == 'eth_sendTransaction':
            base_transaction = params[0]
            # create a fully signed transaction and send through the
            # `eth_sendRawTransaction` endpoint instead.
            full_transaction = self.construct_full_transaction(base_transaction)
            raw_transaction_bytes = self.sign_and_serialize_transaction(
                full_transaction,
            )
            raw_transaction_bytes_as_hex = encode_hex(raw_transaction_bytes)
            return self.request_blocking(
                'eth_sendRawTransaction', [raw_transaction_bytes_as_hex],
            )
 
        result = super(BaseSendRawTransactionMixin, self).request_blocking(
            method, params,
        )
        if method in self.TXN_SENDING_METHODS:
            if method == 'eth_sendRawTransaction':
                txn = rlp.decode(decode_hex(params[0]), Transaction)
                self._known_transactions[to_address(txn.sender)].add(result)
                self._known_nonces[to_address(txn.sender)].add(txn.nonce)
            else:
                txn = params[0]
                self._known_transactions[to_address(txn['from'])].add(result)
                if 'nonce' in txn:
                    self._known_nonces[to_address(txn['from'])].add(
                        to_decimal(txn['nonce'])
                    )
        return result
Ejemplo n.º 11
0
def test_contract_constructor_encoding_encoding(
        WithConstructorArgumentsContract):
    deploy_data = WithConstructorArgumentsContract._encode_constructor_data(
        [1234, 'abcd'])
    encoded_args = '0x00000000000000000000000000000000000000000000000000000000000004d26162636400000000000000000000000000000000000000000000000000000000'
    expected_ending = encode_hex(
        encode_abi(['uint256', 'bytes32'], [1234, b'abcd']))
    assert expected_ending == encoded_args
    assert deploy_data.endswith(remove_0x_prefix(expected_ending))
Ejemplo n.º 12
0
 def sign(self, account, data):
     data_hash = self.web3._requestManager.request_blocking(
         "web3_sha3",
         [encode_hex(data)],
     )
     return self.web3._requestManager.request_blocking(
         "eth_sign",
         [account, data_hash],
     )
def test_special_case_for_txn_hash():
    txn_hash = '0xebb0f76aa6a6bb8d178ac2b54de2fd7ca738d704bf47d135c188ca7b6d35f2e4'
    value_setters = generate_registrar_value_setters(txn_hash)

    assert len(value_setters) == 1

    setter = value_setters[0]
    assert issubclass(setter, RegistrarValue)
    assert encode_hex(setter.value) == txn_hash
    assert setter.value_type == 'bytes32'
Ejemplo n.º 14
0
def unknown_token_id(token_v1, web3):
    token = token_v1
    unknown_token_id = decode_hex(web3.sha3(encode_hex('Hudson James')))

    assert unknown_token_id == sha3_256(b'Hudson James').digest()
    assert token.call().identityOf(unknown_token_id) == ''
    assert token.call().ownerOf(
        unknown_token_id) == '0x0000000000000000000000000000000000000000'

    return unknown_token_id
Ejemplo n.º 15
0
def test_special_case_for_txn_hash():
    txn_hash = '0xebb0f76aa6a6bb8d178ac2b54de2fd7ca738d704bf47d135c188ca7b6d35f2e4'
    value_setters = generate_registrar_value_setters(txn_hash)

    assert len(value_setters) == 1

    setter = value_setters[0]
    assert issubclass(setter, RegistrarValue)
    assert encode_hex(setter.value) == txn_hash
    assert setter.value_type == 'bytes32'
Ejemplo n.º 16
0
 def importRawKey(self, private_key, passphrase):
     if len(private_key) == 66:
         private_key = remove_0x_prefix(private_key)
     elif len(private_key) == 32:
         private_key = remove_0x_prefix(encode_hex(private_key))
     elif len(private_key) == 64:
         pass
     else:
         raise ValueError("Unknown private key format")
     return self.request_manager.request_blocking(
         "personal_importRawKey",
         [private_key, passphrase],
     )
Ejemplo n.º 17
0
 def importRawKey(self, private_key, passphrase):
     if len(private_key) == 66:
         private_key = remove_0x_prefix(private_key)
     elif len(private_key) == 32:
         private_key = remove_0x_prefix(encode_hex(private_key))
     elif len(private_key) == 64:
         pass
     else:
         raise ValueError("Unknown private key format")
     return self.request_manager.request_blocking(
         "personal_importRawKey",
         [private_key, passphrase],
     )
Ejemplo n.º 18
0
 def get_transaction_signature(self, transaction):
     serialized_txn = serialize_transaction(transaction)
     hash_to_sign = self.signing_manager.request_blocking(
         'web3_sha3', [encode_hex(serialized_txn)],
     )
     signature_hex = self.signing_manager.request_blocking(
         'eth_sign',
         [
             transaction['from'],
             hash_to_sign,
         ],
     )
     signature = decode_hex(signature_hex)
     return signature
Ejemplo n.º 19
0
 def get_transaction_signature(self, transaction):
     serialized_txn = serialize_transaction(transaction)
     hash_to_sign = self.signing_manager.request_blocking(
         'web3_sha3', [encode_hex(serialized_txn)],
     )
     signature_hex = self.signing_manager.request_blocking(
         'eth_sign',
         [
             transaction['from'],
             hash_to_sign,
         ],
     )
     signature = decode_hex(signature_hex)
     return signature
Ejemplo n.º 20
0
def inputPostFormatter(post):
    """
    Formats the input of a whisper post and converts all values to HEX
    """

    post["ttl"] = from_decimal(post["ttl"])
    post["workToProve"] = from_decimal(post.get("workToProve", 0))
    post["priority"] = from_decimal(post["priority"])

    if not is_array(post.get("topics")):
        post["topics"] = [post["topics"]] if post.get("topics") else []

    post["topics"] = [topic if is_0x_prefixed(topic) else encode_hex(topic)
                      for topic in post["topics"]]

    return post
def test_migrations_store_receipts_on_completion(web3, MATH, chain):
    registrar = chain.registrar

    class MockOperation(Operation):
        def execute(self, *args, **kwargs):
            return {
                'raw-address': web3.eth.coinbase,
                'raw-txn': '0xebb0f76aa6a6bb8d178ac2354de83d73a728d704bf47d135c188ca7b6d25f2e4',
                'no-key': Address.defer(value=web3.eth.coinbase),
                'with-key': String.defer(key='this-is-a-key', value='this-is-a-string'),
            }


    class TestMigration(Migration):
        migration_id = '0001_initial'
        dependencies = []

        operations = [
            MockOperation(),
        ]

    assert registrar.call().exists('migration/0001_initial') is False
    assert registrar.call().exists('migration/0001_initial/operation/0') is False
    assert registrar.call().exists('migration/0001_initial/operation/0/raw-address') is False
    assert registrar.call().exists('migration/0001_initial/operation/0/raw-txn') is False
    assert registrar.call().exists('migration/0001_initial/operation/0/no-key') is False
    assert registrar.call().exists('this-is-a-key') is False

    migration = TestMigration(chain)
    migration.execute()

    assert registrar.call().exists('migration/0001_initial') is True
    assert registrar.call().exists('migration/0001_initial/operation/0') is True
    assert registrar.call().exists('migration/0001_initial/operation/0/raw-address') is True
    assert registrar.call().exists('migration/0001_initial/operation/0/raw-txn') is True
    assert registrar.call().exists('migration/0001_initial/operation/0/no-key') is True
    assert registrar.call().exists('this-is-a-key') is True


    assert registrar.call().getBool('migration/0001_initial') is True
    assert registrar.call().getBool('migration/0001_initial/operation/0') is True
    assert registrar.call().getAddress('migration/0001_initial/operation/0/raw-address') == web3.eth.coinbase
    assert encode_hex(registrar.call().get('migration/0001_initial/operation/0/raw-txn')) == '0xebb0f76aa6a6bb8d178ac2354de83d73a728d704bf47d135c188ca7b6d25f2e4'
    assert registrar.call().getAddress('migration/0001_initial/operation/0/no-key') == web3.eth.coinbase
    assert registrar.call().getString('this-is-a-key') == 'this-is-a-string'
Ejemplo n.º 22
0
def inputPostFormatter(post):
    """
    Formats the input of a whisper post and converts all values to HEX
    """

    post["ttl"] = from_decimal(post["ttl"])
    post["workToProve"] = from_decimal(post.get("workToProve", 0))
    post["priority"] = from_decimal(post["priority"])

    if not is_array(post.get("topics")):
        post["topics"] = [post["topics"]] if post.get("topics") else []

    post["topics"] = [
        topic if is_0x_prefixed(topic) else encode_hex(topic)
        for topic in post["topics"]
    ]

    return post
Ejemplo n.º 23
0
def test_transaction_serialization():
    transaction = {
        'nonce': hex(0),
        'to': '0xd3cda913deb6f67967b99d67acdfa1712c293601',
        'value': hex(12345),
        'gas': hex(1200300),
        'gasPrice': hex(54321),
        'data': '0x1234567890abcdef',
    }

    serialized_txn = serialize_transaction(transaction)
    unserialized_txn = rlp.decode(serialized_txn, UnsignedTransaction)

    assert to_address(unserialized_txn.to) == transaction['to']
    assert unserialized_txn.startgas == int(transaction['gas'], 16)
    assert unserialized_txn.gasprice == int(transaction['gasPrice'], 16)
    assert unserialized_txn.nonce == int(transaction['nonce'], 16)
    assert unserialized_txn.value == int(transaction['value'], 16)
    assert encode_hex(unserialized_txn.data) == transaction['data']
def test_transaction_serialization():
    transaction = {
        'nonce': hex(0),
        'to': '0xd3cda913deb6f67967b99d67acdfa1712c293601',
        'value': hex(12345),
        'gas': hex(1200300),
        'gasPrice': hex(54321),
        'data': '0x1234567890abcdef',
    }

    serialized_txn = serialize_transaction(transaction)
    unserialized_txn = rlp.decode(serialized_txn, UnsignedTransaction)

    assert to_address(unserialized_txn.to) == transaction['to']
    assert unserialized_txn.startgas == int(transaction['gas'], 16)
    assert unserialized_txn.gasprice == int(transaction['gasPrice'], 16)
    assert unserialized_txn.nonce == int(transaction['nonce'], 16)
    assert unserialized_txn.value == int(transaction['value'], 16)
    assert encode_hex(unserialized_txn.data) == transaction['data']
    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
Ejemplo n.º 26
0
 def sha3(self, value, encoding="hex"):
     if encoding == 'hex':
         hex_string = value
     else:
         hex_string = encode_hex(value)
     return self._requestManager.request_blocking('web3_sha3', [hex_string])
Ejemplo n.º 27
0
 def sha3(self, value, encoding="hex"):
     if encoding == 'hex':
         hex_string = value
     else:
         hex_string = encode_hex(value)
     return self._requestManager.request_blocking('web3_sha3', [hex_string])
Ejemplo n.º 28
0
def test_hex_encode_decode_round_trip(value):
    intermediate_value = encode_hex(value)
    result_value = decode_hex(intermediate_value)
    assert result_value == value, "Expected: {0!r}, Result: {1!r}, Intermediate: {2!r}".format(
        value, result_value, intermediate_value)
Ejemplo n.º 29
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
Ejemplo n.º 30
0
def test_encode_hex(value, expected):
    assert encode_hex(value) == expected
def test_contract_constructor_encoding_encoding(WithConstructorArgumentsContract):
    deploy_data = WithConstructorArgumentsContract.encodeConstructorData([1234, 'abcd'])
    encoded_args = b'0x00000000000000000000000000000000000000000000000000000000000004d26162636400000000000000000000000000000000000000000000000000000000'
    expected_ending = encode_hex(encode_abi(['uint256', 'bytes32'], [1234, b'abcd']))
    assert expected_ending == encoded_args
    assert deploy_data.endswith(remove_0x_prefix(expected_ending))
Ejemplo n.º 32
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
Ejemplo n.º 33
0
def test_encode_hex(value, expected):
    assert encode_hex(value) == expected
Ejemplo n.º 34
0
def test_hex_encode_decode_round_trip(value):
    intermediate_value = encode_hex(value)
    result_value = decode_hex(intermediate_value)
    assert result_value == value, "Expected: {0!r}, Result: {1!r}, Intermediate: {2!r}".format(value, result_value, intermediate_value)