Exemple #1
0
def collect_policy_rate_and_value(alice: Alice, rate: int, value: int,
                                  shares: int, force: bool) -> Tuple[int, int]:

    policy_value_provided = bool(value) or bool(rate)
    if not policy_value_provided:

        # TODO #1709 - Fine tuning and selection of default rates
        rate = alice.default_rate  # wei

        if not force:
            default_gwei = Web3.fromWei(rate, 'gwei')  # wei -> gwei
            prompt = "Confirm rate of {node_rate} gwei * {shares} nodes ({period_rate} gwei per period)?"

            if not click.confirm(prompt.format(
                    node_rate=default_gwei,
                    period_rate=default_gwei * shares,
                    shares=shares),
                                 default=True):
                interactive_rate = click.prompt(
                    'Enter rate per period in gwei', type=GWEI)
                # TODO: Interactive rate sampling & validation (#1709)
                interactive_prompt = prompt.format(
                    node_rate=interactive_rate,
                    period_rate=interactive_rate * shares,
                    shares=shares)
                click.confirm(interactive_prompt, default=True, abort=True)
                rate = Web3.toWei(interactive_rate, 'gwei')  # gwei -> wei

    return rate, value
Exemple #2
0
def to_wei(amount_in_ether: Union[Decimal, str, int],
           decimals: int = DECIMALS_18) -> int:
    """
    Convert token amount to wei from ether, quantized to the specified number of decimal places
    float input is purposfully not supported
    """
    amount_in_ether = normalize_and_validate_ether(amount_in_ether)
    decimal_places = Decimal(10)**-abs(decimals)
    return Web3.toWei(
        amount_in_ether.quantize(decimal_places,
                                 context=ETHEREUM_DECIMAL_CONTEXT),
        "ether",
    )
Exemple #3
0
    def share_data_access(self,
                          pubkeys,
                          label,
                          days=5,
                          m=1,
                          n=1,
                          rate=Web3.toWei(50, 'gwei')):
        """
        Share data access based on public keys

        Args:
            pubkeys (dict): public keys dict containing sig and enc keys
            label (bytes): label for the policy
            days (int): days for which the access should be granted
            m (int): Minimum number of kfrags needed to activate a Capsule
            n (int): Total number of kfrags to generate
            rate (int): rate in wei

        Returns:
            policy_info (dict): dict containing policy_pubkey, alice_sig_pubkey and label keys
        """
        bob = Bob.from_public_keys(verifying_key=pubkeys['sig'],
                                   encrypting_key=pubkeys['enc'],
                                   federated_only=self.federated_only)
        # Policy expiration date
        policy_end_datetime = maya.now() + datetime.timedelta(days=days)
        power_ups = self.alice._crypto_power._CryptoPower__power_ups
        for key, power_up in power_ups.items():
            self.alice._crypto_power.consume_power_up(
                power_up, password=self.__client_password)
        policy = self.alice.grant(bob=bob,
                                  label=label,
                                  m=m,
                                  n=n,
                                  expiration=policy_end_datetime,
                                  rate=rate)
        policy_info = {
            "policy_pubkey": policy.public_key.to_bytes().hex(),
            "alice_sig_pubkey": bytes(self.alice.stamp).hex(),
            "label": label.decode("utf-8"),
        }
        return policy_info
Exemple #4
0
    def calculate_prizes(self):
        """
        :rtype: list
        """
        result = []

        if Web3.isAddress(self.smart_contract_id):
            contract = self.get_smart_contract()
            result = contract.call().calcaultePrizes()
        else:
            calculator = UnilotPrizeCalculator()
            bet = Web3.toWei(((self.prize_amount / self.num_players) / 0.7),
                             'ether')
            rawData = calculator.calculate_prizes(bet, self.num_players)
            result = [
                prize_amount for prize_amount in rawData
                if int(prize_amount) > 0
            ]

        return result
Exemple #5
0
              f'{PASSWORD_ENVVAR} ' \
              f'are required to run grant availability metrics.'
    raise RuntimeError(message)

# Alice Configuration
DOMAIN: str = 'mainnet'  # ibex
DEFAULT_SEEDNODE_URIS: List[str] = [
    *RestMiddleware.TEACHER_NODES[DOMAIN],
]
INSECURE_PASSWORD: str = "METRICS_INSECURE_DEVELOPMENT_PASSWORD"
TEMP_ALICE_DIR: str = Path('/', 'tmp', 'grant-metrics')

# Policy Parameters
M: int = 1
N: int = 1
RATE: Wei = Web3.toWei(50, 'gwei')
DURATION: datetime.timedelta = datetime.timedelta(days=1)

# Tuning
DEFAULT_ITERATIONS = 1  # `None` will run forever
SAMPLE_RATE: int = 15  # seconds
GAS_STRATEGY: str = 'fast'
LABEL_PREFIX = 'random-metrics-label-'
LABEL_SUFFIXER = lambda: os.urandom(16).hex()
HANDPICKED_URSULA_URIS: List[str] = [
    # DEFAULT_SEEDNODE_URIS[0],  # uncomment to use the seednode for granting
]


def make_random_bob():
    """Generates a random ephemeral Bob instance."""
label = b"secret/files/42"
policy_public_key = alice.get_policy_encrypting_key_from_label(label)

