Пример #1
0
def setup_agreements_environment():
    consumer_acc = get_consumer_account()
    publisher_acc = get_publisher_account()
    keeper = Keeper.get_instance()

    ddo = get_ddo_sample()
    ddo._did = DID.did({"0": "0x12341234"})
    keeper.did_registry.register(
        ddo.asset_id,
        checksum=Web3Provider.get_web3().toBytes(hexstr=ddo.asset_id),
        url='aquarius:5000',
        account=publisher_acc,
        providers=None)

    registered_ddo = ddo
    asset_id = registered_ddo.asset_id
    service_agreement = ServiceAgreement.from_ddo(ServiceTypes.ASSET_ACCESS,
                                                  ddo)
    agreement_id = ServiceAgreement.create_new_agreement_id()
    price = service_agreement.get_price()
    (lock_cond_id, access_cond_id,
     escrow_cond_id) = service_agreement.generate_agreement_condition_ids(
         agreement_id, asset_id, consumer_acc.address, publisher_acc.address,
         keeper)

    return (
        keeper,
        publisher_acc,
        consumer_acc,
        agreement_id,
        asset_id,
        price,
        service_agreement,
        (lock_cond_id, access_cond_id, escrow_cond_id),
    )
Пример #2
0
def test_did_resolver_library(publisher_account, aquarius):
    did_registry = keeper().did_registry
    checksum_test = Web3.sha3(text='checksum')
    value_test = aquarius.root_url

    did_resolver = DIDResolver(keeper().did_registry)

    sample_ddo_path = get_resource_path('ddo', 'ddo_sample1.json')
    assert sample_ddo_path.exists(), "{} does not exist!".format(
        sample_ddo_path)
    asset1 = DDO(json_filename=sample_ddo_path)
    asset1._did = DID.did({"0": "0x1098098"})
    did_registry.register(asset1.asset_id,
                          checksum_test,
                          url=value_test,
                          account=publisher_account)
    aquarius.publish_asset_ddo(asset1)

    did_resolved = did_resolver.resolve(asset1.did)
    assert did_resolved
    assert did_resolved.did == asset1.did

    with pytest.raises(ValueError):
        did_resolver.resolve(asset1.asset_id)

    aquarius.retire_asset_ddo(asset1.did)
Пример #3
0
def test_creating_ddo_from_scratch():
    # create an empty ddo
    ddo = DDO()
    assert ddo.did is None
    assert ddo.asset_id is None
    assert ddo.created is not None

    did = DID.did({"0": "0x99999999999999999"})
    ddo.assign_did(did)
    assert ddo.did == did

    pub_acc = get_publisher_account()

    ddo.add_service(TEST_SERVICE_TYPE, TEST_SERVICE_URL)

    # add a proof to the first public_key/authentication
    ddo.add_proof('checksum', pub_acc)
    ddo_text_proof = ddo.as_text()
    assert ddo_text_proof

    pub_acc = get_publisher_account()
    assert not ddo.public_keys
    ddo.add_public_key(did, pub_acc.address)
    assert len(ddo.public_keys) == 1
    assert ddo.get_public_key(0) == ddo.public_keys[0]
    with pytest.raises(IndexError):
        ddo.get_public_key(1)

    assert ddo.get_public_key(did) == ddo.public_keys[0]
    assert ddo.get_public_key('0x32233') is None

    assert not ddo.authentications
    ddo.add_authentication(did, '')
    assert len(ddo.authentications) == 1
Пример #4
0
def test_resolve_did(publisher_ocean_instance, metadata):
    # prep ddo
    # metadata = Metadata.get_example()
    publisher = publisher_ocean_instance.main_account
    # happy path
    original_ddo = publisher_ocean_instance.assets.create(metadata, publisher)
    did = original_ddo.did
    ddo = publisher_ocean_instance.assets.resolve(did).as_dictionary()
    original = original_ddo.as_dictionary()
    assert ddo['publicKey'] == original['publicKey']
    assert ddo['authentication'] == original['authentication']
    assert ddo['service']
    assert original['service']
    metadata = ddo['service'][0]['attributes']
    if 'datePublished' in metadata['main']:
        metadata['main'].pop('datePublished')
    assert ddo['service'][0]['attributes']['main']['name'] == \
        original['service'][0]['attributes']['main']['name']
    assert ddo['service'][1] == original['service'][1]

    # Can't resolve unregistered asset
    unregistered_did = DID.did({"0": "0x00112233445566"})
    with pytest.raises(OceanDIDNotFound):
        publisher_ocean_instance.assets.resolve(unregistered_did)

    # Raise error on bad did
    invalid_did = "did:op:0123456789"
    with pytest.raises(OceanDIDNotFound):
        publisher_ocean_instance.assets.resolve(invalid_did)
    publisher_ocean_instance.assets.retire(did)
