コード例 #1
0
ファイル: blockchain.py プロジェクト: p2p-org/nucypher-old
    def bootstrap_network(
        cls,
        economics: BaseEconomics = None
    ) -> Tuple['TesterBlockchain', 'InMemoryContractRegistry']:
        """For use with metric testing scripts"""

        registry = InMemoryContractRegistry()
        testerchain = cls(compiler=SolidityCompiler())
        BlockchainInterfaceFactory.register_interface(testerchain)
        power = TransactingPower(password=INSECURE_DEVELOPMENT_PASSWORD,
                                 account=testerchain.etherbase_account)
        power.activate()
        testerchain.transacting_power = power

        origin = testerchain.client.etherbase
        deployer = ContractAdministrator(deployer_address=origin,
                                         registry=registry,
                                         economics=economics
                                         or cls._default_token_economics,
                                         staking_escrow_test_mode=True)
        secrets = dict()
        for deployer_class in deployer.upgradeable_deployer_classes:
            secrets[
                deployer_class.contract_name] = INSECURE_DEVELOPMENT_PASSWORD
        _receipts = deployer.deploy_network_contracts(secrets=secrets,
                                                      interactive=False)
        return testerchain, registry
コード例 #2
0
ファイル: blockchain.py プロジェクト: KPrasch/nucypher
    def bootstrap_network(
        cls,
        registry: Optional[BaseContractRegistry] = None,
        economics: Economics = None
    ) -> Tuple['TesterBlockchain', 'InMemoryContractRegistry']:
        """For use with metric testing scripts"""

        # Provider connection
        if registry is None:
            registry = InMemoryContractRegistry()
        testerchain = cls()
        if not BlockchainInterfaceFactory.is_interface_initialized(
                eth_provider_uri=testerchain.eth_provider_uri):
            BlockchainInterfaceFactory.register_interface(
                interface=testerchain)

        # Produce actor
        deployer_power = TransactingPower(
            signer=Web3Signer(testerchain.client),
            account=testerchain.etherbase_account)
        admin = ContractAdministrator(registry=registry,
                                      domain=TEMPORARY_DOMAIN,
                                      transacting_power=deployer_power,
                                      economics=economics
                                      or cls.DEFAULT_ECONOMICS)

        gas_limit = None  # TODO: Gas management - #842
        for deployer_class in admin.primary_deployer_classes:
            admin.deploy_contract(contract_name=deployer_class.contract_name,
                                  gas_limit=gas_limit)
        return testerchain, registry
コード例 #3
0
def test_geth_deployment_integration(instant_geth_dev_node, test_registry):

    # TODO: Move to decorator
    if 'CIRCLECI' in os.environ:
        pytest.skip("Do not run Geth nodes in CI")

    blockchain = BlockchainDeployerInterface(
        provider_process=instant_geth_dev_node)
    BlockchainInterfaceFactory.register_interface(interface=blockchain)

    # Make Deployer
    etherbase = to_checksum_address(instant_geth_dev_node.accounts[0].decode(
    ))  # TODO: Make property on nucypher geth node instances?
    administrator = ContractAdministrator(
        registry=test_registry,
        deployer_address=etherbase,
        client_password=None)  # dev accounts have no password.

    assert int(blockchain.client.chain_id) == 1337

    # Deploy
    secrets = dict()
    for deployer_class in administrator.upgradeable_deployer_classes:
        secrets[deployer_class.contract_name] = INSECURE_DEVELOPMENT_PASSWORD

    administrator.deploy_network_contracts(secrets=secrets, interactive=False)
