def test_collect_rewards_integration(click_runner, configuration_file_location,
                                     blockchain_alice, blockchain_bob,
                                     random_policy_label, staking_participant,
                                     token_economics, policy_value,
                                     policy_rate):

    blockchain = staking_participant.blockchain

    half_stake_time = token_economics.minimum_locked_periods // 2  # Test setup
    logger = staking_participant.log  # Enter the Teacher's Logger, and
    current_period = 1  # State the initial period for incrementing

    miner = Miner(is_me=True,
                  checksum_address=staking_participant.checksum_address,
                  blockchain=blockchain)

    # The miner is staking.
    assert miner.stakes
    assert miner.is_staking
    pre_stake_token_balance = miner.token_balance

    # Confirm for half the first stake duration
    for _ in range(half_stake_time):
        current_period += 1
        logger.debug(
            f">>>>>>>>>>> TEST PERIOD {current_period} <<<<<<<<<<<<<<<<")
        blockchain.time_travel(periods=1)
        miner.confirm_activity()

    # Alice creates a policy and grants Bob access
    blockchain_alice.selection_buffer = 1

    M, N = 1, 1
    expiration = maya.now() + datetime.timedelta(days=3)
    blockchain_policy = blockchain_alice.grant(
        bob=blockchain_bob,
        label=random_policy_label,
        m=M,
        n=N,
        value=policy_value,
        expiration=expiration,
        handpicked_ursulas={staking_participant})

    # Ensure that the handpicked Ursula was selected for the policy
    arrangement = list(blockchain_policy._accepted_arrangements)[0]
    assert arrangement.ursula == staking_participant

    # Bob learns about the new staker and joins the policy
    blockchain_bob.start_learning_loop()
    blockchain_bob.remember_node(node=staking_participant)
    blockchain_bob.join_policy(random_policy_label,
                               bytes(blockchain_alice.stamp))

    # Enrico Encrypts (of course)
    enrico = Enrico(policy_encrypting_key=blockchain_policy.public_key,
                    network_middleware=MockRestMiddleware())

    verifying_key = blockchain_alice.stamp.as_umbral_pubkey()

    for index in range(half_stake_time - 5):
        logger.debug(
            f">>>>>>>>>>> TEST PERIOD {current_period} <<<<<<<<<<<<<<<<")

        # Encrypt
        random_data = os.urandom(random.randrange(20, 100))
        ciphertext, signature = enrico.encrypt_message(message=random_data)

        # Decrypt
        cleartexts = blockchain_bob.retrieve(message_kit=ciphertext,
                                             data_source=enrico,
                                             alice_verifying_key=verifying_key,
                                             label=random_policy_label)
        assert random_data == cleartexts[0]

        # Ursula Staying online and the clock advancing
        blockchain.time_travel(periods=1)
        miner.confirm_activity()
        current_period += 1

    # Finish the passage of time for the first Stake
    for _ in range(5):  # plus the extended periods from stake division
        current_period += 1
        logger.debug(
            f">>>>>>>>>>> TEST PERIOD {current_period} <<<<<<<<<<<<<<<<")
        blockchain.time_travel(periods=1)
        miner.confirm_activity()

    #
    # WHERES THE MONEY URSULA?? - Collecting Rewards
    #

    # The address the client wants Ursula to send rewards to
    burner_wallet = blockchain.interface.w3.eth.account.create(
        INSECURE_DEVELOPMENT_PASSWORD)

    # The rewards wallet is initially empty, because it is freshly created
    assert blockchain.interface.w3.eth.getBalance(burner_wallet.address) == 0

    # Snag a random teacher from the fleet
    collection_args = ('--mock-networking', 'ursula', 'collect-reward',
                       '--config-file', configuration_file_location,
                       '--withdraw-address', burner_wallet.address, '--force')

    result = click_runner.invoke(nucypher_cli,
                                 collection_args,
                                 input=INSECURE_DEVELOPMENT_PASSWORD,
                                 catch_exceptions=False)
    assert result.exit_code == 0

    # Policy Reward
    collected_policy_reward = blockchain.interface.w3.eth.getBalance(
        burner_wallet.address)
    expected_collection = policy_rate * 30
    assert collected_policy_reward == expected_collection

    # Finish the passage of time... once and for all
    # Extended periods from stake division
    for _ in range(9):
        current_period += 1
        logger.debug(
            f">>>>>>>>>>> TEST PERIOD {current_period} <<<<<<<<<<<<<<<<")
        blockchain.time_travel(periods=1)
        miner.confirm_activity()

    # Staking Reward
    calculated_reward = miner.miner_agent.calculate_staking_reward(
        checksum_address=miner.checksum_address)
    assert calculated_reward
    assert miner.token_balance > pre_stake_token_balance
