Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PrivateKey generation from entropy #59

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions btcpy/structs/crypto.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
# propagated, or distributed except according to the terms contained in the
# LICENSE.md file.

import secrets
from binascii import unhexlify
from ..lib.base58 import b58decode_check, b58encode_check
from hashlib import sha256
Expand Down Expand Up @@ -61,6 +62,17 @@ def from_wif(wif, strict=None):
def unhexlify(hexa):
return PrivateKey(bytearray(unhexlify(hexa)))

@staticmethod
def generate(nbytes=32):
"""
Generate a random text string, in hexadecimal with nbytes random bytes. Its length is thus 2 * nbytes.
Args:
nbytes(int): number of random bytes in the random hexadecimal string generated.
Returns:
A random hexadecimal string of length 2 * nbytes.
"""
return secrets.token_hex(nbytes)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are supposed to return a PrivateKey object here, this will just return a random hexadecimal string.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @SimoneBronzini , thanks for the reminder. I've made a correction there such that it returns a PrivateKey object, and I fix the random hexadecimal string to be of 32 bytes (for simplicity). Please let me know if that works or not? Thanks!


def __init__(self, priv, public_compressed=True):
self.key = priv
self.public_compressed = public_compressed
Expand Down
4 changes: 4 additions & 0 deletions tests/unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,10 @@ def test_to_wif(self):
priv.public_compressed = False
self.assertEqual(priv.to_wif(w['mainnet']), w['wif'])

def test_private_key_generation(self):
key = PrivateKey.generate(32)
self.assertEqual(len(key), 64)


class TestPubkey(unittest.TestCase):

Expand Down