Esempio n. 1
0
def test_alderaan_version() -> None:
    """contracts_source_path('0.37.0') exists and contains the expected files"""
    contract_names = [
        "Utils",
        "SecretRegistry",
        "TokenNetworkRegistry",
        "TokenNetwork",
        "ServiceRegistry",
        "MonitoringService",
        "UserDeposit",
        "OneToN",
    ]

    manager = ContractManager(contracts_precompiled_path(ALDERAAN_VERSION))
    assert manager.contracts_version == ALDERAAN_VERSION
    check_precompiled_content(manager, contract_names, PRECOMPILED_DATA_FIELDS)

    assert contracts_precompiled_path(ALDERAAN_VERSION).exists()
    assert contracts_deployed_path(CHAINNAME_TO_ID["mainnet"],
                                   ALDERAAN_VERSION).exists()
    assert contracts_deployed_path(CHAINNAME_TO_ID["rinkeby"],
                                   ALDERAAN_VERSION).exists()
    assert contracts_deployed_path(CHAINNAME_TO_ID["ropsten"],
                                   ALDERAAN_VERSION).exists()
    assert contracts_deployed_path(CHAINNAME_TO_ID["goerli"],
                                   ALDERAAN_VERSION).exists()
Esempio n. 2
0
def test_pre_limits_version():
    """ contracts_source_path('0.3._') exists and contains the expected files """
    contracts_version = '0.3._'
    contract_names = [
        'Utils',
        'EndpointRegistry',
        'SecretRegistry',
        'TokenNetworkRegistry',
        'TokenNetwork',
    ]

    manager = ContractManager(contracts_precompiled_path(contracts_version))
    assert manager.contracts_version == contracts_version
    check_precompiled_content(manager, contract_names, PRECOMPILED_DATA_FIELDS)

    assert contracts_precompiled_path(contracts_version).exists()
    assert contracts_deployed_path(
        NETWORKNAME_TO_ID['rinkeby'],
        contracts_version,
    ).exists()
    assert contracts_deployed_path(
        NETWORKNAME_TO_ID['ropsten'],
        contracts_version,
    ).exists()
    assert contracts_deployed_path(
        NETWORKNAME_TO_ID['kovan'],
        contracts_version,
    ).exists()
def test_current_development_version() -> None:
    """ contracts_source_path() exists and contains the expected files """
    contracts_version = CONTRACTS_VERSION
    contract_names = [
        "Utils",
        "SecretRegistry",
        "TokenNetworkRegistry",
        "TokenNetwork",
        "MonitoringService",
        "ServiceRegistry",
    ]

    manager = ContractManager(contracts_precompiled_path(contracts_version))
    assert manager.contracts_version == contracts_version
    check_precompiled_content(manager, contract_names, PRECOMPILED_DATA_FIELDS)

    for _, source_path in contracts_source_path().items():
        assert source_path.exists()
    assert contracts_precompiled_path().exists()

    # deployment files exist
    assert contracts_deployed_path(NETWORKNAME_TO_ID["rinkeby"]).exists()
    assert contracts_deployed_path(NETWORKNAME_TO_ID["ropsten"]).exists()
    assert contracts_deployed_path(NETWORKNAME_TO_ID["kovan"]).exists()
    # deployment files for service contracts also exist
    assert contracts_deployed_path(NETWORKNAME_TO_ID["rinkeby"],
                                   services=True).exists()
    assert contracts_deployed_path(NETWORKNAME_TO_ID["ropsten"],
                                   services=True).exists()
    assert contracts_deployed_path(NETWORKNAME_TO_ID["kovan"],
                                   services=True).exists()
Esempio n. 4
0
def test_pre_limits_version():
    manager = ContractManager(contracts_precompiled_path('pre_limits'))
    assert manager.contracts_version == '0.3._'
    assert contracts_precompiled_path('pre_limits').exists()
    assert contracts_deployed_path(NETWORKNAME_TO_ID['rinkeby'], 'pre_limits').exists()
    assert contracts_deployed_path(NETWORKNAME_TO_ID['ropsten'], 'pre_limits').exists()
    assert contracts_deployed_path(NETWORKNAME_TO_ID['kovan'], 'pre_limits').exists()
def test_pre_limits_version():
    """ contracts_source_path('0.3._') exists and contains the expected files """
    contracts_version = '0.3._'
    manager = ContractManager(contracts_precompiled_path(contracts_version))
    assert manager.contracts_version == contracts_version
    assert contracts_precompiled_path(contracts_version).exists()
    assert contracts_deployed_path(NETWORKNAME_TO_ID['rinkeby'], contracts_version).exists()
    assert contracts_deployed_path(NETWORKNAME_TO_ID['ropsten'], contracts_version).exists()
    assert contracts_deployed_path(NETWORKNAME_TO_ID['kovan'], contracts_version).exists()