Пример #5
0
def test_create_ddo(metadata):
    pub_acc = get_publisher_account()
    ddo = DDO()
    ddo.add_service(ServiceTypes.METADATA, 'http://myaquarius.com', values=metadata, index='0')
    checksums = dict()
    for service in ddo.services:
        checksums[str(service.index)] = checksum(service.main)
    ddo.add_proof(checksums, pub_acc)
    did = ddo.assign_did(DID.did(ddo.proof['checksum']))
    ddo.proof['signatureValue'] = Keeper.sign_hash(did_to_id_bytes(did), pub_acc)
    ddo.add_public_key(did, pub_acc.address)
    ddo.add_authentication(did, PUBLIC_KEY_TYPE_RSA)
Пример #6
0
def test_create_did():
    proof = {
        "type": "DDOIntegritySignature",
        "created": "2016-02-08T16:02:20Z",
        "creator": "0x00Bd138aBD70e2F00903268F3Db08f2D25677C9e",
        "signatureValue": "0xc9eeb2b8106e…6abfdc5d1192641b",
        "checksum": {
            "0": "0x52b5c93b82dd9e7ecc3d9fdf4755f7f69a54484941897dc517b4adfe3bbc3377",
            "1": "0x999999952b5c93b82dd9e7ecc3d9fdf4755f7f69a54484941897dc517b4adfe3"
        }
    }
    did = DID.did(proof['checksum'])
    assert did == 'did:op:138fccf336883ae6312c9b8b375745a90be369454080e90985fb3e314ab0df25'
Пример #7
0
def test_get_resolve_url(aquarius, publisher_account):
    register_account = publisher_account
    did_registry = keeper().did_registry
    did = DID.did({"0": "0x1"})
    asset_id = did_to_id(did)
    value_test = aquarius.root_url
    did_resolver = DIDResolver(keeper().did_registry)
    did_registry.register(asset_id,
                          b'test',
                          url=value_test,
                          account=register_account)
    url = did_resolver.get_resolve_url(Web3.toBytes(hexstr=asset_id))
    assert url == value_test
Пример #8
0
def test_did_to_id():
    did = DID.did({"0": "0x123"})
    _id = did_to_id(did)
    assert _id is not None and len(_id) == 64, ''

    test_id = '%s' % secrets.token_hex(32)
    assert did_to_id(f'{OCEAN_PREFIX}{test_id}') == test_id
    assert did_to_id('did:op1:011') == '011'
    assert did_to_id('did:op:0') == '0'
    with pytest.raises(ValueError):
        did_to_id(OCEAN_PREFIX)

    assert did_to_id(f'{OCEAN_PREFIX}AB*&$#') == 'AB', ''
Пример #9
0
def test_publish(client):
    endpoint = BaseURLs.ASSETS_URL + '/publish'
    did = DID.did({"0": str(uuid.uuid4())})
    asset_id = did_to_id(did)
    account = get_provider_account()
    test_urls = ['url 00', 'url 11', 'url 22']
    keeper = keeper_instance()
    urls_json = json.dumps(test_urls)
    asset_id_hash = add_ethereum_prefix_and_hash_msg(asset_id)
    signature = keeper.sign_hash(asset_id_hash, account)
    address = web3().eth.account.recoverHash(asset_id_hash,
                                             signature=signature)
    assert address.lower() == account.address.lower()
    address = keeper.personal_ec_recover(asset_id, signature)
    assert address.lower() == account.address.lower()

    payload = {
        'documentId': asset_id,
        'signature': signature,
        'document': urls_json,
        'publisherAddress': account.address
    }
    post_response = client.post(endpoint,
                                data=json.dumps(payload),
                                content_type='application/json')
    encrypted_url = post_response.data.decode('utf-8')
    assert encrypted_url.startswith('0x')

    # publish using auth token
    signature = generate_token(account)
    payload['signature'] = signature
    did = DID.did({"0": str(uuid.uuid4())})
    asset_id = did_to_id(did)
    payload['documentId'] = add_0x_prefix(asset_id)
    post_response = client.post(endpoint,
                                data=json.dumps(payload),
                                content_type='application/json')
    encrypted_url = post_response.data.decode('utf-8')
    assert encrypted_url.startswith('0x')
