Skip to content

Commit

Permalink
Making the keypair hashable, and moving setters out of property funct…
Browse files Browse the repository at this point in the history
…ions (#158)

* Making the keypair hashable, and moving setters out of property functions

* Fixing linter error

* Fixing docstring error
  • Loading branch information
ulmentflam authored Dec 24, 2021
1 parent 2d8d776 commit e9678f9
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 3 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,6 @@ dist

# solana validator logs
test-ledger/

#IDE Files
.idea/
16 changes: 13 additions & 3 deletions src/solana/keypair.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,20 @@ class Keypair:
"""

def __init__(self, keypair: Optional[nacl.public.PrivateKey] = None) -> None:
"""Create a new keypair instance. Generate random keypair if no keypair is provided."""
"""Create a new keypair instance.
Generate random keypair if no keypair is provided. Initialize class variables.
"""
if keypair is None:
# the PrivateKey object comes with a public key too
self._keypair = nacl.public.PrivateKey.generate()
else:
self._keypair = keypair

verify_key = signing.SigningKey(bytes(self._keypair)).verify_key

self._public_key = solana.publickey.PublicKey(verify_key)

@classmethod
def generate(cls) -> Keypair:
"""Generate a new random keypair.
Expand Down Expand Up @@ -88,8 +95,7 @@ def seed(self) -> bytes:
@property
def public_key(self) -> solana.publickey.PublicKey:
"""The public key for this keypair."""
verify_key = signing.SigningKey(self.seed).verify_key
return solana.publickey.PublicKey(verify_key)
return self._public_key

@property
def secret_key(self) -> bytes:
Expand All @@ -105,3 +111,7 @@ def __eq__(self, other) -> bool:
def __ne__(self, other) -> bool:
"""Implemented by negating __eq__."""
return not (self == other) # pylint: disable=superfluous-parens

def __hash__(self):
"""Returns a unique hash for set operations."""
return hash(self._keypair)
11 changes: 11 additions & 0 deletions tests/unit/test_keypair.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,14 @@ def test_create_from_seed() -> None:
keypair = Keypair.from_seed(seed)
assert str(keypair.public_key) == "2KW2XRd9kwqet15Aha2oK3tYvd3nWbTFH1MBiRAv1BE1"
assert keypair.seed == seed


def test_set_operations() -> None:
"""Tests that a keypair is now hashable with the appropriate set operations."""
keypair_primary = Keypair.generate()
keypair_secondary = Keypair.generate()
keypair_duplicate = keypair_secondary
keypair_set = {keypair_primary, keypair_secondary, keypair_duplicate}
assert keypair_primary.__hash__() != keypair_secondary.__hash__()
assert keypair_secondary.__hash__() == keypair_duplicate.__hash__()
assert len(keypair_set) == 2

0 comments on commit e9678f9

Please sign in to comment.