def test_collect_rewards_integration(
        click_runner, funded_blockchain, configuration_file_location,
        alice_blockchain_test_config, bob_blockchain_test_config,
        charlie_blockchain_test_config, random_policy_label,
        blockchain_ursulas, staking_participant):

    blockchain = staking_participant.blockchain

    # Alice creates a policy and grants Bob access
    alice = alice_blockchain_test_config.produce(
        blockchain=funded_blockchain,
        network_middleware=MockRestMiddleware(),
        known_nodes=blockchain_ursulas)

    bob = bob_blockchain_test_config.produce(
        blockchain=blockchain,
        network_middleware=MockRestMiddleware(),
        known_nodes=blockchain_ursulas)

    #
    # Back to the Ursulas...
    #
    half_stake_time = MIN_LOCKED_PERIODS // 2  # Test setup
    logger = staking_participant.log  # Enter the Teacher's Logger, and
    current_period = 1  # State the initial period for incrementing

    miner = Miner(checksum_address=staking_participant.checksum_public_address,
                  blockchain=blockchain,
                  is_me=True)

    pre_stake_eth_balance = miner.eth_balance

    # Finish the passage of time... once and for all
    for _ in range(half_stake_time):
        current_period += 1
        logger.debug(f"period {current_period}")
        blockchain.time_travel(periods=1)
        miner.confirm_activity()

    M, N = 1, 1
    expiration = maya.now() + datetime.timedelta(days=3)
    blockchain_policy = alice.grant(bob=bob,
                                    label=random_policy_label,
                                    m=M,
                                    n=1,
                                    value=POLICY_VALUE,
                                    expiration=expiration,
                                    handpicked_ursulas={staking_participant})

    # Bob joins the policy
    bob.join_policy(random_policy_label, bytes(alice.stamp))

    # Enrico Encrypts (of course)
    enrico = Enrico(policy_encrypting_key=blockchain_policy.public_key,
                    network_middleware=MockRestMiddleware())

    for index, _period in enumerate(range(half_stake_time - 5)):
        logger.debug(f"period {current_period}")

        alphabet = string.ascii_letters + string.digits

        # Random Request Periods
        if not random.choice((True, False)):
            continue  # maybe re-encrypt

        max_reencryptions_per_period = 5
        quantity = random.choice(range(max_reencryptions_per_period + 1))
        quantity *= index  # factorial or 0
        verifying_key = UmbralPublicKey.from_bytes(bytes(alice.stamp))

        # Random Re-encryptions
        for _i in range(quantity):

            # Encrypt
            random_data = ''.join(
                secrets.choice(alphabet)
                for i in range(secrets.choice(range(20, 100))))
            ciphertext, signature = enrico.encrypt_message(
                message=bytes(random_data, encoding='utf-8'))

            # Retrieve
            payload = dict(message_kit=ciphertext,
                           data_source=enrico,
                           alice_verifying_key=verifying_key,
                           label=random_policy_label)

            _cleartext = bob.retrieve(**payload)

        # Ursula Staying online and the clock advancing
        blockchain.time_travel(periods=1)
        miner.confirm_activity()
        current_period += 1

    # Finish the passage of time... once and for all
    for _ in range(5):
        current_period += 1
        logger.debug(f"period {current_period}")
        blockchain.time_travel(periods=1)
        miner.confirm_activity()

    #
    # WHERES THE MONEY URSULA?? - Collecting Rewards
    #

    # The address the client wants Ursula to send rewards to
    burner_wallet = blockchain.interface.w3.eth.account.create(
        INSECURE_DEVELOPMENT_PASSWORD)
    assert blockchain.interface.w3.eth.getBalance(burner_wallet.address) == 0

    # Snag a random teacher from the fleet
    random_teacher = list(blockchain_ursulas).pop()

    collection_args = ('--mock-networking', 'ursula', 'collect-reward',
                       '--teacher-uri', random_teacher.rest_interface,
                       '--config-file', configuration_file_location,
                       '--withdraw-address', burner_wallet.address, '--poa',
                       '--force')

    result = click_runner.invoke(nucypher_cli,
                                 collection_args,
                                 input=INSECURE_DEVELOPMENT_PASSWORD,
                                 catch_exceptions=False)
    assert result.exit_code == 0

    collected_reward = blockchain.interface.w3.eth.getBalance(
        burner_wallet.address)
    assert collected_reward != 0

    expected_reward = Web3.toWei(21, 'gwei') * 30 * M
    assert collected_reward == expected_reward
    assert miner.eth_balance == pre_stake_eth_balance
