Exemplo n.º 1
0
def register_compute_asset():
    # get ocean instance
    config = ExampleConfig.get_config()
    ConfigProvider.set_config(config)
    ocean = Ocean()
    keeper = Keeper.get_instance()

    consumer_account = get_account(0)
    publisher_account = get_account(1)

    # get descriptor for compute service
    compute_descriptor = build_compute_descriptor(ocean)

    # create an asset with compute service
    ddo = ocean.assets.create(example_metadata.metadata,
                              publisher_account,
                              providers=[config.provider_address],
                              use_secret_store=False,
                              service_descriptors=[compute_descriptor])
    event = keeper.did_registry.subscribe_to_event(
        keeper.did_registry.DID_REGISTRY_EVENT_NAME,
        15,
        event_filter={
            '_did': Web3Provider.get_web3().toBytes(hexstr=ddo.asset_id),
            '_owner': publisher_account.address
        },
        wait=True)
    assert event, 'There was a problem registering an asset'
    logging.info(f'Registered asset: did={ddo.did}')

    # buy an asset access
    agreement_id = ocean.compute.order(ddo.did, consumer_account)
    event = keeper.compute_execution_condition.subscribe_condition_fulfilled(
        agreement_id, 15, None, (), wait=True)
    assert event, 'There was a problem creating an agreement'
    logging.info(f'Created asset agreement: agreement_id={agreement_id}')

    # supply metadata describing the algorithm to run against the dataset
    # you can also use an algorithm published as an Ocean asset instead
    algo_meta = AlgorithmMetadata(example_metadata.algo_metadata)

    # whether to publish the algorithm results as an Ocean assets
    output_dict = {
        'publishOutput': False,
        'publishAlgorithmLog': False,
    }

    # start the compute job
    job_id = ocean.compute.start(agreement_id,
                                 consumer_account,
                                 algorithm_meta=algo_meta,
                                 output=output_dict)
    logging.info(f'Started compute job: job_id={job_id}')

    # query operator service for job status
    status = ocean.compute.status(agreement_id, job_id, consumer_account)
    logging.info(f'Job status: {status}')
Exemplo n.º 2
0
def register_asset():
    # make ocean instance
    ConfigProvider.set_config(ExampleConfig.get_config())
    ocn = Ocean()
    account = ([acc for acc in ocn.accounts.list() if acc.password]
               or ocn.accounts.list())[0]
    ddo = ocn.assets.create(Metadata.get_example(), account)

    sleep(ASYNC_DELAY)

    logging.info(
        f'Registered asset: did={ddo.did}, ddo-services={ddo.services}')
    resolved_ddo = ocn.assets.resolve(ddo.did)
    logging.info(
        f'resolved asset ddo: did={resolved_ddo.did}, ddo={resolved_ddo.as_text()}'
    )
Exemplo n.º 3
0
def register_asset():
    # make ocean instance
    ConfigProvider.set_config(ExampleConfig.get_config())
    ocn = Ocean()
    account = get_account(0)
    # account = ([acc for acc in ocn.accounts.list() if acc.password] or ocn.accounts.list())[0]
    ddo = ocn.assets.create(
        example_metadata.metadata,
        account,
        providers=['0xfEF2d5e1670342b9EF22eeeDcb287EC526B48095'])

    sleep(ASYNC_DELAY)

    logging.info(
        f'Registered asset: did={ddo.did}, ddo-services={ddo.services}')
    resolved_ddo = ocn.assets.resolve(ddo.did)
    logging.info(
        f'resolved asset ddo: did={resolved_ddo.did}, ddo={resolved_ddo.as_text()}'
    )