コード例 #4
0
def test_rapid_deployment(token_economics, test_registry, tmpdir,
                          get_random_checksum_address):

    blockchain = _TesterBlockchain(eth_airdrop=False, test_accounts=4)

    # TODO: #1092 - TransactingPower
    blockchain.transacting_power = TransactingPower(
        password=INSECURE_DEVELOPMENT_PASSWORD,
        account=blockchain.etherbase_account)
    blockchain.transacting_power.activate()
    deployer_address = blockchain.etherbase_account

    administrator = ContractAdministrator(deployer_address=deployer_address,
                                          registry=test_registry)
    blockchain.bootstrap_network(registry=test_registry)

    all_yall = blockchain.unassigned_accounts

    # Start with some hard-coded cases...
    allocation_data = [
        {
            'checksum_address': all_yall[1],
            'amount': token_economics.maximum_allowed_locked,
            'lock_periods': token_economics.minimum_locked_periods
        },
        {
            'checksum_address': all_yall[2],
            'amount': token_economics.minimum_allowed_locked,
            'lock_periods': token_economics.minimum_locked_periods
        },
        {
            'checksum_address': all_yall[3],
            'amount': token_economics.minimum_allowed_locked * 100,
            'lock_periods': token_economics.minimum_locked_periods
        },
    ]

    # Pile on the rest
    for _ in range(NUMBER_OF_ALLOCATIONS_IN_TESTS - len(allocation_data)):
        checksum_address = get_random_checksum_address()
        amount = random.randint(token_economics.minimum_allowed_locked,
                                token_economics.maximum_allowed_locked)
        duration = random.randint(token_economics.minimum_locked_periods,
                                  token_economics.maximum_rewarded_periods)
        random_allocation = {
            'checksum_address': checksum_address,
            'amount': amount,
            'lock_periods': duration
        }
        allocation_data.append(random_allocation)

    filepath = tmpdir / "allocations.json"
    with open(filepath, 'w') as f:
        json.dump(allocation_data, f)

    minimum, default, maximum = 10, 20, 30
    administrator.set_fee_rate_range(minimum, default, maximum)
コード例 #5
0
def test_rapid_deployment(token_economics, test_registry, temp_dir_path,
                          get_random_checksum_address):

    blockchain = _TesterBlockchain(eth_airdrop=False, test_accounts=4)

    deployer_address = blockchain.etherbase_account
    deployer_power = TransactingPower(signer=Web3Signer(blockchain.client),
                                      account=deployer_address)

    administrator = ContractAdministrator(transacting_power=deployer_power,
                                          domain=TEMPORARY_DOMAIN,
                                          registry=test_registry)
    blockchain.bootstrap_network(registry=test_registry)

    all_yall = blockchain.unassigned_accounts

    # Start with some hard-coded cases...
    allocation_data = [
        {
            'checksum_address': all_yall[1],
            'amount': token_economics.maximum_allowed_locked,
            'lock_periods': token_economics.minimum_locked_periods
        },
        {
            'checksum_address': all_yall[2],
            'amount': token_economics.minimum_allowed_locked,
            'lock_periods': token_economics.minimum_locked_periods
        },
        {
            'checksum_address': all_yall[3],
            'amount': token_economics.minimum_allowed_locked * 100,
            'lock_periods': token_economics.minimum_locked_periods
        },
    ]

    # Pile on the rest
    for _ in range(NUMBER_OF_ALLOCATIONS_IN_TESTS - len(allocation_data)):
        checksum_address = get_random_checksum_address()
        amount = random.randint(token_economics.minimum_allowed_locked,
                                token_economics.maximum_allowed_locked)
        duration = random.randint(token_economics.minimum_locked_periods,
                                  token_economics.maximum_rewarded_periods)
        random_allocation = {
            'checksum_address': checksum_address,
            'amount': amount,
            'lock_periods': duration
        }
        allocation_data.append(random_allocation)

    filepath = temp_dir_path / "allocations.json"
    with open(filepath, 'w') as f:
        json.dump(allocation_data, f)

    minimum, default, maximum = 10, 20, 30
    administrator.set_fee_rate_range(minimum, default, maximum)
コード例 #6
0
def mock_allocation_registry(testerchain, test_registry,
                             mock_allocation_infile):
    admin = ContractAdministrator(
        registry=test_registry,
        client_password=INSECURE_DEVELOPMENT_PASSWORD,
        deployer_address=testerchain.etherbase_account)

    admin.deploy_beneficiaries_from_file(
        allocation_data_filepath=mock_allocation_infile,
        allocation_outfile=MOCK_ALLOCATION_REGISTRY_FILEPATH)

    allocation_registry = AllocationRegistry(
        filepath=MOCK_ALLOCATION_REGISTRY_FILEPATH)
    yield allocation_registry
    if os.path.isfile(MOCK_ALLOCATION_REGISTRY_FILEPATH):
        os.remove(MOCK_ALLOCATION_REGISTRY_FILEPATH)