Esempio n. 6
0
def transact_call(key, data):
    rpc_client = data["client"]
    contract_manager = ContractManager(contracts_precompiled_path())

    action, contract = TRANSACT_ACTIONS[key]

    log.debug("Fetching ABI..", contract=contract)
    contract_abi = contract_manager.get_contract_abi(contract)
    log.debug(
        "Fetching contract proxy",
        contract=contract,
        abi=contract_abi,
        contract_address=data["contract_address"],
    )

    contract_proxy = rpc_client.new_contract_proxy(contract_abi,
                                                   data["contract_address"])

    log.debug("Transacting..", **data)

    args = data["amount"], data["target_address"]
    if action != "mintFor":
        # The deposit function expects the address first, amount second.
        args = (data["target_address"], data["amount"])

    return contract_proxy.transact(action, data["gas_limit"], *args)
def verify(ctx, rpc_provider, contracts_version):
    web3 = Web3(HTTPProvider(rpc_provider, request_kwargs={'timeout': 60}))
    web3.middleware_stack.inject(geth_poa_middleware, layer=0)
    print('Web3 provider is', web3.providers[0])

    contract_manager = ContractManager(contracts_precompiled_path(contracts_version))
    verify_deployed_contracts(web3, contract_manager)
Esempio n. 8
0
def test_deprecation_immediate_payout(create_account: Callable,
                                      custom_token: Contract,
                                      service_registry: Contract,
                                      web3: Web3) -> None:
    """When the deprecation switch is on, deposits can be withdrawn immediately."""
    # A user makes a deposit
    A = create_account()
    minted = service_registry.functions.currentPrice().call()
    call_and_transact(custom_token.functions.mint(minted), {"from": A})
    call_and_transact(
        custom_token.functions.approve(service_registry.address, minted),
        {"from": A})
    deposit_tx = call_and_transact(service_registry.functions.deposit(minted),
                                   {"from": A})
    # The user obtains the deposit address
    deposit_tx_receipt = web3.eth.get_transaction_receipt(deposit_tx)
    contract_manager = ContractManager(
        contracts_precompiled_path(version=None))
    event_abi = contract_manager.get_event_abi(CONTRACT_SERVICE_REGISTRY,
                                               EVENT_REGISTERED_SERVICE)
    event_data = get_event_data(web3.codec, event_abi,
                                deposit_tx_receipt["logs"][-1])
    deposit_address = event_data["args"]["deposit_contract"]
    # And obtains the Deposit contract instance
    deposit_abi = contract_manager.get_contract_abi(CONTRACT_DEPOSIT)
    deposit = web3.eth.contract(abi=deposit_abi, address=deposit_address)
    # The controller turns on the deprecation switch
    call_and_transact(service_registry.functions.setDeprecationSwitch(),
                      {"from": DEPLOYER_ADDRESS})
    # The user successfully withdraws the deposit
    call_and_transact(deposit.functions.withdraw(A), {"from": A})
    # The user has all the balance it has minted
    assert minted == custom_token.functions.balanceOf(A).call()
    # The Deposit contract has destroyed itself
    assert web3.eth.get_code(deposit.address) == HexBytes("0x")
def _verify_singleton_contract(
    chain_id: ChainID, apikey: str, source_module: DeploymentModule, contract_name: str,
) -> None:
    """ Calls Etherscan API for verifying the Solidity source of a contract.

    This function can only be used to verify contracts which are only deployed
    once. E.g. `TokenNetworkRegistry`, but not `TokenNetwork`.
    Args:
        chain_id: EIP-155 chain id of the Ethereum chain
        apikey: key for calling Etherscan API
        source_module: a module name to look up contracts_source_path()
        contract_name: 'TokenNetworkRegistry', 'SecretRegistry' etc.
    """

    deployment_info = get_contracts_deployment_info(chain_id=chain_id, module=source_module)
    assert deployment_info
    contract_manager = ContractManager(contracts_precompiled_path())
    metadata = json.loads(contract_manager.contracts[contract_name]["metadata"])
    constructor_args = get_constructor_args(
        deployment_info=deployment_info,
        contract_name=contract_name,
        contract_manager=contract_manager,
    )
    contract_deploy_info = deployment_info["contracts"][contract_name]
    etherscan_verify_contract(
        chain_id=chain_id,
        apikey=apikey,
        address=contract_deploy_info["address"],
        contract_name=contract_name,
        metadata=metadata,
        constructor_args=constructor_args,
    )