Пример #10
0
def get_registered_ddo(account, metadata, service_descriptor, providers=None):
    keeper = keeper_instance()
    aqua = Aquarius('http://localhost:5000')

    ddo = DDO()
    ddo_service_endpoint = aqua.get_service_endpoint()

    metadata_service_desc = ServiceDescriptor.metadata_service_descriptor(
        metadata, ddo_service_endpoint)
    service_descriptors = list([
        ServiceDescriptor.authorization_service_descriptor(
            'http://localhost:12001')
    ])
    service_descriptors.append(service_descriptor)
    service_type = service_descriptor[0]

    service_descriptors = [metadata_service_desc] + service_descriptors

    services = ServiceFactory.build_services(service_descriptors)
    checksums = dict()
    for service in services:
        checksums[str(service.index)] = checksum(service.main)

    # Adding proof to the ddo.
    ddo.add_proof(checksums, account)

    did = ddo.assign_did(DID.did(ddo.proof['checksum']))
    ddo_service_endpoint.replace('{did}', did)
    services[0].set_service_endpoint(ddo_service_endpoint)

    stype_to_service = {s.type: s for s in services}
    _service = stype_to_service[service_type]

    name_to_address = {
        cname: cinst.address
        for cname, cinst in keeper.contract_name_to_instance.items()
    }
    _service.init_conditions_values(did,
                                    contract_name_to_address=name_to_address)
    for service in services:
        ddo.add_service(service)

    ddo.proof['signatureValue'] = keeper.sign_hash(did_to_id_bytes(did),
                                                   account)

    ddo.add_public_key(did, account.address)

    ddo.add_authentication(did, PUBLIC_KEY_TYPE_RSA)

    try:
        _oldddo = aqua.get_asset_ddo(ddo.did)
        if _oldddo:
            aqua.retire_asset_ddo(ddo.did)
    except ValueError:
        pass

    if not plecos.is_valid_dict_local(ddo.metadata):
        print(f'invalid metadata: {plecos.validate_dict_local(ddo.metadata)}')
        assert False, f'invalid metadata: {plecos.validate_dict_local(ddo.metadata)}'

    encrypted_files = do_secret_store_encrypt(
        remove_0x_prefix(ddo.asset_id), json.dumps(metadata['main']['files']),
        account, get_config())

    # only assign if the encryption worked
    if encrypted_files:
        index = 0
        for file in metadata['main']['files']:
            file['index'] = index
            index = index + 1
            del file['url']
        metadata['encryptedFiles'] = encrypted_files

    keeper_instance().did_registry.register(
        ddo.asset_id,
        checksum=web3().toBytes(hexstr=ddo.asset_id),
        url=ddo_service_endpoint,
        account=account,
        providers=providers)

    try:
        aqua.publish_asset_ddo(ddo)
    except Exception as e:
        print(f'error publishing ddo {ddo.did} in Aquarius: {e}')
        raise

    return ddo
