2019-08-07 06:31:30 +00:00
|
|
|
"""Cryptography primitives for Hypercore."""
|
|
|
|
|
2019-10-05 09:34:57 +00:00
|
|
|
from typing import Optional, Tuple
|
|
|
|
|
|
|
|
import nacl.exceptions
|
2019-08-07 06:31:30 +00:00
|
|
|
from nacl.bindings import (
|
2019-10-05 09:34:57 +00:00
|
|
|
crypto_sign,
|
2019-08-07 06:31:30 +00:00
|
|
|
crypto_sign_keypair,
|
|
|
|
crypto_sign_seed_keypair,
|
|
|
|
)
|
2019-10-05 09:34:57 +00:00
|
|
|
from nacl.hash import blake2b
|
|
|
|
from nacl.signing import VerifyKey
|
2019-08-07 06:31:30 +00:00
|
|
|
|
|
|
|
# https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
|
|
|
|
LEAF_TYPE = bytearray([0])
|
|
|
|
PARENT_TYPE = bytearray([1])
|
|
|
|
ROOT_TYPE = bytearray([2])
|
|
|
|
HYPERCORE = bytearray('hypercore', encoding='utf-8')
|
|
|
|
|
|
|
|
|
2019-10-05 09:34:57 +00:00
|
|
|
def key_pair(seed: Optional[bytes] = None) -> Tuple[bytes, bytes]:
|
|
|
|
"""A new public key and secret key pair.
|
2019-08-07 06:31:30 +00:00
|
|
|
|
2019-10-05 09:34:57 +00:00
|
|
|
The seed must be at least 32 characters in length.
|
|
|
|
"""
|
2019-08-07 06:31:30 +00:00
|
|
|
if seed:
|
2019-10-05 09:34:57 +00:00
|
|
|
return crypto_sign_seed_keypair(seed)
|
|
|
|
return crypto_sign_keypair()
|
2019-08-07 06:31:30 +00:00
|
|
|
|
|
|
|
|
2019-10-05 09:34:57 +00:00
|
|
|
def sign(message: bytes, secret_key: bytes) -> bytes:
|
|
|
|
"""Signed message from a secret key."""
|
|
|
|
return crypto_sign(message, secret_key)
|
2019-08-07 06:31:30 +00:00
|
|
|
|
|
|
|
|
2019-10-05 09:34:57 +00:00
|
|
|
def verify(signed_message: bytes, signature: bytes, public_key: bytes) -> bool:
|
|
|
|
"""Verify a signed message."""
|
|
|
|
try:
|
|
|
|
VerifyKey(public_key).verify(signed_message, signature=signature)
|
|
|
|
except (nacl.exceptions.TypeError, nacl.exceptions.BadSignatureError):
|
|
|
|
return False
|
|
|
|
return True
|
2019-08-07 06:31:30 +00:00
|
|
|
|
|
|
|
|
2019-10-05 09:34:57 +00:00
|
|
|
def data(data: bytes):
|
2019-08-07 06:31:30 +00:00
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
def leaf():
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
def parent():
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
def tree():
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
def random_bytes():
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
def discovery_key():
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
def encode_unsigned_int64():
|
|
|
|
pass
|