Esempio n. 10
0
def test_store_and_verify_raiden(fs_reload_deployer, web3):
    """ Store some raiden contract deployment information and verify them """
    fs_reload_deployer.add_real_directory(
        contracts_precompiled_path(version=None, ).parent)
    gas_limit = 5860000
    deployer = ContractDeployer(
        web3=web3,
        private_key=FAUCET_PRIVATE_KEY,
        gas_limit=gas_limit,
        gas_price=1,
        wait=10,
        contracts_version=None,
    )
    deployed_contracts_info = deploy_raiden_contracts(
        deployer=deployer,
        max_num_of_token_networks=30,
    )
    store_and_verify_deployment_info_raiden(
        contracts_version=None,
        deployer=deployer,
        deployed_contracts_info=deployed_contracts_info,
        save_info=False,
    )
    store_and_verify_deployment_info_raiden(
        contracts_version=None,
        deployer=deployer,
        deployed_contracts_info=deployed_contracts_info,
        save_info=True,
    )
Esempio n. 11
0
def setup_contracts_or_exit(config: Dict[str, Any],
                            network_id: int) -> Dict[str, Any]:
    """Sets the contract deployment data depending on the network id and environment type

    If an invalid combination of network id and environment type is provided, exits
    the program with an error
    """
    environment_type = config["environment_type"]

    check_raiden_environment(network_id, environment_type)

    contracts: Dict[str, Any] = dict()
    contracts_version = environment_type_to_contracts_version(environment_type)

    config["contracts_path"] = contracts_precompiled_path(contracts_version)

    if network_id in ID_TO_NETWORKNAME and ID_TO_NETWORKNAME[
            network_id] != "smoketest":
        deployment_data = get_contracts_deployment_info(
            chain_id=network_id, version=contracts_version)
        if not deployment_data:
            return contracts

        contracts = deployment_data["contracts"]

    return contracts
Esempio n. 12
0
def _verify_token_networks(chain_id: ChainID, apikey: str) -> None:
    deployment_file_path = contracts_deployed_path(chain_id=chain_id)
    with deployment_file_path.open() as f:
        deployed_contracts_info = json.load(f)
    token_networks = deployed_contracts_info.get("token_networks", [])

    with open(contracts_precompiled_path()) as f:
        contract_dict = json.load(f)["contracts"][CONTRACT_TOKEN_NETWORK]
    metadata = json.loads(contract_dict["metadata"])
    constructor = [
        func for func in contract_dict["abi"] if func["type"] == "constructor"
    ][0]
    arg_types = [arg["type"] for arg in constructor["inputs"]]
    arg_names = [arg["name"] for arg in constructor["inputs"]]

    for tn in token_networks:
        args = [
            tn["constructor_arguments"][arg_name] for arg_name in arg_names
        ]
        etherscan_verify_contract(
            chain_id=chain_id,
            apikey=apikey,
            address=tn["token_network_address"],
            contract_name=CONTRACT_TOKEN_NETWORK,
            metadata=metadata,
            constructor_args=encode_abi(arg_types, args).hex(),
        )
    def __init__(
        self,
        web3: Web3,
        private_key: str,
        gas_limit: int,
        gas_price: int = 1,
        wait: int = 10,
        contracts_version: Optional[str] = None,
    ):
        self.web3 = web3
        self.private_key = private_key
        self.wait = wait
        self.owner = private_key_to_address(private_key)
        self.transaction = {'from': self.owner, 'gas_limit': gas_limit}
        if gas_price != 0:
            self.transaction['gasPrice'] = gas_price * denoms.gwei

        self.contracts_version = contracts_version
        self.precompiled_path = contracts_precompiled_path(
            self.contracts_version)
        self.contract_manager = ContractManager(self.precompiled_path)

        # Check that the precompiled data is correct
        self.contract_manager = ContractManager(contracts_source_path())
        self.contract_manager.checksum_contracts()
        self.contract_manager.verify_precompiled_checksums(
            self.precompiled_path)
Esempio n. 14
0
def test_setURL(custom_token: Contract, service_registry: Contract,
                get_accounts: Callable, web3: Web3) -> None:
    """A ServiceRegistry allows registered service providers to set their URLs"""
    (A, ) = get_accounts(1)
    url1 = "http://example.com"
    url2 = "http://raiden.example.com"

    call_and_transact(custom_token.functions.mint(SERVICE_DEPOSIT),
                      {"from": A})
    call_and_transact(
        custom_token.functions.approve(service_registry.address,
                                       SERVICE_DEPOSIT),
        {"from": A},
    )
    tx = call_and_transact(service_registry.functions.deposit(SERVICE_DEPOSIT),
                           {"from": A})
    tx_receipt = web3.eth.get_transaction_receipt(tx)
    contract_manager = ContractManager(
        contracts_precompiled_path(version=None))
    event_abi = contract_manager.get_event_abi(CONTRACT_SERVICE_REGISTRY,
                                               EVENT_REGISTERED_SERVICE)
    event_data = get_event_data(web3.codec, event_abi, tx_receipt["logs"][-1])
    assert event_data["args"]["service"] == A
    assert event_data["args"]["deposit_contract"] != EMPTY_ADDRESS

    call_and_transact(service_registry.functions.setURL(url1), {"from": A})
    assert service_registry.functions.urls(A).call() == url1

    call_and_transact(service_registry.functions.setURL(url2), {"from": A})
    assert service_registry.functions.urls(A).call() == url2