Пример #11
0
    def create(self,
               metadata,
               publisher_account,
               service_descriptors=None,
               providers=None,
               use_secret_store=True):
        """
        Register an asset in both the keeper's DIDRegistry (on-chain) and in the Metadata store (
        Aquarius).

        :param metadata: dict conforming to the Metadata accepted by Ocean Protocol.
        :param publisher_account: Account of the publisher registering this asset
        :param service_descriptors: list of ServiceDescriptor tuples of length 2.
            The first item must be one of ServiceTypes and the second
            item is a dict of parameters and values required by the service
        :param providers: list of addresses of providers of this asset (a provider is
            an ethereum account that is authorized to provide asset services)
        :param use_secret_store: bool indicate whether to use the secret store directly for
            encrypting urls (Uses Brizo provider service if set to False)
        :return: DDO instance
        """
        assert isinstance(
            metadata,
            dict), f'Expected metadata of type dict, got {type(metadata)}'
        assert service_descriptors is None or isinstance(service_descriptors, list), \
            f'bad type of `service_descriptors` {type(service_descriptors)}'
        # if not metadata or not Metadata.validate(metadata):
        #     raise OceanInvalidMetadata('Metadata seems invalid. Please make sure'
        #                                ' the required metadata values are filled in.')

        # copy metadata so we don't change the original
        metadata_copy = copy.deepcopy(metadata)
        asset_type = metadata_copy['main']['type']
        assert asset_type in (
            'dataset',
            'algorithm'), f'Invalid/unsupported asset type {asset_type}'

        service_descriptors = service_descriptors or []
        brizo = BrizoProvider.get_brizo()

        services = self._process_service_descriptors(service_descriptors,
                                                     metadata_copy,
                                                     publisher_account)
        stype_to_service = {s.type: s for s in services}
        checksum_dict = dict()
        for service in services:
            checksum_dict[str(service.index)] = checksum(service.main)

        # Create a DDO object
        ddo = DDO()
        # Adding proof to the ddo.
        ddo.add_proof(checksum_dict, publisher_account)

        # Generating the did and adding to the ddo.
        did = ddo.assign_did(DID.did(ddo.proof['checksum']))
        logger.debug(f'Generating new did: {did}')
        # Check if it's already registered first!
        if did in self._get_aquarius().list_assets():
            raise OceanDIDAlreadyExist(
                f'Asset id {did} is already registered to another asset.')

        md_service = stype_to_service[ServiceTypes.METADATA]
        ddo_service_endpoint = md_service.service_endpoint
        if '{did}' in ddo_service_endpoint:
            ddo_service_endpoint = ddo_service_endpoint.replace('{did}', did)
            md_service.set_service_endpoint(ddo_service_endpoint)

        # Populate the ddo services
        ddo.add_service(md_service)
        ddo.add_service(stype_to_service[ServiceTypes.AUTHORIZATION])
        access_service = stype_to_service.get(ServiceTypes.ASSET_ACCESS, None)
        compute_service = stype_to_service.get(ServiceTypes.CLOUD_COMPUTE,
                                               None)

        if access_service:
            access_service.init_conditions_values(
                did, {
                    cname: c.address
                    for cname, c in
                    self._keeper.contract_name_to_instance.items()
                })
            ddo.add_service(access_service)
        if compute_service:
            compute_service.init_conditions_values(
                did, {
                    cname: c.address
                    for cname, c in
                    self._keeper.contract_name_to_instance.items()
                })
            ddo.add_service(compute_service)

        ddo.proof['signatureValue'] = self._keeper.sign_hash(
            add_ethereum_prefix_and_hash_msg(did_to_id_bytes(did)),
            publisher_account)

        # Add public key and authentication
        ddo.add_public_key(did, publisher_account.address)

        ddo.add_authentication(did, PUBLIC_KEY_TYPE_RSA)

        # Setup metadata service
        # First compute files_encrypted
        if metadata_copy['main']['type'] == 'dataset':
            assert metadata_copy['main']['files'], \
                'files is required in the metadata main attributes.'
            logger.debug('Encrypting content urls in the metadata.')
            if not use_secret_store:
                encrypt_endpoint = brizo.get_encrypt_endpoint(self._config)
                files_encrypted = brizo.encrypt_files_dict(
                    metadata_copy['main']['files'], encrypt_endpoint,
                    ddo.asset_id, publisher_account.address,
                    self._keeper.sign_hash(
                        add_ethereum_prefix_and_hash_msg(ddo.asset_id),
                        publisher_account))
            else:
                files_encrypted = self._get_secret_store(publisher_account) \
                    .encrypt_document(
                    did_to_id(did),
                    json.dumps(metadata_copy['main']['files']),
                )

            # only assign if the encryption worked
            if files_encrypted:
                logger.debug(
                    f'Content urls encrypted successfully {files_encrypted}')
                index = 0
                for file in metadata_copy['main']['files']:
                    file['index'] = index
                    index = index + 1
                    del file['url']
                metadata_copy['encryptedFiles'] = files_encrypted
            else:
                raise AssertionError('Encrypting the files failed.')

        # DDO url and `Metadata` service

        logger.debug(f'Generated ddo and services, DID is {ddo.did},'
                     f' metadata service @{ddo_service_endpoint}.')
        response = None

        # register on-chain
        registered_on_chain = self._keeper.did_registry.register(
            ddo.asset_id,
            checksum=Web3Provider.get_web3().toBytes(hexstr=ddo.asset_id),
            url=ddo_service_endpoint,
            account=publisher_account,
            providers=providers)
        if registered_on_chain is False:
            logger.warning(f'Registering {did} on-chain failed.')
            return None
        logger.info(f'Successfully registered DDO (DID={did}) on chain.')
        try:
            # publish the new ddo in ocean-db/Aquarius
            response = self._get_aquarius().publish_asset_ddo(ddo)
            logger.info('Asset/ddo published successfully in aquarius.')
        except ValueError as ve:
            raise ValueError(
                f'Invalid value to publish in the metadata: {str(ve)}')
        except Exception as e:
            logger.error(f'Publish asset in aquarius failed: {str(e)}')
        if not response:
            return None
        return ddo