# From this moment on, anyone that knows the public key
# can encrypt data originally intended for Alice, but that
# can be shared with any Bob that Alice grants access.

# Alice already knows Bob's public keys from a side-channel.
remote_bob = Bob.from_public_keys(encrypting_key=encrypting_key,
                                  verifying_key=verifying_key)

# These are the policy details for bob.
# In this example bob will be granted access for 1 day,
# trusting 2 of 3 nodes paying each of them 50 gwei per period.
expiration = maya.now() + datetime.timedelta(days=1)
rate = Web3.toWei(50, 'gwei')
m, n = 2, 3

# Alice grants access to Bob...
alice.grant(remote_bob, label, m=m, n=n, rate=rate, expiration=expiration)

# ...and then disappears from the internet.
#
# Note that local characters (alice and bob), as opposed to objects representing
# remote characters constructed from public data (remote_alice and remote_bob)
# run node discovery in a background thread and must be stopped explicitly.
alice.disenchant()
del alice

#########################
# Enrico, the Encryptor #
Exemple #7
0
def grant(general_config,
          bob,
          bob_encrypting_key,
          bob_verifying_key,
          label,
          value,
          rate,
          expiration,
          m, n,
          character_options,
          config_file,
          force):
    """Create and enact an access policy for some Bob. """

    # Setup
    emitter = setup_emitter(general_config)
    ALICE = character_options.create_character(emitter, config_file, general_config.json_ipc)

    # Policy option validation
    if ALICE.federated_only:
        if any((value, rate)):
            message = "Can't use --value or --rate with a federated Alice."
            raise click.BadOptionUsage(option_name="--value, --rate", message=message)
    elif bool(value) and bool(rate):
        raise click.BadOptionUsage(option_name="--rate", message="Can't use --value if using --rate")

    # Grantee selection
    if bob and any((bob_encrypting_key, bob_verifying_key)):
        message = '--bob cannot be used with --bob-encrypting-key or --bob-veryfying key'
        raise click.BadOptionUsage(option_name='--bob', message=message)

    if bob:
        card = Card.load(identifier=bob)
        if card.character is not Bob:
            emitter.error('Grantee card is not a Bob.')
            raise click.Abort
        paint_single_card(emitter=emitter, card=card)
        if not force:
            click.confirm('Is this the correct grantee (Bob)?', abort=True)
        bob_encrypting_key = card.encrypting_key.hex()
        bob_verifying_key = card.verifying_key.hex()

    # Interactive collection follows:
    # TODO: Extricate to support modules
    # - Disclaimer
    # - Label
    # - Expiration Date & Time
    # - M of N
    # - Policy Value (ETH)

    # Policy Expiration
    # TODO: Remove this line when the time is right.
    paint_probationary_period_disclaimer(emitter)

    # Label
    if not label:
        label = click.prompt(f'Enter label to grant Bob {bob_verifying_key[:8]}', type=click.STRING)

    if not force and not expiration:
        if ALICE.duration_periods:
            # TODO: use a default in days or periods?
            expiration = maya.now() + timedelta(days=ALICE.duration_periods)  # default
            if not click.confirm(f'Use default policy duration (expires {expiration})?'):
                expiration = click.prompt('Enter policy expiration datetime', type=click.DateTime())
        else:
            # No policy duration default default available; Go interactive
            expiration = click.prompt('Enter policy expiration datetime', type=click.DateTime())

    # TODO: Remove this line when the time is right.
    enforce_probationary_period(emitter=emitter, expiration=expiration)

    # Policy Threshold and Shares
    if not n:
        n = ALICE.n
        if not force and not click.confirm(f'Use default value for N ({n})?', default=True):
            n = click.prompt('Enter total number of shares (N)', type=click.INT)
    if not m:
        m = ALICE.m
        if not force and not click.confirm(f'Use default value for M ({m})?', default=True):
            m = click.prompt('Enter threshold (M)', type=click.IntRange(1, n))

    # Policy Value
    policy_value_provided = bool(value) or bool(rate)
    if not ALICE.federated_only and not policy_value_provided:
        rate = ALICE.default_rate  # TODO #1709 - Fine tuning and selection of default rates
        if not force:
            default_gwei = Web3.fromWei(rate, 'gwei')
            prompt = "Confirm rate of {node_rate} gwei ({total_rate} gwei per period)?"
            if not click.confirm(prompt.format(node_rate=default_gwei, total_rate=default_gwei*n), default=True):
                interactive_rate = click.prompt('Enter rate per period in gwei', type=GWEI)
                # TODO: Validate interactively collected rate (#1709)
                click.confirm(prompt.format(node_rate=rate, total_rate=rate*n), default=True, abort=True)
                rate = Web3.toWei(interactive_rate, 'gwei')

    # Request
    grant_request = {
        'bob_encrypting_key': bob_encrypting_key,
        'bob_verifying_key': bob_verifying_key,
        'label': label,
        'm': m,
        'n': n,
        'expiration': expiration,
    }
    if not ALICE.federated_only:
        if value:
            grant_request['value'] = value
        elif rate:
            grant_request['rate'] = rate  # in wei

    if not force and not general_config.json_ipc:
        confirm_staged_grant(emitter=emitter, grant_request=grant_request)
    emitter.echo(f'Granting Access to {bob_verifying_key[:8]}', color='yellow')
    return ALICE.controller.grant(request=grant_request)