Esempio n. 15
0
    def __init__(
        self,
        web3: Web3,
        private_key: str,
        gas_limit: int,
        gas_price: int=1,
        wait: int=10,
        contracts_version: Optional[str]=None,
    ):
        self.web3 = web3
        self.wait = wait
        self.owner = private_key_to_address(private_key)
        self.transaction = {'from': self.owner, 'gas': gas_limit}
        if gas_price != 0:
            self.transaction['gasPrice'] = gas_price * denoms.gwei

        self.contracts_version = contracts_version
        self.precompiled_path = contracts_precompiled_path(self.contracts_version)
        self.contract_manager = ContractManager(self.precompiled_path)
        self.web3.middleware_stack.add(
            construct_sign_and_send_raw_middleware(private_key),
        )

        # Check that the precompiled data matches the source code
        # Only for current version, because this is the only one with source code
        if self.contracts_version in [None, CONTRACTS_VERSION]:
            contract_manager_source = ContractManager(contracts_source_path())
            contract_manager_source.checksum_contracts()
            contract_manager_source.verify_precompiled_checksums(self.precompiled_path)
        else:
            log.info('Skipped checks against the source code because it is not available.')
Esempio n. 16
0
def test_paths():
    for _, source_path in contracts_source_path().items():
        assert source_path.exists()
    assert contracts_precompiled_path().exists()
    assert contracts_deployed_path(NETWORKNAME_TO_ID['rinkeby']).exists()
    assert contracts_deployed_path(NETWORKNAME_TO_ID['ropsten']).exists()
    assert contracts_deployed_path(NETWORKNAME_TO_ID['kovan']).exists()
Esempio n. 17
0
 def __init__(self, generate_keys=0):
     self.tester = EthereumTester(PyEVMBackend())
     self.web3 = Web3(EthereumTesterProvider(self.tester))
     if generate_keys > 0:
         self.private_keys = [urandom(32) for _ in range(generate_keys)]
         self.accounts = [
             self.tester.add_account(encode_hex(key))
             for key in self.private_keys
         ]
         for account in self.accounts:
             self.tester.send_transaction({
                 "from":
                 self.tester.get_accounts()[0],
                 "to":
                 account,
                 "value":
                 10**21,
                 "gas":
                 21000,
             })
     else:
         self.accounts = self.tester.get_accounts()
     self.contract_manager = ContractManager(
         contracts_precompiled_path(RAIDEN_CONTRACT_VERSION))
     self.name_to_creation_hash: Dict[str, bytes] = dict()
     self.name_to_contract: Dict[str, str] = dict()
Esempio n. 18
0
class RaidenConfig:
    chain_id: ChainID
    environment_type: Environment

    reveal_timeout: BlockTimeout = DEFAULT_REVEAL_TIMEOUT
    settle_timeout: BlockTimeout = DEFAULT_SETTLE_TIMEOUT

    contracts_path: Path = contracts_precompiled_path(RAIDEN_CONTRACT_VERSION)
    database_path: DatabasePath = ":memory:"

    blockchain: BlockchainConfig = BlockchainConfig()
    mediation_fees: MediationFeeConfig = MediationFeeConfig()
    services: ServiceConfig = ServiceConfig()

    transport_type: str = "matrix"
    transport: MatrixTransportConfig = MatrixTransportConfig(
        # None causes fetching from url in raiden.settings.py::DEFAULT_MATRIX_KNOWN_SERVERS
        available_servers=[],
        broadcast_rooms=[DISCOVERY_DEFAULT_ROOM],
        retries_before_backoff=DEFAULT_TRANSPORT_RETRIES_BEFORE_BACKOFF,
        retry_interval_initial=DEFAULT_TRANSPORT_MATRIX_RETRY_INTERVAL_INITIAL,
        retry_interval_max=DEFAULT_TRANSPORT_MATRIX_RETRY_INTERVAL_MAX,
        server=MATRIX_AUTO_SELECT_SERVER,
        sync_timeout=DEFAULT_TRANSPORT_MATRIX_SYNC_TIMEOUT,
    )

    rest_api: RestApiConfig = RestApiConfig()

    shutdown_timeout: int = DEFAULT_SHUTDOWN_TIMEOUT
    unrecoverable_error_should_crash: bool = False

    console: bool = False
    resolver_endpoint: Optional[str] = None

    pfs_config: Optional[PFSConfig] = None