Пример #12
0
def asset1():
    asset = _get_asset('ddo_sample1.json')
    asset._did = DID.did(asset.proof['checksum'])
    yield asset
    aquarius.retire_all_assets()
Пример #13
0
def get_registered_ddo(account, providers=None):
    keeper = keeper_instance()
    aqua = Aquarius('http://localhost:5000')

    for did in aqua.list_assets():
        aqua.retire_asset_ddo(did)

    metadata = get_sample_ddo()['service'][0]['attributes']
    metadata['main']['files'][0]['checksum'] = str(uuid.uuid4())
    ddo = DDO()
    ddo_service_endpoint = aqua.get_service_endpoint()

    metadata_service_desc = ServiceDescriptor.metadata_service_descriptor(
        metadata, ddo_service_endpoint)

    access_service_attributes = {
        "main": {
            "name": "dataAssetAccessServiceAgreement",
            "creator": account.address,
            "price": metadata[MetadataMain.KEY]['price'],
            "timeout": 3600,
            "datePublished": metadata[MetadataMain.KEY]['dateCreated']
        }
    }

    service_descriptors = [
        ServiceDescriptor.authorization_service_descriptor(
            'http://localhost:12001')
    ]
    service_descriptors += [
        ServiceDescriptor.access_service_descriptor(
            access_service_attributes, 'http://localhost:8030',
            keeper.escrow_access_secretstore_template.address)
    ]

    service_descriptors = [metadata_service_desc] + service_descriptors

    services = ServiceFactory.build_services(service_descriptors)
    checksums = dict()
    for service in services:
        checksums[str(service.index)] = checksum(service.main)

    # Adding proof to the ddo.
    ddo.add_proof(checksums, account)

    did = ddo.assign_did(DID.did(ddo.proof['checksum']))

    stype_to_service = {s.type: s for s in services}
    access_service = stype_to_service[ServiceTypes.ASSET_ACCESS]

    name_to_address = {
        cname: cinst.address
        for cname, cinst in keeper.contract_name_to_instance.items()
    }
    access_service.init_conditions_values(
        did, contract_name_to_address=name_to_address)
    ddo.add_service(access_service)
    for service in services:
        ddo.add_service(service)

    ddo.proof['signatureValue'] = keeper.sign_hash(did_to_id_bytes(did),
                                                   account)

    ddo.add_public_key(did, account.address)

    ddo.add_authentication(did, PUBLIC_KEY_TYPE_RSA)

    encrypted_files = do_secret_store_encrypt(
        remove_0x_prefix(ddo.asset_id), json.dumps(metadata['main']['files']),
        account, get_config())
    _files = metadata['main']['files']
    # only assign if the encryption worked
    if encrypted_files:
        index = 0
        for file in metadata['main']['files']:
            file['index'] = index
            index = index + 1
            del file['url']
        metadata['encryptedFiles'] = encrypted_files

    keeper_instance().did_registry.register(
        ddo.asset_id,
        checksum=web3().toBytes(hexstr=ddo.asset_id),
        url=ddo_service_endpoint,
        account=account,
        providers=providers)
    aqua.publish_asset_ddo(ddo)
    return ddo