コード例 #7
0
def test_geth_deployment_integration(instant_geth_dev_node, test_registry):
    blockchain = BlockchainDeployerInterface(
        provider_process=instant_geth_dev_node, poa=True)  # always poa here.
    BlockchainInterfaceFactory.register_interface(interface=blockchain)

    # Make Deployer
    etherbase = to_checksum_address(instant_geth_dev_node.accounts[0].decode(
    ))  # TODO: Make property on nucypher geth node instances?
    administrator = ContractAdministrator(
        registry=test_registry,
        deployer_address=etherbase,
        client_password=None)  # dev accounts have no password.

    assert int(blockchain.client.chain_id) == 1337

    # Deploy
    administrator.deploy_network_contracts(interactive=False)  # just do it
コード例 #8
0
ファイル: deploy.py プロジェクト: y3v63n/nucypher
    def create_actor(self, emitter, is_multisig: bool = False):

        _ensure_config_root(self.config_root)
        deployer_interface = _initialize_blockchain(poa=self.poa,
                                                    provider_uri=self.provider_uri,
                                                    emitter=emitter,
                                                    ignore_solidity_check=self.ignore_solidity_check,
                                                    gas_strategy=self.gas_strategy)

        # Warnings
        _pre_launch_warnings(emitter, self.etherscan, self.hw_wallet)

        #
        # Establish Registry
        #
        local_registry = establish_deployer_registry(emitter=emitter,
                                                     use_existing_registry=bool(self.contract_name),
                                                     registry_infile=self.registry_infile,
                                                     registry_outfile=self.registry_outfile,
                                                     dev=self.dev)
        #
        # Make Authenticated Deployment Actor
        #
        # Verify Address & collect password
        password = None
        if is_multisig:
            multisig_agent = ContractAgency.get_agent(MultiSigAgent, registry=local_registry)
            deployer_address = multisig_agent.contract.address
            is_transacting = False
        else:
            is_transacting = True
            deployer_address = self.deployer_address
            if not deployer_address:
                prompt = "Select deployer account"
                deployer_address = select_client_account(emitter=emitter,
                                                         prompt=prompt,
                                                         provider_uri=self.provider_uri,
                                                         show_balances=False)

            if not self.force:
                click.confirm("Selected {} - Continue?".format(deployer_address), abort=True)

            if not self.hw_wallet and not deployer_interface.client.is_local:
                password = get_client_password(checksum_address=deployer_address)
        # Produce Actor
        ADMINISTRATOR = ContractAdministrator(registry=local_registry,
                                              client_password=password,
                                              deployer_address=deployer_address,
                                              is_transacting=is_transacting,
                                              staking_escrow_test_mode=self.se_test_mode)
        # Verify ETH Balance
        emitter.echo(f"\n\nDeployer ETH balance: {ADMINISTRATOR.eth_balance}")
        if is_transacting and ADMINISTRATOR.eth_balance == 0:
            emitter.echo("Deployer address has no ETH.", color='red', bold=True)
            raise click.Abort()
        return ADMINISTRATOR, deployer_address, deployer_interface, local_registry
コード例 #9
0
    def bootstrap_network(cls, economics: BaseEconomics = None) -> Tuple['TesterBlockchain', 'InMemoryContractRegistry']:
        """For use with metric testing scripts"""

        registry = InMemoryContractRegistry()
        testerchain = cls()
        BlockchainInterfaceFactory.register_interface(testerchain)
        power = TransactingPower(password=INSECURE_DEVELOPMENT_PASSWORD,
                                 account=testerchain.etherbase_account)
        power.activate()
        testerchain.transacting_power = power

        origin = testerchain.client.etherbase
        deployer = ContractAdministrator(deployer_address=origin,
                                         registry=registry,
                                         economics=economics or cls.DEFAULT_ECONOMICS,
                                         staking_escrow_test_mode=True)

        _receipts = deployer.deploy_network_contracts(interactive=False)
        return testerchain, registry
