Skip to content

Commit

Permalink
feat: public_key method added to KeyfileAccount class [APE-1466] (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
Aviksaikat authored Oct 19, 2023
1 parent 4c5b853 commit 9e50016
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/ape_accounts/accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import click
from eth_account import Account as EthAccount
from eth_keys import keys # type: ignore
from eth_utils import to_bytes
from ethpm_types import HexBytes

Expand Down Expand Up @@ -92,6 +93,24 @@ def __key(self) -> HexBytes:

return key

@property
def public_key(self) -> HexBytes:
if "public_key" in self.keyfile:
return HexBytes(bytes.fromhex(self.keyfile["public_key"]))
key = self.__key

# Derive the public key from the private key
pk = keys.PrivateKey(key)
# convert from eth_keys.datatypes.PublicKey to str to make it HexBytes
publicKey = str(pk.public_key)

key_file_data = self.keyfile
key_file_data["public_key"] = publicKey[2:]

self.keyfile_path.write_text(json.dumps(key_file_data))

return HexBytes(bytes.fromhex(publicKey[2:]))

def unlock(self, passphrase: Optional[str] = None):
if not passphrase:
# Check if environment variable is available
Expand Down
18 changes: 18 additions & 0 deletions tests/functional/test_accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import pytest
from eip712.messages import EIP712Message
from eth_account.messages import encode_defunct
from hexbytes import HexBytes

import ape
from ape.api import ImpersonatedAccount
Expand Down Expand Up @@ -565,3 +566,20 @@ def test_prepare_transaction_and_call_using_max_gas(tx_type, ethereum, sender, e

actual = sender.call(tx)
assert not actual.failed


def test_public_key(runner, keyfile_account):
with runner.isolation(input="a\ny\n"):
assert isinstance(keyfile_account.public_key, HexBytes)


def test_load_public_key_from_keyfile(runner, keyfile_account):
with runner.isolation(input="a\ny\n"):
assert isinstance(keyfile_account.public_key, HexBytes)

assert (
keyfile_account.public_key.hex()
== "0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8" # noqa: 501
)
# no need for password when loading from the keyfile
assert keyfile_account.public_key

0 comments on commit 9e50016

Please sign in to comment.