Example #3
0
def test_collect_rewards_integration(click_runner, configuration_file_location,
                                     blockchain_alice, blockchain_bob,
                                     random_policy_label, blockchain_ursulas,
                                     staking_participant, token_economics,
                                     policy_value, policy_rate):

    blockchain = staking_participant.blockchain

    half_stake_time = token_economics.minimum_locked_periods // 2  # Test setup
    logger = staking_participant.log  # Enter the Teacher's Logger, and
    current_period = 1  # State the initial period for incrementing

    miner = Miner(checksum_address=staking_participant.checksum_public_address,
                  blockchain=blockchain,
                  is_me=True)

    pre_stake_eth_balance = miner.eth_balance

    # Finish the passage of time... once and for all
    for _ in range(half_stake_time):
        current_period += 1
        logger.debug(f"period {current_period}")
        blockchain.time_travel(periods=1)
        miner.confirm_activity()

    # Alice creates a policy and grants Bob access
    M, N = 1, 1
    expiration = maya.now() + datetime.timedelta(days=3)
    blockchain_policy = blockchain_alice.grant(
        bob=blockchain_bob,
        label=random_policy_label,
        m=M,
        n=N,
        value=policy_value,
        expiration=expiration,
        handpicked_ursulas={staking_participant})

    # Bob joins the policy
    blockchain_bob.join_policy(random_policy_label,
                               bytes(blockchain_alice.stamp))

    # Enrico Encrypts (of course)
    enrico = Enrico(policy_encrypting_key=blockchain_policy.public_key,
                    network_middleware=MockRestMiddleware())

    verifying_key = blockchain_alice.stamp.as_umbral_pubkey()

    for index in range(half_stake_time - 5):
        logger.debug(f"period {current_period}")
        random_data = os.urandom(random.randrange(20, 100))
        ciphertext, signature = enrico.encrypt_message(message=random_data)

        # Retrieve
        cleartexts = blockchain_bob.retrieve(message_kit=ciphertext,
                                             data_source=enrico,
                                             alice_verifying_key=verifying_key,
                                             label=random_policy_label)
        assert random_data == cleartexts[0]

        # Ursula Staying online and the clock advancing
        blockchain.time_travel(periods=1)
        miner.confirm_activity()
        current_period += 1

    # Finish the passage of time... once and for all
    for _ in range(5):
        current_period += 1
        logger.debug(f"period {current_period}")
        blockchain.time_travel(periods=1)
        miner.confirm_activity()

    #
    # WHERES THE MONEY URSULA?? - Collecting Rewards
    #

    # The address the client wants Ursula to send rewards to
    burner_wallet = blockchain.interface.w3.eth.account.create(
        INSECURE_DEVELOPMENT_PASSWORD)
    # The rewards wallet is initially empty
    assert blockchain.interface.w3.eth.getBalance(burner_wallet.address) == 0

    # Snag a random teacher from the fleet
    random_teacher = list(blockchain_ursulas).pop()

    collection_args = ('--mock-networking', 'ursula', 'collect-reward',
                       '--teacher-uri', random_teacher.rest_interface,
                       '--config-file', configuration_file_location,
                       '--withdraw-address', burner_wallet.address, '--poa',
                       '--force')

    result = click_runner.invoke(nucypher_cli,
                                 collection_args,
                                 input=INSECURE_DEVELOPMENT_PASSWORD,
                                 catch_exceptions=False)
    assert result.exit_code == 0

    collected_reward = blockchain.interface.w3.eth.getBalance(
        burner_wallet.address)
    assert collected_reward != 0

    expected_reward = policy_rate * 30
    assert collected_reward == expected_reward
    assert miner.eth_balance == pre_stake_eth_balance