コード例 #10
0
def test_rapid_deployment(token_economics, test_registry):
    compiler = SolidityCompiler()
    allocation_registry = InMemoryAllocationRegistry()

    blockchain = _TesterBlockchain(eth_airdrop=False,
                                   test_accounts=4,
                                   compiler=compiler)

    # TODO: #1092 - TransactingPower
    blockchain.transacting_power = TransactingPower(password=INSECURE_DEVELOPMENT_PASSWORD,
                                                    account=blockchain.etherbase_account)
    blockchain.transacting_power.activate()
    deployer_address = blockchain.etherbase_account

    deployer = ContractAdministrator(deployer_address=deployer_address,
                                     registry=test_registry)

    secrets = dict()
    for deployer_class in deployer.upgradeable_deployer_classes:
        secrets[deployer_class.contract_name] = INSECURE_DEVELOPMENT_PASSWORD

    deployer.deploy_network_contracts(secrets=secrets, emitter=StdoutEmitter())

    all_yall = blockchain.unassigned_accounts

    # Start with some hard-coded cases...
    allocation_data = [{'beneficiary_address': all_yall[1],
                        'amount': token_economics.maximum_allowed_locked,
                        'duration_seconds': ONE_YEAR_IN_SECONDS},

                       {'beneficiary_address': all_yall[2],
                        'amount': token_economics.minimum_allowed_locked,
                        'duration_seconds': ONE_YEAR_IN_SECONDS*2},

                       {'beneficiary_address': all_yall[3],
                        'amount': token_economics.minimum_allowed_locked*100,
                        'duration_seconds': ONE_YEAR_IN_SECONDS*3}
                       ]

    # Pile on the rest
    for _ in range(NUMBER_OF_ALLOCATIONS_IN_TESTS - len(allocation_data)):
        random_password = ''.join(random.SystemRandom().choice(string.ascii_uppercase+string.digits) for _ in range(16))
        acct = w3.eth.account.create(random_password)
        beneficiary_address = acct.address
        amount = random.randint(token_economics.minimum_allowed_locked, token_economics.maximum_allowed_locked)
        duration = random.randint(token_economics.minimum_locked_periods*ONE_YEAR_IN_SECONDS,
                                  (token_economics.maximum_rewarded_periods*ONE_YEAR_IN_SECONDS)*3)
        random_allocation = {'beneficiary_address': beneficiary_address, 'amount': amount, 'duration_seconds': duration}
        allocation_data.append(random_allocation)

    deployer.deploy_beneficiary_contracts(allocations=allocation_data,
                                          allocation_registry=allocation_registry,
                                          interactive=False)
コード例 #11
0
    def bootstrap_network(
        cls,
        registry: Optional[BaseContractRegistry] = None,
        economics: BaseEconomics = None
    ) -> Tuple['TesterBlockchain', 'InMemoryContractRegistry']:
        """For use with metric testing scripts"""

        if registry is None:
            registry = InMemoryContractRegistry()
        testerchain = cls()
        if not BlockchainInterfaceFactory.is_interface_initialized(
                provider_uri=testerchain.provider_uri):
            BlockchainInterfaceFactory.register_interface(
                interface=testerchain)
        power = TransactingPower(password=INSECURE_DEVELOPMENT_PASSWORD,
                                 account=testerchain.etherbase_account)
        power.activate()
        testerchain.transacting_power = power

        origin = testerchain.client.etherbase
        admin = ContractAdministrator(deployer_address=origin,
                                      registry=registry,
                                      economics=economics
                                      or cls.DEFAULT_ECONOMICS)

        gas_limit = None  # TODO: Gas management - #842
        for deployer_class in admin.primary_deployer_classes:
            if deployer_class is StakingEscrowDeployer:
                admin.deploy_contract(
                    contract_name=deployer_class.contract_name,
                    gas_limit=gas_limit,
                    deployment_mode=INIT)
            else:
                admin.deploy_contract(
                    contract_name=deployer_class.contract_name,
                    gas_limit=gas_limit)
        admin.deploy_contract(
            contract_name=StakingEscrowDeployer.contract_name,
            gas_limit=gas_limit)
        return testerchain, registry