Пример #14
0
def test_register_asset(publisher_ocean_instance):
    ocn = publisher_ocean_instance
    ddo_reg = ocn.assets.ddo_registry()
    block = ocn.web3.eth.blockNumber
    alice = get_publisher_wallet()
    bob = get_consumer_wallet()

    def _get_num_assets(_minter):
        dids = [
            add_0x_prefix(did_to_id(a))
            for a in ocn.assets.owner_assets(_minter)
        ]
        dids = [a for a in dids if len(a) == 42]
        return len([
            a for a in dids if DataToken(a).contract_concise.isMinter(_minter)
        ])

    num_assets_owned = _get_num_assets(alice.address)

    original_ddo = create_asset(ocn, alice)
    assert original_ddo, f'create asset failed.'

    # try to resolve new asset
    did = original_ddo.did
    asset_id = original_ddo.asset_id
    log = ddo_reg.get_event_log(ddo_reg.EVENT_METADATA_CREATED, block,
                                asset_id, 30)
    assert log, f'no ddo created event.'

    ddo = wait_for_ddo(ocn, did)
    ddo_dict = ddo.as_dictionary()
    original = original_ddo.as_dictionary()
    assert ddo_dict['publicKey'] == original['publicKey']
    assert ddo_dict['authentication'] == original['authentication']
    assert ddo_dict['service']
    assert original['service']
    metadata = ddo_dict['service'][0]['attributes']
    if 'datePublished' in metadata['main']:
        metadata['main'].pop('datePublished')
    assert ddo_dict['service'][0]['attributes']['main']['name'] == \
        original['service'][0]['attributes']['main']['name']
    assert ddo_dict['service'][1] == original['service'][1]

    # Can't resolve unregistered asset
    unregistered_did = DID.did({"0": "0x00112233445566"})
    with pytest.raises(ValueError):
        ocn.assets.resolve(unregistered_did)

    # Raise error on bad did
    invalid_did = "did:op:0123456789"
    with pytest.raises(ValueError):
        ocn.assets.resolve(invalid_did)

    meta_data_assets = ocn.assets.search('')
    if meta_data_assets:
        print("Currently registered assets:")
        print(meta_data_assets)

    # Publish the metadata
    _ = ddo.metadata['main']['name']
    _name = 'updated name'
    ddo.metadata['main']['name'] = _name
    assert ddo.metadata['main']['name'] == _name
    try:
        ocn.assets.update(ddo, bob)
        assert False, f'this asset update should fail, but did not.'
    except Exception:
        pass

    _ = ocn.assets.update(ddo, alice)
    log = ddo_reg.get_event_log(ddo_reg.EVENT_METADATA_UPDATED, block,
                                asset_id, 30)
    assert log, f'no ddo updated event'
    _asset = wait_for_update(ocn, ddo.did, 'name', _name)
    assert _asset, f'Cannot read asset after update.'
    assert _asset.metadata['main'][
        'name'] == _name, f'updated asset does not have the new updated name !!!'

    assert ocn.assets.owner(
        ddo.did) == alice.address, f'asset owner does not seem correct.'

    assert _get_num_assets(alice.address) == num_assets_owned + 1
Пример #15
0
def asset3():
    asset = _get_asset('ddo_sample3.json')
    asset._did = DID.did(asset.proof['checksum'])
    return asset