def test_paths():
    """ contracts_source_path() exists and contains the expected files """
    for _, source_path in contracts_source_path().items():
        assert source_path.exists()
    assert contracts_precompiled_path().exists()
    assert contracts_deployed_path(NETWORKNAME_TO_ID['rinkeby']).exists()
    assert contracts_deployed_path(NETWORKNAME_TO_ID['ropsten']).exists()
    assert contracts_deployed_path(NETWORKNAME_TO_ID['kovan']).exists()
Esempio n. 20
0
    def run(self):
        from raiden_contracts.contract_manager import (
            ContractManager,
            contracts_precompiled_path,
            contracts_source_path,
        )

        contract_manager = ContractManager(contracts_source_path())
        contract_manager.compile_contracts(contracts_precompiled_path())
Esempio n. 21
0
 def run(self):
     from raiden_contracts.contract_manager import (
         ContractManager,
         contracts_precompiled_path,
         contracts_source_path,
     )
     manager = ContractManager(contracts_source_path())
     manager.checksum_contracts()
     manager.verify_precompiled_checksums(contracts_precompiled_path())
def test_pre_limits_version() -> None:
    """ contracts_source_path('0.3._') exists and contains the expected files """
    contracts_version = "0.3._"
    contract_names = [
        "Utils",
        "EndpointRegistry",
        "SecretRegistry",
        "TokenNetworkRegistry",
        "TokenNetwork",
    ]

    manager = ContractManager(contracts_precompiled_path(contracts_version))
    assert manager.contracts_version == contracts_version
    check_precompiled_content(manager, contract_names, PRECOMPILED_DATA_FIELDS)

    assert contracts_precompiled_path(contracts_version).exists()
    assert contracts_deployed_path(NETWORKNAME_TO_ID["rinkeby"], contracts_version).exists()
    assert contracts_deployed_path(NETWORKNAME_TO_ID["ropsten"], contracts_version).exists()
Esempio n. 23
0
def get_or_deploy_token(runner: 'ScenarioRunner') -> ContractProxy:
    """ Deploy or reuse  """
    contract_manager = ContractManager(contracts_precompiled_path())
    token_contract = contract_manager.get_contract(CONTRACT_CUSTOM_TOKEN)

    token_config = runner.scenario.get('token', {})
    if not token_config:
        token_config = {}
    address = token_config.get('address')
    reuse = token_config.get('reuse', False)

    token_address_file = runner.data_path.joinpath('token.addr')
    if reuse:
        if address:
            raise ScenarioError(
                'Token settings "address" and "reuse" are mutually exclusive.')
        if token_address_file.exists():
            address = token_address_file.read_text()
    if address:
        check_address_has_code(runner.client, address, 'Token')
        token_ctr = runner.client.new_contract_proxy(token_contract['abi'],
                                                     address)

        log.debug(
            "Reusing token",
            address=to_checksum_address(address),
            name=token_ctr.contract.functions.name().call(),
            symbol=token_ctr.contract.functions.symbol().call(),
        )
        return token_ctr

    token_id = uuid.uuid4()
    now = datetime.now()
    name = token_config.get(
        'name', f"Scenario Test Token {token_id!s} {now:%Y-%m-%dT%H:%M}")
    symbol = token_config.get('symbol', f"T{token_id!s:.3}")
    decimals = token_config.get('decimals', 0)

    log.debug("Deploying token", name=name, symbol=symbol, decimals=decimals)

    token_ctr = runner.client.deploy_solidity_contract(
        'CustomToken',
        contract_manager.contracts,
        constructor_parameters=(0, decimals, name, symbol),
        confirmations=1,
    )
    contract_checksum_address = to_checksum_address(token_ctr.contract_address)
    if reuse:
        token_address_file.write_text(contract_checksum_address)

    log.info(
        "Deployed token",
        address=contract_checksum_address,
        name=name,
        symbol=symbol,
    )
    return token_ctr
Esempio n. 24
0
    def run(self) -> None:  # pylint: disable=no-self-use
        from raiden_contracts.contract_manager import contracts_precompiled_path
        from raiden_contracts.contract_source_manager import (
            ContractSourceManager,
            contracts_source_path,
        )

        contract_manager = ContractSourceManager(contracts_source_path(contracts_version=None))
        contract_manager.compile_contracts(contracts_precompiled_path())