コード例 #12
0
ファイル: deploy.py プロジェクト: gs455/nucypher
def _make_authenticated_deployment_actor(emitter, provider_uri,
                                         deployer_address, deployer_interface,
                                         contract_name, registry_infile,
                                         registry_outfile, hw_wallet, dev,
                                         force, se_test_mode):
    #
    # Establish Registry
    #
    local_registry = establish_deployer_registry(
        emitter=emitter,
        use_existing_registry=bool(contract_name),
        registry_infile=registry_infile,
        registry_outfile=registry_outfile,
        dev=dev)
    #
    # Make Authenticated Deployment Actor
    #
    # Verify Address & collect password
    if not deployer_address:
        prompt = "Select deployer account"
        deployer_address = select_client_account(emitter=emitter,
                                                 prompt=prompt,
                                                 provider_uri=provider_uri,
                                                 show_balances=False)
    if not force:
        click.confirm("Selected {} - Continue?".format(deployer_address),
                      abort=True)
    password = None
    if not hw_wallet and not deployer_interface.client.is_local:
        password = get_client_password(checksum_address=deployer_address)
    # Produce Actor
    ADMINISTRATOR = ContractAdministrator(
        registry=local_registry,
        client_password=password,
        deployer_address=deployer_address,
        staking_escrow_test_mode=se_test_mode)
    # Verify ETH Balance
    emitter.echo(f"\n\nDeployer ETH balance: {ADMINISTRATOR.eth_balance}")
    if ADMINISTRATOR.eth_balance == 0:
        emitter.echo("Deployer address has no ETH.", color='red', bold=True)
        raise click.Abort()
    return ADMINISTRATOR, deployer_address, local_registry
コード例 #13
0
    def create_actor(self,
                     emitter: StdoutEmitter,
                     is_multisig: bool = False
                     ) -> Tuple[ContractAdministrator, str, BlockchainInterface, BaseContractRegistry]:

        ensure_config_root(self.config_root)
        deployer_interface = initialize_deployer_interface(poa=self.poa,
                                                           provider_uri=self.provider_uri,
                                                           emitter=emitter,
                                                           ignore_solidity_check=self.ignore_solidity_check,
                                                           gas_strategy=self.gas_strategy,
                                                           max_gas_price=self.max_gas_price)

        # Warnings
        deployer_pre_launch_warnings(emitter, self.etherscan, self.hw_wallet)

        #
        # Establish Registry
        #

        local_registry = establish_deployer_registry(emitter=emitter,
                                                     use_existing_registry=bool(self.contract_name),  # TODO: Issue #2314
                                                     registry_infile=self.registry_infile,
                                                     registry_outfile=self.registry_outfile,
                                                     dev=self.dev,
                                                     network=self.network)
        #
        # Make Authenticated Deployment Actor
        #
        # Verify Address & collect password
        password = None
        if is_multisig:
            multisig_agent = ContractAgency.get_agent(MultiSigAgent, registry=local_registry)
            deployer_address = multisig_agent.contract.address
            is_transacting = False
        else:
            is_transacting = True
            deployer_address = self.deployer_address
            if not deployer_address:
                deployer_address = select_client_account(emitter=emitter,
                                                         prompt=SELECT_DEPLOYER_ACCOUNT,
                                                         provider_uri=self.provider_uri,
                                                         signer_uri=self.signer_uri,
                                                         show_eth_balance=True)

            if not self.force:
                click.confirm(CONFIRM_SELECTED_ACCOUNT.format(address=deployer_address), abort=True)

            is_clef = ClefSigner.is_valid_clef_uri(self.signer_uri)
            eth_password_is_needed = not self.hw_wallet and not deployer_interface.client.is_local and not is_clef
            if eth_password_is_needed:
                password = get_client_password(checksum_address=deployer_address)

        # Produce Actor
        testnet = deployer_interface.client.chain_name != PUBLIC_CHAINS[1]  # Mainnet
        signer = Signer.from_signer_uri(self.signer_uri, testnet=testnet) if self.signer_uri else None
        ADMINISTRATOR = ContractAdministrator(registry=local_registry,
                                              client_password=password,
                                              deployer_address=deployer_address,
                                              is_transacting=is_transacting,
                                              signer=signer)
        # Verify ETH Balance
        emitter.echo(DEPLOYER_BALANCE.format(eth_balance=ADMINISTRATOR.eth_balance))
        if is_transacting and ADMINISTRATOR.eth_balance == 0:
            emitter.echo(DEPLOYER_ADDRESS_ZERO_ETH, color='red', bold=True)
            raise click.Abort()
        return ADMINISTRATOR, deployer_address, deployer_interface, local_registry
