type hints for blockchain submodules

pull/444/head
Kieran Prasch 2018-09-21 11:04:52 -07:00
parent ba8bfdf435
commit 824ef32a85
5 changed files with 37 additions and 27 deletions

View File

@ -1,6 +1,6 @@
from collections import OrderedDict
from datetime import datetime
from typing import Tuple
from typing import Tuple, List
import maya
@ -37,7 +37,7 @@ class NucypherTokenActor:
"""
try:
parent_address = self.checksum_public_address
parent_address = self.checksum_public_address # type: str
if checksum_address is not None:
if parent_address != checksum_address:
raise ValueError("Can't have two different addresses.")
@ -206,7 +206,7 @@ class Miner(NucypherTokenActor):
if entire_balance is True:
amount = self.token_balance
staking_transactions = OrderedDict() # Time series of txhases
staking_transactions = OrderedDict() # type: OrderedDict # Time series of txhases
# Validate
assert self.__validate_stake(amount=amount, lock_periods=lock_periods)
@ -281,7 +281,7 @@ class PolicyAuthor(NucypherTokenActor):
checksum_address=checksum_address,
)
def recruit(self, quantity: int, **options) -> None:
def recruit(self, quantity: int, **options) -> List[str]:
"""
Uses sampling logic to gather miners from the blockchain and
caches the resulting node ethereum addresses.

View File

@ -103,7 +103,12 @@ class MinerAgent(EthereumContractAgent):
class NotEnoughMiners(Exception):
pass
def __init__(self, token_agent: NucypherTokenAgent=None, registry_filepath=None, *args, **kwargs) -> None:
def __init__(self,
token_agent: NucypherTokenAgent = None,
registry_filepath: str = None,
*args, **kwargs
) -> None:
token_agent = token_agent if token_agent is not None else NucypherTokenAgent(registry_filepath=registry_filepath)
super().__init__(blockchain=token_agent.blockchain, registry_filepath=registry_filepath, *args, **kwargs)
self.token_agent = token_agent

View File

@ -155,7 +155,7 @@ class BlockchainInterface:
@classmethod
def from_config(cls, config: NodeConfiguration) -> 'BlockchainInterface':
# Parse
payload = parse_blockchain_config(filepath=config.ini_filepath)
payload = parse_blockchain_config(filepath=config.config_file_location)
# Init deps
compiler = SolidityCompiler() if payload['compile'] else None

View File

@ -1,5 +1,5 @@
from collections import deque
from typing import List
from typing import List, Tuple
from typing import Set
import math
@ -28,11 +28,12 @@ class BlockchainArrangement(Arrangement):
lock_periods: int,
expiration: maya.MayaDT,
*args, **kwargs) -> None:
super().__init__(alice=author, ursula=miner, *args, **kwargs)
delta = expiration - maya.now()
hours = (delta.total_seconds() / 60) / 60
periods = int(math.ceil(hours / int(constants.HOURS_PER_PERIOD)))
hours = (delta.total_seconds() / 60) / 60 # type: int
periods = int(math.ceil(hours / int(constants.HOURS_PER_PERIOD))) # type: int
# The relationship exists between two addresses
self.author = author
@ -111,7 +112,7 @@ class BlockchainPolicy(Policy):
def __find_ursulas(self, ether_addresses: List[str], target_quantity: int, timeout: int = 120):
start_time = maya.now() # Marker for timeout calculation
found_ursulas, unknown_addresses = set(), deque()
found_ursulas, unknown_addresses = set(), deque() # type: Tuple[set, deque]
while len(found_ursulas) < target_quantity:
# Check for a timeout
@ -146,24 +147,27 @@ class BlockchainPolicy(Policy):
return found_ursulas
def make_arrangements(self, network_middleware: RestMiddleware,
deposit: int, expiration: maya.MayaDT,
handpicked_ursulas: Set[Ursula] = set()) -> None:
def make_arrangements(self,
network_middleware: RestMiddleware,
deposit: int,
expiration: maya.MayaDT,
handpicked_ursulas: Set[Ursula] = None
) -> None:
"""
Create and consider n Arrangements from sampled miners, a list of Ursulas, or a combination of both.
"""
ADDITIONAL_URSULAS = 1.5 # TODO: Make constant
ADDITIONAL_URSULAS = 1.5 # TODO: Make constant
handpicked_ursulas = handpicked_ursulas or set() # type: set
target_sample_quantity = self.n - len(handpicked_ursulas)
selected_addresses = set()
try: # Sample by reading from the Blockchain
selected_addresses = set() # type: set
try: # Sample by reading from the Blockchain
actual_sample_quantity = math.ceil(target_sample_quantity * ADDITIONAL_URSULAS)
duration = int(calculate_period_duration(expiration))
sampled_addresses = self.alice.recruit(quantity=actual_sample_quantity,
duration=duration,
)
duration=duration)
except MinerAgent.NotEnoughMiners:
error = "Cannot create policy with {} arrangements."
raise self.NotEnoughBlockchainUrsulas(error.format(self.n))

View File

@ -1,12 +1,13 @@
import json
import os
from typing import Union
import shutil
import tempfile
from constant_sorrow import constants
# from nucypher.config.config import DEFAULT_CONFIG_ROOT, NodeConfiguration
# from nucypher.config.parsers import parse_blockchain_config
from nucypher.config.constants import DEFAULT_CONFIG_ROOT
class EthereumContractRegistry:
@ -17,7 +18,8 @@ class EthereumContractRegistry:
WARNING: Unless you are developing NuCypher, you most likely won't ever need
to use this.
"""
# __default_registry_path = os.path.join(DEFAULT_CONFIG_ROOT, 'registry.json')
# TODO: Integrate with config classes
__default_registry_path = os.path.join(DEFAULT_CONFIG_ROOT, 'contract_registry.json')
class RegistryError(Exception):
pass
@ -32,18 +34,17 @@ class EthereumContractRegistry:
self.__registry_filepath = registry_filepath or self.__default_registry_path
@classmethod
def from_config(cls, config) -> 'EthereumContractRegistry':
if config.temp_registry is True: # In memory only
registry = TemporaryEthereumContractRegistry()
def from_config(cls, config) -> Union['EthereumContractRegistry', 'TemporaryEthereumContractRegistry']:
if config.temp_registry is True: # In memory only
return TemporaryEthereumContractRegistry()
else:
registry = EthereumContractRegistry()
return registry
return EthereumContractRegistry()
@property
def registry_filepath(self):
return self.__registry_filepath
def _swap_registry(self, filepath: str) -> True:
def _swap_registry(self, filepath: str) -> bool:
self.__registry_filepath = filepath
return True