Esempio n. 25
0
def contract_manager(testing_network_id, testing_contracts_version):
    # Keeping this only for documentation purposes if we want to test specific
    # contract versions apart from the last one
    if False:
        contracts_path = contracts_deployed_path(testing_network_id,
                                                 testing_contracts_version)
    else:
        contracts_path = contracts_precompiled_path()
    return ContractManager(contracts_path)
Esempio n. 26
0
def _get_contract(w3: Web3, contract_name: str):
    chain_id = int(w3.net.version)
    manager = ContractManager(contracts_precompiled_path())

    contract_data = get_contracts_deployment_info(chain_id)
    assert contract_data
    address = contract_data["contracts"][contract_name]["address"]

    abi = manager.get_contract_abi(contract_name)
    return w3.eth.contract(abi=abi, address=address)
Esempio n. 27
0
 def __init__(
     self,
     web3: Web3,
     contracts_version: Optional[str] = None,
 ):
     self.web3 = web3
     self.contracts_version = contracts_version
     self.precompiled_path = contracts_precompiled_path(
         self.contracts_version)
     self.contract_manager = ContractManager(self.precompiled_path)
Esempio n. 28
0
def get_token_network_registry_contract(w3: Web3):
    chain_id = int(w3.net.version)
    manager = ContractManager(contracts_precompiled_path())

    contract_data = get_contracts_deployment_info(ChainID(chain_id))
    assert contract_data
    address = contract_data["contracts"][CONTRACT_TOKEN_NETWORK_REGISTRY]["address"]

    abi = manager.get_contract_abi(CONTRACT_TOKEN_NETWORK_REGISTRY)
    return w3.eth.contract(abi=abi, address=address)
Esempio n. 29
0
def balance(rpc_url: URI, token_address: str, address: str) -> None:
    token_address = to_checksum_address(token_address)
    address = to_checksum_address(address)
    web3 = Web3(HTTPProvider(rpc_url))
    token_contract = ContractManager(contracts_precompiled_path()).get_contract(
        CONTRACT_CUSTOM_TOKEN
    )
    token_proxy = web3.eth.contract(address=token_address, abi=token_contract["abi"])
    balance = token_proxy.functions.balanceOf(address).call()
    print(f"Balance of the {address} : {balance}")
def test_store_and_verify_raiden(fs_reload_deployer, deployed_raiden_info, deployer):
    """ Store some raiden contract deployment information and verify them """
    fs_reload_deployer.add_real_directory(contracts_precompiled_path(version=None).parent)
    deployed_contracts_info = deployed_raiden_info
    deployer.store_and_verify_deployment_info_raiden(
        deployed_contracts_info=deployed_contracts_info
    )
    deployer.store_and_verify_deployment_info_raiden(
        deployed_contracts_info=deployed_contracts_info
    )
Esempio n. 31
0
def get_or_deploy_token(runner) -> ContractProxy:
    """ Deploy or reuse  """
    contract_manager = ContractManager(contracts_precompiled_path())
    token_contract = contract_manager.get_contract(CONTRACT_CUSTOM_TOKEN)

    token_config = runner.scenario.get('token', {})
    if not token_config:
        token_config = {}
    address = token_config.get('address')
    reuse = token_config.get('reuse', False)

    token_address_file = runner.data_path.joinpath('token.addr')
    if reuse:
        if address:
            raise ScenarioError('Token settings "address" and "reuse" are mutually exclusive.')
        if token_address_file.exists():
            address = token_address_file.read_text()
    if address:
        check_address_has_code(runner.client, address, 'Token')
        token_ctr = runner.client.new_contract_proxy(token_contract['abi'], address)

        log.debug(
            "Reusing token",
            address=to_checksum_address(address),
            name=token_ctr.contract.functions.name().call(),
            symbol=token_ctr.contract.functions.symbol().call(),
        )
        return token_ctr

    token_id = uuid.uuid4()
    now = datetime.now()
    name = token_config.get('name', f"Scenario Test Token {token_id!s} {now:%Y-%m-%dT%H:%M}")
    symbol = token_config.get('symbol', f"T{token_id!s:.3}")
    decimals = token_config.get('decimals', 0)

    log.debug("Deploying token", name=name, symbol=symbol, decimals=decimals)

    token_ctr = runner.client.deploy_solidity_contract(
        'CustomToken',
        contract_manager.contracts,
        constructor_parameters=(0, decimals, name, symbol),
    )
    contract_checksum_address = to_checksum_address(token_ctr.contract_address)
    if reuse:
        token_address_file.write_text(contract_checksum_address)

    log.info(
        "Deployed token",
        address=contract_checksum_address,
        name=name,
        symbol=symbol,
    )
    return token_ctr