Пример #16
0
def test_get_resolve_multiple_urls(publisher_account):
    register_account = publisher_account
    did_registry = keeper().did_registry
    did = DID.did({"0": "0x1"})
    did2 = DID.did({"0": "0x2"})
    did3 = DID.did({"0": "0x3"})
    did4 = DID.did({"0": "0x4"})
    did5 = DID.did({"0": "0x5"})
    did6 = DID.did({"0": "0x6"})
    did7 = DID.did({"0": "0x7"})
    did8 = DID.did({"0": "0x8"})
    did9 = DID.did({"0": "0x9"})
    did10 = DID.did({"0": "0x10"})
    value_test = 'http://localhost:5000'
    value_test2 = 'http://localhost:5001'
    value_test3 = 'http://localhost:5002'
    value_test4 = 'http://localhost:5003'
    value_test5 = 'http://localhost:5004'
    value_test6 = 'http://localhost:5005'
    value_test7 = 'http://localhost:5006'
    value_test8 = 'http://localhost:5007'
    value_test9 = 'http://localhost:5008'
    value_test10 = 'http://localhost:5009'
    did_id = did_to_id(did)
    did_id2 = did_to_id(did2)
    did_id3 = did_to_id(did3)
    did_id4 = did_to_id(did4)
    did_id5 = did_to_id(did5)
    did_id6 = did_to_id(did6)
    did_id7 = did_to_id(did7)
    did_id8 = did_to_id(did8)
    did_id9 = did_to_id(did9)
    did_id10 = did_to_id(did10)
    did_resolver = DIDResolver(keeper().did_registry)
    did_registry.register(did_id,
                          b'test',
                          url=value_test,
                          account=register_account)
    did_registry.register(did_id2,
                          b'test',
                          url=value_test2,
                          account=register_account)
    did_registry.register(did_id3,
                          b'test',
                          url=value_test3,
                          account=register_account)
    did_registry.register(did_id4,
                          b'test',
                          url=value_test4,
                          account=register_account)
    did_registry.register(did_id5,
                          b'test',
                          url=value_test5,
                          account=register_account)
    did_registry.register(did_id6,
                          b'test',
                          url=value_test6,
                          account=register_account)
    did_registry.register(did_id7,
                          b'test',
                          url=value_test7,
                          account=register_account)
    did_registry.register(did_id8,
                          b'test',
                          url=value_test8,
                          account=register_account)
    did_registry.register(did_id9,
                          b'test',
                          url=value_test9,
                          account=register_account)
    did_registry.register(did_id10,
                          b'test',
                          url=value_test10,
                          account=register_account)
    url = did_resolver.get_resolve_url(Web3.toBytes(hexstr=did_id))
    url2 = did_resolver.get_resolve_url(Web3.toBytes(hexstr=did_id2))
    url3 = did_resolver.get_resolve_url(Web3.toBytes(hexstr=did_id3))
    url4 = did_resolver.get_resolve_url(Web3.toBytes(hexstr=did_id4))
    url5 = did_resolver.get_resolve_url(Web3.toBytes(hexstr=did_id5))
    url6 = did_resolver.get_resolve_url(Web3.toBytes(hexstr=did_id6))
    url7 = did_resolver.get_resolve_url(Web3.toBytes(hexstr=did_id7))
    url8 = did_resolver.get_resolve_url(Web3.toBytes(hexstr=did_id8))
    url9 = did_resolver.get_resolve_url(Web3.toBytes(hexstr=did_id9))
    url10 = did_resolver.get_resolve_url(Web3.toBytes(hexstr=did_id10))
    assert url == value_test
    assert url2 == value_test2
    assert url3 == value_test3
    assert url4 == value_test4
    assert url5 == value_test5
    assert url6 == value_test6
    assert url7 == value_test7
    assert url8 == value_test8
    assert url9 == value_test9
    assert url10 == value_test10
Пример #17
0
def test_did():
    assert DID.did({"0": "0x123"}).startswith(OCEAN_PREFIX)
    assert len(DID.did({"0": "0x123"})) - len(OCEAN_PREFIX) == 64
    _id = did_to_id(DID.did({"0": "0x123"}))
    assert not _id.startswith('0x'), 'id portion of did should not have a 0x prefix.'