コード例 #14
0
def deploy(action, poa, etherscan, provider_uri, gas, deployer_address,
           contract_name, allocation_infile, allocation_outfile,
           registry_infile, registry_outfile, value, target_address,
           config_root, hw_wallet, force, dev):
    """
    Manage contract and registry deployment.

    \b
    Actions
    -----------------------------------------------------------------------------
    contracts              Compile and deploy contracts.
    allocations            Deploy pre-allocation contracts.
    upgrade                Upgrade NuCypher existing proxy contract deployments.
    rollback               Rollback a proxy contract's target.
    inspect                Echo owner information and bare contract metadata.
    transfer-tokens        Transfer tokens from a contract to another address using the owner's address.
    transfer-ownership     Transfer ownership of contracts to another address.
    """

    emitter = StdoutEmitter()

    #
    # Validate
    #

    # Ensure config root exists, because we need a default place to put output files.
    config_root = config_root or DEFAULT_CONFIG_ROOT
    if not os.path.exists(config_root):
        os.makedirs(config_root)

    if not provider_uri:
        raise click.BadOptionUsage(
            message=f"--provider is required to deploy.",
            option_name="--provider")

    #
    # Pre-Launch Warnings
    #

    if not hw_wallet:
        emitter.echo("WARNING: --no-hw-wallet is enabled.", color='yellow')

    if etherscan:
        emitter.echo(
            "WARNING: --etherscan is enabled. "
            "A browser tab will be opened with deployed contracts and TXs as provided by Etherscan.",
            color='yellow')
    else:
        emitter.echo(
            "WARNING: --etherscan is disabled. "
            "If you want to see deployed contracts and TXs in your browser, activate --etherscan.",
            color='yellow')

    #
    # Connect to Blockchain
    #

    if not BlockchainInterfaceFactory.is_interface_initialized(
            provider_uri=provider_uri):
        # Note: For test compatibility.
        deployer_interface = BlockchainDeployerInterface(
            provider_uri=provider_uri, poa=poa)
        BlockchainInterfaceFactory.register_interface(
            interface=deployer_interface, sync=False, show_sync_progress=False)
    else:
        deployer_interface = BlockchainInterfaceFactory.get_interface(
            provider_uri=provider_uri)

    if action == "inspect":
        if registry_infile:
            registry = LocalContractRegistry(filepath=registry_infile)
        else:
            registry = InMemoryContractRegistry.from_latest_publication()
        administrator = ContractAdministrator(
            registry=registry, deployer_address=deployer_address)
        paint_deployer_contract_inspection(emitter=emitter,
                                           administrator=administrator)
        return  # Exit

    #
    # Establish Registry
    #

    # Establish a contract registry from disk if specified
    default_registry_filepath = os.path.join(
        DEFAULT_CONFIG_ROOT, BaseContractRegistry.REGISTRY_NAME)
    registry_filepath = (registry_outfile
                         or registry_infile) or default_registry_filepath
    if dev:
        # TODO: Need a way to detect a geth --dev registry filepath here. (then deprecate the --dev flag)
        registry_filepath = os.path.join(config_root,
                                         'dev_contract_registry.json')
    registry = LocalContractRegistry(filepath=registry_filepath)
    emitter.message(f"Configured to registry filepath {registry_filepath}")

    #
    # Make Authenticated Deployment Actor
    #

    # Verify Address & collect password
    if not deployer_address:
        prompt = "Select deployer account"
        deployer_address = select_client_account(emitter=emitter,
                                                 prompt=prompt,
                                                 provider_uri=provider_uri,
                                                 show_balances=False)

    if not force:
        click.confirm("Selected {} - Continue?".format(deployer_address),
                      abort=True)

    password = None
    if not hw_wallet and not deployer_interface.client.is_local:
        password = get_client_password(checksum_address=deployer_address)

    # Produce Actor
    ADMINISTRATOR = ContractAdministrator(registry=registry,
                                          client_password=password,
                                          deployer_address=deployer_address)

    # Verify ETH Balance
    emitter.echo(f"\n\nDeployer ETH balance: {ADMINISTRATOR.eth_balance}")
    if ADMINISTRATOR.eth_balance == 0:
        emitter.echo("Deployer address has no ETH.", color='red', bold=True)
        raise click.Abort()

    #
    # Action switch
    #

    if action == 'upgrade':
        if not contract_name:
            raise click.BadArgumentUsage(
                message="--contract-name is required when using --upgrade")
        existing_secret = click.prompt(
            'Enter existing contract upgrade secret', hide_input=True)
        new_secret = click.prompt('Enter new contract upgrade secret',
                                  hide_input=True,
                                  confirmation_prompt=True)
        ADMINISTRATOR.upgrade_contract(
            contract_name=contract_name,
            existing_plaintext_secret=existing_secret,
            new_plaintext_secret=new_secret)
        return  # Exit

    elif action == 'rollback':
        if not contract_name:
            raise click.BadArgumentUsage(
                message="--contract-name is required when using --rollback")
        existing_secret = click.prompt(
            'Enter existing contract upgrade secret', hide_input=True)
        new_secret = click.prompt('Enter new contract upgrade secret',
                                  hide_input=True,
                                  confirmation_prompt=True)
        ADMINISTRATOR.rollback_contract(
            contract_name=contract_name,
            existing_plaintext_secret=existing_secret,
            new_plaintext_secret=new_secret)
        return  # Exit

    elif action == "contracts":

        #
        # Deploy Single Contract (Amend Registry)
        #

        if contract_name:
            try:
                contract_deployer = ADMINISTRATOR.deployers[contract_name]
            except KeyError:
                message = f"No such contract {contract_name}. Available contracts are {ADMINISTRATOR.deployers.keys()}"
                emitter.echo(message, color='red', bold=True)
                raise click.Abort()
            else:
                emitter.echo(f"Deploying {contract_name}")
                if contract_deployer._upgradeable:
                    secret = ADMINISTRATOR.collect_deployment_secret(
                        deployer=contract_deployer)
                    receipts, agent = ADMINISTRATOR.deploy_contract(
                        contract_name=contract_name, plaintext_secret=secret)
                else:
                    receipts, agent = ADMINISTRATOR.deploy_contract(
                        contract_name=contract_name, gas_limit=gas)
                paint_contract_deployment(
                    contract_name=contract_name,
                    contract_address=agent.contract_address,
                    receipts=receipts,
                    emitter=emitter,
                    chain_name=deployer_interface.client.chain_name,
                    open_in_browser=etherscan)
            return  # Exit

        #
        # Deploy Automated Series (Create Registry)
        #

        # Confirm filesystem registry writes.
        if os.path.isfile(registry_filepath):
            emitter.echo(
                f"\nThere is an existing contract registry at {registry_filepath}.\n"
                f"Did you mean 'nucypher-deploy upgrade'?\n",
                color='yellow')
            click.confirm("*DESTROY* existing local registry and continue?",
                          abort=True)
            os.remove(registry_filepath)

        # Stage Deployment
        secrets = ADMINISTRATOR.collect_deployment_secrets()
        paint_staged_deployment(deployer_interface=deployer_interface,
                                administrator=ADMINISTRATOR,
                                emitter=emitter)

        # Confirm Trigger Deployment
        if not confirm_deployment(emitter=emitter,
                                  deployer_interface=deployer_interface):
            raise click.Abort()

        # Delay - Last chance to abort via KeyboardInterrupt
        paint_deployment_delay(emitter=emitter)

        # Execute Deployment
        deployment_receipts = ADMINISTRATOR.deploy_network_contracts(
            secrets=secrets,
            emitter=emitter,
            interactive=not force,
            etherscan=etherscan)

        # Paint outfile paths
        registry_outfile = registry_filepath
        emitter.echo('Generated registry {}'.format(registry_outfile),
                     bold=True,
                     color='blue')

        # Save transaction metadata
        receipts_filepath = ADMINISTRATOR.save_deployment_receipts(
            receipts=deployment_receipts)
        emitter.echo(f"Saved deployment receipts to {receipts_filepath}",
                     color='blue',
                     bold=True)
        return  # Exit

    elif action == "allocations":
        if not allocation_infile:
            allocation_infile = click.prompt("Enter allocation data filepath")
        click.confirm("Continue deploying and allocating?", abort=True)
        ADMINISTRATOR.deploy_beneficiaries_from_file(
            allocation_data_filepath=allocation_infile,
            allocation_outfile=allocation_outfile)
        return  # Exit

    elif action == "transfer-tokens":
        token_agent = ContractAgency.get_agent(NucypherTokenAgent,
                                               registry=registry)
        if not target_address:
            target_address = click.prompt("Enter recipient's checksum address",
                                          type=EIP55_CHECKSUM_ADDRESS)
        if not value:
            stake_value_range = click.FloatRange(min=0, clamp=False)
            value = NU.from_tokens(
                click.prompt(f"Enter value in NU", type=stake_value_range))

        click.confirm(
            f"Transfer {value} from {deployer_address} to {target_address}?",
            abort=True)
        receipt = token_agent.transfer(amount=value,
                                       sender_address=deployer_address,
                                       target_address=target_address)
        emitter.echo(f"OK | Receipt: {receipt['transactionHash'].hex()}")
        return  # Exit

    elif action == "transfer-ownership":
        if not target_address:
            target_address = click.prompt("Enter new owner's checksum address",
                                          type=EIP55_CHECKSUM_ADDRESS)

        if contract_name:
            try:
                contract_deployer_class = ADMINISTRATOR.deployers[
                    contract_name]
            except KeyError:
                message = f"No such contract {contract_name}. Available contracts are {ADMINISTRATOR.deployers.keys()}"
                emitter.echo(message, color='red', bold=True)
                raise click.Abort()
            else:
                contract_deployer = contract_deployer_class(
                    registry=ADMINISTRATOR.registry,
                    deployer_address=ADMINISTRATOR.deployer_address)
                receipt = contract_deployer.transfer_ownership(
                    new_owner=target_address, transaction_gas_limit=gas)
                emitter.ipc(receipt, request_id=0, duration=0)  # TODO: #1216
                return  # Exit
        else:
            receipts = ADMINISTRATOR.relinquish_ownership(
                new_owner=target_address, transaction_gas_limit=gas)
            emitter.ipc(receipts, request_id=0, duration=0)  # TODO: #1216
            return  # Exit

    else:
        raise click.BadArgumentUsage(message=f"Unknown action '{action}'")