Esempio n. 32
0
def contract_manager(environment_type):
    version = None
    if environment_type == Environment.DEVELOPMENT:
        version = 'pre_limits'

    return ContractManager(contracts_precompiled_path(version))
Esempio n. 33
0
def run_app(
        address,
        keystore_path,
        gas_price,
        eth_rpc_endpoint,
        tokennetwork_registry_contract_address,
        secret_registry_contract_address,
        endpoint_registry_contract_address,
        listen_address,
        mapped_socket,
        max_unresponsive_time,
        api_address,
        rpc,
        sync_check,
        console,
        password_file,
        web_ui,
        datadir,
        transport,
        matrix_server,
        network_id,
        environment_type,
        unrecoverable_error_should_crash,
        pathfinding_service_address,
        pathfinding_max_paths,
        config=None,
        extra_config=None,
        **kwargs,
):
    # pylint: disable=too-many-locals,too-many-branches,too-many-statements,unused-argument

    from raiden.app import App

    _assert_sql_version()

    if transport == 'udp' and not mapped_socket:
        raise RuntimeError('Missing socket')

    if datadir is None:
        datadir = os.path.join(os.path.expanduser('~'), '.raiden')

    address_hex = to_normalized_address(address) if address else None
    address_hex, privatekey_bin = prompt_account(address_hex, keystore_path, password_file)
    address = to_canonical_address(address_hex)

    (listen_host, listen_port) = split_endpoint(listen_address)
    (api_host, api_port) = split_endpoint(api_address)

    config['transport']['udp']['host'] = listen_host
    config['transport']['udp']['port'] = listen_port
    config['console'] = console
    config['rpc'] = rpc
    config['web_ui'] = rpc and web_ui
    config['api_host'] = api_host
    config['api_port'] = api_port
    if mapped_socket:
        config['socket'] = mapped_socket.socket
        config['transport']['udp']['external_ip'] = mapped_socket.external_ip
        config['transport']['udp']['external_port'] = mapped_socket.external_port
    config['transport_type'] = transport
    config['transport']['matrix']['server'] = matrix_server
    config['transport']['udp']['nat_keepalive_retries'] = DEFAULT_NAT_KEEPALIVE_RETRIES
    timeout = max_unresponsive_time / DEFAULT_NAT_KEEPALIVE_RETRIES
    config['transport']['udp']['nat_keepalive_timeout'] = timeout
    config['privatekey_hex'] = encode_hex(privatekey_bin)
    config['unrecoverable_error_should_crash'] = unrecoverable_error_should_crash
    config['services']['pathfinding_service_address'] = pathfinding_service_address
    config['services']['pathfinding_max_paths'] = pathfinding_max_paths

    parsed_eth_rpc_endpoint = urlparse(eth_rpc_endpoint)
    if not parsed_eth_rpc_endpoint.scheme:
        eth_rpc_endpoint = f'http://{eth_rpc_endpoint}'

    web3 = _setup_web3(eth_rpc_endpoint)

    rpc_client = JSONRPCClient(
        web3,
        privatekey_bin,
        gas_price_strategy=gas_price,
        block_num_confirmations=DEFAULT_NUMBER_OF_BLOCK_CONFIRMATIONS,
        uses_infura='infura.io' in eth_rpc_endpoint,
    )

    blockchain_service = BlockChainService(
        privatekey_bin=privatekey_bin,
        jsonrpc_client=rpc_client,
        # Not giving the contract manager here, but injecting it later
        # since we first need blockchain service to calculate the network id
    )

    given_network_id = network_id
    node_network_id = blockchain_service.network_id
    known_given_network_id = given_network_id in ID_TO_NETWORKNAME
    known_node_network_id = node_network_id in ID_TO_NETWORKNAME

    if node_network_id != given_network_id:
        if known_given_network_id and known_node_network_id:
            click.secho(
                f"The chosen ethereum network '{ID_TO_NETWORKNAME[given_network_id]}' "
                f"differs from the ethereum client '{ID_TO_NETWORKNAME[node_network_id]}'. "
                "Please update your settings.",
                fg='red',
            )
        else:
            click.secho(
                f"The chosen ethereum network id '{given_network_id}' differs "
                f"from the ethereum client '{node_network_id}'. "
                "Please update your settings.",
                fg='red',
            )
        sys.exit(1)

    config['chain_id'] = given_network_id

    # interpret the provided string argument
    if environment_type == Environment.PRODUCTION:
        # Safe configuration: restrictions for mainnet apply and matrix rooms have to be private
        config['environment_type'] = Environment.PRODUCTION
        config['transport']['matrix']['private_rooms'] = True
    else:
        config['environment_type'] = Environment.DEVELOPMENT

    environment_type = config['environment_type']
    print(f'Raiden is running in {environment_type.value.lower()} mode')

    chain_config = {}
    contract_addresses_known = False
    contracts = dict()
    contracts_version = 'pre_limits' if environment_type == Environment.DEVELOPMENT else None
    config['contracts_path'] = contracts_precompiled_path(contracts_version)
    if node_network_id in ID_TO_NETWORKNAME and ID_TO_NETWORKNAME[node_network_id] != 'smoketest':
        deployment_data = get_contracts_deployed(node_network_id, contracts_version)
        not_allowed = (  # for now we only disallow mainnet with test configuration
            network_id == 1 and
            environment_type == Environment.DEVELOPMENT
        )
        if not_allowed:
            click.secho(
                f'The chosen network ({ID_TO_NETWORKNAME[node_network_id]}) is not a testnet, '
                'but the "development" environment was selected.\n'
                'This is not allowed. Please start again with a safe environment setting '
                '(--environment production).',
                fg='red',
            )
            sys.exit(1)

        contracts = deployment_data['contracts']
        contract_addresses_known = True

    blockchain_service.inject_contract_manager(ContractManager(config['contracts_path']))

    if sync_check:
        check_synced(blockchain_service, known_node_network_id)

    contract_addresses_given = (
        tokennetwork_registry_contract_address is not None and
        secret_registry_contract_address is not None and
        endpoint_registry_contract_address is not None
    )

    if not contract_addresses_given and not contract_addresses_known:
        click.secho(
            f"There are no known contract addresses for network id '{given_network_id}'. "
            "Please provide them on the command line or in the configuration file.",
            fg='red',
        )
        sys.exit(1)

    try:
        token_network_registry = blockchain_service.token_network_registry(
            tokennetwork_registry_contract_address or to_canonical_address(
                contracts[CONTRACT_TOKEN_NETWORK_REGISTRY]['address'],
            ),
        )
    except ContractVersionMismatch as e:
        handle_contract_version_mismatch(e)
    except AddressWithoutCode:
        handle_contract_no_code('token network registry', tokennetwork_registry_contract_address)
    except AddressWrongContract:
        handle_contract_wrong_address(
            'token network registry',
            tokennetwork_registry_contract_address,
        )

    try:
        secret_registry = blockchain_service.secret_registry(
            secret_registry_contract_address or to_canonical_address(
                contracts[CONTRACT_SECRET_REGISTRY]['address'],
            ),
        )
    except ContractVersionMismatch as e:
        handle_contract_version_mismatch(e)
    except AddressWithoutCode:
        handle_contract_no_code('secret registry', secret_registry_contract_address)
    except AddressWrongContract:
        handle_contract_wrong_address('secret registry', secret_registry_contract_address)

    database_path = os.path.join(
        datadir,
        f'node_{pex(address)}',
        f'netid_{given_network_id}',
        f'network_{pex(token_network_registry.address)}',
        f'v{RAIDEN_DB_VERSION}_log.db',
    )
    config['database_path'] = database_path

    print(
        '\nYou are connected to the \'{}\' network and the DB path is: {}'.format(
            ID_TO_NETWORKNAME.get(given_network_id, given_network_id),
            database_path,
        ),
    )

    discovery = None
    if transport == 'udp':
        transport, discovery = _setup_udp(
            config,
            blockchain_service,
            address,
            contracts,
            endpoint_registry_contract_address,
        )
    elif transport == 'matrix':
        transport = _setup_matrix(config)
    else:
        raise RuntimeError(f'Unknown transport type "{transport}" given')

    raiden_event_handler = RaidenEventHandler()
    message_handler = MessageHandler()

    try:
        if 'contracts' in chain_config:
            start_block = chain_config['contracts']['TokenNetworkRegistry']['block_number']
        else:
            start_block = 0

        raiden_app = App(
            config=config,
            chain=blockchain_service,
            query_start_block=start_block,
            default_registry=token_network_registry,
            default_secret_registry=secret_registry,
            transport=transport,
            raiden_event_handler=raiden_event_handler,
            message_handler=message_handler,
            discovery=discovery,
        )
    except RaidenError as e:
        click.secho(f'FATAL: {e}', fg='red')
        sys.exit(1)

    try:
        raiden_app.start()
    except RuntimeError as e:
        click.secho(f'FATAL: {e}', fg='red')
        sys.exit(1)
    except filelock.Timeout:
        name_or_id = ID_TO_NETWORKNAME.get(given_network_id, given_network_id)
        click.secho(
            f'FATAL: Another Raiden instance already running for account {address_hex} on '
            f'network id {name_or_id}',
            fg='red',
        )
        sys.exit(1)

    return raiden_app