Exemplo n.º 4
0
    def __init__(self, config=None):
        """
        Initialize Ocean class.
           >> # Make a new Ocean instance
           >> ocean = Ocean({...})

        This class provides the main top-level functions in ocean protocol:
         * Publish assets metadata and associated services
            * Each asset is assigned a unique DID and a DID Document (DDO)
            * The DDO contains the asset's services including the metadata
            * The DID is registered on-chain with a URL of the metadata store
              to retrieve the DDO from

            >> ddo = ocean.assets.create(metadata, publisher_account)

         * Discover/Search assets via the current configured metadata store (Aquarius)
            >> assets_list = ocean.assets.search('search text')

         * Purchase asset services by choosing a service agreement from the
           asset's DDO. Purchase goes through the service agreements interface
           and starts by signing a service agreement then sending the signature
           to the publisher's Brizo server via the `purchaseEndpoint` in the service
           definition:

           >> service_def_id = ddo.get_service(ServiceTypes.ASSET_ACCESS).service_definition_id
           >> service_agreement_id = ocean.assets.order(did, service_def_id, consumer_account)

        An instance of Ocean is parameterized by a `Config` instance.

        :param config: Config instance
        """
        # Configuration information for the market is stored in the Config class
        # config = Config(filename=config_file, options_dict=config_dict)
        if config:
            ConfigProvider.set_config(config)

        self._config = ConfigProvider.get_config()
        self._keeper = Keeper.get_instance()
        self._did_resolver = DIDResolver(self._keeper.did_registry)

        # Initialize the public sub-modules
        self.tokens = OceanTokens(self._keeper)
        self.accounts = OceanAccounts(self._keeper, self._config, self.tokens)
        self.secret_store = OceanSecretStore(self._config)
        self.templates = OceanTemplates(
            self._keeper,
            ConfigProvider.get_config()
        )
        self.agreements = self._make_ocean_agreements()
        self.assets = OceanAssets(
            self._keeper,
            self._did_resolver,
            self._make_ocean_agreements(),
            AssetConsumer,
            self._config
        )
        self.services = OceanServices()
        self.ocean_providers = OceanProviders(self._keeper, self._did_resolver, self._config)

        # Verify keeper contracts
        Diagnostics.verify_contracts()
        # Diagnostics.check_deployed_agreement_templates()
        logger.info('Squid Ocean instance initialized: ')
        logger.info(f'\tOther accounts: {sorted([a.address for a in self.accounts.list()])}')
        # logger.info(f'\taquarius: {self._aquarius.url}')
        logger.info(f'\tDIDRegistry @ {self._keeper.did_registry.address}')
Exemplo n.º 5
0
def test_buy_asset(consumer_ocean_instance, publisher_ocean_instance):
    config = ExampleConfig.get_config()
    ConfigProvider.set_config(config)
    keeper = Keeper.get_instance()
    # :TODO: enable the actual SecretStore
    # SecretStoreProvider.set_secret_store_class(SecretStore)
    w3 = Web3Provider.get_web3()
    pub_acc = get_publisher_account(config)

    # Register ddo
    ddo = get_registered_ddo(publisher_ocean_instance, pub_acc)
    assert isinstance(ddo, DDO)
    # ocn here will be used only to publish the asset. Handling the asset by the publisher
    # will be performed by the Brizo server running locally

    cons_ocn = consumer_ocean_instance
    # restore the http client because we want the actual Brizo server to do the work
    # not the BrizoMock.
    # Brizo.set_http_client(requests)
    consumer_account = get_account_from_config(cons_ocn._config, 'parity.address1',
                                               'parity.password1')

    downloads_path_elements = len(
        os.listdir(consumer_ocean_instance._config.downloads_path)) if os.path.exists(
        consumer_ocean_instance._config.downloads_path) else 0
    # sign agreement using the registered asset did above
    service = ddo.get_service(service_type=ServiceTypes.ASSET_ACCESS)
    assert ServiceAgreement.SERVICE_DEFINITION_ID in service.as_dictionary()
    sa = ServiceAgreement.from_service_dict(service.as_dictionary())
    # This will send the purchase request to Brizo which in turn will execute the agreement on-chain
    cons_ocn.accounts.request_tokens(consumer_account, 100)
    agreement_id = cons_ocn.assets.order(
        ddo.did, sa.service_definition_id, consumer_account, auto_consume=True)

    event = keeper.escrow_access_secretstore_template.subscribe_agreement_created(
        agreement_id,
        20,
        log_event(keeper.escrow_access_secretstore_template.AGREEMENT_CREATED_EVENT),
        (),
        wait=True
    )
    assert event, 'no event for EscrowAccessSecretStoreTemplate.AgreementCreated'

    event = keeper.lock_reward_condition.subscribe_condition_fulfilled(
        agreement_id,
        20,
        log_event(keeper.lock_reward_condition.FULFILLED_EVENT),
        (),
        wait=True
    )
    assert event, 'no event for LockRewardCondition.Fulfilled'

    event = keeper.escrow_reward_condition.subscribe_condition_fulfilled(
        agreement_id,
        10,
        log_event(keeper.escrow_reward_condition.FULFILLED_EVENT),
        (),
        wait=True
    )
    assert event, 'no event for EscrowReward.Fulfilled'

    assert w3.toHex(event.args['_agreementId']) == agreement_id
    assert len(os.listdir(config.downloads_path)) == downloads_path_elements + 1

    # decrypt the contentUrls using the publisher account instead of consumer account.
    # if the secret store is working and ACL check is enabled, this should fail
    # since SecretStore decrypt will fail the checkPermissions check
    try:
        cons_ocn.assets.consume(
            agreement_id, ddo.did, service.service_definition_id, pub_acc, config.downloads_path
        )
    except RPCError:
        print('hooray, secret store is working as expected.')
 def __init__(self):
     self.config = Config('config.ini')
     self.COMMAND_SENT_EVENT = 'CarCommandSent'
     ConfigProvider.set_config(self.config)