bulk renaming of Keyring -> Keystore

pull/2701/head
Kieran R. Prasch 2021-05-18 13:21:48 -07:00
parent e0c6f84263
commit 6aef077172
36 changed files with 127 additions and 117 deletions

View File

@ -27,7 +27,7 @@ import maya
from bytestring_splitter import BytestringSplitter
from eth_typing import ChecksumAddress
from nucypher.crypto.api import keccak_digest
from ..crypto.utils import keccak_digest
from nucypher.utilities.logging import Logger
from .nicknames import Nickname

View File

@ -54,7 +54,7 @@ from nucypher.blockchain.eth.decorators import contract_api
from nucypher.blockchain.eth.events import ContractEvents
from nucypher.blockchain.eth.interfaces import BlockchainInterfaceFactory
from nucypher.blockchain.eth.registry import BaseContractRegistry
from nucypher.crypto.api import sha256_digest
from nucypher.crypto.utils import sha256_digest
from nucypher.crypto.powers import TransactingPower
from nucypher.types import (
Agent,

View File

@ -17,6 +17,9 @@ along with nucypher. If not, see <https://www.gnu.org/licenses/>.
import contextlib
from contextlib import suppress
from typing import ClassVar, Dict, List, Optional, Union
from constant_sorrow import default_constant_splitter
from constant_sorrow.constants import (
DO_NOT_SIGN,
@ -29,19 +32,15 @@ from constant_sorrow.constants import (
SIGNATURE_TO_FOLLOW,
STRANGER
)
from contextlib import suppress
from cryptography.exceptions import InvalidSignature
from eth_keys import KeyAPI as EthKeyAPI
from eth_utils import to_canonical_address, to_checksum_address
from typing import ClassVar, Dict, List, Optional, Union
from nucypher.acumen.nicknames import Nickname
from nucypher.blockchain.eth.interfaces import BlockchainInterfaceFactory
from nucypher.blockchain.eth.registry import BaseContractRegistry, InMemoryContractRegistry
from nucypher.blockchain.eth.signers.base import Signer
from nucypher.characters.control.controllers import CLIController, JSONRPCController
from nucypher.config.keyring import NucypherKeyring
from nucypher.crypto.api import encrypt_and_sign
from nucypher.crypto.keystore import Keystore
from nucypher.crypto.kits import UmbralMessageKit
from nucypher.crypto.powers import (
CryptoPower,
@ -57,6 +56,7 @@ from nucypher.crypto.signing import (
)
from nucypher.crypto.splitters import signature_splitter
from nucypher.crypto.umbral_adapter import PublicKey, Signature
from nucypher.crypto.utils import encrypt_and_sign
from nucypher.network.middleware import RestMiddleware
from nucypher.network.nodes import Learner
@ -76,7 +76,7 @@ class Character(Learner):
federated_only: bool = False,
checksum_address: str = None,
network_middleware: RestMiddleware = None,
keyring: NucypherKeyring = None,
keyring: Keystore = None,
crypto_power: CryptoPower = None,
crypto_power_ups: List[CryptoPowerUp] = None,
provider_uri: str = None,

View File

@ -16,14 +16,20 @@ along with nucypher. If not, see <https://www.gnu.org/licenses/>.
"""
import json
from collections import OrderedDict, defaultdict
import contextlib
import maya
import json
import random
import time
from base64 import b64decode, b64encode
from collections import OrderedDict, defaultdict
from datetime import datetime
from functools import partial
from json.decoder import JSONDecodeError
from queue import Queue
from random import shuffle
from typing import Dict, Iterable, List, NamedTuple, Tuple, Union, Optional, Sequence, Set, Any
import maya
import time
from bytestring_splitter import (
BytestringKwargifier,
BytestringSplitter,
@ -43,19 +49,13 @@ from constant_sorrow.constants import (
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.serialization import Encoding
from cryptography.x509 import Certificate, NameOID, load_pem_x509_certificate
from datetime import datetime
from eth_typing.evm import ChecksumAddress
from eth_utils import to_checksum_address
from flask import Response, request
from functools import partial
from json.decoder import JSONDecodeError
from queue import Queue
from random import shuffle
from twisted.internet import reactor, stdio, threads
from twisted.internet.defer import Deferred
from twisted.internet.task import LoopingCall
from twisted.logger import Logger
from typing import Dict, Iterable, List, NamedTuple, Tuple, Union, Optional, Sequence, Set, Any
import nucypher
from nucypher.acumen.nicknames import Nickname
@ -74,7 +74,6 @@ from nucypher.characters.control.interfaces import AliceInterface, BobInterface,
from nucypher.cli.processes import UrsulaCommandProtocol
from nucypher.config.constants import END_OF_POLICIES_PROBATIONARY_PERIOD
from nucypher.config.storages import ForgetfulNodeStorage, NodeStorage
from nucypher.crypto.api import encrypt_and_sign, keccak_digest
from nucypher.crypto.constants import HRAC_LENGTH
from nucypher.crypto.keypairs import HostingKeypair
from nucypher.crypto.kits import UmbralMessageKit
@ -88,6 +87,7 @@ from nucypher.crypto.powers import (
from nucypher.crypto.signing import InvalidSignature
from nucypher.crypto.splitters import key_splitter, signature_splitter
from nucypher.crypto.umbral_adapter import Capsule, PublicKey, VerifiedKeyFrag, Signature, VerificationError, reencrypt
from nucypher.crypto.utils import keccak_digest, encrypt_and_sign
from nucypher.datastore.datastore import DatastoreTransactionError, RecordNotFound
from nucypher.datastore.queries import find_expired_policies, find_expired_treasure_maps
from nucypher.network.exceptions import NodeSeemsToBeDown

View File

@ -25,7 +25,7 @@ from eth_tester.exceptions import ValidationError
from nucypher.blockchain.eth.signers.software import Web3Signer
from nucypher.characters.lawful import Alice, Ursula
from nucypher.config.constants import TEMPORARY_DOMAIN
from nucypher.crypto.api import encrypt_and_sign
from nucypher.crypto.utils import encrypt_and_sign
from nucypher.crypto.powers import CryptoPower, SigningPower, DecryptingPower, TransactingPower
from nucypher.exceptions import DevelopmentInstallationRequired
from nucypher.policy.collections import SignedTreasureMap

View File

@ -33,7 +33,7 @@ from nucypher.cli.literature import (
)
from nucypher.config.base import CharacterConfiguration
from nucypher.config.constants import NUCYPHER_ENVVAR_KEYRING_PASSWORD
from nucypher.config.keyring import NucypherKeyring
from nucypher.crypto.keystore import Keystore
def get_password_from_prompt(prompt: str = GENERIC_PASSWORD_PROMPT, envvar: str = None, confirm: bool = False) -> str:
@ -82,9 +82,9 @@ def get_nucypher_password(emitter, confirm: bool = False, envvar=NUCYPHER_ENVVAR
"""Interactively collect a nucypher password"""
prompt = COLLECT_NUCYPHER_PASSWORD
if confirm:
from nucypher.config.keyring import NucypherKeyring
from nucypher.crypto.keystore import Keystore
emitter.message(PASSWORD_COLLECTION_NOTICE)
prompt += f" ({NucypherKeyring.MINIMUM_PASSWORD_LENGTH} character minimum)"
prompt += f" ({Keystore.MINIMUM_PASSWORD_LENGTH} character minimum)"
keyring_password = get_password_from_prompt(prompt=prompt, confirm=confirm, envvar=envvar)
return keyring_password
@ -102,6 +102,6 @@ def unlock_nucypher_keyring(emitter: StdoutEmitter, password: str, character_con
character_configuration.attach_keyring()
character_configuration.keyring.unlock(password=password) # Takes ~3 seconds, ~1GB Ram
except CryptoError:
raise NucypherKeyring.AuthenticationFailed
raise Keystore.AuthenticationFailed
else:
return True

View File

@ -65,7 +65,7 @@ from nucypher.config.characters import AliceConfiguration
from nucypher.config.constants import (
TEMPORARY_DOMAIN,
)
from nucypher.config.keyring import NucypherKeyring
from nucypher.crypto.keystore import Keystore
from nucypher.network.middleware import RestMiddleware
from nucypher.policy.identity import Card
@ -272,7 +272,7 @@ class AliceCharacterOptions:
lonely=self.config_options.lonely,
json_ipc=json_ipc)
return ALICE
except NucypherKeyring.AuthenticationFailed as e:
except Keystore.AuthenticationFailed as e:
emitter.echo(str(e), color='red', bold=True)
click.get_current_context().exit(1)

View File

@ -63,7 +63,7 @@ from nucypher.config.constants import (
NUCYPHER_ENVVAR_WORKER_ETH_PASSWORD,
TEMPORARY_DOMAIN
)
from nucypher.config.keyring import NucypherKeyring
from nucypher.crypto.keystore import Keystore
class UrsulaConfigOptions:
@ -156,7 +156,7 @@ class UrsulaConfigOptions:
)
except FileNotFoundError:
return handle_missing_configuration_file(character_config_class=UrsulaConfiguration, config_file=config_file)
except NucypherKeyring.AuthenticationFailed as e:
except Keystore.AuthenticationFailed as e:
emitter.echo(str(e), color='red', bold=True)
# TODO: Exit codes (not only for this, but for other exceptions)
return click.get_current_context().exit(1)
@ -271,7 +271,7 @@ class UrsulaCharacterOptions:
json_ipc=json_ipc)
return ursula_config, URSULA
except NucypherKeyring.AuthenticationFailed as e:
except Keystore.AuthenticationFailed as e:
emitter.echo(str(e), color='red', bold=True)
# TODO: Exit codes (not only for this, but for other exceptions)
return click.get_current_context().exit(1)

View File

@ -45,12 +45,12 @@ from nucypher.blockchain.eth.registry import (
from nucypher.blockchain.eth.signers import Signer
from nucypher.characters.lawful import Ursula
from nucypher.config import constants
from nucypher.config.keyring import NucypherKeyring
from nucypher.config.storages import (
ForgetfulNodeStorage,
LocalFileBasedNodeStorage,
NodeStorage
)
from nucypher.crypto.keystore import Keystore
from nucypher.crypto.powers import CryptoPower, CryptoPowerUp
from nucypher.crypto.umbral_adapter import Signature
from nucypher.network.middleware import RestMiddleware
@ -355,7 +355,7 @@ class CharacterConfiguration(BaseConfiguration):
crypto_power: CryptoPower = None,
# Keyring
keyring: NucypherKeyring = None,
keyring: Keystore = None,
keyring_root: str = None,
# Learner
@ -745,7 +745,7 @@ class CharacterConfiguration(BaseConfiguration):
if self.keyring.checksum_address != account:
raise self.ConfigurationError("There is already a keyring attached to this configuration.")
return
self.keyring = NucypherKeyring(keyring_root=self.keyring_root, account=account, *args, **kwargs)
self.keyring = Keystore(keyring_root=self.keyring_root, account=account, *args, **kwargs)
def derive_node_power_ups(self) -> List[CryptoPowerUp]:
power_ups = list()
@ -780,7 +780,7 @@ class CharacterConfiguration(BaseConfiguration):
self.log.debug(message)
return self.config_root
def write_keyring(self, password: str, checksum_address: str = None, **generation_kwargs) -> NucypherKeyring:
def write_keyring(self, password: str, checksum_address: str = None, **generation_kwargs) -> Keystore:
# Configure checksum address
checksum_address = checksum_address or self.checksum_address
@ -790,10 +790,10 @@ class CharacterConfiguration(BaseConfiguration):
raise self.ConfigurationError(f'No checksum address provided for decentralized configuration.')
# Generate new keys
self.keyring = NucypherKeyring.generate(password=password,
keyring_root=self.keyring_root,
checksum_address=checksum_address,
**generation_kwargs)
self.keyring = Keystore.generate(password=password,
keyring_root=self.keyring_root,
checksum_address=checksum_address,
**generation_kwargs)
# In the case of a federated keyring generation,
# the generated federated address must be set here.

View File

@ -33,7 +33,7 @@ from nucypher.config.constants import (
NUCYPHER_ENVVAR_ALICE_ETH_PASSWORD,
NUCYPHER_ENVVAR_BOB_ETH_PASSWORD
)
from nucypher.config.keyring import NucypherKeyring
from nucypher.crypto.keystore import Keystore
from nucypher.utilities.networking import LOOPBACK_ADDRESS
@ -145,7 +145,7 @@ class UrsulaConfiguration(CharacterConfiguration):
account = checksum_address or self.worker_address
return super().attach_keyring(checksum_address=account)
def write_keyring(self, password: str, **generation_kwargs) -> NucypherKeyring:
def write_keyring(self, password: str, **generation_kwargs) -> Keystore:
keyring = super().write_keyring(password=password,
encrypting=True,
rest=True,
@ -217,7 +217,7 @@ class AliceConfiguration(CharacterConfiguration):
payload['payment_periods'] = self.payment_periods
return {**super().static_payload(), **payload}
def write_keyring(self, password: str, **generation_kwargs) -> NucypherKeyring:
def write_keyring(self, password: str, **generation_kwargs) -> Keystore:
return super().write_keyring(password=password,
encrypting=True,
rest=False,
@ -248,7 +248,7 @@ class BobConfiguration(CharacterConfiguration):
self.store_policies = store_policies
self.store_cards = store_cards
def write_keyring(self, password: str, **generation_kwargs) -> NucypherKeyring:
def write_keyring(self, password: str, **generation_kwargs) -> Keystore:
return super().write_keyring(password=password,
encrypting=True,
rest=False,
@ -302,7 +302,7 @@ class FelixConfiguration(CharacterConfiguration):
)
return {**super().static_payload(), **payload}
def write_keyring(self, password: str, **generation_kwargs) -> NucypherKeyring:
def write_keyring(self, password: str, **generation_kwargs) -> Keystore:
return super().write_keyring(password=password,
encrypting=True, # TODO: #668
rest=True,

View File

@ -42,8 +42,8 @@ NUCYPHER_TEST_DIR = BASE_DIR / 'tests'
# User Application Filepaths
APP_DIR = AppDirs(nucypher.__title__, nucypher.__author__)
DEFAULT_CONFIG_ROOT = os.getenv('NUCYPHER_CONFIG_ROOT', default=APP_DIR.user_data_dir)
USER_LOG_DIR = os.getenv('NUCYPHER_USER_LOG_DIR', default=APP_DIR.user_log_dir)
DEFAULT_CONFIG_ROOT = Path(os.getenv('NUCYPHER_CONFIG_ROOT', default=APP_DIR.user_data_dir))
USER_LOG_DIR = Path(os.getenv('NUCYPHER_USER_LOG_DIR', default=APP_DIR.user_log_dir))
DEFAULT_LOG_FILENAME = "nucypher.log"
DEFAULT_JSON_LOG_FILENAME = "nucypher.json"

View File

@ -35,7 +35,8 @@ from nucypher.acumen.nicknames import Nickname
from nucypher.blockchain.eth.decorators import validate_checksum_address
from nucypher.blockchain.eth.registry import BaseContractRegistry
from nucypher.config.constants import DEFAULT_CONFIG_ROOT
from nucypher.crypto.api import read_certificate_pseudonym, InvalidNodeCertificate
from nucypher.crypto.utils import InvalidNodeCertificate
from nucypher.crypto.tls import read_certificate_pseudonym
from nucypher.utilities.logging import Logger

View File

@ -14,7 +14,7 @@ GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with nucypher. If not, see <https://www.gnu.org/licenses/>.
"""
import base64
from typing import Union
import sha3
@ -26,11 +26,16 @@ from hendrix.deploy.tls import HendrixDeployTLS
from hendrix.facilities.services import ExistingKeyTLSContextFactory
from nucypher.config.constants import MAX_UPLOAD_CONTENT_LENGTH
from nucypher.crypto import api as API
from nucypher.crypto.api import generate_teacher_certificate, _TLS_CURVE
from nucypher.crypto.kits import MessageKit
from nucypher.crypto.signing import SignatureStamp, StrangerStamp
from nucypher.crypto.umbral_adapter import SecretKey, PublicKey, Signature, Signer, decrypt_original, decrypt_reencrypted
from nucypher.crypto.umbral_adapter import (
SecretKey,
PublicKey,
Signature,
Signer,
decrypt_original,
decrypt_reencrypted
)
from nucypher.network.resources import get_static_resources
@ -147,16 +152,16 @@ class HostingKeypair(Keypair):
if private_key:
if not certificate_filepath:
raise ValueError('public certificate required to load a hosting keypair.')
from nucypher.config.keyring import _read_tls_public_certificate
certificate = _read_tls_public_certificate(filepath=certificate_filepath)
from nucypher.config.keyring import _read_tls_certificate
certificate = _read_tls_certificate(filepath=certificate_filepath)
super().__init__(private_key=private_key)
elif certificate:
super().__init__(public_key=certificate.public_key())
elif certificate_filepath:
from nucypher.config.keyring import _read_tls_public_certificate
certificate = _read_tls_public_certificate(filepath=certificate_filepath)
from nucypher.config.keyring import _read_tls_certificate
certificate = _read_tls_certificate(filepath=certificate_filepath)
super().__init__(public_key=certificate.public_key())
elif generate_certificate:

View File

@ -15,11 +15,7 @@ You should have received a copy of the GNU Affero General Public License
along with nucypher. If not, see <https://www.gnu.org/licenses/>.
"""
from bytestring_splitter import BytestringSplitter
from nucypher.crypto.api import keccak_digest
from nucypher.crypto.umbral_adapter import Signature, Signer
from nucypher.crypto.umbral_adapter import Signer
class SignatureStamp(object):
@ -69,6 +65,7 @@ class SignatureStamp(object):
:return: Hexdigest fingerprint of key (keccak-256) in bytes
"""
from nucypher.crypto.utils import keccak_digest
return keccak_digest(bytes(self)).hex().encode()

View File

@ -15,11 +15,10 @@ You should have received a copy of the GNU Affero General Public License
along with nucypher. If not, see <https://www.gnu.org/licenses/>.
"""
from coincurve import PublicKey
from eth_keys import KeyAPI as EthKeyAPI
from typing import Any, Union
from nucypher.crypto.api import keccak_digest
from eth_keys import KeyAPI as EthKeyAPI
from nucypher.crypto.signing import SignatureStamp
from nucypher.crypto.umbral_adapter import PublicKey
@ -47,3 +46,4 @@ def canonical_address_from_umbral_key(public_key: Union[PublicKey, SignatureStam
eth_pubkey = EthKeyAPI.PublicKey.from_compressed_bytes(pubkey_compressed_bytes)
canonical_address = eth_pubkey.to_canonical_address()
return canonical_address

View File

@ -54,7 +54,7 @@ from nucypher.blockchain.eth.networks import NetworksInventory
from nucypher.blockchain.eth.registry import BaseContractRegistry
from nucypher.config.constants import SeednodeMetadata
from nucypher.config.storages import ForgetfulNodeStorage
from nucypher.crypto.api import InvalidNodeCertificate, recover_address_eip_191, verify_eip_191
from nucypher.crypto.utils import InvalidNodeCertificate, recover_address_eip_191, verify_eip_191
from nucypher.crypto.kits import UmbralMessageKit
from nucypher.crypto.powers import DecryptingPower, NoSigningPower, SigningPower
from nucypher.crypto.splitters import signature_splitter

View File

@ -16,35 +16,33 @@ along with nucypher. If not, see <https://www.gnu.org/licenses/>.
"""
import binascii
import os
import uuid
import weakref
from datetime import datetime, timedelta
from typing import Tuple
import binascii
from bytestring_splitter import BytestringSplitter
from constant_sorrow import constants
from constant_sorrow.constants import (
FLEET_STATES_MATCH,
NO_BLOCKCHAIN_CONNECTION,
NO_KNOWN_NODES,
RELAX
)
from datetime import datetime, timedelta
from flask import Flask, Response, jsonify, request
from mako import exceptions as mako_exceptions
from mako.template import Template
from maya import MayaDT
from typing import Tuple
from web3.exceptions import TimeExhausted
import nucypher
from nucypher.crypto.api import InvalidNodeCertificate
from nucypher.config.constants import MAX_UPLOAD_CONTENT_LENGTH
from nucypher.crypto.keypairs import HostingKeypair
from nucypher.crypto.kits import UmbralMessageKit
from nucypher.crypto.powers import KeyPairBasedPower, PowerUpError
from nucypher.crypto.signing import InvalidSignature
from nucypher.crypto.umbral_adapter import KeyFrag, VerificationError
from nucypher.crypto.utils import canonical_address_from_umbral_key
from nucypher.crypto.utils import canonical_address_from_umbral_key, InvalidNodeCertificate
from nucypher.datastore.datastore import Datastore, RecordNotFound, DatastoreTransactionError
from nucypher.datastore.models import PolicyArrangement, TreasureMap, Workorder
from nucypher.network import LEARNING_LOOP_VERSION

View File

@ -22,7 +22,7 @@ from twisted.internet import reactor
from twisted.internet.task import LoopingCall
from typing import Union
from nucypher.crypto.api import InvalidNodeCertificate
from nucypher.crypto.utils import InvalidNodeCertificate
from nucypher.network.exceptions import NodeSeemsToBeDown
from nucypher.network.middleware import RestMiddleware
from nucypher.network.nodes import NodeSprout

View File

@ -16,6 +16,7 @@ along with nucypher. If not, see <https://www.gnu.org/licenses/>.
"""
from collections import OrderedDict
from typing import Optional
import maya
from bytestring_splitter import BytestringKwargifier
@ -26,15 +27,10 @@ from bytestring_splitter import (
)
from constant_sorrow.constants import CFRAG_NOT_RETAINED, NO_DECRYPTION_PERFORMED
from constant_sorrow.constants import NOT_SIGNED
from cryptography.hazmat.backends.openssl import backend
from cryptography.hazmat.primitives import hashes
from eth_utils import to_canonical_address, to_checksum_address
from typing import Optional, Tuple
from nucypher.blockchain.eth.constants import ETH_ADDRESS_BYTE_LENGTH, ETH_HASH_BYTE_LENGTH
from nucypher.characters.lawful import Bob, Character
from nucypher.crypto.api import encrypt_and_sign, keccak_digest
from nucypher.crypto.api import verify_eip_191
from nucypher.crypto.constants import HRAC_LENGTH
from nucypher.crypto.kits import UmbralMessageKit
from nucypher.crypto.signing import InvalidSignature, Signature, SignatureStamp
@ -42,6 +38,9 @@ from nucypher.crypto.splitters import capsule_splitter, cfrag_splitter, key_spli
from nucypher.crypto.umbral_adapter import PublicKey, Capsule
from nucypher.crypto.utils import (
canonical_address_from_umbral_key,
keccak_digest,
verify_eip_191,
encrypt_and_sign
)
from nucypher.network.middleware import RestMiddleware

View File

@ -38,6 +38,7 @@ from twisted.python.threadpool import ThreadPool
from nucypher.blockchain.eth.actors import BlockchainPolicyAuthor
from nucypher.blockchain.eth.agents import PolicyManagerAgent, StakersReservoir, StakingEscrowAgent
from nucypher.characters.lawful import Alice, Ursula
<<<<<<< HEAD
from nucypher.crypto.api import keccak_digest, secure_random
from nucypher.crypto.constants import HRAC_LENGTH
from nucypher.crypto.kits import RevocationKit
@ -45,6 +46,12 @@ from nucypher.crypto.powers import DecryptingPower, SigningPower, TransactingPow
from nucypher.crypto.splitters import key_splitter
from nucypher.crypto.umbral_adapter import PublicKey, KeyFrag
from nucypher.crypto.utils import construct_policy_id
=======
from nucypher.crypto.constants import HRAC_LENGTH, PUBLIC_KEY_LENGTH
from nucypher.crypto.kits import RevocationKit
from nucypher.crypto.powers import DecryptingPower, SigningPower, TransactingPower
from nucypher.crypto.utils import construct_policy_id, secure_random, keccak_digest
>>>>>>> c20ee57ec... bulk renaming of Keyring -> Keystore
from nucypher.network.exceptions import NodeSeemsToBeDown
from nucypher.network.middleware import RestMiddleware
from nucypher.utilities.concurrency import WorkerPool, AllAtOnceFactory

View File

@ -22,7 +22,7 @@ from eth_utils import to_checksum_address
from nucypher.blockchain.eth.signers.software import Web3Signer
from nucypher.blockchain.eth.agents import NucypherTokenAgent
from nucypher.crypto.api import verify_eip_191
from nucypher.crypto.utils import verify_eip_191
from nucypher.crypto.powers import TransactingPower
from tests.conftest import LOCK_FUNCTION
from tests.constants import INSECURE_DEVELOPMENT_PASSWORD

View File

@ -19,7 +19,7 @@ import datetime
import maya
import pytest
from nucypher.crypto.api import keccak_digest
from nucypher.crypto.utils import keccak_digest
from nucypher.datastore.models import PolicyArrangement
from nucypher.datastore.models import TreasureMap as DatastoreTreasureMap
from nucypher.policy.collections import SignedTreasureMap as DecentralizedTreasureMap

View File

@ -20,7 +20,7 @@ from eth_utils import to_checksum_address
from nucypher.blockchain.eth.signers.software import Web3Signer
from nucypher.characters.lawful import Character
from nucypher.crypto.api import verify_eip_191
from nucypher.crypto.utils import verify_eip_191
from nucypher.crypto.powers import (TransactingPower)
from tests.constants import INSECURE_DEVELOPMENT_PASSWORD, MOCK_PROVIDER_URI

View File

@ -21,7 +21,7 @@ from eth_account._utils.signing import to_standard_signature_bytes
from nucypher.characters.lawful import Enrico
from nucypher.characters.unlawful import Vladimir
from nucypher.crypto.api import verify_eip_191
from nucypher.crypto.utils import verify_eip_191
from nucypher.crypto.powers import SigningPower
from nucypher.policy.policies import BlockchainPolicy
from tests.constants import INSECURE_DEVELOPMENT_PASSWORD

View File

@ -16,18 +16,22 @@
"""
import os
import shutil
from pathlib import Path
from unittest.mock import patch, PropertyMock
import pytest
import shutil
from pathlib import Path
from nucypher.blockchain.eth.actors import Worker
from nucypher.cli.main import nucypher_cli
from nucypher.config.characters import AliceConfiguration, FelixConfiguration, UrsulaConfiguration
from nucypher.config.constants import NUCYPHER_ENVVAR_KEYRING_PASSWORD, TEMPORARY_DOMAIN, \
NUCYPHER_ENVVAR_ALICE_ETH_PASSWORD, NUCYPHER_ENVVAR_BOB_ETH_PASSWORD
from nucypher.config.keyring import NucypherKeyring
from nucypher.config.constants import (
NUCYPHER_ENVVAR_KEYRING_PASSWORD,
TEMPORARY_DOMAIN,
NUCYPHER_ENVVAR_ALICE_ETH_PASSWORD,
NUCYPHER_ENVVAR_BOB_ETH_PASSWORD
)
from nucypher.crypto.keystore import Keystore
from nucypher.crypto.umbral_adapter import SecretKey
from nucypher.network.nodes import Teacher
from tests.constants import (
@ -279,7 +283,7 @@ def test_corrupted_configuration(click_runner,
# Fails because password is too short and the command uses incomplete args (needs either -F or blockchain details)
envvars = {NUCYPHER_ENVVAR_KEYRING_PASSWORD: ''}
with pytest.raises(NucypherKeyring.AuthenticationFailed):
with pytest.raises(Keystore.AuthenticationFailed):
result = click_runner.invoke(nucypher_cli, init_args, catch_exceptions=False, env=envvars)
assert result.exit_code != 0

View File

@ -45,7 +45,7 @@ Learner._DEBUG_MODE = False
@pytest.fixture(autouse=True, scope='session')
def __very_pretty_and_insecure_scrypt_do_not_use():
def __very_pretty_and_insecure_scrypt_do_not_use(request):
"""
# WARNING: DO NOT USE THIS CODE ANYWHERE #

View File

@ -76,7 +76,7 @@ NUMBER_OF_ALLOCATIONS_IN_TESTS = 50 # TODO: Move to constants
__valid_password_chars = string.ascii_uppercase + string.ascii_lowercase + string.digits
INSECURE_DEVELOPMENT_PASSWORD = ''.join(SystemRandom().choice(__valid_password_chars) for _ in range(16))
INSECURE_DEVELOPMENT_PASSWORD = ''.join(SystemRandom().choice(__valid_password_chars) for _ in range(32))
#
# Temporary Directories and Files

View File

@ -23,7 +23,7 @@ from web3.contract import Contract
from nucypher.blockchain.economics import BaseEconomics
from nucypher.blockchain.eth.constants import NULL_ADDRESS
from nucypher.crypto.api import sha256_digest
from nucypher.crypto.utils import sha256_digest
from nucypher.crypto.signing import SignatureStamp
from nucypher.crypto.umbral_adapter import SecretKey, Signer
from nucypher.utilities.ethereum import to_32byte_hex

View File

@ -20,7 +20,7 @@ import maya
import pytest
from nucypher.characters.lawful import Enrico
from nucypher.crypto.api import keccak_digest
from nucypher.crypto.utils import keccak_digest
from nucypher.datastore.models import PolicyArrangement
from nucypher.policy.collections import Revocation

View File

@ -34,7 +34,7 @@ from nucypher.cli.literature import (
DECRYPTING_CHARACTER_KEYRING,
GENERIC_PASSWORD_PROMPT
)
from nucypher.config.keyring import NucypherKeyring
from nucypher.crypto.keystore import Keystore
from nucypher.config.base import CharacterConfiguration
from tests.constants import INSECURE_DEVELOPMENT_PASSWORD
@ -97,7 +97,7 @@ def test_get_nucypher_password(mock_stdin, mock_account, confirm, capsys):
captured = capsys.readouterr()
assert COLLECT_NUCYPHER_PASSWORD in captured.out
if confirm:
prompt = COLLECT_NUCYPHER_PASSWORD + f" ({NucypherKeyring.MINIMUM_PASSWORD_LENGTH} character minimum)"
prompt = COLLECT_NUCYPHER_PASSWORD + f" ({Keystore.MINIMUM_PASSWORD_LENGTH} character minimum)"
assert prompt in captured.out
@ -105,14 +105,14 @@ def test_unlock_nucypher_keyring_invalid_password(mocker, test_emitter, alice_bl
# Setup
keyring_attach_spy = mocker.spy(CharacterConfiguration, 'attach_keyring')
mocker.patch.object(NucypherKeyring, 'unlock', side_effect=CryptoError)
mocker.patch.object(Keystore, 'unlock', side_effect=CryptoError)
mocker.patch.object(CharacterConfiguration,
'dev_mode',
return_value=False,
new_callable=mocker.PropertyMock)
# Test
with pytest.raises(NucypherKeyring.AuthenticationFailed):
with pytest.raises(Keystore.AuthenticationFailed):
unlock_nucypher_keyring(emitter=test_emitter,
password=INSECURE_DEVELOPMENT_PASSWORD+'typo',
character_configuration=alice_blockchain_test_config)
@ -125,7 +125,7 @@ def test_unlock_nucypher_keyring_invalid_password(mocker, test_emitter, alice_bl
def test_unlock_nucypher_keyring_dev_mode(mocker, test_emitter, capsys, alice_blockchain_test_config):
# Setup
unlock_spy = mocker.spy(NucypherKeyring, 'unlock')
unlock_spy = mocker.spy(Keystore, 'unlock')
attach_spy = mocker.spy(CharacterConfiguration, 'attach_keyring')
mocker.patch.object(CharacterConfiguration,
'dev_mode',
@ -154,7 +154,7 @@ def test_unlock_nucypher_keyring(mocker,
# Setup
# Do not test "real" unlocking here, just the plumbing
unlock_spy = mocker.patch.object(NucypherKeyring, 'unlock', return_value=True)
unlock_spy = mocker.patch.object(Keystore, 'unlock', return_value=True)
attach_spy = mocker.spy(CharacterConfiguration, 'attach_keyring')
mocker.patch.object(CharacterConfiguration,
'dev_mode',

View File

@ -16,18 +16,18 @@
"""
import os
import tempfile
from unittest.mock import Mock
import pytest
import tempfile
from constant_sorrow.constants import CERTIFICATE_NOT_SAVED, NO_KEYRING_ATTACHED
from tests.constants import MOCK_IP_ADDRESS
from nucypher.blockchain.eth.actors import StakeHolder
from nucypher.characters.chaotic import Felix
from nucypher.characters.lawful import Alice, Bob, Ursula
from nucypher.cli.actions.configure import destroy_configuration
from nucypher.cli.literature import SUCCESSFUL_DESTRUCTION
from nucypher.config.base import CharacterConfiguration
from nucypher.config.characters import (
AliceConfiguration,
BobConfiguration,
@ -36,11 +36,10 @@ from nucypher.config.characters import (
UrsulaConfiguration
)
from nucypher.config.constants import TEMPORARY_DOMAIN
from nucypher.config.keyring import NucypherKeyring
from nucypher.config.base import CharacterConfiguration
from nucypher.config.storages import ForgetfulNodeStorage
from nucypher.crypto.keystore import Keystore
from nucypher.crypto.umbral_adapter import SecretKey
from tests.constants import MOCK_IP_ADDRESS
# Main Cast
configurations = (AliceConfiguration, BobConfiguration, UrsulaConfiguration)
@ -128,7 +127,7 @@ def test_default_character_configuration_preservation(configuration_class, teste
elif configuration_class == UrsulaConfiguration:
# special case for rest_host & dev mode
# use keyring
keyring = Mock(spec=NucypherKeyring)
keyring = Mock(spec=Keystore)
keyring.signing_public_key = SecretKey.random().public_key()
character_config = configuration_class(checksum_address=fake_address,
domain=network,
@ -211,7 +210,7 @@ def test_destroy_configuration(config,
# Isolate from filesystem and Spy on the methods we're testing here
spy_keyring_attached = mocker.spy(CharacterConfiguration, 'attach_keyring')
mock_config_destroy = mocker.patch.object(CharacterConfiguration, 'destroy')
spy_keyring_destroy = mocker.spy(NucypherKeyring, 'destroy')
spy_keyring_destroy = mocker.spy(Keystore, 'destroy')
mock_os_remove = mocker.patch('os.remove')
# Test

View File

@ -26,7 +26,7 @@ from flask import Flask
from nucypher.characters.lawful import Alice, Bob, Ursula
from nucypher.config.constants import TEMPORARY_DOMAIN
from nucypher.config.keyring import NucypherKeyring
from nucypher.crypto.keystore import Keystore
from nucypher.crypto.powers import DecryptingPower, DelegatingPower
from nucypher.crypto.umbral_adapter import SecretKey, Signer
from nucypher.datastore.datastore import Datastore
@ -38,7 +38,7 @@ from tests.utils.matchers import IsType
def test_generate_alice_keyring(tmpdir):
keyring = NucypherKeyring.generate(
keyring = Keystore.generate(
checksum_address=FEDERATED_ADDRESS,
password=INSECURE_DEVELOPMENT_PASSWORD,
encrypting=True,
@ -49,7 +49,7 @@ def test_generate_alice_keyring(tmpdir):
enc_pubkey = keyring.encrypting_public_key
assert enc_pubkey is not None
with pytest.raises(NucypherKeyring.KeyringLocked):
with pytest.raises(Keystore.KeyringLocked):
_dec_keypair = keyring.derive_crypto_power(DecryptingPower).keypair
keyring.unlock(password=INSECURE_DEVELOPMENT_PASSWORD)
@ -77,7 +77,7 @@ def test_generate_alice_keyring(tmpdir):
def test_characters_use_keyring(tmpdir):
keyring = NucypherKeyring.generate(
keyring = Keystore.generate(
checksum_address=FEDERATED_ADDRESS,
password=INSECURE_DEVELOPMENT_PASSWORD,
encrypting=True,
@ -98,7 +98,7 @@ def test_characters_use_keyring(tmpdir):
def test_tls_hosting_certificate_remains_the_same(tmpdir, mocker):
keyring = NucypherKeyring.generate(
keyring = Keystore.generate(
checksum_address=FEDERATED_ADDRESS,
password=INSECURE_DEVELOPMENT_PASSWORD,
encrypting=True,

View File

@ -18,7 +18,7 @@
import pytest
from nucypher.characters.lawful import Ursula
from nucypher.crypto.api import keccak_digest
from nucypher.crypto.utils import keccak_digest
from nucypher.datastore.models import TreasureMap as DatastoreTreasureMap
from nucypher.policy.collections import TreasureMap as FederatedTreasureMap
from tests.utils.middleware import MockRestMiddleware

View File

@ -21,7 +21,6 @@ from constant_sorrow import constants
from cryptography.exceptions import InvalidSignature
from nucypher.characters.lawful import Alice, Bob, Character
from nucypher.crypto import api
from nucypher.crypto.powers import (CryptoPower, NoSigningPower, SigningPower)
"""

View File

@ -19,14 +19,15 @@ import unittest
import sha3
import nucypher.crypto.utils
from nucypher.crypto import api
class TestCrypto(unittest.TestCase):
def test_secure_random(self):
rand1 = api.secure_random(10)
rand2 = api.secure_random(10)
rand1 = nucypher.crypto.utils.secure_random(10)
rand2 = nucypher.crypto.utils.secure_random(10)
self.assertNotEqual(rand1, rand2)
self.assertEqual(bytes, type(rand1))
@ -35,13 +36,13 @@ class TestCrypto(unittest.TestCase):
self.assertEqual(10, len(rand2))
def test_secure_random_range(self):
output = [api.secure_random_range(1, 3) for _ in range(20)]
output = [nucypher.crypto.utils.secure_random_range(1, 3) for _ in range(20)]
# Test that highest output can be max-1
self.assertNotIn(3, output)
# Test that min is present
output = [api.secure_random_range(1, 2) for _ in range(20)]
output = [nucypher.crypto.utils.secure_random_range(1, 2) for _ in range(20)]
self.assertNotIn(2, output)
self.assertIn(1, output)
@ -49,7 +50,7 @@ class TestCrypto(unittest.TestCase):
data = b'this is a test'
digest1 = sha3.keccak_256(data).digest()
digest2 = api.keccak_digest(data)
digest2 = nucypher.crypto.utils.keccak_digest(data)
self.assertEqual(digest1, digest2)
@ -57,6 +58,6 @@ class TestCrypto(unittest.TestCase):
data = data.split()
digest1 = sha3.keccak_256(b''.join(data)).digest()
digest2 = api.keccak_digest(*data)
digest2 = nucypher.crypto.utils.keccak_digest(*data)
self.assertEqual(digest1, digest2)

View File

@ -18,7 +18,7 @@ import pytest
from bytestring_splitter import BytestringSplitter, BytestringSplittingError
from nucypher.characters.lawful import Enrico
from nucypher.crypto.api import secure_random
from nucypher.crypto.utils import secure_random
from nucypher.crypto.kits import UmbralMessageKit
from nucypher.crypto.signing import Signature
from nucypher.crypto.splitters import signature_splitter