Skip to content

Commit

Permalink
UPDATE. explicitly requiring from_entropy() method to have a string d…
Browse files Browse the repository at this point in the history
…efault value for passphrase parameter

REFACTOR. pulling out duplicate seed creating logic into a class method

ADD. adding test_is_entropy() testcase against meumonic package generated entropy value
  • Loading branch information
daehan-koreapool committed Oct 17, 2022
1 parent 692682e commit d6838b3
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 15 deletions.
28 changes: 13 additions & 15 deletions pycardano/crypto/bip32.py
Expand Up @@ -155,18 +155,8 @@ def from_mnemonic(cls, mnemonic: str, passphrase: str = "") -> HDWallet:
raise ValueError("Invalid mnemonic words.")

mnemonic = unicodedata.normalize("NFKD", mnemonic)
passphrase = str(passphrase) if passphrase else ""
entropy = Mnemonic(language="english").to_entropy(words=mnemonic)

seed = bytearray(
hashlib.pbkdf2_hmac(
"sha512",
password=passphrase.encode(),
salt=entropy,
iterations=4096,
dklen=96,
)
)
seed = cls._generate_seed(passphrase, entropy)

return cls.from_seed(
seed=hexlify(seed).decode(),
Expand All @@ -176,7 +166,7 @@ def from_mnemonic(cls, mnemonic: str, passphrase: str = "") -> HDWallet:
)

@classmethod
def from_entropy(cls, entropy: str, passphrase: str = None) -> HDWallet:
def from_entropy(cls, entropy: str, passphrase: str = "") -> HDWallet:
"""
Create master key and HDWallet from Mnemonic words.
Expand All @@ -191,12 +181,20 @@ def from_entropy(cls, entropy: str, passphrase: str = None) -> HDWallet:
if not cls.is_entropy(entropy):
raise ValueError("Invalid entropy")

seed = bytearray(
seed = cls._generate_seed(passphrase, bytearray.fromhex(entropy))
return cls.from_seed(seed=hexlify(seed).decode(), entropy=entropy)

@classmethod
def _generate_seed(cls, passphrase: str, entropy: bytearray) -> bytearray:
return bytearray(
hashlib.pbkdf2_hmac(
"sha512", password=passphrase, salt=entropy, iterations=4096, dklen=96
"sha512",
password=passphrase.encode(),
salt=entropy,
iterations=4096,
dklen=96,
)
)
return cls.from_seed(seed=hexlify(seed).decode(), entropy=entropy)

@classmethod
def _tweak_bits(cls, seed: bytearray) -> bytes:
Expand Down
8 changes: 8 additions & 0 deletions test/pycardano/backend/test_bip32.py
@@ -1,3 +1,5 @@
import pytest

from pycardano.address import Address
from pycardano.crypto.bip32 import HDWallet
from pycardano.key import PaymentVerificationKey
Expand Down Expand Up @@ -108,3 +110,9 @@ def test_payment_address_24_base():
Address(spend_vk.hash(), stake_vk.hash(), network=Network.MAINNET).encode()
== "addr1qyy6nhfyks7wdu3dudslys37v252w2nwhv0fw2nfawemmn8k8ttq8f3gag0h89aepvx3xf69g0l9pf80tqv7cve0l33sdn8p3d"
)


def test_is_entropy():
entropy = "df9ed25ed146bf43336a5d7cf7395994"
is_entropy = HDWallet.is_entropy(entropy)
assert is_entropy

0 comments on commit d6838b3

Please sign in to comment.