コード例 #15
0
def test_rapid_deployment(token_economics, test_registry, tmpdir,
                          get_random_checksum_address):
    compiler = SolidityCompiler()

    blockchain = _TesterBlockchain(eth_airdrop=False,
                                   test_accounts=4,
                                   compiler=compiler)

    # TODO: #1092 - TransactingPower
    blockchain.transacting_power = TransactingPower(
        password=INSECURE_DEVELOPMENT_PASSWORD,
        account=blockchain.etherbase_account)
    blockchain.transacting_power.activate()
    deployer_address = blockchain.etherbase_account

    administrator = ContractAdministrator(deployer_address=deployer_address,
                                          registry=test_registry)

    administrator.deploy_network_contracts(emitter=StdoutEmitter(),
                                           interactive=False)

    all_yall = blockchain.unassigned_accounts

    # Start with some hard-coded cases...
    allocation_data = [
        {
            'checksum_address': all_yall[1],
            'amount': token_economics.maximum_allowed_locked,
            'lock_periods': token_economics.minimum_locked_periods
        },
        {
            'checksum_address': all_yall[2],
            'amount': token_economics.minimum_allowed_locked,
            'lock_periods': token_economics.minimum_locked_periods
        },
        {
            'checksum_address': all_yall[3],
            'amount': token_economics.minimum_allowed_locked * 100,
            'lock_periods': token_economics.minimum_locked_periods
        },
    ]

    # Pile on the rest
    for _ in range(NUMBER_OF_ALLOCATIONS_IN_TESTS - len(allocation_data)):
        checksum_address = get_random_checksum_address()
        amount = random.randint(token_economics.minimum_allowed_locked,
                                token_economics.maximum_allowed_locked)
        duration = random.randint(token_economics.minimum_locked_periods,
                                  token_economics.maximum_rewarded_periods)
        random_allocation = {
            'checksum_address': checksum_address,
            'amount': amount,
            'lock_periods': duration
        }
        allocation_data.append(random_allocation)

    filepath = tmpdir / "allocations.json"
    with open(filepath, 'w') as f:
        json.dump(allocation_data, f)

    staking_agent = ContractAgency.get_agent(StakingEscrowAgent,
                                             registry=test_registry)
    current_period = staking_agent.get_current_period()
    administrator.batch_deposits(allocation_data_filepath=str(filepath),
                                 interactive=False,
                                 release_period=current_period + 10)

    minimum, default, maximum = 10, 20, 30
    administrator.set_fee_rate_range(minimum, default, maximum)