Пример #18
0
def test_register_asset(publisher_ocean_instance):
    """Test various paths for asset registration."""
    ocn = publisher_ocean_instance
    ddo_reg = ocn.assets.ddo_registry()
    block = ocn.web3.eth.blockNumber
    alice = get_publisher_wallet()
    bob = get_consumer_wallet()

    def _get_num_assets(_minter):
        dids = [
            add_0x_prefix(did_to_id(a))
            for a in ocn.assets.owner_assets(_minter)
        ]
        dids = [a for a in dids if len(a) == 42]
        return len([
            a for a in dids if DataToken(a).contract_concise.isMinter(_minter)
        ])

    num_assets_owned = _get_num_assets(alice.address)

    original_ddo = create_asset(ocn, alice)
    assert original_ddo, "create asset failed."

    # try to resolve new asset
    did = original_ddo.did
    asset_id = original_ddo.asset_id
    log = ddo_reg.get_event_log(ddo_reg.EVENT_METADATA_CREATED, block,
                                asset_id, 30)
    assert log, "no ddo created event."

    ddo = wait_for_ddo(ocn, did)
    assert ddo, "ddo is not found in cache."
    ddo_dict = ddo.as_dictionary()
    original = original_ddo.as_dictionary()
    assert ddo_dict["publicKey"] == original["publicKey"]
    assert ddo_dict["authentication"] == original["authentication"]
    assert ddo_dict["service"]
    assert original["service"]
    metadata = ddo_dict["service"][0]["attributes"]
    if "datePublished" in metadata["main"]:
        metadata["main"].pop("datePublished")
    assert (ddo_dict["service"][0]["attributes"]["main"]["name"] ==
            original["service"][0]["attributes"]["main"]["name"])
    assert ddo_dict["service"][1] == original["service"][1]

    # Can't resolve unregistered asset
    unregistered_did = DID.did({"0": "0x00112233445566"})
    with pytest.raises(ValueError):
        ocn.assets.resolve(unregistered_did)

    # Raise error on bad did
    invalid_did = "did:op:0123456789"
    with pytest.raises(ValueError):
        ocn.assets.resolve(invalid_did)

    meta_data_assets = ocn.assets.search("")
    if meta_data_assets:
        print("Currently registered assets:")
        print(meta_data_assets)

    # Publish the metadata
    _ = ddo.metadata["main"]["name"]
    _name = "updated name"
    ddo.metadata["main"]["name"] = _name
    assert ddo.metadata["main"]["name"] == _name
    with pytest.raises(ValueError):
        ocn.assets.update(ddo, bob)

    _ = ocn.assets.update(ddo, alice)
    log = ddo_reg.get_event_log(ddo_reg.EVENT_METADATA_UPDATED, block,
                                asset_id, 30)
    assert log, "no ddo updated event"
    _asset = wait_for_update(ocn, ddo.did, "name", _name)
    assert _asset, "Cannot read asset after update."
    assert (_asset.metadata["main"]["name"] == _name
            ), "updated asset does not have the new updated name !!!"

    assert (ocn.assets.owner(
        ddo.did) == alice.address), "asset owner does not seem correct."

    assert _get_num_assets(alice.address) == num_assets_owned + 1
Пример #19
0
def get_registered_ddo(account, metadata, service_descriptor):
    aqua = Aquarius('http://localhost:5000')

    ddo = DDO()
    ddo_service_endpoint = aqua.get_service_endpoint()

    # Create new data token contract
    dt_contract = FactoryContract(get_config().factory_address)\
        .create_data_token(account, metadata_url=ddo_service_endpoint)
    if not dt_contract:
        raise AssertionError('Creation of data token contract failed.')

    ddo._other_values = {'dataTokenAddress': dt_contract.address}

    metadata_service_desc = ServiceDescriptor.metadata_service_descriptor(
        metadata, ddo_service_endpoint
    )
    service_descriptors = list(
        [ServiceDescriptor.authorization_service_descriptor('http://localhost:12001')])
    service_descriptors.append(service_descriptor)
    service_type = service_descriptor[0]

    service_descriptors = [metadata_service_desc] + service_descriptors

    services = ServiceFactory.build_services(service_descriptors)
    checksums = dict()
    for service in services:
        checksums[str(service.index)] = checksum(service.main)

    # Adding proof to the ddo.
    ddo.add_proof(checksums, account)

    did = ddo.assign_did(DID.did(ddo.proof['checksum']))
    ddo_service_endpoint.replace('{did}', did)
    services[0].set_service_endpoint(ddo_service_endpoint)

    stype_to_service = {s.type: s for s in services}
    _service = stype_to_service[service_type]

    for service in services:
        ddo.add_service(service)

    # ddo.proof['signatureValue'] = ocean_lib.sign_hash(
    #     did_to_id_bytes(did), account)

    ddo.add_public_key(did, account.address)

    ddo.add_authentication(did, PUBLIC_KEY_TYPE_RSA)

    try:
        _oldddo = aqua.get_asset_ddo(ddo.did)
        if _oldddo:
            aqua.retire_asset_ddo(ddo.did)
    except ValueError:
        pass

    if not plecos.is_valid_dict_local(ddo.metadata):
        print(f'invalid metadata: {plecos.validate_dict_local(ddo.metadata)}')
        assert False, f'invalid metadata: {plecos.validate_dict_local(ddo.metadata)}'

    encrypted_files = do_encrypt(
        json.dumps(metadata['main']['files']),
        account,
    )

    # only assign if the encryption worked
    if encrypted_files:
        index = 0
        for file in metadata['main']['files']:
            file['index'] = index
            index = index + 1
            del file['url']
        metadata['encryptedFiles'] = encrypted_files

    # ddo._other_values
    try:
        aqua.publish_asset_ddo(ddo)
    except Exception as e:
        print(f'error publishing ddo {ddo.did} in Aquarius: {e}')
        raise

    return ddo