repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 39
1.84M
| func_code_tokens
listlengths 15
672k
| func_documentation_string
stringlengths 1
47.2k
| func_documentation_tokens
listlengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|---|---|---|
oceanprotocol/squid-py | squid_py/ocean/ocean_assets.py | OceanAssets.create | 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)
:return: DDO instance
"""
assert isinstance(metadata, dict), f'Expected metadata of type dict, got {type(metadata)}'
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)
# Create a DDO object
did = DID.did()
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.')
ddo = DDO(did)
# 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 replace `files` with encrypted `files`
assert metadata_copy['base'][
'files'], 'files is required in the metadata base attributes.'
assert Metadata.validate(metadata), 'metadata seems invalid.'
logger.debug('Encrypting content urls in the metadata.')
brizo = BrizoProvider.get_brizo()
if not use_secret_store:
encrypt_endpoint = brizo.get_encrypt_endpoint(self._config)
files_encrypted = brizo.encrypt_files_dict(
metadata_copy['base']['files'],
encrypt_endpoint,
ddo.asset_id,
publisher_account.address,
self._keeper.sign_hash(ddo.asset_id, publisher_account)
)
else:
files_encrypted = self._get_secret_store(publisher_account) \
.encrypt_document(
did_to_id(did),
json.dumps(metadata_copy['base']['files']),
)
metadata_copy['base']['checksum'] = ddo.generate_checksum(did, metadata)
ddo.add_proof(metadata_copy['base']['checksum'], publisher_account, self._keeper)
# only assign if the encryption worked
if files_encrypted:
logger.info(f'Content urls encrypted successfully {files_encrypted}')
index = 0
for file in metadata_copy['base']['files']:
file['index'] = index
index = index + 1
del file['url']
metadata_copy['base']['encryptedFiles'] = files_encrypted
else:
raise AssertionError('Encrypting the files failed. Make sure the secret store is'
' setup properly in your config file.')
# DDO url and `Metadata` service
ddo_service_endpoint = self._get_aquarius().get_service_endpoint(did)
metadata_service_desc = ServiceDescriptor.metadata_service_descriptor(metadata_copy,
ddo_service_endpoint)
if not service_descriptors:
service_descriptors = [ServiceDescriptor.authorization_service_descriptor(
self._config.secret_store_url)]
brizo = BrizoProvider.get_brizo()
service_descriptors += [ServiceDescriptor.access_service_descriptor(
metadata[MetadataBase.KEY]['price'],
brizo.get_consume_endpoint(self._config),
brizo.get_service_endpoint(self._config),
3600,
self._keeper.escrow_access_secretstore_template.address
)]
else:
service_types = set(map(lambda x: x[0], service_descriptors))
if ServiceTypes.AUTHORIZATION not in service_types:
service_descriptors += [ServiceDescriptor.authorization_service_descriptor(
self._config.secret_store_url)]
else:
brizo = BrizoProvider.get_brizo()
service_descriptors += [ServiceDescriptor.access_service_descriptor(
metadata[MetadataBase.KEY]['price'],
brizo.get_consume_endpoint(self._config),
brizo.get_service_endpoint(self._config),
3600,
self._keeper.escrow_access_secretstore_template.address
)]
# Add all services to ddo
service_descriptors = service_descriptors + [metadata_service_desc]
for service in ServiceFactory.build_services(did, service_descriptors):
ddo.add_service(service)
logger.debug(
f'Generated ddo and services, DID is {ddo.did},'
f' metadata service @{ddo_service_endpoint}, '
f'`Access` service initialize @{ddo.services[0].endpoints.service}.')
response = None
# register on-chain
registered_on_chain = self._keeper.did_registry.register(
did,
checksum=Web3Provider.get_web3().sha3(text=metadata_copy['base']['checksum']),
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'DDO with DID {did} successfully registered on chain.')
try:
# publish the new ddo in ocean-db/Aquarius
response = self._get_aquarius().publish_asset_ddo(ddo)
logger.debug('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 | python | def create(self, metadata, publisher_account,
service_descriptors=None, providers=None,
use_secret_store=True):
assert isinstance(metadata, dict), f'Expected metadata of type dict, got {type(metadata)}'
if not metadata or not Metadata.validate(metadata):
raise OceanInvalidMetadata('Metadata seems invalid. Please make sure'
' the required metadata values are filled in.')
metadata_copy = copy.deepcopy(metadata)
did = DID.did()
logger.debug(f'Generating new did: {did}')
if did in self._get_aquarius().list_assets():
raise OceanDIDAlreadyExist(
f'Asset id {did} is already registered to another asset.')
ddo = DDO(did)
ddo.add_public_key(did, publisher_account.address)
ddo.add_authentication(did, PUBLIC_KEY_TYPE_RSA)
assert metadata_copy['base'][
'files'], 'files is required in the metadata base attributes.'
assert Metadata.validate(metadata), 'metadata seems invalid.'
logger.debug('Encrypting content urls in the metadata.')
brizo = BrizoProvider.get_brizo()
if not use_secret_store:
encrypt_endpoint = brizo.get_encrypt_endpoint(self._config)
files_encrypted = brizo.encrypt_files_dict(
metadata_copy['base']['files'],
encrypt_endpoint,
ddo.asset_id,
publisher_account.address,
self._keeper.sign_hash(ddo.asset_id, publisher_account)
)
else:
files_encrypted = self._get_secret_store(publisher_account) \
.encrypt_document(
did_to_id(did),
json.dumps(metadata_copy['base']['files']),
)
metadata_copy['base']['checksum'] = ddo.generate_checksum(did, metadata)
ddo.add_proof(metadata_copy['base']['checksum'], publisher_account, self._keeper)
if files_encrypted:
logger.info(f'Content urls encrypted successfully {files_encrypted}')
index = 0
for file in metadata_copy['base']['files']:
file['index'] = index
index = index + 1
del file['url']
metadata_copy['base']['encryptedFiles'] = files_encrypted
else:
raise AssertionError('Encrypting the files failed. Make sure the secret store is'
' setup properly in your config file.')
ddo_service_endpoint = self._get_aquarius().get_service_endpoint(did)
metadata_service_desc = ServiceDescriptor.metadata_service_descriptor(metadata_copy,
ddo_service_endpoint)
if not service_descriptors:
service_descriptors = [ServiceDescriptor.authorization_service_descriptor(
self._config.secret_store_url)]
brizo = BrizoProvider.get_brizo()
service_descriptors += [ServiceDescriptor.access_service_descriptor(
metadata[MetadataBase.KEY]['price'],
brizo.get_consume_endpoint(self._config),
brizo.get_service_endpoint(self._config),
3600,
self._keeper.escrow_access_secretstore_template.address
)]
else:
service_types = set(map(lambda x: x[0], service_descriptors))
if ServiceTypes.AUTHORIZATION not in service_types:
service_descriptors += [ServiceDescriptor.authorization_service_descriptor(
self._config.secret_store_url)]
else:
brizo = BrizoProvider.get_brizo()
service_descriptors += [ServiceDescriptor.access_service_descriptor(
metadata[MetadataBase.KEY]['price'],
brizo.get_consume_endpoint(self._config),
brizo.get_service_endpoint(self._config),
3600,
self._keeper.escrow_access_secretstore_template.address
)]
service_descriptors = service_descriptors + [metadata_service_desc]
for service in ServiceFactory.build_services(did, service_descriptors):
ddo.add_service(service)
logger.debug(
f'Generated ddo and services, DID is {ddo.did},'
f' metadata service @{ddo_service_endpoint}, '
f'`Access` service initialize @{ddo.services[0].endpoints.service}.')
response = None
registered_on_chain = self._keeper.did_registry.register(
did,
checksum=Web3Provider.get_web3().sha3(text=metadata_copy['base']['checksum']),
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'DDO with DID {did} successfully registered on chain.')
try:
response = self._get_aquarius().publish_asset_ddo(ddo)
logger.debug('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 | [
"def",
"create",
"(",
"self",
",",
"metadata",
",",
"publisher_account",
",",
"service_descriptors",
"=",
"None",
",",
"providers",
"=",
"None",
",",
"use_secret_store",
"=",
"True",
")",
":",
"assert",
"isinstance",
"(",
"metadata",
",",
"dict",
")",
",",
"f'Expected metadata of type dict, got {type(metadata)}'",
"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",
")",
"# Create a DDO object",
"did",
"=",
"DID",
".",
"did",
"(",
")",
"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.'",
")",
"ddo",
"=",
"DDO",
"(",
"did",
")",
"# 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 replace `files` with encrypted `files`",
"assert",
"metadata_copy",
"[",
"'base'",
"]",
"[",
"'files'",
"]",
",",
"'files is required in the metadata base attributes.'",
"assert",
"Metadata",
".",
"validate",
"(",
"metadata",
")",
",",
"'metadata seems invalid.'",
"logger",
".",
"debug",
"(",
"'Encrypting content urls in the metadata.'",
")",
"brizo",
"=",
"BrizoProvider",
".",
"get_brizo",
"(",
")",
"if",
"not",
"use_secret_store",
":",
"encrypt_endpoint",
"=",
"brizo",
".",
"get_encrypt_endpoint",
"(",
"self",
".",
"_config",
")",
"files_encrypted",
"=",
"brizo",
".",
"encrypt_files_dict",
"(",
"metadata_copy",
"[",
"'base'",
"]",
"[",
"'files'",
"]",
",",
"encrypt_endpoint",
",",
"ddo",
".",
"asset_id",
",",
"publisher_account",
".",
"address",
",",
"self",
".",
"_keeper",
".",
"sign_hash",
"(",
"ddo",
".",
"asset_id",
",",
"publisher_account",
")",
")",
"else",
":",
"files_encrypted",
"=",
"self",
".",
"_get_secret_store",
"(",
"publisher_account",
")",
".",
"encrypt_document",
"(",
"did_to_id",
"(",
"did",
")",
",",
"json",
".",
"dumps",
"(",
"metadata_copy",
"[",
"'base'",
"]",
"[",
"'files'",
"]",
")",
",",
")",
"metadata_copy",
"[",
"'base'",
"]",
"[",
"'checksum'",
"]",
"=",
"ddo",
".",
"generate_checksum",
"(",
"did",
",",
"metadata",
")",
"ddo",
".",
"add_proof",
"(",
"metadata_copy",
"[",
"'base'",
"]",
"[",
"'checksum'",
"]",
",",
"publisher_account",
",",
"self",
".",
"_keeper",
")",
"# only assign if the encryption worked",
"if",
"files_encrypted",
":",
"logger",
".",
"info",
"(",
"f'Content urls encrypted successfully {files_encrypted}'",
")",
"index",
"=",
"0",
"for",
"file",
"in",
"metadata_copy",
"[",
"'base'",
"]",
"[",
"'files'",
"]",
":",
"file",
"[",
"'index'",
"]",
"=",
"index",
"index",
"=",
"index",
"+",
"1",
"del",
"file",
"[",
"'url'",
"]",
"metadata_copy",
"[",
"'base'",
"]",
"[",
"'encryptedFiles'",
"]",
"=",
"files_encrypted",
"else",
":",
"raise",
"AssertionError",
"(",
"'Encrypting the files failed. Make sure the secret store is'",
"' setup properly in your config file.'",
")",
"# DDO url and `Metadata` service",
"ddo_service_endpoint",
"=",
"self",
".",
"_get_aquarius",
"(",
")",
".",
"get_service_endpoint",
"(",
"did",
")",
"metadata_service_desc",
"=",
"ServiceDescriptor",
".",
"metadata_service_descriptor",
"(",
"metadata_copy",
",",
"ddo_service_endpoint",
")",
"if",
"not",
"service_descriptors",
":",
"service_descriptors",
"=",
"[",
"ServiceDescriptor",
".",
"authorization_service_descriptor",
"(",
"self",
".",
"_config",
".",
"secret_store_url",
")",
"]",
"brizo",
"=",
"BrizoProvider",
".",
"get_brizo",
"(",
")",
"service_descriptors",
"+=",
"[",
"ServiceDescriptor",
".",
"access_service_descriptor",
"(",
"metadata",
"[",
"MetadataBase",
".",
"KEY",
"]",
"[",
"'price'",
"]",
",",
"brizo",
".",
"get_consume_endpoint",
"(",
"self",
".",
"_config",
")",
",",
"brizo",
".",
"get_service_endpoint",
"(",
"self",
".",
"_config",
")",
",",
"3600",
",",
"self",
".",
"_keeper",
".",
"escrow_access_secretstore_template",
".",
"address",
")",
"]",
"else",
":",
"service_types",
"=",
"set",
"(",
"map",
"(",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
",",
"service_descriptors",
")",
")",
"if",
"ServiceTypes",
".",
"AUTHORIZATION",
"not",
"in",
"service_types",
":",
"service_descriptors",
"+=",
"[",
"ServiceDescriptor",
".",
"authorization_service_descriptor",
"(",
"self",
".",
"_config",
".",
"secret_store_url",
")",
"]",
"else",
":",
"brizo",
"=",
"BrizoProvider",
".",
"get_brizo",
"(",
")",
"service_descriptors",
"+=",
"[",
"ServiceDescriptor",
".",
"access_service_descriptor",
"(",
"metadata",
"[",
"MetadataBase",
".",
"KEY",
"]",
"[",
"'price'",
"]",
",",
"brizo",
".",
"get_consume_endpoint",
"(",
"self",
".",
"_config",
")",
",",
"brizo",
".",
"get_service_endpoint",
"(",
"self",
".",
"_config",
")",
",",
"3600",
",",
"self",
".",
"_keeper",
".",
"escrow_access_secretstore_template",
".",
"address",
")",
"]",
"# Add all services to ddo",
"service_descriptors",
"=",
"service_descriptors",
"+",
"[",
"metadata_service_desc",
"]",
"for",
"service",
"in",
"ServiceFactory",
".",
"build_services",
"(",
"did",
",",
"service_descriptors",
")",
":",
"ddo",
".",
"add_service",
"(",
"service",
")",
"logger",
".",
"debug",
"(",
"f'Generated ddo and services, DID is {ddo.did},'",
"f' metadata service @{ddo_service_endpoint}, '",
"f'`Access` service initialize @{ddo.services[0].endpoints.service}.'",
")",
"response",
"=",
"None",
"# register on-chain",
"registered_on_chain",
"=",
"self",
".",
"_keeper",
".",
"did_registry",
".",
"register",
"(",
"did",
",",
"checksum",
"=",
"Web3Provider",
".",
"get_web3",
"(",
")",
".",
"sha3",
"(",
"text",
"=",
"metadata_copy",
"[",
"'base'",
"]",
"[",
"'checksum'",
"]",
")",
",",
"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'DDO with DID {did} successfully registered on chain.'",
")",
"try",
":",
"# publish the new ddo in ocean-db/Aquarius",
"response",
"=",
"self",
".",
"_get_aquarius",
"(",
")",
".",
"publish_asset_ddo",
"(",
"ddo",
")",
"logger",
".",
"debug",
"(",
"'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"
]
| 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)
:return: DDO instance | [
"Register",
"an",
"asset",
"in",
"both",
"the",
"keeper",
"s",
"DIDRegistry",
"(",
"on",
"-",
"chain",
")",
"and",
"in",
"the",
"Metadata",
"store",
"(",
"Aquarius",
")",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_assets.py#L56-L195 |
oceanprotocol/squid-py | squid_py/ocean/ocean_assets.py | OceanAssets.retire | def retire(self, did):
"""
Retire this did of Aquarius
:param did: DID, str
:return: bool
"""
try:
ddo = self.resolve(did)
metadata_service = ddo.find_service_by_type(ServiceTypes.METADATA)
self._get_aquarius(metadata_service.endpoints.service).retire_asset_ddo(did)
return True
except AquariusGenericError as err:
logger.error(err)
return False | python | def retire(self, did):
try:
ddo = self.resolve(did)
metadata_service = ddo.find_service_by_type(ServiceTypes.METADATA)
self._get_aquarius(metadata_service.endpoints.service).retire_asset_ddo(did)
return True
except AquariusGenericError as err:
logger.error(err)
return False | [
"def",
"retire",
"(",
"self",
",",
"did",
")",
":",
"try",
":",
"ddo",
"=",
"self",
".",
"resolve",
"(",
"did",
")",
"metadata_service",
"=",
"ddo",
".",
"find_service_by_type",
"(",
"ServiceTypes",
".",
"METADATA",
")",
"self",
".",
"_get_aquarius",
"(",
"metadata_service",
".",
"endpoints",
".",
"service",
")",
".",
"retire_asset_ddo",
"(",
"did",
")",
"return",
"True",
"except",
"AquariusGenericError",
"as",
"err",
":",
"logger",
".",
"error",
"(",
"err",
")",
"return",
"False"
]
| Retire this did of Aquarius
:param did: DID, str
:return: bool | [
"Retire",
"this",
"did",
"of",
"Aquarius"
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_assets.py#L197-L211 |
oceanprotocol/squid-py | squid_py/ocean/ocean_assets.py | OceanAssets.search | def search(self, text, sort=None, offset=100, page=1, aquarius_url=None):
"""
Search an asset in oceanDB using aquarius.
:param text: String with the value that you are searching
:param sort: Dictionary to choose order base in some value
:param offset: Number of elements shows by page
:param page: Page number
:param aquarius_url: Url of the aquarius where you want to search. If there is not
provided take the default
:return: List of assets that match with the query
"""
assert page >= 1, f'Invalid page value {page}. Required page >= 1.'
logger.info(f'Searching asset containing: {text}')
return [DDO(dictionary=ddo_dict) for ddo_dict in
self._get_aquarius(aquarius_url).text_search(text, sort, offset, page)['results']] | python | def search(self, text, sort=None, offset=100, page=1, aquarius_url=None):
assert page >= 1, f'Invalid page value {page}. Required page >= 1.'
logger.info(f'Searching asset containing: {text}')
return [DDO(dictionary=ddo_dict) for ddo_dict in
self._get_aquarius(aquarius_url).text_search(text, sort, offset, page)['results']] | [
"def",
"search",
"(",
"self",
",",
"text",
",",
"sort",
"=",
"None",
",",
"offset",
"=",
"100",
",",
"page",
"=",
"1",
",",
"aquarius_url",
"=",
"None",
")",
":",
"assert",
"page",
">=",
"1",
",",
"f'Invalid page value {page}. Required page >= 1.'",
"logger",
".",
"info",
"(",
"f'Searching asset containing: {text}'",
")",
"return",
"[",
"DDO",
"(",
"dictionary",
"=",
"ddo_dict",
")",
"for",
"ddo_dict",
"in",
"self",
".",
"_get_aquarius",
"(",
"aquarius_url",
")",
".",
"text_search",
"(",
"text",
",",
"sort",
",",
"offset",
",",
"page",
")",
"[",
"'results'",
"]",
"]"
]
| Search an asset in oceanDB using aquarius.
:param text: String with the value that you are searching
:param sort: Dictionary to choose order base in some value
:param offset: Number of elements shows by page
:param page: Page number
:param aquarius_url: Url of the aquarius where you want to search. If there is not
provided take the default
:return: List of assets that match with the query | [
"Search",
"an",
"asset",
"in",
"oceanDB",
"using",
"aquarius",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_assets.py#L222-L237 |
oceanprotocol/squid-py | squid_py/ocean/ocean_assets.py | OceanAssets.query | def query(self, query, sort=None, offset=100, page=1, aquarius_url=None):
"""
Search an asset in oceanDB using search query.
:param query: dict with query parameters
(e.g.) https://github.com/oceanprotocol/aquarius/blob/develop/docs/for_api_users/API.md
:param sort: Dictionary to choose order base in some value
:param offset: Number of elements shows by page
:param page: Page number
:param aquarius_url: Url of the aquarius where you want to search. If there is not
provided take the default
:return: List of assets that match with the query.
"""
logger.info(f'Searching asset query: {query}')
aquarius = self._get_aquarius(aquarius_url)
return [DDO(dictionary=ddo_dict) for ddo_dict in
aquarius.query_search(query, sort, offset, page)['results']] | python | def query(self, query, sort=None, offset=100, page=1, aquarius_url=None):
logger.info(f'Searching asset query: {query}')
aquarius = self._get_aquarius(aquarius_url)
return [DDO(dictionary=ddo_dict) for ddo_dict in
aquarius.query_search(query, sort, offset, page)['results']] | [
"def",
"query",
"(",
"self",
",",
"query",
",",
"sort",
"=",
"None",
",",
"offset",
"=",
"100",
",",
"page",
"=",
"1",
",",
"aquarius_url",
"=",
"None",
")",
":",
"logger",
".",
"info",
"(",
"f'Searching asset query: {query}'",
")",
"aquarius",
"=",
"self",
".",
"_get_aquarius",
"(",
"aquarius_url",
")",
"return",
"[",
"DDO",
"(",
"dictionary",
"=",
"ddo_dict",
")",
"for",
"ddo_dict",
"in",
"aquarius",
".",
"query_search",
"(",
"query",
",",
"sort",
",",
"offset",
",",
"page",
")",
"[",
"'results'",
"]",
"]"
]
| Search an asset in oceanDB using search query.
:param query: dict with query parameters
(e.g.) https://github.com/oceanprotocol/aquarius/blob/develop/docs/for_api_users/API.md
:param sort: Dictionary to choose order base in some value
:param offset: Number of elements shows by page
:param page: Page number
:param aquarius_url: Url of the aquarius where you want to search. If there is not
provided take the default
:return: List of assets that match with the query. | [
"Search",
"an",
"asset",
"in",
"oceanDB",
"using",
"search",
"query",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_assets.py#L239-L255 |
oceanprotocol/squid-py | squid_py/ocean/ocean_assets.py | OceanAssets.order | def order(self, did, service_definition_id, consumer_account, auto_consume=False):
"""
Sign service agreement.
Sign the service agreement defined in the service section identified
by `service_definition_id` in the ddo and send the signed agreement to the purchase endpoint
associated with this service.
:param did: str starting with the prefix `did:op:` and followed by the asset id which is
a hex str
:param service_definition_id: str the service definition id identifying a specific
service in the DDO (DID document)
:param consumer_account: Account instance of the consumer
:param auto_consume: boolean
:return: tuple(agreement_id, signature) the service agreement id (can be used to query
the keeper-contracts for the status of the service agreement) and signed agreement hash
"""
assert consumer_account.address in self._keeper.accounts, f'Unrecognized consumer ' \
f'address `consumer_account`'
agreement_id, signature = self._agreements.prepare(
did, service_definition_id, consumer_account
)
logger.debug(f'about to request create agreement: {agreement_id}')
self._agreements.send(
did,
agreement_id,
service_definition_id,
signature,
consumer_account,
auto_consume=auto_consume
)
return agreement_id | python | def order(self, did, service_definition_id, consumer_account, auto_consume=False):
assert consumer_account.address in self._keeper.accounts, f'Unrecognized consumer ' \
f'address `consumer_account`'
agreement_id, signature = self._agreements.prepare(
did, service_definition_id, consumer_account
)
logger.debug(f'about to request create agreement: {agreement_id}')
self._agreements.send(
did,
agreement_id,
service_definition_id,
signature,
consumer_account,
auto_consume=auto_consume
)
return agreement_id | [
"def",
"order",
"(",
"self",
",",
"did",
",",
"service_definition_id",
",",
"consumer_account",
",",
"auto_consume",
"=",
"False",
")",
":",
"assert",
"consumer_account",
".",
"address",
"in",
"self",
".",
"_keeper",
".",
"accounts",
",",
"f'Unrecognized consumer '",
"f'address `consumer_account`'",
"agreement_id",
",",
"signature",
"=",
"self",
".",
"_agreements",
".",
"prepare",
"(",
"did",
",",
"service_definition_id",
",",
"consumer_account",
")",
"logger",
".",
"debug",
"(",
"f'about to request create agreement: {agreement_id}'",
")",
"self",
".",
"_agreements",
".",
"send",
"(",
"did",
",",
"agreement_id",
",",
"service_definition_id",
",",
"signature",
",",
"consumer_account",
",",
"auto_consume",
"=",
"auto_consume",
")",
"return",
"agreement_id"
]
| Sign service agreement.
Sign the service agreement defined in the service section identified
by `service_definition_id` in the ddo and send the signed agreement to the purchase endpoint
associated with this service.
:param did: str starting with the prefix `did:op:` and followed by the asset id which is
a hex str
:param service_definition_id: str the service definition id identifying a specific
service in the DDO (DID document)
:param consumer_account: Account instance of the consumer
:param auto_consume: boolean
:return: tuple(agreement_id, signature) the service agreement id (can be used to query
the keeper-contracts for the status of the service agreement) and signed agreement hash | [
"Sign",
"service",
"agreement",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_assets.py#L257-L289 |
oceanprotocol/squid-py | squid_py/ocean/ocean_assets.py | OceanAssets.consume | def consume(self, service_agreement_id, did, service_definition_id, consumer_account,
destination, index=None):
"""
Consume the asset data.
Using the service endpoint defined in the ddo's service pointed to by service_definition_id.
Consumer's permissions is checked implicitly by the secret-store during decryption
of the contentUrls.
The service endpoint is expected to also verify the consumer's permissions to consume this
asset.
This method downloads and saves the asset datafiles to disk.
:param service_agreement_id: str
:param did: DID, str
:param service_definition_id: identifier of the service inside the asset DDO, str
:param consumer_account: Account instance of the consumer
:param destination: str path
:param index: Index of the document that is going to be downloaded, int
:return: str path to saved files
"""
ddo = self.resolve(did)
if index is not None:
assert isinstance(index, int), logger.error('index has to be an integer.')
assert index >= 0, logger.error('index has to be 0 or a positive integer.')
return self._asset_consumer.download(
service_agreement_id,
service_definition_id,
ddo,
consumer_account,
destination,
BrizoProvider.get_brizo(),
self._get_secret_store(consumer_account),
index
) | python | def consume(self, service_agreement_id, did, service_definition_id, consumer_account,
destination, index=None):
ddo = self.resolve(did)
if index is not None:
assert isinstance(index, int), logger.error('index has to be an integer.')
assert index >= 0, logger.error('index has to be 0 or a positive integer.')
return self._asset_consumer.download(
service_agreement_id,
service_definition_id,
ddo,
consumer_account,
destination,
BrizoProvider.get_brizo(),
self._get_secret_store(consumer_account),
index
) | [
"def",
"consume",
"(",
"self",
",",
"service_agreement_id",
",",
"did",
",",
"service_definition_id",
",",
"consumer_account",
",",
"destination",
",",
"index",
"=",
"None",
")",
":",
"ddo",
"=",
"self",
".",
"resolve",
"(",
"did",
")",
"if",
"index",
"is",
"not",
"None",
":",
"assert",
"isinstance",
"(",
"index",
",",
"int",
")",
",",
"logger",
".",
"error",
"(",
"'index has to be an integer.'",
")",
"assert",
"index",
">=",
"0",
",",
"logger",
".",
"error",
"(",
"'index has to be 0 or a positive integer.'",
")",
"return",
"self",
".",
"_asset_consumer",
".",
"download",
"(",
"service_agreement_id",
",",
"service_definition_id",
",",
"ddo",
",",
"consumer_account",
",",
"destination",
",",
"BrizoProvider",
".",
"get_brizo",
"(",
")",
",",
"self",
".",
"_get_secret_store",
"(",
"consumer_account",
")",
",",
"index",
")"
]
| Consume the asset data.
Using the service endpoint defined in the ddo's service pointed to by service_definition_id.
Consumer's permissions is checked implicitly by the secret-store during decryption
of the contentUrls.
The service endpoint is expected to also verify the consumer's permissions to consume this
asset.
This method downloads and saves the asset datafiles to disk.
:param service_agreement_id: str
:param did: DID, str
:param service_definition_id: identifier of the service inside the asset DDO, str
:param consumer_account: Account instance of the consumer
:param destination: str path
:param index: Index of the document that is going to be downloaded, int
:return: str path to saved files | [
"Consume",
"the",
"asset",
"data",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_assets.py#L291-L324 |
oceanprotocol/squid-py | squid_py/ocean/ocean_templates.py | OceanTemplates.propose | def propose(self, template_address, account):
"""
Propose a new template.
:param template_address: Address of the template contract, str
:param account: account proposing the template, Account
:return: bool
"""
try:
proposed = self._keeper.template_manager.propose_template(template_address, account)
return proposed
except ValueError as err:
template_values = self._keeper.template_manager.get_template(template_address)
if not template_values:
logger.warning(f'Propose template failed: {err}')
return False
if template_values.state != 1:
logger.warning(
f'Propose template failed, current state is set to {template_values.state}')
return False
return True | python | def propose(self, template_address, account):
try:
proposed = self._keeper.template_manager.propose_template(template_address, account)
return proposed
except ValueError as err:
template_values = self._keeper.template_manager.get_template(template_address)
if not template_values:
logger.warning(f'Propose template failed: {err}')
return False
if template_values.state != 1:
logger.warning(
f'Propose template failed, current state is set to {template_values.state}')
return False
return True | [
"def",
"propose",
"(",
"self",
",",
"template_address",
",",
"account",
")",
":",
"try",
":",
"proposed",
"=",
"self",
".",
"_keeper",
".",
"template_manager",
".",
"propose_template",
"(",
"template_address",
",",
"account",
")",
"return",
"proposed",
"except",
"ValueError",
"as",
"err",
":",
"template_values",
"=",
"self",
".",
"_keeper",
".",
"template_manager",
".",
"get_template",
"(",
"template_address",
")",
"if",
"not",
"template_values",
":",
"logger",
".",
"warning",
"(",
"f'Propose template failed: {err}'",
")",
"return",
"False",
"if",
"template_values",
".",
"state",
"!=",
"1",
":",
"logger",
".",
"warning",
"(",
"f'Propose template failed, current state is set to {template_values.state}'",
")",
"return",
"False",
"return",
"True"
]
| Propose a new template.
:param template_address: Address of the template contract, str
:param account: account proposing the template, Account
:return: bool | [
"Propose",
"a",
"new",
"template",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_templates.py#L18-L40 |
oceanprotocol/squid-py | squid_py/ocean/ocean_templates.py | OceanTemplates.approve | def approve(self, template_address, account):
"""
Approve a template already proposed. The account needs to be owner of the templateManager
contract to be able of approve the template.
:param template_address: Address of the template contract, str
:param account: account approving the template, Account
:return: bool
"""
try:
approved = self._keeper.template_manager.approve_template(template_address, account)
return approved
except ValueError as err:
template_values = self._keeper.template_manager.get_template(template_address)
if not template_values:
logger.warning(f'Approve template failed: {err}')
return False
if template_values.state == 1:
logger.warning(f'Approve template failed, this template is '
f'currently in "proposed" state.')
return False
if template_values.state == 3:
logger.warning(f'Approve template failed, this template appears to be '
f'revoked.')
return False
if template_values.state == 2:
return True
return False | python | def approve(self, template_address, account):
try:
approved = self._keeper.template_manager.approve_template(template_address, account)
return approved
except ValueError as err:
template_values = self._keeper.template_manager.get_template(template_address)
if not template_values:
logger.warning(f'Approve template failed: {err}')
return False
if template_values.state == 1:
logger.warning(f'Approve template failed, this template is '
f'currently in "proposed" state.')
return False
if template_values.state == 3:
logger.warning(f'Approve template failed, this template appears to be '
f'revoked.')
return False
if template_values.state == 2:
return True
return False | [
"def",
"approve",
"(",
"self",
",",
"template_address",
",",
"account",
")",
":",
"try",
":",
"approved",
"=",
"self",
".",
"_keeper",
".",
"template_manager",
".",
"approve_template",
"(",
"template_address",
",",
"account",
")",
"return",
"approved",
"except",
"ValueError",
"as",
"err",
":",
"template_values",
"=",
"self",
".",
"_keeper",
".",
"template_manager",
".",
"get_template",
"(",
"template_address",
")",
"if",
"not",
"template_values",
":",
"logger",
".",
"warning",
"(",
"f'Approve template failed: {err}'",
")",
"return",
"False",
"if",
"template_values",
".",
"state",
"==",
"1",
":",
"logger",
".",
"warning",
"(",
"f'Approve template failed, this template is '",
"f'currently in \"proposed\" state.'",
")",
"return",
"False",
"if",
"template_values",
".",
"state",
"==",
"3",
":",
"logger",
".",
"warning",
"(",
"f'Approve template failed, this template appears to be '",
"f'revoked.'",
")",
"return",
"False",
"if",
"template_values",
".",
"state",
"==",
"2",
":",
"return",
"True",
"return",
"False"
]
| Approve a template already proposed. The account needs to be owner of the templateManager
contract to be able of approve the template.
:param template_address: Address of the template contract, str
:param account: account approving the template, Account
:return: bool | [
"Approve",
"a",
"template",
"already",
"proposed",
".",
"The",
"account",
"needs",
"to",
"be",
"owner",
"of",
"the",
"templateManager",
"contract",
"to",
"be",
"able",
"of",
"approve",
"the",
"template",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_templates.py#L42-L73 |
oceanprotocol/squid-py | squid_py/ocean/ocean_templates.py | OceanTemplates.revoke | def revoke(self, template_address, account):
"""
Revoke a template already approved. The account needs to be owner of the templateManager
contract to be able of revoke the template.
:param template_address: Address of the template contract, str
:param account: account revoking the template, Account
:return: bool
"""
try:
revoked = self._keeper.template_manager.revoke_template(template_address, account)
return revoked
except ValueError as err:
template_values = self._keeper.template_manager.get_template(template_address)
if not template_values:
logger.warning(f'Cannot revoke template since it does not exist: {err}')
return False
logger.warning(f'Only template admin or owner can revoke a template: {err}')
return False | python | def revoke(self, template_address, account):
try:
revoked = self._keeper.template_manager.revoke_template(template_address, account)
return revoked
except ValueError as err:
template_values = self._keeper.template_manager.get_template(template_address)
if not template_values:
logger.warning(f'Cannot revoke template since it does not exist: {err}')
return False
logger.warning(f'Only template admin or owner can revoke a template: {err}')
return False | [
"def",
"revoke",
"(",
"self",
",",
"template_address",
",",
"account",
")",
":",
"try",
":",
"revoked",
"=",
"self",
".",
"_keeper",
".",
"template_manager",
".",
"revoke_template",
"(",
"template_address",
",",
"account",
")",
"return",
"revoked",
"except",
"ValueError",
"as",
"err",
":",
"template_values",
"=",
"self",
".",
"_keeper",
".",
"template_manager",
".",
"get_template",
"(",
"template_address",
")",
"if",
"not",
"template_values",
":",
"logger",
".",
"warning",
"(",
"f'Cannot revoke template since it does not exist: {err}'",
")",
"return",
"False",
"logger",
".",
"warning",
"(",
"f'Only template admin or owner can revoke a template: {err}'",
")",
"return",
"False"
]
| Revoke a template already approved. The account needs to be owner of the templateManager
contract to be able of revoke the template.
:param template_address: Address of the template contract, str
:param account: account revoking the template, Account
:return: bool | [
"Revoke",
"a",
"template",
"already",
"approved",
".",
"The",
"account",
"needs",
"to",
"be",
"owner",
"of",
"the",
"templateManager",
"contract",
"to",
"be",
"able",
"of",
"revoke",
"the",
"template",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_templates.py#L75-L94 |
oceanprotocol/squid-py | squid_py/agreements/service_agreement.py | ServiceAgreement.get_price | def get_price(self):
"""
Return the price from the conditions parameters.
:return: Int
"""
for cond in self.conditions:
for p in cond.parameters:
if p.name == '_amount':
return p.value | python | def get_price(self):
for cond in self.conditions:
for p in cond.parameters:
if p.name == '_amount':
return p.value | [
"def",
"get_price",
"(",
"self",
")",
":",
"for",
"cond",
"in",
"self",
".",
"conditions",
":",
"for",
"p",
"in",
"cond",
".",
"parameters",
":",
"if",
"p",
".",
"name",
"==",
"'_amount'",
":",
"return",
"p",
".",
"value"
]
| Return the price from the conditions parameters.
:return: Int | [
"Return",
"the",
"price",
"from",
"the",
"conditions",
"parameters",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_agreement.py#L47-L56 |
oceanprotocol/squid-py | squid_py/agreements/service_agreement.py | ServiceAgreement.get_service_agreement_hash | def get_service_agreement_hash(
self, agreement_id, asset_id, consumer_address, publisher_address, keeper):
"""Return the hash of the service agreement values to be signed by a consumer.
:param agreement_id:id of the agreement, hex str
:param asset_id:
:param consumer_address: ethereum account address of consumer, hex str
:param publisher_address: ethereum account address of publisher, hex str
:param keeper:
:return:
"""
agreement_hash = ServiceAgreement.generate_service_agreement_hash(
self.template_id,
self.generate_agreement_condition_ids(
agreement_id, asset_id, consumer_address, publisher_address, keeper),
self.conditions_timelocks,
self.conditions_timeouts,
agreement_id
)
return agreement_hash | python | def get_service_agreement_hash(
self, agreement_id, asset_id, consumer_address, publisher_address, keeper):
agreement_hash = ServiceAgreement.generate_service_agreement_hash(
self.template_id,
self.generate_agreement_condition_ids(
agreement_id, asset_id, consumer_address, publisher_address, keeper),
self.conditions_timelocks,
self.conditions_timeouts,
agreement_id
)
return agreement_hash | [
"def",
"get_service_agreement_hash",
"(",
"self",
",",
"agreement_id",
",",
"asset_id",
",",
"consumer_address",
",",
"publisher_address",
",",
"keeper",
")",
":",
"agreement_hash",
"=",
"ServiceAgreement",
".",
"generate_service_agreement_hash",
"(",
"self",
".",
"template_id",
",",
"self",
".",
"generate_agreement_condition_ids",
"(",
"agreement_id",
",",
"asset_id",
",",
"consumer_address",
",",
"publisher_address",
",",
"keeper",
")",
",",
"self",
".",
"conditions_timelocks",
",",
"self",
".",
"conditions_timeouts",
",",
"agreement_id",
")",
"return",
"agreement_hash"
]
| Return the hash of the service agreement values to be signed by a consumer.
:param agreement_id:id of the agreement, hex str
:param asset_id:
:param consumer_address: ethereum account address of consumer, hex str
:param publisher_address: ethereum account address of publisher, hex str
:param keeper:
:return: | [
"Return",
"the",
"hash",
"of",
"the",
"service",
"agreement",
"values",
"to",
"be",
"signed",
"by",
"a",
"consumer",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_agreement.py#L226-L245 |
oceanprotocol/squid-py | squid_py/config.py | Config.keeper_path | def keeper_path(self):
"""Path where the keeper-contracts artifacts are allocated."""
keeper_path_string = self.get(self._section_name, NAME_KEEPER_PATH)
path = Path(keeper_path_string).expanduser().resolve()
# TODO: Handle the default case and make default empty string
# assert path.exists(), "Can't find the keeper path: {} ({})"..format(keeper_path_string,
# path)
if os.path.exists(path):
pass
elif os.getenv('VIRTUAL_ENV'):
path = os.path.join(os.getenv('VIRTUAL_ENV'), 'artifacts')
else:
path = os.path.join(site.PREFIXES[0], 'artifacts')
return path | python | def keeper_path(self):
keeper_path_string = self.get(self._section_name, NAME_KEEPER_PATH)
path = Path(keeper_path_string).expanduser().resolve()
if os.path.exists(path):
pass
elif os.getenv('VIRTUAL_ENV'):
path = os.path.join(os.getenv('VIRTUAL_ENV'), 'artifacts')
else:
path = os.path.join(site.PREFIXES[0], 'artifacts')
return path | [
"def",
"keeper_path",
"(",
"self",
")",
":",
"keeper_path_string",
"=",
"self",
".",
"get",
"(",
"self",
".",
"_section_name",
",",
"NAME_KEEPER_PATH",
")",
"path",
"=",
"Path",
"(",
"keeper_path_string",
")",
".",
"expanduser",
"(",
")",
".",
"resolve",
"(",
")",
"# TODO: Handle the default case and make default empty string",
"# assert path.exists(), \"Can't find the keeper path: {} ({})\"..format(keeper_path_string,",
"# path)",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"pass",
"elif",
"os",
".",
"getenv",
"(",
"'VIRTUAL_ENV'",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getenv",
"(",
"'VIRTUAL_ENV'",
")",
",",
"'artifacts'",
")",
"else",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"site",
".",
"PREFIXES",
"[",
"0",
"]",
",",
"'artifacts'",
")",
"return",
"path"
]
| Path where the keeper-contracts artifacts are allocated. | [
"Path",
"where",
"the",
"keeper",
"-",
"contracts",
"artifacts",
"are",
"allocated",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/config.py#L116-L129 |
oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO.add_public_key | def add_public_key(self, did, public_key):
"""
Add a public key object to the list of public keys.
:param public_key: Public key, PublicKeyHex
"""
logger.debug(f'Adding public key {public_key} to the did {did}')
self._public_keys.append(
PublicKeyBase(did, **{"owner": public_key, "type": "EthereumECDSAKey"})) | python | def add_public_key(self, did, public_key):
logger.debug(f'Adding public key {public_key} to the did {did}')
self._public_keys.append(
PublicKeyBase(did, **{"owner": public_key, "type": "EthereumECDSAKey"})) | [
"def",
"add_public_key",
"(",
"self",
",",
"did",
",",
"public_key",
")",
":",
"logger",
".",
"debug",
"(",
"f'Adding public key {public_key} to the did {did}'",
")",
"self",
".",
"_public_keys",
".",
"append",
"(",
"PublicKeyBase",
"(",
"did",
",",
"*",
"*",
"{",
"\"owner\"",
":",
"public_key",
",",
"\"type\"",
":",
"\"EthereumECDSAKey\"",
"}",
")",
")"
]
| Add a public key object to the list of public keys.
:param public_key: Public key, PublicKeyHex | [
"Add",
"a",
"public",
"key",
"object",
"to",
"the",
"list",
"of",
"public",
"keys",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L79-L87 |
oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO.add_authentication | def add_authentication(self, public_key, authentication_type=None):
"""
Add a authentication public key id and type to the list of authentications.
:param key_id: Key id, Authentication
:param authentication_type: Authentication type, str
"""
authentication = {}
if public_key:
authentication = {'type': authentication_type, 'publicKey': public_key}
logger.debug(f'Adding authentication {authentication}')
self._authentications.append(authentication) | python | def add_authentication(self, public_key, authentication_type=None):
authentication = {}
if public_key:
authentication = {'type': authentication_type, 'publicKey': public_key}
logger.debug(f'Adding authentication {authentication}')
self._authentications.append(authentication) | [
"def",
"add_authentication",
"(",
"self",
",",
"public_key",
",",
"authentication_type",
"=",
"None",
")",
":",
"authentication",
"=",
"{",
"}",
"if",
"public_key",
":",
"authentication",
"=",
"{",
"'type'",
":",
"authentication_type",
",",
"'publicKey'",
":",
"public_key",
"}",
"logger",
".",
"debug",
"(",
"f'Adding authentication {authentication}'",
")",
"self",
".",
"_authentications",
".",
"append",
"(",
"authentication",
")"
]
| Add a authentication public key id and type to the list of authentications.
:param key_id: Key id, Authentication
:param authentication_type: Authentication type, str | [
"Add",
"a",
"authentication",
"public",
"key",
"id",
"and",
"type",
"to",
"the",
"list",
"of",
"authentications",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L89-L100 |
oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO.add_service | def add_service(self, service_type, service_endpoint=None, values=None):
"""
Add a service to the list of services on the DDO.
:param service_type: Service
:param service_endpoint: Service endpoint, str
:param values: Python dict with serviceDefinitionId, templateId, serviceAgreementContract,
list of conditions and consume endpoint.
"""
if isinstance(service_type, Service):
service = service_type
else:
service = Service(service_endpoint, service_type, values, did=self._did)
logger.debug(f'Adding service with service type {service_type} with did {self._did}')
self._services.append(service) | python | def add_service(self, service_type, service_endpoint=None, values=None):
if isinstance(service_type, Service):
service = service_type
else:
service = Service(service_endpoint, service_type, values, did=self._did)
logger.debug(f'Adding service with service type {service_type} with did {self._did}')
self._services.append(service) | [
"def",
"add_service",
"(",
"self",
",",
"service_type",
",",
"service_endpoint",
"=",
"None",
",",
"values",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"service_type",
",",
"Service",
")",
":",
"service",
"=",
"service_type",
"else",
":",
"service",
"=",
"Service",
"(",
"service_endpoint",
",",
"service_type",
",",
"values",
",",
"did",
"=",
"self",
".",
"_did",
")",
"logger",
".",
"debug",
"(",
"f'Adding service with service type {service_type} with did {self._did}'",
")",
"self",
".",
"_services",
".",
"append",
"(",
"service",
")"
]
| Add a service to the list of services on the DDO.
:param service_type: Service
:param service_endpoint: Service endpoint, str
:param values: Python dict with serviceDefinitionId, templateId, serviceAgreementContract,
list of conditions and consume endpoint. | [
"Add",
"a",
"service",
"to",
"the",
"list",
"of",
"services",
"on",
"the",
"DDO",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L102-L116 |
oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO.as_text | def as_text(self, is_proof=True, is_pretty=False):
"""Return the DDO as a JSON text.
:param if is_proof: if False then do not include the 'proof' element.
:param is_pretty: If True return dictionary in a prettier way, bool
:return: str
"""
data = self.as_dictionary(is_proof)
if is_pretty:
return json.dumps(data, indent=2, separators=(',', ': '))
return json.dumps(data) | python | def as_text(self, is_proof=True, is_pretty=False):
data = self.as_dictionary(is_proof)
if is_pretty:
return json.dumps(data, indent=2, separators=(',', ': '))
return json.dumps(data) | [
"def",
"as_text",
"(",
"self",
",",
"is_proof",
"=",
"True",
",",
"is_pretty",
"=",
"False",
")",
":",
"data",
"=",
"self",
".",
"as_dictionary",
"(",
"is_proof",
")",
"if",
"is_pretty",
":",
"return",
"json",
".",
"dumps",
"(",
"data",
",",
"indent",
"=",
"2",
",",
"separators",
"=",
"(",
"','",
",",
"': '",
")",
")",
"return",
"json",
".",
"dumps",
"(",
"data",
")"
]
| Return the DDO as a JSON text.
:param if is_proof: if False then do not include the 'proof' element.
:param is_pretty: If True return dictionary in a prettier way, bool
:return: str | [
"Return",
"the",
"DDO",
"as",
"a",
"JSON",
"text",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L118-L129 |
oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO.as_dictionary | def as_dictionary(self, is_proof=True):
"""
Return the DDO as a JSON dict.
:param if is_proof: if False then do not include the 'proof' element.
:return: dict
"""
if self._created is None:
self._created = DDO._get_timestamp()
data = {
'@context': DID_DDO_CONTEXT_URL,
'id': self._did,
'created': self._created,
}
if self._public_keys:
values = []
for public_key in self._public_keys:
values.append(public_key.as_dictionary())
data['publicKey'] = values
if self._authentications:
values = []
for authentication in self._authentications:
values.append(authentication)
data['authentication'] = values
if self._services:
values = []
for service in self._services:
values.append(service.as_dictionary())
data['service'] = values
if self._proof and is_proof:
data['proof'] = self._proof
return data | python | def as_dictionary(self, is_proof=True):
if self._created is None:
self._created = DDO._get_timestamp()
data = {
'@context': DID_DDO_CONTEXT_URL,
'id': self._did,
'created': self._created,
}
if self._public_keys:
values = []
for public_key in self._public_keys:
values.append(public_key.as_dictionary())
data['publicKey'] = values
if self._authentications:
values = []
for authentication in self._authentications:
values.append(authentication)
data['authentication'] = values
if self._services:
values = []
for service in self._services:
values.append(service.as_dictionary())
data['service'] = values
if self._proof and is_proof:
data['proof'] = self._proof
return data | [
"def",
"as_dictionary",
"(",
"self",
",",
"is_proof",
"=",
"True",
")",
":",
"if",
"self",
".",
"_created",
"is",
"None",
":",
"self",
".",
"_created",
"=",
"DDO",
".",
"_get_timestamp",
"(",
")",
"data",
"=",
"{",
"'@context'",
":",
"DID_DDO_CONTEXT_URL",
",",
"'id'",
":",
"self",
".",
"_did",
",",
"'created'",
":",
"self",
".",
"_created",
",",
"}",
"if",
"self",
".",
"_public_keys",
":",
"values",
"=",
"[",
"]",
"for",
"public_key",
"in",
"self",
".",
"_public_keys",
":",
"values",
".",
"append",
"(",
"public_key",
".",
"as_dictionary",
"(",
")",
")",
"data",
"[",
"'publicKey'",
"]",
"=",
"values",
"if",
"self",
".",
"_authentications",
":",
"values",
"=",
"[",
"]",
"for",
"authentication",
"in",
"self",
".",
"_authentications",
":",
"values",
".",
"append",
"(",
"authentication",
")",
"data",
"[",
"'authentication'",
"]",
"=",
"values",
"if",
"self",
".",
"_services",
":",
"values",
"=",
"[",
"]",
"for",
"service",
"in",
"self",
".",
"_services",
":",
"values",
".",
"append",
"(",
"service",
".",
"as_dictionary",
"(",
")",
")",
"data",
"[",
"'service'",
"]",
"=",
"values",
"if",
"self",
".",
"_proof",
"and",
"is_proof",
":",
"data",
"[",
"'proof'",
"]",
"=",
"self",
".",
"_proof",
"return",
"data"
]
| Return the DDO as a JSON dict.
:param if is_proof: if False then do not include the 'proof' element.
:return: dict | [
"Return",
"the",
"DDO",
"as",
"a",
"JSON",
"dict",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L131-L164 |
oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO._read_dict | def _read_dict(self, dictionary):
"""Import a JSON dict into this DDO."""
values = dictionary
self._did = values['id']
self._created = values.get('created', None)
if 'publicKey' in values:
self._public_keys = []
for value in values['publicKey']:
if isinstance(value, str):
value = json.loads(value)
self._public_keys.append(DDO.create_public_key_from_json(value))
if 'authentication' in values:
self._authentications = []
for value in values['authentication']:
if isinstance(value, str):
value = json.loads(value)
self._authentications.append(DDO.create_authentication_from_json(value))
if 'service' in values:
self._services = []
for value in values['service']:
if isinstance(value, str):
value = json.loads(value)
service = Service.from_json(value)
service.set_did(self._did)
self._services.append(service)
if 'proof' in values:
self._proof = values['proof'] | python | def _read_dict(self, dictionary):
values = dictionary
self._did = values['id']
self._created = values.get('created', None)
if 'publicKey' in values:
self._public_keys = []
for value in values['publicKey']:
if isinstance(value, str):
value = json.loads(value)
self._public_keys.append(DDO.create_public_key_from_json(value))
if 'authentication' in values:
self._authentications = []
for value in values['authentication']:
if isinstance(value, str):
value = json.loads(value)
self._authentications.append(DDO.create_authentication_from_json(value))
if 'service' in values:
self._services = []
for value in values['service']:
if isinstance(value, str):
value = json.loads(value)
service = Service.from_json(value)
service.set_did(self._did)
self._services.append(service)
if 'proof' in values:
self._proof = values['proof'] | [
"def",
"_read_dict",
"(",
"self",
",",
"dictionary",
")",
":",
"values",
"=",
"dictionary",
"self",
".",
"_did",
"=",
"values",
"[",
"'id'",
"]",
"self",
".",
"_created",
"=",
"values",
".",
"get",
"(",
"'created'",
",",
"None",
")",
"if",
"'publicKey'",
"in",
"values",
":",
"self",
".",
"_public_keys",
"=",
"[",
"]",
"for",
"value",
"in",
"values",
"[",
"'publicKey'",
"]",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"value",
"=",
"json",
".",
"loads",
"(",
"value",
")",
"self",
".",
"_public_keys",
".",
"append",
"(",
"DDO",
".",
"create_public_key_from_json",
"(",
"value",
")",
")",
"if",
"'authentication'",
"in",
"values",
":",
"self",
".",
"_authentications",
"=",
"[",
"]",
"for",
"value",
"in",
"values",
"[",
"'authentication'",
"]",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"value",
"=",
"json",
".",
"loads",
"(",
"value",
")",
"self",
".",
"_authentications",
".",
"append",
"(",
"DDO",
".",
"create_authentication_from_json",
"(",
"value",
")",
")",
"if",
"'service'",
"in",
"values",
":",
"self",
".",
"_services",
"=",
"[",
"]",
"for",
"value",
"in",
"values",
"[",
"'service'",
"]",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"value",
"=",
"json",
".",
"loads",
"(",
"value",
")",
"service",
"=",
"Service",
".",
"from_json",
"(",
"value",
")",
"service",
".",
"set_did",
"(",
"self",
".",
"_did",
")",
"self",
".",
"_services",
".",
"append",
"(",
"service",
")",
"if",
"'proof'",
"in",
"values",
":",
"self",
".",
"_proof",
"=",
"values",
"[",
"'proof'",
"]"
]
| Import a JSON dict into this DDO. | [
"Import",
"a",
"JSON",
"dict",
"into",
"this",
"DDO",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L166-L192 |
oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO.add_proof | def add_proof(self, text, publisher_account, keeper):
"""Add a proof to the DDO, based on the public_key id/index and signed with the private key
add a static proof to the DDO, based on one of the public keys."""
# just incase clear out the current static proof property
self._proof = None
self._proof = {
'type': PROOF_TYPE,
'created': DDO._get_timestamp(),
'creator': publisher_account.address,
'signatureValue': keeper.sign_hash(text, publisher_account),
} | python | def add_proof(self, text, publisher_account, keeper):
self._proof = None
self._proof = {
'type': PROOF_TYPE,
'created': DDO._get_timestamp(),
'creator': publisher_account.address,
'signatureValue': keeper.sign_hash(text, publisher_account),
} | [
"def",
"add_proof",
"(",
"self",
",",
"text",
",",
"publisher_account",
",",
"keeper",
")",
":",
"# just incase clear out the current static proof property",
"self",
".",
"_proof",
"=",
"None",
"self",
".",
"_proof",
"=",
"{",
"'type'",
":",
"PROOF_TYPE",
",",
"'created'",
":",
"DDO",
".",
"_get_timestamp",
"(",
")",
",",
"'creator'",
":",
"publisher_account",
".",
"address",
",",
"'signatureValue'",
":",
"keeper",
".",
"sign_hash",
"(",
"text",
",",
"publisher_account",
")",
",",
"}"
]
| Add a proof to the DDO, based on the public_key id/index and signed with the private key
add a static proof to the DDO, based on one of the public keys. | [
"Add",
"a",
"proof",
"to",
"the",
"DDO",
"based",
"on",
"the",
"public_key",
"id",
"/",
"index",
"and",
"signed",
"with",
"the",
"private",
"key",
"add",
"a",
"static",
"proof",
"to",
"the",
"DDO",
"based",
"on",
"one",
"of",
"the",
"public",
"keys",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L194-L205 |
oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO.get_public_key | def get_public_key(self, key_id, is_search_embedded=False):
"""Key_id can be a string, or int. If int then the index in the list of keys."""
if isinstance(key_id, int):
return self._public_keys[key_id]
for item in self._public_keys:
if item.get_id() == key_id:
return item
if is_search_embedded:
for authentication in self._authentications:
if authentication.get_public_key_id() == key_id:
return authentication.get_public_key()
return None | python | def get_public_key(self, key_id, is_search_embedded=False):
if isinstance(key_id, int):
return self._public_keys[key_id]
for item in self._public_keys:
if item.get_id() == key_id:
return item
if is_search_embedded:
for authentication in self._authentications:
if authentication.get_public_key_id() == key_id:
return authentication.get_public_key()
return None | [
"def",
"get_public_key",
"(",
"self",
",",
"key_id",
",",
"is_search_embedded",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"key_id",
",",
"int",
")",
":",
"return",
"self",
".",
"_public_keys",
"[",
"key_id",
"]",
"for",
"item",
"in",
"self",
".",
"_public_keys",
":",
"if",
"item",
".",
"get_id",
"(",
")",
"==",
"key_id",
":",
"return",
"item",
"if",
"is_search_embedded",
":",
"for",
"authentication",
"in",
"self",
".",
"_authentications",
":",
"if",
"authentication",
".",
"get_public_key_id",
"(",
")",
"==",
"key_id",
":",
"return",
"authentication",
".",
"get_public_key",
"(",
")",
"return",
"None"
]
| Key_id can be a string, or int. If int then the index in the list of keys. | [
"Key_id",
"can",
"be",
"a",
"string",
"or",
"int",
".",
"If",
"int",
"then",
"the",
"index",
"in",
"the",
"list",
"of",
"keys",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L211-L224 |
oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO._get_public_key_count | def _get_public_key_count(self):
"""Return the count of public keys in the list and embedded."""
index = len(self._public_keys)
for authentication in self._authentications:
if authentication.is_public_key():
index += 1
return index | python | def _get_public_key_count(self):
index = len(self._public_keys)
for authentication in self._authentications:
if authentication.is_public_key():
index += 1
return index | [
"def",
"_get_public_key_count",
"(",
"self",
")",
":",
"index",
"=",
"len",
"(",
"self",
".",
"_public_keys",
")",
"for",
"authentication",
"in",
"self",
".",
"_authentications",
":",
"if",
"authentication",
".",
"is_public_key",
"(",
")",
":",
"index",
"+=",
"1",
"return",
"index"
]
| Return the count of public keys in the list and embedded. | [
"Return",
"the",
"count",
"of",
"public",
"keys",
"in",
"the",
"list",
"and",
"embedded",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L226-L232 |
oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO._get_authentication_from_public_key_id | def _get_authentication_from_public_key_id(self, key_id):
"""Return the authentication based on it's id."""
for authentication in self._authentications:
if authentication.is_key_id(key_id):
return authentication
return None | python | def _get_authentication_from_public_key_id(self, key_id):
for authentication in self._authentications:
if authentication.is_key_id(key_id):
return authentication
return None | [
"def",
"_get_authentication_from_public_key_id",
"(",
"self",
",",
"key_id",
")",
":",
"for",
"authentication",
"in",
"self",
".",
"_authentications",
":",
"if",
"authentication",
".",
"is_key_id",
"(",
"key_id",
")",
":",
"return",
"authentication",
"return",
"None"
]
| Return the authentication based on it's id. | [
"Return",
"the",
"authentication",
"based",
"on",
"it",
"s",
"id",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L234-L239 |
oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO.get_service | def get_service(self, service_type=None):
"""Return a service using."""
for service in self._services:
if service.type == service_type and service_type:
return service
return None | python | def get_service(self, service_type=None):
for service in self._services:
if service.type == service_type and service_type:
return service
return None | [
"def",
"get_service",
"(",
"self",
",",
"service_type",
"=",
"None",
")",
":",
"for",
"service",
"in",
"self",
".",
"_services",
":",
"if",
"service",
".",
"type",
"==",
"service_type",
"and",
"service_type",
":",
"return",
"service",
"return",
"None"
]
| Return a service using. | [
"Return",
"a",
"service",
"using",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L241-L246 |
oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO.find_service_by_id | def find_service_by_id(self, service_id):
"""
Get service for a given service_id.
:param service_id: Service id, str
:return: Service
"""
service_id_key = 'serviceDefinitionId'
service_id = str(service_id)
for service in self._services:
if service_id_key in service.values and str(
service.values[service_id_key]) == service_id:
return service
try:
# If service_id is int or can be converted to int then we couldn't find it
int(service_id)
return None
except ValueError:
pass
# try to find by type
return self.find_service_by_type(service_id) | python | def find_service_by_id(self, service_id):
service_id_key = 'serviceDefinitionId'
service_id = str(service_id)
for service in self._services:
if service_id_key in service.values and str(
service.values[service_id_key]) == service_id:
return service
try:
int(service_id)
return None
except ValueError:
pass
return self.find_service_by_type(service_id) | [
"def",
"find_service_by_id",
"(",
"self",
",",
"service_id",
")",
":",
"service_id_key",
"=",
"'serviceDefinitionId'",
"service_id",
"=",
"str",
"(",
"service_id",
")",
"for",
"service",
"in",
"self",
".",
"_services",
":",
"if",
"service_id_key",
"in",
"service",
".",
"values",
"and",
"str",
"(",
"service",
".",
"values",
"[",
"service_id_key",
"]",
")",
"==",
"service_id",
":",
"return",
"service",
"try",
":",
"# If service_id is int or can be converted to int then we couldn't find it",
"int",
"(",
"service_id",
")",
"return",
"None",
"except",
"ValueError",
":",
"pass",
"# try to find by type",
"return",
"self",
".",
"find_service_by_type",
"(",
"service_id",
")"
]
| Get service for a given service_id.
:param service_id: Service id, str
:return: Service | [
"Get",
"service",
"for",
"a",
"given",
"service_id",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L248-L270 |
oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO.find_service_by_type | def find_service_by_type(self, service_type):
"""
Get service for a given service type.
:param service_type: Service type, ServiceType
:return: Service
"""
for service in self._services:
if service_type == service.type:
return service
return None | python | def find_service_by_type(self, service_type):
for service in self._services:
if service_type == service.type:
return service
return None | [
"def",
"find_service_by_type",
"(",
"self",
",",
"service_type",
")",
":",
"for",
"service",
"in",
"self",
".",
"_services",
":",
"if",
"service_type",
"==",
"service",
".",
"type",
":",
"return",
"service",
"return",
"None"
]
| Get service for a given service type.
:param service_type: Service type, ServiceType
:return: Service | [
"Get",
"service",
"for",
"a",
"given",
"service",
"type",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L272-L282 |
oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO.create_public_key_from_json | def create_public_key_from_json(values):
"""Create a public key object based on the values from the JSON record."""
# currently we only support RSA public keys
_id = values.get('id')
if not _id:
# Make it more forgiving for now.
_id = ''
# raise ValueError('publicKey definition is missing the "id" value.')
if values.get('type') == PUBLIC_KEY_TYPE_RSA:
public_key = PublicKeyRSA(_id, owner=values.get('owner'))
else:
public_key = PublicKeyBase(_id, owner=values.get('owner'), type='EthereumECDSAKey')
public_key.set_key_value(values)
return public_key | python | def create_public_key_from_json(values):
_id = values.get('id')
if not _id:
_id = ''
if values.get('type') == PUBLIC_KEY_TYPE_RSA:
public_key = PublicKeyRSA(_id, owner=values.get('owner'))
else:
public_key = PublicKeyBase(_id, owner=values.get('owner'), type='EthereumECDSAKey')
public_key.set_key_value(values)
return public_key | [
"def",
"create_public_key_from_json",
"(",
"values",
")",
":",
"# currently we only support RSA public keys",
"_id",
"=",
"values",
".",
"get",
"(",
"'id'",
")",
"if",
"not",
"_id",
":",
"# Make it more forgiving for now.",
"_id",
"=",
"''",
"# raise ValueError('publicKey definition is missing the \"id\" value.')",
"if",
"values",
".",
"get",
"(",
"'type'",
")",
"==",
"PUBLIC_KEY_TYPE_RSA",
":",
"public_key",
"=",
"PublicKeyRSA",
"(",
"_id",
",",
"owner",
"=",
"values",
".",
"get",
"(",
"'owner'",
")",
")",
"else",
":",
"public_key",
"=",
"PublicKeyBase",
"(",
"_id",
",",
"owner",
"=",
"values",
".",
"get",
"(",
"'owner'",
")",
",",
"type",
"=",
"'EthereumECDSAKey'",
")",
"public_key",
".",
"set_key_value",
"(",
"values",
")",
"return",
"public_key"
]
| Create a public key object based on the values from the JSON record. | [
"Create",
"a",
"public",
"key",
"object",
"based",
"on",
"the",
"values",
"from",
"the",
"JSON",
"record",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L295-L310 |
oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO.create_authentication_from_json | def create_authentication_from_json(values):
"""Create authentitaciton object from a JSON string."""
key_id = values.get('publicKey')
authentication_type = values.get('type')
if not key_id:
raise ValueError(
f'Invalid authentication definition, "publicKey" is missing: {values}')
authentication = {'type': authentication_type, 'publicKey': key_id}
return authentication | python | def create_authentication_from_json(values):
key_id = values.get('publicKey')
authentication_type = values.get('type')
if not key_id:
raise ValueError(
f'Invalid authentication definition, "publicKey" is missing: {values}')
authentication = {'type': authentication_type, 'publicKey': key_id}
return authentication | [
"def",
"create_authentication_from_json",
"(",
"values",
")",
":",
"key_id",
"=",
"values",
".",
"get",
"(",
"'publicKey'",
")",
"authentication_type",
"=",
"values",
".",
"get",
"(",
"'type'",
")",
"if",
"not",
"key_id",
":",
"raise",
"ValueError",
"(",
"f'Invalid authentication definition, \"publicKey\" is missing: {values}'",
")",
"authentication",
"=",
"{",
"'type'",
":",
"authentication_type",
",",
"'publicKey'",
":",
"key_id",
"}",
"return",
"authentication"
]
| Create authentitaciton object from a JSON string. | [
"Create",
"authentitaciton",
"object",
"from",
"a",
"JSON",
"string",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L313-L323 |
oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO.generate_checksum | def generate_checksum(did, metadata):
"""
Generation of the hash for integrity checksum.
:param did: DID, str
:param metadata: conforming to the Metadata accepted by Ocean Protocol, dict
:return: hex str
"""
files_checksum = ''
for file in metadata['base']['files']:
if 'checksum' in file:
files_checksum = files_checksum + file['checksum']
return hashlib.sha3_256((files_checksum +
metadata['base']['name'] +
metadata['base']['author'] +
metadata['base']['license'] +
did).encode('UTF-8')).hexdigest() | python | def generate_checksum(did, metadata):
files_checksum = ''
for file in metadata['base']['files']:
if 'checksum' in file:
files_checksum = files_checksum + file['checksum']
return hashlib.sha3_256((files_checksum +
metadata['base']['name'] +
metadata['base']['author'] +
metadata['base']['license'] +
did).encode('UTF-8')).hexdigest() | [
"def",
"generate_checksum",
"(",
"did",
",",
"metadata",
")",
":",
"files_checksum",
"=",
"''",
"for",
"file",
"in",
"metadata",
"[",
"'base'",
"]",
"[",
"'files'",
"]",
":",
"if",
"'checksum'",
"in",
"file",
":",
"files_checksum",
"=",
"files_checksum",
"+",
"file",
"[",
"'checksum'",
"]",
"return",
"hashlib",
".",
"sha3_256",
"(",
"(",
"files_checksum",
"+",
"metadata",
"[",
"'base'",
"]",
"[",
"'name'",
"]",
"+",
"metadata",
"[",
"'base'",
"]",
"[",
"'author'",
"]",
"+",
"metadata",
"[",
"'base'",
"]",
"[",
"'license'",
"]",
"+",
"did",
")",
".",
"encode",
"(",
"'UTF-8'",
")",
")",
".",
"hexdigest",
"(",
")"
]
| Generation of the hash for integrity checksum.
:param did: DID, str
:param metadata: conforming to the Metadata accepted by Ocean Protocol, dict
:return: hex str | [
"Generation",
"of",
"the",
"hash",
"for",
"integrity",
"checksum",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L331-L347 |
oceanprotocol/squid-py | squid_py/keeper/didregistry.py | DIDRegistry.register | def register(self, did, checksum, url, account, providers=None):
"""
Register or update a DID on the block chain using the DIDRegistry smart contract.
:param did: DID to register/update, can be a 32 byte or hexstring
:param checksum: hex str hash of TODO
:param url: URL of the resolved DID
:param account: instance of Account to use to register/update the DID
:param providers: list of addresses of providers to be allowed to serve the asset and play
a part in creating and fulfilling service agreements
:return: Receipt
"""
did_source_id = did_to_id_bytes(did)
if not did_source_id:
raise ValueError(f'{did} must be a valid DID to register')
if not urlparse(url):
raise ValueError(f'Invalid URL {url} to register for DID {did}')
if checksum is None:
checksum = Web3Provider.get_web3().toBytes(0)
if not isinstance(checksum, bytes):
raise ValueError(f'Invalid checksum value {checksum}, must be bytes or string')
if account is None:
raise ValueError('You must provide an account to use to register a DID')
transaction = self._register_attribute(
did_source_id, checksum, url, account, providers or []
)
receipt = self.get_tx_receipt(transaction)
return receipt and receipt.status == 1 | python | def register(self, did, checksum, url, account, providers=None):
did_source_id = did_to_id_bytes(did)
if not did_source_id:
raise ValueError(f'{did} must be a valid DID to register')
if not urlparse(url):
raise ValueError(f'Invalid URL {url} to register for DID {did}')
if checksum is None:
checksum = Web3Provider.get_web3().toBytes(0)
if not isinstance(checksum, bytes):
raise ValueError(f'Invalid checksum value {checksum}, must be bytes or string')
if account is None:
raise ValueError('You must provide an account to use to register a DID')
transaction = self._register_attribute(
did_source_id, checksum, url, account, providers or []
)
receipt = self.get_tx_receipt(transaction)
return receipt and receipt.status == 1 | [
"def",
"register",
"(",
"self",
",",
"did",
",",
"checksum",
",",
"url",
",",
"account",
",",
"providers",
"=",
"None",
")",
":",
"did_source_id",
"=",
"did_to_id_bytes",
"(",
"did",
")",
"if",
"not",
"did_source_id",
":",
"raise",
"ValueError",
"(",
"f'{did} must be a valid DID to register'",
")",
"if",
"not",
"urlparse",
"(",
"url",
")",
":",
"raise",
"ValueError",
"(",
"f'Invalid URL {url} to register for DID {did}'",
")",
"if",
"checksum",
"is",
"None",
":",
"checksum",
"=",
"Web3Provider",
".",
"get_web3",
"(",
")",
".",
"toBytes",
"(",
"0",
")",
"if",
"not",
"isinstance",
"(",
"checksum",
",",
"bytes",
")",
":",
"raise",
"ValueError",
"(",
"f'Invalid checksum value {checksum}, must be bytes or string'",
")",
"if",
"account",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'You must provide an account to use to register a DID'",
")",
"transaction",
"=",
"self",
".",
"_register_attribute",
"(",
"did_source_id",
",",
"checksum",
",",
"url",
",",
"account",
",",
"providers",
"or",
"[",
"]",
")",
"receipt",
"=",
"self",
".",
"get_tx_receipt",
"(",
"transaction",
")",
"return",
"receipt",
"and",
"receipt",
".",
"status",
"==",
"1"
]
| Register or update a DID on the block chain using the DIDRegistry smart contract.
:param did: DID to register/update, can be a 32 byte or hexstring
:param checksum: hex str hash of TODO
:param url: URL of the resolved DID
:param account: instance of Account to use to register/update the DID
:param providers: list of addresses of providers to be allowed to serve the asset and play
a part in creating and fulfilling service agreements
:return: Receipt | [
"Register",
"or",
"update",
"a",
"DID",
"on",
"the",
"block",
"chain",
"using",
"the",
"DIDRegistry",
"smart",
"contract",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/didregistry.py#L29-L62 |
oceanprotocol/squid-py | squid_py/keeper/didregistry.py | DIDRegistry._register_attribute | def _register_attribute(self, did, checksum, value, account, providers):
"""Register an DID attribute as an event on the block chain.
:param did: 32 byte string/hex of the DID
:param checksum: checksum of the ddo, hex str
:param value: url for resolve the did, str
:param account: account owner of this DID registration record
:param providers: list of providers addresses
"""
assert isinstance(providers, list), ''
return self.send_transaction(
'registerAttribute',
(did,
checksum,
providers,
value),
transact={'from': account.address,
'passphrase': account.password}
) | python | def _register_attribute(self, did, checksum, value, account, providers):
assert isinstance(providers, list), ''
return self.send_transaction(
'registerAttribute',
(did,
checksum,
providers,
value),
transact={'from': account.address,
'passphrase': account.password}
) | [
"def",
"_register_attribute",
"(",
"self",
",",
"did",
",",
"checksum",
",",
"value",
",",
"account",
",",
"providers",
")",
":",
"assert",
"isinstance",
"(",
"providers",
",",
"list",
")",
",",
"''",
"return",
"self",
".",
"send_transaction",
"(",
"'registerAttribute'",
",",
"(",
"did",
",",
"checksum",
",",
"providers",
",",
"value",
")",
",",
"transact",
"=",
"{",
"'from'",
":",
"account",
".",
"address",
",",
"'passphrase'",
":",
"account",
".",
"password",
"}",
")"
]
| Register an DID attribute as an event on the block chain.
:param did: 32 byte string/hex of the DID
:param checksum: checksum of the ddo, hex str
:param value: url for resolve the did, str
:param account: account owner of this DID registration record
:param providers: list of providers addresses | [
"Register",
"an",
"DID",
"attribute",
"as",
"an",
"event",
"on",
"the",
"block",
"chain",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/didregistry.py#L64-L82 |
oceanprotocol/squid-py | squid_py/keeper/didregistry.py | DIDRegistry.remove_provider | def remove_provider(self, did, provider_address, account):
"""
Remove a provider
:param did: the id of an asset on-chain, hex str
:param provider_address: ethereum account address of the provider, hex str
:param account: Account executing the action
:return:
"""
tx_hash = self.send_transaction(
'removeDIDProvider',
(did,
provider_address),
transact={'from': account.address,
'passphrase': account.password}
)
return self.get_tx_receipt(tx_hash) | python | def remove_provider(self, did, provider_address, account):
tx_hash = self.send_transaction(
'removeDIDProvider',
(did,
provider_address),
transact={'from': account.address,
'passphrase': account.password}
)
return self.get_tx_receipt(tx_hash) | [
"def",
"remove_provider",
"(",
"self",
",",
"did",
",",
"provider_address",
",",
"account",
")",
":",
"tx_hash",
"=",
"self",
".",
"send_transaction",
"(",
"'removeDIDProvider'",
",",
"(",
"did",
",",
"provider_address",
")",
",",
"transact",
"=",
"{",
"'from'",
":",
"account",
".",
"address",
",",
"'passphrase'",
":",
"account",
".",
"password",
"}",
")",
"return",
"self",
".",
"get_tx_receipt",
"(",
"tx_hash",
")"
]
| Remove a provider
:param did: the id of an asset on-chain, hex str
:param provider_address: ethereum account address of the provider, hex str
:param account: Account executing the action
:return: | [
"Remove",
"a",
"provider"
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/didregistry.py#L115-L131 |
oceanprotocol/squid-py | squid_py/keeper/didregistry.py | DIDRegistry.get_did_providers | def get_did_providers(self, did):
"""
Return the list providers registered on-chain for the given did.
:param did: hex str the id of an asset on-chain
:return:
list of addresses
None if asset has no registerd providers
"""
register_values = self.contract_concise.getDIDRegister(did)
if register_values and len(register_values) == 5:
return DIDRegisterValues(*register_values).providers
return None | python | def get_did_providers(self, did):
register_values = self.contract_concise.getDIDRegister(did)
if register_values and len(register_values) == 5:
return DIDRegisterValues(*register_values).providers
return None | [
"def",
"get_did_providers",
"(",
"self",
",",
"did",
")",
":",
"register_values",
"=",
"self",
".",
"contract_concise",
".",
"getDIDRegister",
"(",
"did",
")",
"if",
"register_values",
"and",
"len",
"(",
"register_values",
")",
"==",
"5",
":",
"return",
"DIDRegisterValues",
"(",
"*",
"register_values",
")",
".",
"providers",
"return",
"None"
]
| Return the list providers registered on-chain for the given did.
:param did: hex str the id of an asset on-chain
:return:
list of addresses
None if asset has no registerd providers | [
"Return",
"the",
"list",
"providers",
"registered",
"on",
"-",
"chain",
"for",
"the",
"given",
"did",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/didregistry.py#L143-L156 |
oceanprotocol/squid-py | squid_py/keeper/didregistry.py | DIDRegistry.get_owner_asset_ids | def get_owner_asset_ids(self, address):
"""
Get the list of assets owned by an address owner.
:param address: ethereum account address, hex str
:return:
"""
block_filter = self._get_event_filter(owner=address)
log_items = block_filter.get_all_entries(max_tries=5)
did_list = []
for log_i in log_items:
did_list.append(id_to_did(log_i.args['_did']))
return did_list | python | def get_owner_asset_ids(self, address):
block_filter = self._get_event_filter(owner=address)
log_items = block_filter.get_all_entries(max_tries=5)
did_list = []
for log_i in log_items:
did_list.append(id_to_did(log_i.args['_did']))
return did_list | [
"def",
"get_owner_asset_ids",
"(",
"self",
",",
"address",
")",
":",
"block_filter",
"=",
"self",
".",
"_get_event_filter",
"(",
"owner",
"=",
"address",
")",
"log_items",
"=",
"block_filter",
".",
"get_all_entries",
"(",
"max_tries",
"=",
"5",
")",
"did_list",
"=",
"[",
"]",
"for",
"log_i",
"in",
"log_items",
":",
"did_list",
".",
"append",
"(",
"id_to_did",
"(",
"log_i",
".",
"args",
"[",
"'_did'",
"]",
")",
")",
"return",
"did_list"
]
| Get the list of assets owned by an address owner.
:param address: ethereum account address, hex str
:return: | [
"Get",
"the",
"list",
"of",
"assets",
"owned",
"by",
"an",
"address",
"owner",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/didregistry.py#L158-L171 |
oceanprotocol/squid-py | squid_py/ddo/public_key_rsa.py | PublicKeyRSA.set_encode_key_value | def set_encode_key_value(self, value, store_type=PUBLIC_KEY_STORE_TYPE_BASE64):
"""Set the value based on the type of encoding supported by RSA."""
if store_type == PUBLIC_KEY_STORE_TYPE_PEM:
PublicKeyBase.set_encode_key_value(self, value.exportKey('PEM').decode(), store_type)
else:
PublicKeyBase.set_encode_key_value(self, value.exportKey('DER'), store_type) | python | def set_encode_key_value(self, value, store_type=PUBLIC_KEY_STORE_TYPE_BASE64):
if store_type == PUBLIC_KEY_STORE_TYPE_PEM:
PublicKeyBase.set_encode_key_value(self, value.exportKey('PEM').decode(), store_type)
else:
PublicKeyBase.set_encode_key_value(self, value.exportKey('DER'), store_type) | [
"def",
"set_encode_key_value",
"(",
"self",
",",
"value",
",",
"store_type",
"=",
"PUBLIC_KEY_STORE_TYPE_BASE64",
")",
":",
"if",
"store_type",
"==",
"PUBLIC_KEY_STORE_TYPE_PEM",
":",
"PublicKeyBase",
".",
"set_encode_key_value",
"(",
"self",
",",
"value",
".",
"exportKey",
"(",
"'PEM'",
")",
".",
"decode",
"(",
")",
",",
"store_type",
")",
"else",
":",
"PublicKeyBase",
".",
"set_encode_key_value",
"(",
"self",
",",
"value",
".",
"exportKey",
"(",
"'DER'",
")",
",",
"store_type",
")"
]
| Set the value based on the type of encoding supported by RSA. | [
"Set",
"the",
"value",
"based",
"on",
"the",
"type",
"of",
"encoding",
"supported",
"by",
"RSA",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/public_key_rsa.py#L27-L32 |
oceanprotocol/squid-py | squid_py/did.py | did_parse | def did_parse(did):
"""
Parse a DID into it's parts.
:param did: Asset did, str.
:return: Python dictionary with the method and the id.
"""
if not isinstance(did, str):
raise TypeError(f'Expecting DID of string type, got {did} of {type(did)} type')
match = re.match('^did:([a-z0-9]+):([a-zA-Z0-9-.]+)(.*)', did)
if not match:
raise ValueError(f'DID {did} does not seem to be valid.')
result = {
'method': match.group(1),
'id': match.group(2),
}
return result | python | def did_parse(did):
if not isinstance(did, str):
raise TypeError(f'Expecting DID of string type, got {did} of {type(did)} type')
match = re.match('^did:([a-z0-9]+):([a-zA-Z0-9-.]+)(.*)', did)
if not match:
raise ValueError(f'DID {did} does not seem to be valid.')
result = {
'method': match.group(1),
'id': match.group(2),
}
return result | [
"def",
"did_parse",
"(",
"did",
")",
":",
"if",
"not",
"isinstance",
"(",
"did",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"f'Expecting DID of string type, got {did} of {type(did)} type'",
")",
"match",
"=",
"re",
".",
"match",
"(",
"'^did:([a-z0-9]+):([a-zA-Z0-9-.]+)(.*)'",
",",
"did",
")",
"if",
"not",
"match",
":",
"raise",
"ValueError",
"(",
"f'DID {did} does not seem to be valid.'",
")",
"result",
"=",
"{",
"'method'",
":",
"match",
".",
"group",
"(",
"1",
")",
",",
"'id'",
":",
"match",
".",
"group",
"(",
"2",
")",
",",
"}",
"return",
"result"
]
| Parse a DID into it's parts.
:param did: Asset did, str.
:return: Python dictionary with the method and the id. | [
"Parse",
"a",
"DID",
"into",
"it",
"s",
"parts",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/did.py#L31-L50 |
oceanprotocol/squid-py | squid_py/did.py | id_to_did | def id_to_did(did_id, method='op'):
"""Return an Ocean DID from given a hex id."""
if isinstance(did_id, bytes):
did_id = Web3.toHex(did_id)
# remove leading '0x' of a hex string
if isinstance(did_id, str):
did_id = remove_0x_prefix(did_id)
else:
raise TypeError("did id must be a hex string or bytes")
# test for zero address
if Web3.toBytes(hexstr=did_id) == b'':
did_id = '0'
return f'did:{method}:{did_id}' | python | def id_to_did(did_id, method='op'):
if isinstance(did_id, bytes):
did_id = Web3.toHex(did_id)
if isinstance(did_id, str):
did_id = remove_0x_prefix(did_id)
else:
raise TypeError("did id must be a hex string or bytes")
if Web3.toBytes(hexstr=did_id) == b'':
did_id = '0'
return f'did:{method}:{did_id}' | [
"def",
"id_to_did",
"(",
"did_id",
",",
"method",
"=",
"'op'",
")",
":",
"if",
"isinstance",
"(",
"did_id",
",",
"bytes",
")",
":",
"did_id",
"=",
"Web3",
".",
"toHex",
"(",
"did_id",
")",
"# remove leading '0x' of a hex string",
"if",
"isinstance",
"(",
"did_id",
",",
"str",
")",
":",
"did_id",
"=",
"remove_0x_prefix",
"(",
"did_id",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"did id must be a hex string or bytes\"",
")",
"# test for zero address",
"if",
"Web3",
".",
"toBytes",
"(",
"hexstr",
"=",
"did_id",
")",
"==",
"b''",
":",
"did_id",
"=",
"'0'",
"return",
"f'did:{method}:{did_id}'"
]
| Return an Ocean DID from given a hex id. | [
"Return",
"an",
"Ocean",
"DID",
"from",
"given",
"a",
"hex",
"id",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/did.py#L69-L83 |
oceanprotocol/squid-py | squid_py/did.py | did_to_id_bytes | def did_to_id_bytes(did):
"""
Return an Ocean DID to it's correspondng hex id in bytes.
So did:op:<hex>, will return <hex> in byte format
"""
if isinstance(did, str):
if re.match('^[0x]?[0-9A-Za-z]+$', did):
raise ValueError(f'{did} must be a DID not a hex string')
else:
did_result = did_parse(did)
if not did_result:
raise ValueError(f'{did} is not a valid did')
if not did_result['id']:
raise ValueError(f'{did} is not a valid ocean did')
id_bytes = Web3.toBytes(hexstr=did_result['id'])
elif isinstance(did, bytes):
id_bytes = did
else:
raise TypeError(
f'Unknown did format, expected str or bytes, got {did} of type {type(did)}')
return id_bytes | python | def did_to_id_bytes(did):
if isinstance(did, str):
if re.match('^[0x]?[0-9A-Za-z]+$', did):
raise ValueError(f'{did} must be a DID not a hex string')
else:
did_result = did_parse(did)
if not did_result:
raise ValueError(f'{did} is not a valid did')
if not did_result['id']:
raise ValueError(f'{did} is not a valid ocean did')
id_bytes = Web3.toBytes(hexstr=did_result['id'])
elif isinstance(did, bytes):
id_bytes = did
else:
raise TypeError(
f'Unknown did format, expected str or bytes, got {did} of type {type(did)}')
return id_bytes | [
"def",
"did_to_id_bytes",
"(",
"did",
")",
":",
"if",
"isinstance",
"(",
"did",
",",
"str",
")",
":",
"if",
"re",
".",
"match",
"(",
"'^[0x]?[0-9A-Za-z]+$'",
",",
"did",
")",
":",
"raise",
"ValueError",
"(",
"f'{did} must be a DID not a hex string'",
")",
"else",
":",
"did_result",
"=",
"did_parse",
"(",
"did",
")",
"if",
"not",
"did_result",
":",
"raise",
"ValueError",
"(",
"f'{did} is not a valid did'",
")",
"if",
"not",
"did_result",
"[",
"'id'",
"]",
":",
"raise",
"ValueError",
"(",
"f'{did} is not a valid ocean did'",
")",
"id_bytes",
"=",
"Web3",
".",
"toBytes",
"(",
"hexstr",
"=",
"did_result",
"[",
"'id'",
"]",
")",
"elif",
"isinstance",
"(",
"did",
",",
"bytes",
")",
":",
"id_bytes",
"=",
"did",
"else",
":",
"raise",
"TypeError",
"(",
"f'Unknown did format, expected str or bytes, got {did} of type {type(did)}'",
")",
"return",
"id_bytes"
]
| Return an Ocean DID to it's correspondng hex id in bytes.
So did:op:<hex>, will return <hex> in byte format | [
"Return",
"an",
"Ocean",
"DID",
"to",
"it",
"s",
"correspondng",
"hex",
"id",
"in",
"bytes",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/did.py#L94-L115 |
oceanprotocol/squid-py | squid_py/keeper/templates/template_manager.py | TemplateStoreManager.get_template | def get_template(self, template_id):
"""
Get the template for a given template id.
:param template_id: id of the template, str
:return:
"""
template = self.contract_concise.getTemplate(template_id)
if template and len(template) == 4:
return AgreementTemplate(*template)
return None | python | def get_template(self, template_id):
template = self.contract_concise.getTemplate(template_id)
if template and len(template) == 4:
return AgreementTemplate(*template)
return None | [
"def",
"get_template",
"(",
"self",
",",
"template_id",
")",
":",
"template",
"=",
"self",
".",
"contract_concise",
".",
"getTemplate",
"(",
"template_id",
")",
"if",
"template",
"and",
"len",
"(",
"template",
")",
"==",
"4",
":",
"return",
"AgreementTemplate",
"(",
"*",
"template",
")",
"return",
"None"
]
| Get the template for a given template id.
:param template_id: id of the template, str
:return: | [
"Get",
"the",
"template",
"for",
"a",
"given",
"template",
"id",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/templates/template_manager.py#L19-L30 |
oceanprotocol/squid-py | squid_py/keeper/templates/template_manager.py | TemplateStoreManager.propose_template | def propose_template(self, template_id, from_account):
"""Propose a template.
:param template_id: id of the template, str
:param from_account: Account
:return: bool
"""
tx_hash = self.send_transaction(
'proposeTemplate',
(template_id,),
transact={'from': from_account.address,
'passphrase': from_account.password})
return self.get_tx_receipt(tx_hash).status == 1 | python | def propose_template(self, template_id, from_account):
tx_hash = self.send_transaction(
'proposeTemplate',
(template_id,),
transact={'from': from_account.address,
'passphrase': from_account.password})
return self.get_tx_receipt(tx_hash).status == 1 | [
"def",
"propose_template",
"(",
"self",
",",
"template_id",
",",
"from_account",
")",
":",
"tx_hash",
"=",
"self",
".",
"send_transaction",
"(",
"'proposeTemplate'",
",",
"(",
"template_id",
",",
")",
",",
"transact",
"=",
"{",
"'from'",
":",
"from_account",
".",
"address",
",",
"'passphrase'",
":",
"from_account",
".",
"password",
"}",
")",
"return",
"self",
".",
"get_tx_receipt",
"(",
"tx_hash",
")",
".",
"status",
"==",
"1"
]
| Propose a template.
:param template_id: id of the template, str
:param from_account: Account
:return: bool | [
"Propose",
"a",
"template",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/templates/template_manager.py#L32-L44 |
oceanprotocol/squid-py | squid_py/agreements/service_factory.py | ServiceDescriptor.access_service_descriptor | def access_service_descriptor(price, consume_endpoint, service_endpoint, timeout, template_id):
"""
Access service descriptor.
:param price: Asset price, int
:param consume_endpoint: url of the service provider, str
:param service_endpoint: identifier of the service inside the asset DDO, str
:param timeout: amount of time in seconds before the agreement expires, int
:param template_id: id of the template use to create the service, str
:return: Service descriptor.
"""
return (ServiceTypes.ASSET_ACCESS,
{'price': price, 'consumeEndpoint': consume_endpoint,
'serviceEndpoint': service_endpoint,
'timeout': timeout, 'templateId': template_id}) | python | def access_service_descriptor(price, consume_endpoint, service_endpoint, timeout, template_id):
return (ServiceTypes.ASSET_ACCESS,
{'price': price, 'consumeEndpoint': consume_endpoint,
'serviceEndpoint': service_endpoint,
'timeout': timeout, 'templateId': template_id}) | [
"def",
"access_service_descriptor",
"(",
"price",
",",
"consume_endpoint",
",",
"service_endpoint",
",",
"timeout",
",",
"template_id",
")",
":",
"return",
"(",
"ServiceTypes",
".",
"ASSET_ACCESS",
",",
"{",
"'price'",
":",
"price",
",",
"'consumeEndpoint'",
":",
"consume_endpoint",
",",
"'serviceEndpoint'",
":",
"service_endpoint",
",",
"'timeout'",
":",
"timeout",
",",
"'templateId'",
":",
"template_id",
"}",
")"
]
| Access service descriptor.
:param price: Asset price, int
:param consume_endpoint: url of the service provider, str
:param service_endpoint: identifier of the service inside the asset DDO, str
:param timeout: amount of time in seconds before the agreement expires, int
:param template_id: id of the template use to create the service, str
:return: Service descriptor. | [
"Access",
"service",
"descriptor",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_factory.py#L42-L56 |
oceanprotocol/squid-py | squid_py/agreements/service_factory.py | ServiceDescriptor.compute_service_descriptor | def compute_service_descriptor(price, consume_endpoint, service_endpoint, timeout):
"""
Compute service descriptor.
:param price: Asset price, int
:param consume_endpoint: url of the service provider, str
:param service_endpoint: identifier of the service inside the asset DDO, str
:param timeout: amount of time in seconds before the agreement expires, int
:return: Service descriptor.
"""
return (ServiceTypes.CLOUD_COMPUTE,
{'price': price, 'consumeEndpoint': consume_endpoint,
'serviceEndpoint': service_endpoint,
'timeout': timeout}) | python | def compute_service_descriptor(price, consume_endpoint, service_endpoint, timeout):
return (ServiceTypes.CLOUD_COMPUTE,
{'price': price, 'consumeEndpoint': consume_endpoint,
'serviceEndpoint': service_endpoint,
'timeout': timeout}) | [
"def",
"compute_service_descriptor",
"(",
"price",
",",
"consume_endpoint",
",",
"service_endpoint",
",",
"timeout",
")",
":",
"return",
"(",
"ServiceTypes",
".",
"CLOUD_COMPUTE",
",",
"{",
"'price'",
":",
"price",
",",
"'consumeEndpoint'",
":",
"consume_endpoint",
",",
"'serviceEndpoint'",
":",
"service_endpoint",
",",
"'timeout'",
":",
"timeout",
"}",
")"
]
| Compute service descriptor.
:param price: Asset price, int
:param consume_endpoint: url of the service provider, str
:param service_endpoint: identifier of the service inside the asset DDO, str
:param timeout: amount of time in seconds before the agreement expires, int
:return: Service descriptor. | [
"Compute",
"service",
"descriptor",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_factory.py#L59-L72 |
oceanprotocol/squid-py | squid_py/agreements/service_factory.py | ServiceFactory.build_services | def build_services(did, service_descriptors):
"""
Build a list of services.
:param did: DID, str
:param service_descriptors: List of 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
:return: List of Services
"""
services = []
sa_def_key = ServiceAgreement.SERVICE_DEFINITION_ID
for i, service_desc in enumerate(service_descriptors):
service = ServiceFactory.build_service(service_desc, did)
# set serviceDefinitionId for each service
service.update_value(sa_def_key, str(i))
services.append(service)
return services | python | def build_services(did, service_descriptors):
services = []
sa_def_key = ServiceAgreement.SERVICE_DEFINITION_ID
for i, service_desc in enumerate(service_descriptors):
service = ServiceFactory.build_service(service_desc, did)
service.update_value(sa_def_key, str(i))
services.append(service)
return services | [
"def",
"build_services",
"(",
"did",
",",
"service_descriptors",
")",
":",
"services",
"=",
"[",
"]",
"sa_def_key",
"=",
"ServiceAgreement",
".",
"SERVICE_DEFINITION_ID",
"for",
"i",
",",
"service_desc",
"in",
"enumerate",
"(",
"service_descriptors",
")",
":",
"service",
"=",
"ServiceFactory",
".",
"build_service",
"(",
"service_desc",
",",
"did",
")",
"# set serviceDefinitionId for each service",
"service",
".",
"update_value",
"(",
"sa_def_key",
",",
"str",
"(",
"i",
")",
")",
"services",
".",
"append",
"(",
"service",
")",
"return",
"services"
]
| Build a list of services.
:param did: DID, str
:param service_descriptors: List of 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
:return: List of Services | [
"Build",
"a",
"list",
"of",
"services",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_factory.py#L79-L97 |
oceanprotocol/squid-py | squid_py/agreements/service_factory.py | ServiceFactory.build_service | def build_service(service_descriptor, did):
"""
Build a service.
:param service_descriptor: 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 did: DID, str
:return: Service
"""
assert isinstance(service_descriptor, tuple) and len(
service_descriptor) == 2, 'Unknown service descriptor format.'
service_type, kwargs = service_descriptor
if service_type == ServiceTypes.METADATA:
return ServiceFactory.build_metadata_service(
did,
kwargs['metadata'],
kwargs['serviceEndpoint']
)
elif service_type == ServiceTypes.AUTHORIZATION:
return ServiceFactory.build_authorization_service(
kwargs['serviceEndpoint']
)
elif service_type == ServiceTypes.ASSET_ACCESS:
return ServiceFactory.build_access_service(
did, kwargs['price'],
kwargs['consumeEndpoint'], kwargs['serviceEndpoint'],
kwargs['timeout'], kwargs['templateId']
)
elif service_type == ServiceTypes.CLOUD_COMPUTE:
return ServiceFactory.build_compute_service(
did, kwargs['price'],
kwargs['consumeEndpoint'], kwargs['serviceEndpoint'], kwargs['timeout']
)
raise ValueError(f'Unknown service type {service_type}') | python | def build_service(service_descriptor, did):
assert isinstance(service_descriptor, tuple) and len(
service_descriptor) == 2, 'Unknown service descriptor format.'
service_type, kwargs = service_descriptor
if service_type == ServiceTypes.METADATA:
return ServiceFactory.build_metadata_service(
did,
kwargs['metadata'],
kwargs['serviceEndpoint']
)
elif service_type == ServiceTypes.AUTHORIZATION:
return ServiceFactory.build_authorization_service(
kwargs['serviceEndpoint']
)
elif service_type == ServiceTypes.ASSET_ACCESS:
return ServiceFactory.build_access_service(
did, kwargs['price'],
kwargs['consumeEndpoint'], kwargs['serviceEndpoint'],
kwargs['timeout'], kwargs['templateId']
)
elif service_type == ServiceTypes.CLOUD_COMPUTE:
return ServiceFactory.build_compute_service(
did, kwargs['price'],
kwargs['consumeEndpoint'], kwargs['serviceEndpoint'], kwargs['timeout']
)
raise ValueError(f'Unknown service type {service_type}') | [
"def",
"build_service",
"(",
"service_descriptor",
",",
"did",
")",
":",
"assert",
"isinstance",
"(",
"service_descriptor",
",",
"tuple",
")",
"and",
"len",
"(",
"service_descriptor",
")",
"==",
"2",
",",
"'Unknown service descriptor format.'",
"service_type",
",",
"kwargs",
"=",
"service_descriptor",
"if",
"service_type",
"==",
"ServiceTypes",
".",
"METADATA",
":",
"return",
"ServiceFactory",
".",
"build_metadata_service",
"(",
"did",
",",
"kwargs",
"[",
"'metadata'",
"]",
",",
"kwargs",
"[",
"'serviceEndpoint'",
"]",
")",
"elif",
"service_type",
"==",
"ServiceTypes",
".",
"AUTHORIZATION",
":",
"return",
"ServiceFactory",
".",
"build_authorization_service",
"(",
"kwargs",
"[",
"'serviceEndpoint'",
"]",
")",
"elif",
"service_type",
"==",
"ServiceTypes",
".",
"ASSET_ACCESS",
":",
"return",
"ServiceFactory",
".",
"build_access_service",
"(",
"did",
",",
"kwargs",
"[",
"'price'",
"]",
",",
"kwargs",
"[",
"'consumeEndpoint'",
"]",
",",
"kwargs",
"[",
"'serviceEndpoint'",
"]",
",",
"kwargs",
"[",
"'timeout'",
"]",
",",
"kwargs",
"[",
"'templateId'",
"]",
")",
"elif",
"service_type",
"==",
"ServiceTypes",
".",
"CLOUD_COMPUTE",
":",
"return",
"ServiceFactory",
".",
"build_compute_service",
"(",
"did",
",",
"kwargs",
"[",
"'price'",
"]",
",",
"kwargs",
"[",
"'consumeEndpoint'",
"]",
",",
"kwargs",
"[",
"'serviceEndpoint'",
"]",
",",
"kwargs",
"[",
"'timeout'",
"]",
")",
"raise",
"ValueError",
"(",
"f'Unknown service type {service_type}'",
")"
]
| Build a service.
:param service_descriptor: 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 did: DID, str
:return: Service | [
"Build",
"a",
"service",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_factory.py#L100-L137 |
oceanprotocol/squid-py | squid_py/agreements/service_factory.py | ServiceFactory.build_metadata_service | def build_metadata_service(did, metadata, service_endpoint):
"""
Build a metadata service.
:param did: DID, str
:param metadata: conforming to the Metadata accepted by Ocean Protocol, dict
:param service_endpoint: identifier of the service inside the asset DDO, str
:return: Service
"""
return Service(service_endpoint,
ServiceTypes.METADATA,
values={'metadata': metadata},
did=did) | python | def build_metadata_service(did, metadata, service_endpoint):
return Service(service_endpoint,
ServiceTypes.METADATA,
values={'metadata': metadata},
did=did) | [
"def",
"build_metadata_service",
"(",
"did",
",",
"metadata",
",",
"service_endpoint",
")",
":",
"return",
"Service",
"(",
"service_endpoint",
",",
"ServiceTypes",
".",
"METADATA",
",",
"values",
"=",
"{",
"'metadata'",
":",
"metadata",
"}",
",",
"did",
"=",
"did",
")"
]
| Build a metadata service.
:param did: DID, str
:param metadata: conforming to the Metadata accepted by Ocean Protocol, dict
:param service_endpoint: identifier of the service inside the asset DDO, str
:return: Service | [
"Build",
"a",
"metadata",
"service",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_factory.py#L140-L152 |
oceanprotocol/squid-py | squid_py/agreements/service_factory.py | ServiceFactory.build_access_service | def build_access_service(did, price, consume_endpoint, service_endpoint, timeout, template_id):
"""
Build the access service.
:param did: DID, str
:param price: Asset price, int
:param consume_endpoint: url of the service provider, str
:param service_endpoint: identifier of the service inside the asset DDO, str
:param timeout: amount of time in seconds before the agreement expires, int
:param template_id: id of the template use to create the service, str
:return: ServiceAgreement
"""
# TODO fill all the possible mappings
param_map = {
'_documentId': did_to_id(did),
'_amount': price,
'_rewardAddress': Keeper.get_instance().escrow_reward_condition.address,
}
sla_template_path = get_sla_template_path()
sla_template = ServiceAgreementTemplate.from_json_file(sla_template_path)
sla_template.template_id = template_id
conditions = sla_template.conditions[:]
for cond in conditions:
for param in cond.parameters:
param.value = param_map.get(param.name, '')
if cond.timeout > 0:
cond.timeout = timeout
sla_template.set_conditions(conditions)
sa = ServiceAgreement(
1,
sla_template,
consume_endpoint,
service_endpoint,
ServiceTypes.ASSET_ACCESS
)
sa.set_did(did)
return sa | python | def build_access_service(did, price, consume_endpoint, service_endpoint, timeout, template_id):
param_map = {
'_documentId': did_to_id(did),
'_amount': price,
'_rewardAddress': Keeper.get_instance().escrow_reward_condition.address,
}
sla_template_path = get_sla_template_path()
sla_template = ServiceAgreementTemplate.from_json_file(sla_template_path)
sla_template.template_id = template_id
conditions = sla_template.conditions[:]
for cond in conditions:
for param in cond.parameters:
param.value = param_map.get(param.name, '')
if cond.timeout > 0:
cond.timeout = timeout
sla_template.set_conditions(conditions)
sa = ServiceAgreement(
1,
sla_template,
consume_endpoint,
service_endpoint,
ServiceTypes.ASSET_ACCESS
)
sa.set_did(did)
return sa | [
"def",
"build_access_service",
"(",
"did",
",",
"price",
",",
"consume_endpoint",
",",
"service_endpoint",
",",
"timeout",
",",
"template_id",
")",
":",
"# TODO fill all the possible mappings",
"param_map",
"=",
"{",
"'_documentId'",
":",
"did_to_id",
"(",
"did",
")",
",",
"'_amount'",
":",
"price",
",",
"'_rewardAddress'",
":",
"Keeper",
".",
"get_instance",
"(",
")",
".",
"escrow_reward_condition",
".",
"address",
",",
"}",
"sla_template_path",
"=",
"get_sla_template_path",
"(",
")",
"sla_template",
"=",
"ServiceAgreementTemplate",
".",
"from_json_file",
"(",
"sla_template_path",
")",
"sla_template",
".",
"template_id",
"=",
"template_id",
"conditions",
"=",
"sla_template",
".",
"conditions",
"[",
":",
"]",
"for",
"cond",
"in",
"conditions",
":",
"for",
"param",
"in",
"cond",
".",
"parameters",
":",
"param",
".",
"value",
"=",
"param_map",
".",
"get",
"(",
"param",
".",
"name",
",",
"''",
")",
"if",
"cond",
".",
"timeout",
">",
"0",
":",
"cond",
".",
"timeout",
"=",
"timeout",
"sla_template",
".",
"set_conditions",
"(",
"conditions",
")",
"sa",
"=",
"ServiceAgreement",
"(",
"1",
",",
"sla_template",
",",
"consume_endpoint",
",",
"service_endpoint",
",",
"ServiceTypes",
".",
"ASSET_ACCESS",
")",
"sa",
".",
"set_did",
"(",
"did",
")",
"return",
"sa"
]
| Build the access service.
:param did: DID, str
:param price: Asset price, int
:param consume_endpoint: url of the service provider, str
:param service_endpoint: identifier of the service inside the asset DDO, str
:param timeout: amount of time in seconds before the agreement expires, int
:param template_id: id of the template use to create the service, str
:return: ServiceAgreement | [
"Build",
"the",
"access",
"service",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_factory.py#L166-L204 |
oceanprotocol/squid-py | squid_py/keeper/conditions/lock_reward.py | LockRewardCondition.fulfill | def fulfill(self, agreement_id, reward_address, amount, account):
"""
Fulfill the lock reward condition.
:param agreement_id: id of the agreement, hex str
:param reward_address: ethereum account address, hex str
:param amount: Amount of tokens, int
:param account: Account instance
:return:
"""
return self._fulfill(
agreement_id,
reward_address,
amount,
transact={'from': account.address,
'passphrase': account.password}
) | python | def fulfill(self, agreement_id, reward_address, amount, account):
return self._fulfill(
agreement_id,
reward_address,
amount,
transact={'from': account.address,
'passphrase': account.password}
) | [
"def",
"fulfill",
"(",
"self",
",",
"agreement_id",
",",
"reward_address",
",",
"amount",
",",
"account",
")",
":",
"return",
"self",
".",
"_fulfill",
"(",
"agreement_id",
",",
"reward_address",
",",
"amount",
",",
"transact",
"=",
"{",
"'from'",
":",
"account",
".",
"address",
",",
"'passphrase'",
":",
"account",
".",
"password",
"}",
")"
]
| Fulfill the lock reward condition.
:param agreement_id: id of the agreement, hex str
:param reward_address: ethereum account address, hex str
:param amount: Amount of tokens, int
:param account: Account instance
:return: | [
"Fulfill",
"the",
"lock",
"reward",
"condition",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/conditions/lock_reward.py#L11-L27 |
oceanprotocol/squid-py | squid_py/agreements/storage.py | record_service_agreement | def record_service_agreement(storage_path, service_agreement_id, did, service_definition_id, price,
files, start_time,
status='pending'):
"""
Records the given pending service agreement.
:param storage_path: storage path for the internal db, str
:param service_agreement_id:
:param did: DID, str
:param service_definition_id: identifier of the service inside the asset DDO, str
:param price: Asset price, int
:param files:
:param start_time:
:param status:
:return:
"""
conn = sqlite3.connect(storage_path)
try:
cursor = conn.cursor()
cursor.execute(
'''CREATE TABLE IF NOT EXISTS service_agreements
(id VARCHAR PRIMARY KEY, did VARCHAR, service_definition_id INTEGER,
price INTEGER, files VARCHAR, start_time INTEGER, status VARCHAR(10));'''
)
cursor.execute(
'INSERT OR REPLACE INTO service_agreements VALUES (?,?,?,?,?,?,?)',
[service_agreement_id, did, service_definition_id, price, files, start_time,
status],
)
conn.commit()
finally:
conn.close() | python | def record_service_agreement(storage_path, service_agreement_id, did, service_definition_id, price,
files, start_time,
status='pending'):
conn = sqlite3.connect(storage_path)
try:
cursor = conn.cursor()
cursor.execute(
)
cursor.execute(
'INSERT OR REPLACE INTO service_agreements VALUES (?,?,?,?,?,?,?)',
[service_agreement_id, did, service_definition_id, price, files, start_time,
status],
)
conn.commit()
finally:
conn.close() | [
"def",
"record_service_agreement",
"(",
"storage_path",
",",
"service_agreement_id",
",",
"did",
",",
"service_definition_id",
",",
"price",
",",
"files",
",",
"start_time",
",",
"status",
"=",
"'pending'",
")",
":",
"conn",
"=",
"sqlite3",
".",
"connect",
"(",
"storage_path",
")",
"try",
":",
"cursor",
"=",
"conn",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"'''CREATE TABLE IF NOT EXISTS service_agreements\n (id VARCHAR PRIMARY KEY, did VARCHAR, service_definition_id INTEGER, \n price INTEGER, files VARCHAR, start_time INTEGER, status VARCHAR(10));'''",
")",
"cursor",
".",
"execute",
"(",
"'INSERT OR REPLACE INTO service_agreements VALUES (?,?,?,?,?,?,?)'",
",",
"[",
"service_agreement_id",
",",
"did",
",",
"service_definition_id",
",",
"price",
",",
"files",
",",
"start_time",
",",
"status",
"]",
",",
")",
"conn",
".",
"commit",
"(",
")",
"finally",
":",
"conn",
".",
"close",
"(",
")"
]
| Records the given pending service agreement.
:param storage_path: storage path for the internal db, str
:param service_agreement_id:
:param did: DID, str
:param service_definition_id: identifier of the service inside the asset DDO, str
:param price: Asset price, int
:param files:
:param start_time:
:param status:
:return: | [
"Records",
"the",
"given",
"pending",
"service",
"agreement",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/storage.py#L8-L39 |
oceanprotocol/squid-py | squid_py/agreements/storage.py | update_service_agreement_status | def update_service_agreement_status(storage_path, service_agreement_id, status='pending'):
"""
Update the service agreement status.
:param storage_path: storage path for the internal db, str
:param service_agreement_id:
:param status:
:return:
"""
conn = sqlite3.connect(storage_path)
try:
cursor = conn.cursor()
cursor.execute(
'UPDATE service_agreements SET status=? WHERE id=?',
(status, service_agreement_id),
)
conn.commit()
finally:
conn.close() | python | def update_service_agreement_status(storage_path, service_agreement_id, status='pending'):
conn = sqlite3.connect(storage_path)
try:
cursor = conn.cursor()
cursor.execute(
'UPDATE service_agreements SET status=? WHERE id=?',
(status, service_agreement_id),
)
conn.commit()
finally:
conn.close() | [
"def",
"update_service_agreement_status",
"(",
"storage_path",
",",
"service_agreement_id",
",",
"status",
"=",
"'pending'",
")",
":",
"conn",
"=",
"sqlite3",
".",
"connect",
"(",
"storage_path",
")",
"try",
":",
"cursor",
"=",
"conn",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"'UPDATE service_agreements SET status=? WHERE id=?'",
",",
"(",
"status",
",",
"service_agreement_id",
")",
",",
")",
"conn",
".",
"commit",
"(",
")",
"finally",
":",
"conn",
".",
"close",
"(",
")"
]
| Update the service agreement status.
:param storage_path: storage path for the internal db, str
:param service_agreement_id:
:param status:
:return: | [
"Update",
"the",
"service",
"agreement",
"status",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/storage.py#L42-L60 |
oceanprotocol/squid-py | squid_py/agreements/storage.py | get_service_agreements | def get_service_agreements(storage_path, status='pending'):
"""
Get service agreements pending to be executed.
:param storage_path: storage path for the internal db, str
:param status:
:return:
"""
conn = sqlite3.connect(storage_path)
try:
cursor = conn.cursor()
return [
row for row in
cursor.execute(
'''
SELECT id, did, service_definition_id, price, files, start_time, status
FROM service_agreements
WHERE status=?;
''',
(status,))
]
finally:
conn.close() | python | def get_service_agreements(storage_path, status='pending'):
conn = sqlite3.connect(storage_path)
try:
cursor = conn.cursor()
return [
row for row in
cursor.execute(
,
(status,))
]
finally:
conn.close() | [
"def",
"get_service_agreements",
"(",
"storage_path",
",",
"status",
"=",
"'pending'",
")",
":",
"conn",
"=",
"sqlite3",
".",
"connect",
"(",
"storage_path",
")",
"try",
":",
"cursor",
"=",
"conn",
".",
"cursor",
"(",
")",
"return",
"[",
"row",
"for",
"row",
"in",
"cursor",
".",
"execute",
"(",
"'''\n SELECT id, did, service_definition_id, price, files, start_time, status\n FROM service_agreements \n WHERE status=?;\n '''",
",",
"(",
"status",
",",
")",
")",
"]",
"finally",
":",
"conn",
".",
"close",
"(",
")"
]
| Get service agreements pending to be executed.
:param storage_path: storage path for the internal db, str
:param status:
:return: | [
"Get",
"service",
"agreements",
"pending",
"to",
"be",
"executed",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/storage.py#L63-L85 |
oceanprotocol/squid-py | squid_py/log.py | setup_logging | def setup_logging(default_path='logging.yaml', default_level=logging.INFO, env_key='LOG_CFG'):
"""Logging setup."""
path = default_path
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(path):
with open(path, 'rt') as file:
try:
config = yaml.safe_load(file.read())
logging.config.dictConfig(config)
coloredlogs.install()
logging.info(f'Logging configuration loaded from file: {path}')
except Exception as ex:
print(ex)
print('Error in Logging Configuration. Using default configs')
logging.basicConfig(level=default_level)
coloredlogs.install(level=default_level)
else:
logging.basicConfig(level=default_level)
coloredlogs.install(level=default_level)
print('Using default logging settings.') | python | def setup_logging(default_path='logging.yaml', default_level=logging.INFO, env_key='LOG_CFG'):
path = default_path
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(path):
with open(path, 'rt') as file:
try:
config = yaml.safe_load(file.read())
logging.config.dictConfig(config)
coloredlogs.install()
logging.info(f'Logging configuration loaded from file: {path}')
except Exception as ex:
print(ex)
print('Error in Logging Configuration. Using default configs')
logging.basicConfig(level=default_level)
coloredlogs.install(level=default_level)
else:
logging.basicConfig(level=default_level)
coloredlogs.install(level=default_level)
print('Using default logging settings.') | [
"def",
"setup_logging",
"(",
"default_path",
"=",
"'logging.yaml'",
",",
"default_level",
"=",
"logging",
".",
"INFO",
",",
"env_key",
"=",
"'LOG_CFG'",
")",
":",
"path",
"=",
"default_path",
"value",
"=",
"os",
".",
"getenv",
"(",
"env_key",
",",
"None",
")",
"if",
"value",
":",
"path",
"=",
"value",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'rt'",
")",
"as",
"file",
":",
"try",
":",
"config",
"=",
"yaml",
".",
"safe_load",
"(",
"file",
".",
"read",
"(",
")",
")",
"logging",
".",
"config",
".",
"dictConfig",
"(",
"config",
")",
"coloredlogs",
".",
"install",
"(",
")",
"logging",
".",
"info",
"(",
"f'Logging configuration loaded from file: {path}'",
")",
"except",
"Exception",
"as",
"ex",
":",
"print",
"(",
"ex",
")",
"print",
"(",
"'Error in Logging Configuration. Using default configs'",
")",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"default_level",
")",
"coloredlogs",
".",
"install",
"(",
"level",
"=",
"default_level",
")",
"else",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"default_level",
")",
"coloredlogs",
".",
"install",
"(",
"level",
"=",
"default_level",
")",
"print",
"(",
"'Using default logging settings.'",
")"
]
| Logging setup. | [
"Logging",
"setup",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/log.py#L13-L34 |
oceanprotocol/squid-py | squid_py/ocean/ocean_secret_store.py | OceanSecretStore.encrypt | def encrypt(self, document_id, content, account):
"""
Encrypt string data using the DID as an secret store id,
if secret store is enabled then return the result from secret store encryption
None for no encryption performed
:param document_id: hex str id of document to use for encryption session
:param content: str to be encrypted
:param account: Account instance encrypting this content
:return: hex str encrypted content
"""
return self._secret_store(account).encrypt_document(document_id, content) | python | def encrypt(self, document_id, content, account):
return self._secret_store(account).encrypt_document(document_id, content) | [
"def",
"encrypt",
"(",
"self",
",",
"document_id",
",",
"content",
",",
"account",
")",
":",
"return",
"self",
".",
"_secret_store",
"(",
"account",
")",
".",
"encrypt_document",
"(",
"document_id",
",",
"content",
")"
]
| Encrypt string data using the DID as an secret store id,
if secret store is enabled then return the result from secret store encryption
None for no encryption performed
:param document_id: hex str id of document to use for encryption session
:param content: str to be encrypted
:param account: Account instance encrypting this content
:return: hex str encrypted content | [
"Encrypt",
"string",
"data",
"using",
"the",
"DID",
"as",
"an",
"secret",
"store",
"id",
"if",
"secret",
"store",
"is",
"enabled",
"then",
"return",
"the",
"result",
"from",
"secret",
"store",
"encryption"
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_secret_store.py#L34-L46 |
oceanprotocol/squid-py | squid_py/ocean/ocean_secret_store.py | OceanSecretStore.decrypt | def decrypt(self, document_id, encrypted_content, account):
"""
Decrypt a previously encrypted content using the secret store keys identified
by document_id.
Note that decryption requires permission already granted to the consumer account.
:param document_id: hex str id of document to use to retrieve the decryption keys
:param encrypted_content: hex str
:param account: Account instance to use for decrypting the `encrypted_content`
:return: str original content
"""
return self._secret_store(account).decrypt_document(document_id, encrypted_content) | python | def decrypt(self, document_id, encrypted_content, account):
return self._secret_store(account).decrypt_document(document_id, encrypted_content) | [
"def",
"decrypt",
"(",
"self",
",",
"document_id",
",",
"encrypted_content",
",",
"account",
")",
":",
"return",
"self",
".",
"_secret_store",
"(",
"account",
")",
".",
"decrypt_document",
"(",
"document_id",
",",
"encrypted_content",
")"
]
| Decrypt a previously encrypted content using the secret store keys identified
by document_id.
Note that decryption requires permission already granted to the consumer account.
:param document_id: hex str id of document to use to retrieve the decryption keys
:param encrypted_content: hex str
:param account: Account instance to use for decrypting the `encrypted_content`
:return: str original content | [
"Decrypt",
"a",
"previously",
"encrypted",
"content",
"using",
"the",
"secret",
"store",
"keys",
"identified",
"by",
"document_id",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_secret_store.py#L48-L60 |
oceanprotocol/squid-py | squid_py/did_resolver/did_resolver.py | DIDResolver.resolve | def resolve(self, did):
"""
Resolve a DID to an URL/DDO or later an internal/external DID.
:param did: 32 byte value or DID string to resolver, this is part of the ocean
DID did:op:<32 byte value>
:return string: URL or DDO of the resolved DID
:return None: if the DID cannot be resolved
:raises ValueError: if did is invalid
:raises TypeError: if did has invalid format
:raises TypeError: on non 32byte value as the DID
:raises TypeError: on any of the resolved values are not string/DID bytes.
:raises OceanDIDNotFound: if no DID can be found to resolve.
"""
did_bytes = did_to_id_bytes(did)
if not isinstance(did_bytes, bytes):
raise TypeError('Invalid did: a 32 Byte DID value required.')
# resolve a DID to a DDO
url = self.get_resolve_url(did_bytes)
logger.debug(f'found did {did} -> url={url}')
return AquariusProvider.get_aquarius(url).get_asset_ddo(did) | python | def resolve(self, did):
did_bytes = did_to_id_bytes(did)
if not isinstance(did_bytes, bytes):
raise TypeError('Invalid did: a 32 Byte DID value required.')
url = self.get_resolve_url(did_bytes)
logger.debug(f'found did {did} -> url={url}')
return AquariusProvider.get_aquarius(url).get_asset_ddo(did) | [
"def",
"resolve",
"(",
"self",
",",
"did",
")",
":",
"did_bytes",
"=",
"did_to_id_bytes",
"(",
"did",
")",
"if",
"not",
"isinstance",
"(",
"did_bytes",
",",
"bytes",
")",
":",
"raise",
"TypeError",
"(",
"'Invalid did: a 32 Byte DID value required.'",
")",
"# resolve a DID to a DDO",
"url",
"=",
"self",
".",
"get_resolve_url",
"(",
"did_bytes",
")",
"logger",
".",
"debug",
"(",
"f'found did {did} -> url={url}'",
")",
"return",
"AquariusProvider",
".",
"get_aquarius",
"(",
"url",
")",
".",
"get_asset_ddo",
"(",
"did",
")"
]
| Resolve a DID to an URL/DDO or later an internal/external DID.
:param did: 32 byte value or DID string to resolver, this is part of the ocean
DID did:op:<32 byte value>
:return string: URL or DDO of the resolved DID
:return None: if the DID cannot be resolved
:raises ValueError: if did is invalid
:raises TypeError: if did has invalid format
:raises TypeError: on non 32byte value as the DID
:raises TypeError: on any of the resolved values are not string/DID bytes.
:raises OceanDIDNotFound: if no DID can be found to resolve. | [
"Resolve",
"a",
"DID",
"to",
"an",
"URL",
"/",
"DDO",
"or",
"later",
"an",
"internal",
"/",
"external",
"DID",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/did_resolver/did_resolver.py#L22-L44 |
oceanprotocol/squid-py | squid_py/did_resolver/did_resolver.py | DIDResolver.get_resolve_url | def get_resolve_url(self, did_bytes):
"""Return a did value and value type from the block chain event record using 'did'.
:param did_bytes: DID, hex-str
:return url: Url, str
"""
data = self._did_registry.get_registered_attribute(did_bytes)
if not (data and data.get('value')):
return None
return data['value'] | python | def get_resolve_url(self, did_bytes):
data = self._did_registry.get_registered_attribute(did_bytes)
if not (data and data.get('value')):
return None
return data['value'] | [
"def",
"get_resolve_url",
"(",
"self",
",",
"did_bytes",
")",
":",
"data",
"=",
"self",
".",
"_did_registry",
".",
"get_registered_attribute",
"(",
"did_bytes",
")",
"if",
"not",
"(",
"data",
"and",
"data",
".",
"get",
"(",
"'value'",
")",
")",
":",
"return",
"None",
"return",
"data",
"[",
"'value'",
"]"
]
| Return a did value and value type from the block chain event record using 'did'.
:param did_bytes: DID, hex-str
:return url: Url, str | [
"Return",
"a",
"did",
"value",
"and",
"value",
"type",
"from",
"the",
"block",
"chain",
"event",
"record",
"using",
"did",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/did_resolver/did_resolver.py#L46-L56 |
oceanprotocol/squid-py | squid_py/keeper/contract_base.py | ContractBase.get_instance | def get_instance(cls, dependencies=None):
"""
Return an instance for a contract name.
:param dependencies:
:return: Contract base instance
"""
assert cls is not ContractBase, 'ContractBase is not meant to be used directly.'
assert cls.CONTRACT_NAME, 'CONTRACT_NAME must be set to a valid keeper contract name.'
return cls(cls.CONTRACT_NAME, dependencies) | python | def get_instance(cls, dependencies=None):
assert cls is not ContractBase, 'ContractBase is not meant to be used directly.'
assert cls.CONTRACT_NAME, 'CONTRACT_NAME must be set to a valid keeper contract name.'
return cls(cls.CONTRACT_NAME, dependencies) | [
"def",
"get_instance",
"(",
"cls",
",",
"dependencies",
"=",
"None",
")",
":",
"assert",
"cls",
"is",
"not",
"ContractBase",
",",
"'ContractBase is not meant to be used directly.'",
"assert",
"cls",
".",
"CONTRACT_NAME",
",",
"'CONTRACT_NAME must be set to a valid keeper contract name.'",
"return",
"cls",
"(",
"cls",
".",
"CONTRACT_NAME",
",",
"dependencies",
")"
]
| Return an instance for a contract name.
:param dependencies:
:return: Contract base instance | [
"Return",
"an",
"instance",
"for",
"a",
"contract",
"name",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/contract_base.py#L38-L47 |
oceanprotocol/squid-py | squid_py/keeper/contract_base.py | ContractBase.get_tx_receipt | def get_tx_receipt(tx_hash):
"""
Get the receipt of a tx.
:param tx_hash: hash of the transaction
:return: Tx receipt
"""
try:
Web3Provider.get_web3().eth.waitForTransactionReceipt(tx_hash, timeout=20)
except Timeout:
logger.info('Waiting for transaction receipt timed out.')
return
return Web3Provider.get_web3().eth.getTransactionReceipt(tx_hash) | python | def get_tx_receipt(tx_hash):
try:
Web3Provider.get_web3().eth.waitForTransactionReceipt(tx_hash, timeout=20)
except Timeout:
logger.info('Waiting for transaction receipt timed out.')
return
return Web3Provider.get_web3().eth.getTransactionReceipt(tx_hash) | [
"def",
"get_tx_receipt",
"(",
"tx_hash",
")",
":",
"try",
":",
"Web3Provider",
".",
"get_web3",
"(",
")",
".",
"eth",
".",
"waitForTransactionReceipt",
"(",
"tx_hash",
",",
"timeout",
"=",
"20",
")",
"except",
"Timeout",
":",
"logger",
".",
"info",
"(",
"'Waiting for transaction receipt timed out.'",
")",
"return",
"return",
"Web3Provider",
".",
"get_web3",
"(",
")",
".",
"eth",
".",
"getTransactionReceipt",
"(",
"tx_hash",
")"
]
| Get the receipt of a tx.
:param tx_hash: hash of the transaction
:return: Tx receipt | [
"Get",
"the",
"receipt",
"of",
"a",
"tx",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/contract_base.py#L83-L95 |
oceanprotocol/squid-py | squid_py/keeper/contract_base.py | ContractBase.subscribe_to_event | def subscribe_to_event(self, event_name, timeout, event_filter, callback=False,
timeout_callback=None, args=None, wait=False):
"""
Create a listener for the event choose.
:param event_name: name of the event to subscribe, str
:param timeout:
:param event_filter:
:param callback:
:param timeout_callback:
:param args:
:param wait: if true block the listener until get the event, bool
:return:
"""
from squid_py.keeper.event_listener import EventListener
return EventListener(
self.CONTRACT_NAME,
event_name,
args,
filters=event_filter
).listen_once(
callback,
timeout_callback=timeout_callback,
timeout=timeout,
blocking=wait
) | python | def subscribe_to_event(self, event_name, timeout, event_filter, callback=False,
timeout_callback=None, args=None, wait=False):
from squid_py.keeper.event_listener import EventListener
return EventListener(
self.CONTRACT_NAME,
event_name,
args,
filters=event_filter
).listen_once(
callback,
timeout_callback=timeout_callback,
timeout=timeout,
blocking=wait
) | [
"def",
"subscribe_to_event",
"(",
"self",
",",
"event_name",
",",
"timeout",
",",
"event_filter",
",",
"callback",
"=",
"False",
",",
"timeout_callback",
"=",
"None",
",",
"args",
"=",
"None",
",",
"wait",
"=",
"False",
")",
":",
"from",
"squid_py",
".",
"keeper",
".",
"event_listener",
"import",
"EventListener",
"return",
"EventListener",
"(",
"self",
".",
"CONTRACT_NAME",
",",
"event_name",
",",
"args",
",",
"filters",
"=",
"event_filter",
")",
".",
"listen_once",
"(",
"callback",
",",
"timeout_callback",
"=",
"timeout_callback",
",",
"timeout",
"=",
"timeout",
",",
"blocking",
"=",
"wait",
")"
]
| Create a listener for the event choose.
:param event_name: name of the event to subscribe, str
:param timeout:
:param event_filter:
:param callback:
:param timeout_callback:
:param args:
:param wait: if true block the listener until get the event, bool
:return: | [
"Create",
"a",
"listener",
"for",
"the",
"event",
"choose",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/contract_base.py#L97-L122 |
oceanprotocol/squid-py | squid_py/keeper/contract_base.py | ContractBase.send_transaction | def send_transaction(self, fn_name, fn_args, transact=None):
"""Calls a smart contract function using either `personal_sendTransaction` (if
passphrase is available) or `ether_sendTransaction`.
:param fn_name: str the smart contract function name
:param fn_args: tuple arguments to pass to function above
:param transact: dict arguments for the transaction such as from, gas, etc.
:return:
"""
contract_fn = getattr(self.contract.functions, fn_name)(*fn_args)
contract_function = SquidContractFunction(
contract_fn
)
return contract_function.transact(transact) | python | def send_transaction(self, fn_name, fn_args, transact=None):
contract_fn = getattr(self.contract.functions, fn_name)(*fn_args)
contract_function = SquidContractFunction(
contract_fn
)
return contract_function.transact(transact) | [
"def",
"send_transaction",
"(",
"self",
",",
"fn_name",
",",
"fn_args",
",",
"transact",
"=",
"None",
")",
":",
"contract_fn",
"=",
"getattr",
"(",
"self",
".",
"contract",
".",
"functions",
",",
"fn_name",
")",
"(",
"*",
"fn_args",
")",
"contract_function",
"=",
"SquidContractFunction",
"(",
"contract_fn",
")",
"return",
"contract_function",
".",
"transact",
"(",
"transact",
")"
]
| Calls a smart contract function using either `personal_sendTransaction` (if
passphrase is available) or `ether_sendTransaction`.
:param fn_name: str the smart contract function name
:param fn_args: tuple arguments to pass to function above
:param transact: dict arguments for the transaction such as from, gas, etc.
:return: | [
"Calls",
"a",
"smart",
"contract",
"function",
"using",
"either",
"personal_sendTransaction",
"(",
"if",
"passphrase",
"is",
"available",
")",
"or",
"ether_sendTransaction",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/contract_base.py#L124-L137 |
oceanprotocol/squid-py | squid_py/agreements/events/escrow_reward_condition.py | refund_reward | def refund_reward(event, agreement_id, did, service_agreement, price, consumer_account,
publisher_address, condition_ids):
"""
Refund the reward to the publisher address.
:param event: AttributeDict with the event data.
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param service_agreement: ServiceAgreement instance
:param price: Asset price, int
:param consumer_account: Account instance of the consumer
:param publisher_address: ethereum account address of publisher, hex str
:param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32
"""
logger.debug(f"trigger refund after event {event}.")
access_id, lock_id = condition_ids[:2]
name_to_parameter = {param.name: param for param in
service_agreement.condition_by_name['escrowReward'].parameters}
document_id = add_0x_prefix(name_to_parameter['_documentId'].value)
asset_id = add_0x_prefix(did_to_id(did))
assert document_id == asset_id, f'document_id {document_id} <=> asset_id {asset_id} mismatch.'
assert price == service_agreement.get_price(), 'price mismatch.'
# logger.info(f'About to do grantAccess: account {account.address},
# saId {service_agreement_id}, '
# f'documentKeyId {document_key_id}')
try:
tx_hash = Keeper.get_instance().escrow_reward_condition.fulfill(
agreement_id,
price,
publisher_address,
consumer_account.address,
lock_id,
access_id,
consumer_account
)
process_tx_receipt(
tx_hash,
Keeper.get_instance().escrow_reward_condition.FULFILLED_EVENT,
'EscrowReward.Fulfilled'
)
except Exception as e:
# logger.error(f'Error when doing escrow_reward_condition.fulfills: {e}')
raise e | python | def refund_reward(event, agreement_id, did, service_agreement, price, consumer_account,
publisher_address, condition_ids):
logger.debug(f"trigger refund after event {event}.")
access_id, lock_id = condition_ids[:2]
name_to_parameter = {param.name: param for param in
service_agreement.condition_by_name['escrowReward'].parameters}
document_id = add_0x_prefix(name_to_parameter['_documentId'].value)
asset_id = add_0x_prefix(did_to_id(did))
assert document_id == asset_id, f'document_id {document_id} <=> asset_id {asset_id} mismatch.'
assert price == service_agreement.get_price(), 'price mismatch.'
try:
tx_hash = Keeper.get_instance().escrow_reward_condition.fulfill(
agreement_id,
price,
publisher_address,
consumer_account.address,
lock_id,
access_id,
consumer_account
)
process_tx_receipt(
tx_hash,
Keeper.get_instance().escrow_reward_condition.FULFILLED_EVENT,
'EscrowReward.Fulfilled'
)
except Exception as e:
raise e | [
"def",
"refund_reward",
"(",
"event",
",",
"agreement_id",
",",
"did",
",",
"service_agreement",
",",
"price",
",",
"consumer_account",
",",
"publisher_address",
",",
"condition_ids",
")",
":",
"logger",
".",
"debug",
"(",
"f\"trigger refund after event {event}.\"",
")",
"access_id",
",",
"lock_id",
"=",
"condition_ids",
"[",
":",
"2",
"]",
"name_to_parameter",
"=",
"{",
"param",
".",
"name",
":",
"param",
"for",
"param",
"in",
"service_agreement",
".",
"condition_by_name",
"[",
"'escrowReward'",
"]",
".",
"parameters",
"}",
"document_id",
"=",
"add_0x_prefix",
"(",
"name_to_parameter",
"[",
"'_documentId'",
"]",
".",
"value",
")",
"asset_id",
"=",
"add_0x_prefix",
"(",
"did_to_id",
"(",
"did",
")",
")",
"assert",
"document_id",
"==",
"asset_id",
",",
"f'document_id {document_id} <=> asset_id {asset_id} mismatch.'",
"assert",
"price",
"==",
"service_agreement",
".",
"get_price",
"(",
")",
",",
"'price mismatch.'",
"# logger.info(f'About to do grantAccess: account {account.address},",
"# saId {service_agreement_id}, '",
"# f'documentKeyId {document_key_id}')",
"try",
":",
"tx_hash",
"=",
"Keeper",
".",
"get_instance",
"(",
")",
".",
"escrow_reward_condition",
".",
"fulfill",
"(",
"agreement_id",
",",
"price",
",",
"publisher_address",
",",
"consumer_account",
".",
"address",
",",
"lock_id",
",",
"access_id",
",",
"consumer_account",
")",
"process_tx_receipt",
"(",
"tx_hash",
",",
"Keeper",
".",
"get_instance",
"(",
")",
".",
"escrow_reward_condition",
".",
"FULFILLED_EVENT",
",",
"'EscrowReward.Fulfilled'",
")",
"except",
"Exception",
"as",
"e",
":",
"# logger.error(f'Error when doing escrow_reward_condition.fulfills: {e}')",
"raise",
"e"
]
| Refund the reward to the publisher address.
:param event: AttributeDict with the event data.
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param service_agreement: ServiceAgreement instance
:param price: Asset price, int
:param consumer_account: Account instance of the consumer
:param publisher_address: ethereum account address of publisher, hex str
:param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32 | [
"Refund",
"the",
"reward",
"to",
"the",
"publisher",
"address",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/events/escrow_reward_condition.py#L56-L98 |
oceanprotocol/squid-py | squid_py/agreements/events/escrow_reward_condition.py | consume_asset | def consume_asset(event, agreement_id, did, service_agreement, consumer_account, consume_callback):
"""
Consumption of an asset after get the event call.
:param event: AttributeDict with the event data.
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param service_agreement: ServiceAgreement instance
:param consumer_account: Account instance of the consumer
:param consume_callback:
"""
logger.debug(f"consuming asset after event {event}.")
if consume_callback:
config = ConfigProvider.get_config()
secret_store = SecretStoreProvider.get_secret_store(
config.secret_store_url, config.parity_url, consumer_account
)
brizo = BrizoProvider.get_brizo()
consume_callback(
agreement_id,
service_agreement.service_definition_id,
DIDResolver(Keeper.get_instance().did_registry).resolve(did),
consumer_account,
ConfigProvider.get_config().downloads_path,
brizo,
secret_store
) | python | def consume_asset(event, agreement_id, did, service_agreement, consumer_account, consume_callback):
logger.debug(f"consuming asset after event {event}.")
if consume_callback:
config = ConfigProvider.get_config()
secret_store = SecretStoreProvider.get_secret_store(
config.secret_store_url, config.parity_url, consumer_account
)
brizo = BrizoProvider.get_brizo()
consume_callback(
agreement_id,
service_agreement.service_definition_id,
DIDResolver(Keeper.get_instance().did_registry).resolve(did),
consumer_account,
ConfigProvider.get_config().downloads_path,
brizo,
secret_store
) | [
"def",
"consume_asset",
"(",
"event",
",",
"agreement_id",
",",
"did",
",",
"service_agreement",
",",
"consumer_account",
",",
"consume_callback",
")",
":",
"logger",
".",
"debug",
"(",
"f\"consuming asset after event {event}.\"",
")",
"if",
"consume_callback",
":",
"config",
"=",
"ConfigProvider",
".",
"get_config",
"(",
")",
"secret_store",
"=",
"SecretStoreProvider",
".",
"get_secret_store",
"(",
"config",
".",
"secret_store_url",
",",
"config",
".",
"parity_url",
",",
"consumer_account",
")",
"brizo",
"=",
"BrizoProvider",
".",
"get_brizo",
"(",
")",
"consume_callback",
"(",
"agreement_id",
",",
"service_agreement",
".",
"service_definition_id",
",",
"DIDResolver",
"(",
"Keeper",
".",
"get_instance",
"(",
")",
".",
"did_registry",
")",
".",
"resolve",
"(",
"did",
")",
",",
"consumer_account",
",",
"ConfigProvider",
".",
"get_config",
"(",
")",
".",
"downloads_path",
",",
"brizo",
",",
"secret_store",
")"
]
| Consumption of an asset after get the event call.
:param event: AttributeDict with the event data.
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param service_agreement: ServiceAgreement instance
:param consumer_account: Account instance of the consumer
:param consume_callback: | [
"Consumption",
"of",
"an",
"asset",
"after",
"get",
"the",
"event",
"call",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/events/escrow_reward_condition.py#L101-L128 |
oceanprotocol/squid-py | squid_py/keeper/diagnostics.py | Diagnostics.verify_contracts | def verify_contracts():
"""
Verify that the contracts are deployed correctly in the network.
:raise Exception: raise exception if the contracts are not deployed correctly.
"""
artifacts_path = ConfigProvider.get_config().keeper_path
logger.info(f'Keeper contract artifacts (JSON abi files) at: {artifacts_path}')
if os.environ.get('KEEPER_NETWORK_NAME'):
logger.warning(f'The `KEEPER_NETWORK_NAME` env var is set to '
f'{os.environ.get("KEEPER_NETWORK_NAME")}. '
f'This enables the user to override the method of how the network name '
f'is inferred from network id.')
# try to find contract with this network name
contract_name = Diagnostics.TEST_CONTRACT_NAME
network_id = Keeper.get_network_id()
network_name = Keeper.get_network_name(network_id)
logger.info(f'Using keeper contracts from network {network_name}, '
f'network id is {network_id}')
logger.info(f'Looking for keeper contracts ending with ".{network_name}.json", '
f'e.g. "{contract_name}.{network_name}.json".')
existing_contract_names = os.listdir(artifacts_path)
try:
ContractHandler.get(contract_name)
except Exception as e:
logger.error(e)
logger.error(f'Cannot find the keeper contracts. \n'
f'Current network id is {network_id} and network name is {network_name}.'
f'Expected to find contracts ending with ".{network_name}.json",'
f' e.g. "{contract_name}.{network_name}.json"')
raise OceanKeeperContractsNotFound(
f'Keeper contracts for keeper network {network_name} were not found '
f'in {artifacts_path}. \n'
f'Found the following contracts: \n\t{existing_contract_names}'
)
keeper = Keeper.get_instance()
contracts = [keeper.dispenser, keeper.token, keeper.did_registry,
keeper.agreement_manager, keeper.template_manager, keeper.condition_manager,
keeper.access_secret_store_condition, keeper.sign_condition,
keeper.lock_reward_condition, keeper.escrow_access_secretstore_template,
keeper.escrow_reward_condition, keeper.hash_lock_condition
]
addresses = '\n'.join([f'\t{c.name}: {c.address}' for c in contracts])
logging.info('Finished loading keeper contracts:\n'
'%s', addresses) | python | def verify_contracts():
artifacts_path = ConfigProvider.get_config().keeper_path
logger.info(f'Keeper contract artifacts (JSON abi files) at: {artifacts_path}')
if os.environ.get('KEEPER_NETWORK_NAME'):
logger.warning(f'The `KEEPER_NETWORK_NAME` env var is set to '
f'{os.environ.get("KEEPER_NETWORK_NAME")}. '
f'This enables the user to override the method of how the network name '
f'is inferred from network id.')
contract_name = Diagnostics.TEST_CONTRACT_NAME
network_id = Keeper.get_network_id()
network_name = Keeper.get_network_name(network_id)
logger.info(f'Using keeper contracts from network {network_name}, '
f'network id is {network_id}')
logger.info(f'Looking for keeper contracts ending with ".{network_name}.json", '
f'e.g. "{contract_name}.{network_name}.json".')
existing_contract_names = os.listdir(artifacts_path)
try:
ContractHandler.get(contract_name)
except Exception as e:
logger.error(e)
logger.error(f'Cannot find the keeper contracts. \n'
f'Current network id is {network_id} and network name is {network_name}.'
f'Expected to find contracts ending with ".{network_name}.json",'
f' e.g. "{contract_name}.{network_name}.json"')
raise OceanKeeperContractsNotFound(
f'Keeper contracts for keeper network {network_name} were not found '
f'in {artifacts_path}. \n'
f'Found the following contracts: \n\t{existing_contract_names}'
)
keeper = Keeper.get_instance()
contracts = [keeper.dispenser, keeper.token, keeper.did_registry,
keeper.agreement_manager, keeper.template_manager, keeper.condition_manager,
keeper.access_secret_store_condition, keeper.sign_condition,
keeper.lock_reward_condition, keeper.escrow_access_secretstore_template,
keeper.escrow_reward_condition, keeper.hash_lock_condition
]
addresses = '\n'.join([f'\t{c.name}: {c.address}' for c in contracts])
logging.info('Finished loading keeper contracts:\n'
'%s', addresses) | [
"def",
"verify_contracts",
"(",
")",
":",
"artifacts_path",
"=",
"ConfigProvider",
".",
"get_config",
"(",
")",
".",
"keeper_path",
"logger",
".",
"info",
"(",
"f'Keeper contract artifacts (JSON abi files) at: {artifacts_path}'",
")",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'KEEPER_NETWORK_NAME'",
")",
":",
"logger",
".",
"warning",
"(",
"f'The `KEEPER_NETWORK_NAME` env var is set to '",
"f'{os.environ.get(\"KEEPER_NETWORK_NAME\")}. '",
"f'This enables the user to override the method of how the network name '",
"f'is inferred from network id.'",
")",
"# try to find contract with this network name",
"contract_name",
"=",
"Diagnostics",
".",
"TEST_CONTRACT_NAME",
"network_id",
"=",
"Keeper",
".",
"get_network_id",
"(",
")",
"network_name",
"=",
"Keeper",
".",
"get_network_name",
"(",
"network_id",
")",
"logger",
".",
"info",
"(",
"f'Using keeper contracts from network {network_name}, '",
"f'network id is {network_id}'",
")",
"logger",
".",
"info",
"(",
"f'Looking for keeper contracts ending with \".{network_name}.json\", '",
"f'e.g. \"{contract_name}.{network_name}.json\".'",
")",
"existing_contract_names",
"=",
"os",
".",
"listdir",
"(",
"artifacts_path",
")",
"try",
":",
"ContractHandler",
".",
"get",
"(",
"contract_name",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"error",
"(",
"e",
")",
"logger",
".",
"error",
"(",
"f'Cannot find the keeper contracts. \\n'",
"f'Current network id is {network_id} and network name is {network_name}.'",
"f'Expected to find contracts ending with \".{network_name}.json\",'",
"f' e.g. \"{contract_name}.{network_name}.json\"'",
")",
"raise",
"OceanKeeperContractsNotFound",
"(",
"f'Keeper contracts for keeper network {network_name} were not found '",
"f'in {artifacts_path}. \\n'",
"f'Found the following contracts: \\n\\t{existing_contract_names}'",
")",
"keeper",
"=",
"Keeper",
".",
"get_instance",
"(",
")",
"contracts",
"=",
"[",
"keeper",
".",
"dispenser",
",",
"keeper",
".",
"token",
",",
"keeper",
".",
"did_registry",
",",
"keeper",
".",
"agreement_manager",
",",
"keeper",
".",
"template_manager",
",",
"keeper",
".",
"condition_manager",
",",
"keeper",
".",
"access_secret_store_condition",
",",
"keeper",
".",
"sign_condition",
",",
"keeper",
".",
"lock_reward_condition",
",",
"keeper",
".",
"escrow_access_secretstore_template",
",",
"keeper",
".",
"escrow_reward_condition",
",",
"keeper",
".",
"hash_lock_condition",
"]",
"addresses",
"=",
"'\\n'",
".",
"join",
"(",
"[",
"f'\\t{c.name}: {c.address}'",
"for",
"c",
"in",
"contracts",
"]",
")",
"logging",
".",
"info",
"(",
"'Finished loading keeper contracts:\\n'",
"'%s'",
",",
"addresses",
")"
]
| Verify that the contracts are deployed correctly in the network.
:raise Exception: raise exception if the contracts are not deployed correctly. | [
"Verify",
"that",
"the",
"contracts",
"are",
"deployed",
"correctly",
"in",
"the",
"network",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/diagnostics.py#L19-L66 |
oceanprotocol/squid-py | squid_py/ocean/ocean_services.py | OceanServices.create_access_service | def create_access_service(price, service_endpoint, consume_endpoint, timeout=None):
"""
Publish an asset with an `Access` service according to the supplied attributes.
:param price: Asset price, int
:param service_endpoint: str URL for initiating service access request
:param consume_endpoint: str URL to consume service
:param timeout: int amount of time in seconds before the agreement expires
:return: Service instance or None
"""
timeout = timeout or 3600 # default to one hour timeout
service = ServiceDescriptor.access_service_descriptor(
price, service_endpoint, consume_endpoint, timeout, ''
)
return service | python | def create_access_service(price, service_endpoint, consume_endpoint, timeout=None):
timeout = timeout or 3600
service = ServiceDescriptor.access_service_descriptor(
price, service_endpoint, consume_endpoint, timeout, ''
)
return service | [
"def",
"create_access_service",
"(",
"price",
",",
"service_endpoint",
",",
"consume_endpoint",
",",
"timeout",
"=",
"None",
")",
":",
"timeout",
"=",
"timeout",
"or",
"3600",
"# default to one hour timeout",
"service",
"=",
"ServiceDescriptor",
".",
"access_service_descriptor",
"(",
"price",
",",
"service_endpoint",
",",
"consume_endpoint",
",",
"timeout",
",",
"''",
")",
"return",
"service"
]
| Publish an asset with an `Access` service according to the supplied attributes.
:param price: Asset price, int
:param service_endpoint: str URL for initiating service access request
:param consume_endpoint: str URL to consume service
:param timeout: int amount of time in seconds before the agreement expires
:return: Service instance or None | [
"Publish",
"an",
"asset",
"with",
"an",
"Access",
"service",
"according",
"to",
"the",
"supplied",
"attributes",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_services.py#L12-L27 |
oceanprotocol/squid-py | squid_py/agreements/events/lock_reward_condition.py | fulfill_lock_reward_condition | def fulfill_lock_reward_condition(event, agreement_id, price, consumer_account):
"""
Fulfill the lock reward condition.
:param event: AttributeDict with the event data.
:param agreement_id: id of the agreement, hex str
:param price: Asset price, int
:param consumer_account: Account instance of the consumer
"""
logger.debug(f"about to lock reward after event {event}.")
keeper = Keeper.get_instance()
tx_hash = None
try:
keeper.token.token_approve(keeper.lock_reward_condition.address, price, consumer_account)
tx_hash = keeper.lock_reward_condition.fulfill(
agreement_id, keeper.escrow_reward_condition.address, price, consumer_account
)
process_tx_receipt(
tx_hash,
keeper.lock_reward_condition.FULFILLED_EVENT,
'LockRewardCondition.Fulfilled'
)
except Exception as e:
logger.debug(f'error locking reward: {e}')
if not tx_hash:
raise e | python | def fulfill_lock_reward_condition(event, agreement_id, price, consumer_account):
logger.debug(f"about to lock reward after event {event}.")
keeper = Keeper.get_instance()
tx_hash = None
try:
keeper.token.token_approve(keeper.lock_reward_condition.address, price, consumer_account)
tx_hash = keeper.lock_reward_condition.fulfill(
agreement_id, keeper.escrow_reward_condition.address, price, consumer_account
)
process_tx_receipt(
tx_hash,
keeper.lock_reward_condition.FULFILLED_EVENT,
'LockRewardCondition.Fulfilled'
)
except Exception as e:
logger.debug(f'error locking reward: {e}')
if not tx_hash:
raise e | [
"def",
"fulfill_lock_reward_condition",
"(",
"event",
",",
"agreement_id",
",",
"price",
",",
"consumer_account",
")",
":",
"logger",
".",
"debug",
"(",
"f\"about to lock reward after event {event}.\"",
")",
"keeper",
"=",
"Keeper",
".",
"get_instance",
"(",
")",
"tx_hash",
"=",
"None",
"try",
":",
"keeper",
".",
"token",
".",
"token_approve",
"(",
"keeper",
".",
"lock_reward_condition",
".",
"address",
",",
"price",
",",
"consumer_account",
")",
"tx_hash",
"=",
"keeper",
".",
"lock_reward_condition",
".",
"fulfill",
"(",
"agreement_id",
",",
"keeper",
".",
"escrow_reward_condition",
".",
"address",
",",
"price",
",",
"consumer_account",
")",
"process_tx_receipt",
"(",
"tx_hash",
",",
"keeper",
".",
"lock_reward_condition",
".",
"FULFILLED_EVENT",
",",
"'LockRewardCondition.Fulfilled'",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"debug",
"(",
"f'error locking reward: {e}'",
")",
"if",
"not",
"tx_hash",
":",
"raise",
"e"
]
| Fulfill the lock reward condition.
:param event: AttributeDict with the event data.
:param agreement_id: id of the agreement, hex str
:param price: Asset price, int
:param consumer_account: Account instance of the consumer | [
"Fulfill",
"the",
"lock",
"reward",
"condition",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/events/lock_reward_condition.py#L13-L38 |
oceanprotocol/squid-py | squid_py/ocean/ocean_conditions.py | OceanConditions.lock_reward | def lock_reward(self, agreement_id, amount, account):
"""
Lock reward condition.
:param agreement_id: id of the agreement, hex str
:param amount: Amount of tokens, int
:param account: Account
:return: bool
"""
return self._keeper.lock_reward_condition.fulfill(
agreement_id, self._keeper.escrow_reward_condition.address, amount, account
) | python | def lock_reward(self, agreement_id, amount, account):
return self._keeper.lock_reward_condition.fulfill(
agreement_id, self._keeper.escrow_reward_condition.address, amount, account
) | [
"def",
"lock_reward",
"(",
"self",
",",
"agreement_id",
",",
"amount",
",",
"account",
")",
":",
"return",
"self",
".",
"_keeper",
".",
"lock_reward_condition",
".",
"fulfill",
"(",
"agreement_id",
",",
"self",
".",
"_keeper",
".",
"escrow_reward_condition",
".",
"address",
",",
"amount",
",",
"account",
")"
]
| Lock reward condition.
:param agreement_id: id of the agreement, hex str
:param amount: Amount of tokens, int
:param account: Account
:return: bool | [
"Lock",
"reward",
"condition",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_conditions.py#L15-L26 |
oceanprotocol/squid-py | squid_py/ocean/ocean_conditions.py | OceanConditions.grant_access | def grant_access(self, agreement_id, did, grantee_address, account):
"""
Grant access condition.
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param grantee_address: Address, hex str
:param account: Account
:return:
"""
return self._keeper.access_secret_store_condition.fulfill(
agreement_id, add_0x_prefix(did_to_id(did)), grantee_address, account
) | python | def grant_access(self, agreement_id, did, grantee_address, account):
return self._keeper.access_secret_store_condition.fulfill(
agreement_id, add_0x_prefix(did_to_id(did)), grantee_address, account
) | [
"def",
"grant_access",
"(",
"self",
",",
"agreement_id",
",",
"did",
",",
"grantee_address",
",",
"account",
")",
":",
"return",
"self",
".",
"_keeper",
".",
"access_secret_store_condition",
".",
"fulfill",
"(",
"agreement_id",
",",
"add_0x_prefix",
"(",
"did_to_id",
"(",
"did",
")",
")",
",",
"grantee_address",
",",
"account",
")"
]
| Grant access condition.
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param grantee_address: Address, hex str
:param account: Account
:return: | [
"Grant",
"access",
"condition",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_conditions.py#L28-L40 |
oceanprotocol/squid-py | squid_py/ocean/ocean_conditions.py | OceanConditions.release_reward | def release_reward(self, agreement_id, amount, account):
"""
Release reward condition.
:param agreement_id: id of the agreement, hex str
:param amount: Amount of tokens, int
:param account: Account
:return:
"""
agreement_values = self._keeper.agreement_manager.get_agreement(agreement_id)
consumer, provider = self._keeper.escrow_access_secretstore_template.get_agreement_data(
agreement_id)
access_id, lock_id = agreement_values.condition_ids[:2]
return self._keeper.escrow_reward_condition.fulfill(
agreement_id,
amount,
provider,
consumer,
lock_id,
access_id,
account
) | python | def release_reward(self, agreement_id, amount, account):
agreement_values = self._keeper.agreement_manager.get_agreement(agreement_id)
consumer, provider = self._keeper.escrow_access_secretstore_template.get_agreement_data(
agreement_id)
access_id, lock_id = agreement_values.condition_ids[:2]
return self._keeper.escrow_reward_condition.fulfill(
agreement_id,
amount,
provider,
consumer,
lock_id,
access_id,
account
) | [
"def",
"release_reward",
"(",
"self",
",",
"agreement_id",
",",
"amount",
",",
"account",
")",
":",
"agreement_values",
"=",
"self",
".",
"_keeper",
".",
"agreement_manager",
".",
"get_agreement",
"(",
"agreement_id",
")",
"consumer",
",",
"provider",
"=",
"self",
".",
"_keeper",
".",
"escrow_access_secretstore_template",
".",
"get_agreement_data",
"(",
"agreement_id",
")",
"access_id",
",",
"lock_id",
"=",
"agreement_values",
".",
"condition_ids",
"[",
":",
"2",
"]",
"return",
"self",
".",
"_keeper",
".",
"escrow_reward_condition",
".",
"fulfill",
"(",
"agreement_id",
",",
"amount",
",",
"provider",
",",
"consumer",
",",
"lock_id",
",",
"access_id",
",",
"account",
")"
]
| Release reward condition.
:param agreement_id: id of the agreement, hex str
:param amount: Amount of tokens, int
:param account: Account
:return: | [
"Release",
"reward",
"condition",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_conditions.py#L42-L63 |
oceanprotocol/squid-py | squid_py/ocean/ocean_conditions.py | OceanConditions.refund_reward | def refund_reward(self, agreement_id, amount, account):
"""
Refund reaward condition.
:param agreement_id: id of the agreement, hex str
:param amount: Amount of tokens, int
:param account: Account
:return:
"""
return self.release_reward(agreement_id, amount, account) | python | def refund_reward(self, agreement_id, amount, account):
return self.release_reward(agreement_id, amount, account) | [
"def",
"refund_reward",
"(",
"self",
",",
"agreement_id",
",",
"amount",
",",
"account",
")",
":",
"return",
"self",
".",
"release_reward",
"(",
"agreement_id",
",",
"amount",
",",
"account",
")"
]
| Refund reaward condition.
:param agreement_id: id of the agreement, hex str
:param amount: Amount of tokens, int
:param account: Account
:return: | [
"Refund",
"reaward",
"condition",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_conditions.py#L65-L74 |
oceanprotocol/squid-py | squid_py/agreements/service_agreement_template.py | ServiceAgreementTemplate.from_json_file | def from_json_file(cls, path):
"""
Return a template from a json allocated in a path.
:param path: string
:return: ServiceAgreementTemplate
"""
with open(path) as jsf:
template_json = json.load(jsf)
return cls(template_json=template_json) | python | def from_json_file(cls, path):
with open(path) as jsf:
template_json = json.load(jsf)
return cls(template_json=template_json) | [
"def",
"from_json_file",
"(",
"cls",
",",
"path",
")",
":",
"with",
"open",
"(",
"path",
")",
"as",
"jsf",
":",
"template_json",
"=",
"json",
".",
"load",
"(",
"jsf",
")",
"return",
"cls",
"(",
"template_json",
"=",
"template_json",
")"
]
| Return a template from a json allocated in a path.
:param path: string
:return: ServiceAgreementTemplate | [
"Return",
"a",
"template",
"from",
"a",
"json",
"allocated",
"in",
"a",
"path",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_agreement_template.py#L24-L33 |
oceanprotocol/squid-py | squid_py/agreements/service_agreement_template.py | ServiceAgreementTemplate.parse_template_json | def parse_template_json(self, template_json):
"""
Parse a template from a json.
:param template_json: json dict
"""
assert template_json['type'] == self.DOCUMENT_TYPE, ''
self.template_id = template_json['templateId']
self.name = template_json.get('name')
self.creator = template_json.get('creator')
self.template = template_json['serviceAgreementTemplate'] | python | def parse_template_json(self, template_json):
assert template_json['type'] == self.DOCUMENT_TYPE, ''
self.template_id = template_json['templateId']
self.name = template_json.get('name')
self.creator = template_json.get('creator')
self.template = template_json['serviceAgreementTemplate'] | [
"def",
"parse_template_json",
"(",
"self",
",",
"template_json",
")",
":",
"assert",
"template_json",
"[",
"'type'",
"]",
"==",
"self",
".",
"DOCUMENT_TYPE",
",",
"''",
"self",
".",
"template_id",
"=",
"template_json",
"[",
"'templateId'",
"]",
"self",
".",
"name",
"=",
"template_json",
".",
"get",
"(",
"'name'",
")",
"self",
".",
"creator",
"=",
"template_json",
".",
"get",
"(",
"'creator'",
")",
"self",
".",
"template",
"=",
"template_json",
"[",
"'serviceAgreementTemplate'",
"]"
]
| Parse a template from a json.
:param template_json: json dict | [
"Parse",
"a",
"template",
"from",
"a",
"json",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_agreement_template.py#L35-L45 |
oceanprotocol/squid-py | squid_py/agreements/service_agreement_template.py | ServiceAgreementTemplate.as_dictionary | def as_dictionary(self):
"""
Return the service agreement template as a dictionary.
:return: dict
"""
template = {
'contractName': self.contract_name,
'events': [e.as_dictionary() for e in self.agreement_events],
'fulfillmentOrder': self.fulfillment_order,
'conditionDependency': self.condition_dependency,
'conditions': [cond.as_dictionary() for cond in self.conditions]
}
return {
# 'type': self.DOCUMENT_TYPE,
'name': self.name,
'creator': self.creator,
'serviceAgreementTemplate': template
} | python | def as_dictionary(self):
template = {
'contractName': self.contract_name,
'events': [e.as_dictionary() for e in self.agreement_events],
'fulfillmentOrder': self.fulfillment_order,
'conditionDependency': self.condition_dependency,
'conditions': [cond.as_dictionary() for cond in self.conditions]
}
return {
'name': self.name,
'creator': self.creator,
'serviceAgreementTemplate': template
} | [
"def",
"as_dictionary",
"(",
"self",
")",
":",
"template",
"=",
"{",
"'contractName'",
":",
"self",
".",
"contract_name",
",",
"'events'",
":",
"[",
"e",
".",
"as_dictionary",
"(",
")",
"for",
"e",
"in",
"self",
".",
"agreement_events",
"]",
",",
"'fulfillmentOrder'",
":",
"self",
".",
"fulfillment_order",
",",
"'conditionDependency'",
":",
"self",
".",
"condition_dependency",
",",
"'conditions'",
":",
"[",
"cond",
".",
"as_dictionary",
"(",
")",
"for",
"cond",
"in",
"self",
".",
"conditions",
"]",
"}",
"return",
"{",
"# 'type': self.DOCUMENT_TYPE,",
"'name'",
":",
"self",
".",
"name",
",",
"'creator'",
":",
"self",
".",
"creator",
",",
"'serviceAgreementTemplate'",
":",
"template",
"}"
]
| Return the service agreement template as a dictionary.
:return: dict | [
"Return",
"the",
"service",
"agreement",
"template",
"as",
"a",
"dictionary",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_agreement_template.py#L110-L128 |
oceanprotocol/squid-py | squid_py/ocean/ocean_tokens.py | OceanTokens.request | def request(self, account, amount):
"""
Request a number of tokens to be minted and transfered to `account`
:param account: Account instance requesting the tokens
:param amount: int number of tokens to request
:return: bool
"""
return self._keeper.dispenser.request_tokens(amount, account) | python | def request(self, account, amount):
return self._keeper.dispenser.request_tokens(amount, account) | [
"def",
"request",
"(",
"self",
",",
"account",
",",
"amount",
")",
":",
"return",
"self",
".",
"_keeper",
".",
"dispenser",
".",
"request_tokens",
"(",
"amount",
",",
"account",
")"
]
| Request a number of tokens to be minted and transfered to `account`
:param account: Account instance requesting the tokens
:param amount: int number of tokens to request
:return: bool | [
"Request",
"a",
"number",
"of",
"tokens",
"to",
"be",
"minted",
"and",
"transfered",
"to",
"account"
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_tokens.py#L11-L19 |
oceanprotocol/squid-py | squid_py/ocean/ocean_tokens.py | OceanTokens.transfer | def transfer(self, receiver_address, amount, sender_account):
"""
Transfer a number of tokens from `sender_account` to `receiver_address`
:param receiver_address: hex str ethereum address to receive this transfer of tokens
:param amount: int number of tokens to transfer
:param sender_account: Account instance to take the tokens from
:return: bool
"""
self._keeper.token.token_approve(receiver_address, amount,
sender_account)
self._keeper.token.transfer(receiver_address, amount, sender_account) | python | def transfer(self, receiver_address, amount, sender_account):
self._keeper.token.token_approve(receiver_address, amount,
sender_account)
self._keeper.token.transfer(receiver_address, amount, sender_account) | [
"def",
"transfer",
"(",
"self",
",",
"receiver_address",
",",
"amount",
",",
"sender_account",
")",
":",
"self",
".",
"_keeper",
".",
"token",
".",
"token_approve",
"(",
"receiver_address",
",",
"amount",
",",
"sender_account",
")",
"self",
".",
"_keeper",
".",
"token",
".",
"transfer",
"(",
"receiver_address",
",",
"amount",
",",
"sender_account",
")"
]
| Transfer a number of tokens from `sender_account` to `receiver_address`
:param receiver_address: hex str ethereum address to receive this transfer of tokens
:param amount: int number of tokens to transfer
:param sender_account: Account instance to take the tokens from
:return: bool | [
"Transfer",
"a",
"number",
"of",
"tokens",
"from",
"sender_account",
"to",
"receiver_address"
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_tokens.py#L21-L32 |
oceanprotocol/squid-py | squid_py/aquarius/aquarius.py | Aquarius.list_assets | def list_assets(self):
"""
List all the assets registered in the aquarius instance.
:return: List of DID string
"""
response = self.requests_session.get(self._base_url).content
if not response:
return {}
try:
asset_list = json.loads(response)
except TypeError:
asset_list = None
except ValueError:
raise ValueError(response.decode('UTF-8'))
if not asset_list:
return []
if 'ids' in asset_list:
return asset_list['ids']
return [] | python | def list_assets(self):
response = self.requests_session.get(self._base_url).content
if not response:
return {}
try:
asset_list = json.loads(response)
except TypeError:
asset_list = None
except ValueError:
raise ValueError(response.decode('UTF-8'))
if not asset_list:
return []
if 'ids' in asset_list:
return asset_list['ids']
return [] | [
"def",
"list_assets",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"requests_session",
".",
"get",
"(",
"self",
".",
"_base_url",
")",
".",
"content",
"if",
"not",
"response",
":",
"return",
"{",
"}",
"try",
":",
"asset_list",
"=",
"json",
".",
"loads",
"(",
"response",
")",
"except",
"TypeError",
":",
"asset_list",
"=",
"None",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"response",
".",
"decode",
"(",
"'UTF-8'",
")",
")",
"if",
"not",
"asset_list",
":",
"return",
"[",
"]",
"if",
"'ids'",
"in",
"asset_list",
":",
"return",
"asset_list",
"[",
"'ids'",
"]",
"return",
"[",
"]"
]
| List all the assets registered in the aquarius instance.
:return: List of DID string | [
"List",
"all",
"the",
"assets",
"registered",
"in",
"the",
"aquarius",
"instance",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/aquarius/aquarius.py#L55-L77 |
oceanprotocol/squid-py | squid_py/aquarius/aquarius.py | Aquarius.get_asset_ddo | def get_asset_ddo(self, did):
"""
Retrieve asset ddo for a given did.
:param did: Asset DID string
:return: DDO instance
"""
response = self.requests_session.get(f'{self.url}/{did}').content
if not response:
return {}
try:
parsed_response = json.loads(response)
except TypeError:
parsed_response = None
except ValueError:
raise ValueError(response.decode('UTF-8'))
if parsed_response is None:
return {}
return Asset(dictionary=parsed_response) | python | def get_asset_ddo(self, did):
response = self.requests_session.get(f'{self.url}/{did}').content
if not response:
return {}
try:
parsed_response = json.loads(response)
except TypeError:
parsed_response = None
except ValueError:
raise ValueError(response.decode('UTF-8'))
if parsed_response is None:
return {}
return Asset(dictionary=parsed_response) | [
"def",
"get_asset_ddo",
"(",
"self",
",",
"did",
")",
":",
"response",
"=",
"self",
".",
"requests_session",
".",
"get",
"(",
"f'{self.url}/{did}'",
")",
".",
"content",
"if",
"not",
"response",
":",
"return",
"{",
"}",
"try",
":",
"parsed_response",
"=",
"json",
".",
"loads",
"(",
"response",
")",
"except",
"TypeError",
":",
"parsed_response",
"=",
"None",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"response",
".",
"decode",
"(",
"'UTF-8'",
")",
")",
"if",
"parsed_response",
"is",
"None",
":",
"return",
"{",
"}",
"return",
"Asset",
"(",
"dictionary",
"=",
"parsed_response",
")"
]
| Retrieve asset ddo for a given did.
:param did: Asset DID string
:return: DDO instance | [
"Retrieve",
"asset",
"ddo",
"for",
"a",
"given",
"did",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/aquarius/aquarius.py#L79-L97 |
oceanprotocol/squid-py | squid_py/aquarius/aquarius.py | Aquarius.get_asset_metadata | def get_asset_metadata(self, did):
"""
Retrieve asset metadata for a given did.
:param did: Asset DID string
:return: metadata key of the DDO instance
"""
response = self.requests_session.get(f'{self._base_url}/metadata/{did}').content
if not response:
return {}
try:
parsed_response = json.loads(response)
except TypeError:
parsed_response = None
except ValueError:
raise ValueError(response.decode('UTF-8'))
if parsed_response is None:
return {}
return parsed_response['metadata'] | python | def get_asset_metadata(self, did):
response = self.requests_session.get(f'{self._base_url}/metadata/{did}').content
if not response:
return {}
try:
parsed_response = json.loads(response)
except TypeError:
parsed_response = None
except ValueError:
raise ValueError(response.decode('UTF-8'))
if parsed_response is None:
return {}
return parsed_response['metadata'] | [
"def",
"get_asset_metadata",
"(",
"self",
",",
"did",
")",
":",
"response",
"=",
"self",
".",
"requests_session",
".",
"get",
"(",
"f'{self._base_url}/metadata/{did}'",
")",
".",
"content",
"if",
"not",
"response",
":",
"return",
"{",
"}",
"try",
":",
"parsed_response",
"=",
"json",
".",
"loads",
"(",
"response",
")",
"except",
"TypeError",
":",
"parsed_response",
"=",
"None",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"response",
".",
"decode",
"(",
"'UTF-8'",
")",
")",
"if",
"parsed_response",
"is",
"None",
":",
"return",
"{",
"}",
"return",
"parsed_response",
"[",
"'metadata'",
"]"
]
| Retrieve asset metadata for a given did.
:param did: Asset DID string
:return: metadata key of the DDO instance | [
"Retrieve",
"asset",
"metadata",
"for",
"a",
"given",
"did",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/aquarius/aquarius.py#L99-L117 |
oceanprotocol/squid-py | squid_py/aquarius/aquarius.py | Aquarius.list_assets_ddo | def list_assets_ddo(self):
"""
List all the ddos registered in the aquarius instance.
:return: List of DDO instance
"""
return json.loads(self.requests_session.get(self.url).content) | python | def list_assets_ddo(self):
return json.loads(self.requests_session.get(self.url).content) | [
"def",
"list_assets_ddo",
"(",
"self",
")",
":",
"return",
"json",
".",
"loads",
"(",
"self",
".",
"requests_session",
".",
"get",
"(",
"self",
".",
"url",
")",
".",
"content",
")"
]
| List all the ddos registered in the aquarius instance.
:return: List of DDO instance | [
"List",
"all",
"the",
"ddos",
"registered",
"in",
"the",
"aquarius",
"instance",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/aquarius/aquarius.py#L119-L125 |
oceanprotocol/squid-py | squid_py/aquarius/aquarius.py | Aquarius.publish_asset_ddo | def publish_asset_ddo(self, ddo):
"""
Register asset ddo in aquarius.
:param ddo: DDO instance
:return: API response (depends on implementation)
"""
try:
asset_did = ddo.did
response = self.requests_session.post(self.url, data=ddo.as_text(),
headers=self._headers)
except AttributeError:
raise AttributeError('DDO invalid. Review that all the required parameters are filled.')
if response.status_code == 500:
raise ValueError(
f'This Asset ID already exists! \n\tHTTP Error message: \n\t\t{response.text}')
elif response.status_code != 201:
raise Exception(f'{response.status_code} ERROR Full error: \n{response.text}')
elif response.status_code == 201:
response = json.loads(response.content)
logger.debug(f'Published asset DID {asset_did}')
return response
else:
raise Exception(f'Unhandled ERROR: status-code {response.status_code}, '
f'error message {response.text}') | python | def publish_asset_ddo(self, ddo):
try:
asset_did = ddo.did
response = self.requests_session.post(self.url, data=ddo.as_text(),
headers=self._headers)
except AttributeError:
raise AttributeError('DDO invalid. Review that all the required parameters are filled.')
if response.status_code == 500:
raise ValueError(
f'This Asset ID already exists! \n\tHTTP Error message: \n\t\t{response.text}')
elif response.status_code != 201:
raise Exception(f'{response.status_code} ERROR Full error: \n{response.text}')
elif response.status_code == 201:
response = json.loads(response.content)
logger.debug(f'Published asset DID {asset_did}')
return response
else:
raise Exception(f'Unhandled ERROR: status-code {response.status_code}, '
f'error message {response.text}') | [
"def",
"publish_asset_ddo",
"(",
"self",
",",
"ddo",
")",
":",
"try",
":",
"asset_did",
"=",
"ddo",
".",
"did",
"response",
"=",
"self",
".",
"requests_session",
".",
"post",
"(",
"self",
".",
"url",
",",
"data",
"=",
"ddo",
".",
"as_text",
"(",
")",
",",
"headers",
"=",
"self",
".",
"_headers",
")",
"except",
"AttributeError",
":",
"raise",
"AttributeError",
"(",
"'DDO invalid. Review that all the required parameters are filled.'",
")",
"if",
"response",
".",
"status_code",
"==",
"500",
":",
"raise",
"ValueError",
"(",
"f'This Asset ID already exists! \\n\\tHTTP Error message: \\n\\t\\t{response.text}'",
")",
"elif",
"response",
".",
"status_code",
"!=",
"201",
":",
"raise",
"Exception",
"(",
"f'{response.status_code} ERROR Full error: \\n{response.text}'",
")",
"elif",
"response",
".",
"status_code",
"==",
"201",
":",
"response",
"=",
"json",
".",
"loads",
"(",
"response",
".",
"content",
")",
"logger",
".",
"debug",
"(",
"f'Published asset DID {asset_did}'",
")",
"return",
"response",
"else",
":",
"raise",
"Exception",
"(",
"f'Unhandled ERROR: status-code {response.status_code}, '",
"f'error message {response.text}'",
")"
]
| Register asset ddo in aquarius.
:param ddo: DDO instance
:return: API response (depends on implementation) | [
"Register",
"asset",
"ddo",
"in",
"aquarius",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/aquarius/aquarius.py#L127-L151 |
oceanprotocol/squid-py | squid_py/aquarius/aquarius.py | Aquarius.update_asset_ddo | def update_asset_ddo(self, did, ddo):
"""
Update the ddo of a did already registered.
:param did: Asset DID string
:param ddo: DDO instance
:return: API response (depends on implementation)
"""
response = self.requests_session.put(f'{self.url}/{did}', data=ddo.as_text(),
headers=self._headers)
if response.status_code == 200 or response.status_code == 201:
return json.loads(response.content)
else:
raise Exception(f'Unable to update DDO: {response.content}') | python | def update_asset_ddo(self, did, ddo):
response = self.requests_session.put(f'{self.url}/{did}', data=ddo.as_text(),
headers=self._headers)
if response.status_code == 200 or response.status_code == 201:
return json.loads(response.content)
else:
raise Exception(f'Unable to update DDO: {response.content}') | [
"def",
"update_asset_ddo",
"(",
"self",
",",
"did",
",",
"ddo",
")",
":",
"response",
"=",
"self",
".",
"requests_session",
".",
"put",
"(",
"f'{self.url}/{did}'",
",",
"data",
"=",
"ddo",
".",
"as_text",
"(",
")",
",",
"headers",
"=",
"self",
".",
"_headers",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
"or",
"response",
".",
"status_code",
"==",
"201",
":",
"return",
"json",
".",
"loads",
"(",
"response",
".",
"content",
")",
"else",
":",
"raise",
"Exception",
"(",
"f'Unable to update DDO: {response.content}'",
")"
]
| Update the ddo of a did already registered.
:param did: Asset DID string
:param ddo: DDO instance
:return: API response (depends on implementation) | [
"Update",
"the",
"ddo",
"of",
"a",
"did",
"already",
"registered",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/aquarius/aquarius.py#L153-L166 |
oceanprotocol/squid-py | squid_py/aquarius/aquarius.py | Aquarius.text_search | def text_search(self, text, sort=None, offset=100, page=1):
"""
Search in aquarius using text query.
Given the string aquarius will do a full-text query to search in all documents.
Currently implemented are the MongoDB and Elastic Search drivers.
For a detailed guide on how to search, see the MongoDB driver documentation:
mongodb driverCurrently implemented in:
https://docs.mongodb.com/manual/reference/operator/query/text/
And the Elastic Search documentation:
https://www.elastic.co/guide/en/elasticsearch/guide/current/full-text-search.html
Other drivers are possible according to each implementation.
:param text: String to be search.
:param sort: 1/-1 to sort ascending or descending.
:param offset: Integer with the number of elements displayed per page.
:param page: Integer with the number of page.
:return: List of DDO instance
"""
assert page >= 1, f'Invalid page value {page}. Required page >= 1.'
payload = {"text": text, "sort": sort, "offset": offset, "page": page}
response = self.requests_session.get(
f'{self.url}/query',
params=payload,
headers=self._headers
)
if response.status_code == 200:
return self._parse_search_response(response.content)
else:
raise Exception(f'Unable to search for DDO: {response.content}') | python | def text_search(self, text, sort=None, offset=100, page=1):
assert page >= 1, f'Invalid page value {page}. Required page >= 1.'
payload = {"text": text, "sort": sort, "offset": offset, "page": page}
response = self.requests_session.get(
f'{self.url}/query',
params=payload,
headers=self._headers
)
if response.status_code == 200:
return self._parse_search_response(response.content)
else:
raise Exception(f'Unable to search for DDO: {response.content}') | [
"def",
"text_search",
"(",
"self",
",",
"text",
",",
"sort",
"=",
"None",
",",
"offset",
"=",
"100",
",",
"page",
"=",
"1",
")",
":",
"assert",
"page",
">=",
"1",
",",
"f'Invalid page value {page}. Required page >= 1.'",
"payload",
"=",
"{",
"\"text\"",
":",
"text",
",",
"\"sort\"",
":",
"sort",
",",
"\"offset\"",
":",
"offset",
",",
"\"page\"",
":",
"page",
"}",
"response",
"=",
"self",
".",
"requests_session",
".",
"get",
"(",
"f'{self.url}/query'",
",",
"params",
"=",
"payload",
",",
"headers",
"=",
"self",
".",
"_headers",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"return",
"self",
".",
"_parse_search_response",
"(",
"response",
".",
"content",
")",
"else",
":",
"raise",
"Exception",
"(",
"f'Unable to search for DDO: {response.content}'",
")"
]
| Search in aquarius using text query.
Given the string aquarius will do a full-text query to search in all documents.
Currently implemented are the MongoDB and Elastic Search drivers.
For a detailed guide on how to search, see the MongoDB driver documentation:
mongodb driverCurrently implemented in:
https://docs.mongodb.com/manual/reference/operator/query/text/
And the Elastic Search documentation:
https://www.elastic.co/guide/en/elasticsearch/guide/current/full-text-search.html
Other drivers are possible according to each implementation.
:param text: String to be search.
:param sort: 1/-1 to sort ascending or descending.
:param offset: Integer with the number of elements displayed per page.
:param page: Integer with the number of page.
:return: List of DDO instance | [
"Search",
"in",
"aquarius",
"using",
"text",
"query",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/aquarius/aquarius.py#L168-L200 |
oceanprotocol/squid-py | squid_py/aquarius/aquarius.py | Aquarius.query_search | def query_search(self, search_query, sort=None, offset=100, page=1):
"""
Search using a query.
Currently implemented is the MongoDB query model to search for documents according to:
https://docs.mongodb.com/manual/tutorial/query-documents/
And an Elastic Search driver, which implements a basic parser to convert the query into
elastic search format.
Example: query_search({"price":[0,10]})
:param search_query: Python dictionary, query following mongodb syntax
:param sort: 1/-1 to sort ascending or descending.
:param offset: Integer with the number of elements displayed per page.
:param page: Integer with the number of page.
:return: List of DDO instance
"""
assert page >= 1, f'Invalid page value {page}. Required page >= 1.'
search_query['sort'] = sort
search_query['offset'] = offset
search_query['page'] = page
response = self.requests_session.post(
f'{self.url}/query',
data=json.dumps(search_query),
headers=self._headers
)
if response.status_code == 200:
return self._parse_search_response(response.content)
else:
raise Exception(f'Unable to search for DDO: {response.content}') | python | def query_search(self, search_query, sort=None, offset=100, page=1):
assert page >= 1, f'Invalid page value {page}. Required page >= 1.'
search_query['sort'] = sort
search_query['offset'] = offset
search_query['page'] = page
response = self.requests_session.post(
f'{self.url}/query',
data=json.dumps(search_query),
headers=self._headers
)
if response.status_code == 200:
return self._parse_search_response(response.content)
else:
raise Exception(f'Unable to search for DDO: {response.content}') | [
"def",
"query_search",
"(",
"self",
",",
"search_query",
",",
"sort",
"=",
"None",
",",
"offset",
"=",
"100",
",",
"page",
"=",
"1",
")",
":",
"assert",
"page",
">=",
"1",
",",
"f'Invalid page value {page}. Required page >= 1.'",
"search_query",
"[",
"'sort'",
"]",
"=",
"sort",
"search_query",
"[",
"'offset'",
"]",
"=",
"offset",
"search_query",
"[",
"'page'",
"]",
"=",
"page",
"response",
"=",
"self",
".",
"requests_session",
".",
"post",
"(",
"f'{self.url}/query'",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"search_query",
")",
",",
"headers",
"=",
"self",
".",
"_headers",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"return",
"self",
".",
"_parse_search_response",
"(",
"response",
".",
"content",
")",
"else",
":",
"raise",
"Exception",
"(",
"f'Unable to search for DDO: {response.content}'",
")"
]
| Search using a query.
Currently implemented is the MongoDB query model to search for documents according to:
https://docs.mongodb.com/manual/tutorial/query-documents/
And an Elastic Search driver, which implements a basic parser to convert the query into
elastic search format.
Example: query_search({"price":[0,10]})
:param search_query: Python dictionary, query following mongodb syntax
:param sort: 1/-1 to sort ascending or descending.
:param offset: Integer with the number of elements displayed per page.
:param page: Integer with the number of page.
:return: List of DDO instance | [
"Search",
"using",
"a",
"query",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/aquarius/aquarius.py#L202-L232 |
oceanprotocol/squid-py | squid_py/aquarius/aquarius.py | Aquarius.retire_asset_ddo | def retire_asset_ddo(self, did):
"""
Retire asset ddo of Aquarius.
:param did: Asset DID string
:return: API response (depends on implementation)
"""
response = self.requests_session.delete(f'{self.url}/{did}', headers=self._headers)
if response.status_code == 200:
logging.debug(f'Removed asset DID: {did} from metadata store')
return response
raise AquariusGenericError(f'Unable to remove DID: {response}') | python | def retire_asset_ddo(self, did):
response = self.requests_session.delete(f'{self.url}/{did}', headers=self._headers)
if response.status_code == 200:
logging.debug(f'Removed asset DID: {did} from metadata store')
return response
raise AquariusGenericError(f'Unable to remove DID: {response}') | [
"def",
"retire_asset_ddo",
"(",
"self",
",",
"did",
")",
":",
"response",
"=",
"self",
".",
"requests_session",
".",
"delete",
"(",
"f'{self.url}/{did}'",
",",
"headers",
"=",
"self",
".",
"_headers",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"logging",
".",
"debug",
"(",
"f'Removed asset DID: {did} from metadata store'",
")",
"return",
"response",
"raise",
"AquariusGenericError",
"(",
"f'Unable to remove DID: {response}'",
")"
]
| Retire asset ddo of Aquarius.
:param did: Asset DID string
:return: API response (depends on implementation) | [
"Retire",
"asset",
"ddo",
"of",
"Aquarius",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/aquarius/aquarius.py#L234-L246 |
oceanprotocol/squid-py | squid_py/aquarius/aquarius.py | Aquarius.validate_metadata | def validate_metadata(self, metadata):
"""
Validate that the metadata of your ddo is valid.
:param metadata: conforming to the Metadata accepted by Ocean Protocol, dict
:return: bool
"""
response = self.requests_session.post(
f'{self.url}/validate',
data=json.dumps(metadata),
headers=self._headers
)
if response.content == b'true\n':
return True
else:
logger.info(self._parse_search_response(response.content))
return False | python | def validate_metadata(self, metadata):
response = self.requests_session.post(
f'{self.url}/validate',
data=json.dumps(metadata),
headers=self._headers
)
if response.content == b'true\n':
return True
else:
logger.info(self._parse_search_response(response.content))
return False | [
"def",
"validate_metadata",
"(",
"self",
",",
"metadata",
")",
":",
"response",
"=",
"self",
".",
"requests_session",
".",
"post",
"(",
"f'{self.url}/validate'",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"metadata",
")",
",",
"headers",
"=",
"self",
".",
"_headers",
")",
"if",
"response",
".",
"content",
"==",
"b'true\\n'",
":",
"return",
"True",
"else",
":",
"logger",
".",
"info",
"(",
"self",
".",
"_parse_search_response",
"(",
"response",
".",
"content",
")",
")",
"return",
"False"
]
| Validate that the metadata of your ddo is valid.
:param metadata: conforming to the Metadata accepted by Ocean Protocol, dict
:return: bool | [
"Validate",
"that",
"the",
"metadata",
"of",
"your",
"ddo",
"is",
"valid",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/aquarius/aquarius.py#L248-L264 |
oceanprotocol/squid-py | squid_py/agreements/utils.py | get_sla_template_path | def get_sla_template_path(service_type=ServiceTypes.ASSET_ACCESS):
"""
Get the template for a ServiceType.
:param service_type: ServiceTypes
:return: Path of the template, str
"""
if service_type == ServiceTypes.ASSET_ACCESS:
name = 'access_sla_template.json'
elif service_type == ServiceTypes.CLOUD_COMPUTE:
name = 'compute_sla_template.json'
elif service_type == ServiceTypes.FITCHAIN_COMPUTE:
name = 'fitchain_sla_template.json'
else:
raise ValueError(f'Invalid/unsupported service agreement type {service_type}')
return os.path.join(os.path.sep, *os.path.realpath(__file__).split(os.path.sep)[1:-1], name) | python | def get_sla_template_path(service_type=ServiceTypes.ASSET_ACCESS):
if service_type == ServiceTypes.ASSET_ACCESS:
name = 'access_sla_template.json'
elif service_type == ServiceTypes.CLOUD_COMPUTE:
name = 'compute_sla_template.json'
elif service_type == ServiceTypes.FITCHAIN_COMPUTE:
name = 'fitchain_sla_template.json'
else:
raise ValueError(f'Invalid/unsupported service agreement type {service_type}')
return os.path.join(os.path.sep, *os.path.realpath(__file__).split(os.path.sep)[1:-1], name) | [
"def",
"get_sla_template_path",
"(",
"service_type",
"=",
"ServiceTypes",
".",
"ASSET_ACCESS",
")",
":",
"if",
"service_type",
"==",
"ServiceTypes",
".",
"ASSET_ACCESS",
":",
"name",
"=",
"'access_sla_template.json'",
"elif",
"service_type",
"==",
"ServiceTypes",
".",
"CLOUD_COMPUTE",
":",
"name",
"=",
"'compute_sla_template.json'",
"elif",
"service_type",
"==",
"ServiceTypes",
".",
"FITCHAIN_COMPUTE",
":",
"name",
"=",
"'fitchain_sla_template.json'",
"else",
":",
"raise",
"ValueError",
"(",
"f'Invalid/unsupported service agreement type {service_type}'",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"sep",
",",
"*",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
".",
"split",
"(",
"os",
".",
"path",
".",
"sep",
")",
"[",
"1",
":",
"-",
"1",
"]",
",",
"name",
")"
]
| Get the template for a ServiceType.
:param service_type: ServiceTypes
:return: Path of the template, str | [
"Get",
"the",
"template",
"for",
"a",
"ServiceType",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/utils.py#L11-L27 |
oceanprotocol/squid-py | squid_py/ocean/ocean_accounts.py | OceanAccounts.balance | def balance(self, account):
"""
Return the balance, a tuple with the eth and ocn balance.
:param account: Account instance to return the balance of
:return: Balance tuple of (eth, ocn)
"""
return Balance(self._keeper.get_ether_balance(account.address),
self._keeper.token.get_token_balance(account.address)) | python | def balance(self, account):
return Balance(self._keeper.get_ether_balance(account.address),
self._keeper.token.get_token_balance(account.address)) | [
"def",
"balance",
"(",
"self",
",",
"account",
")",
":",
"return",
"Balance",
"(",
"self",
".",
"_keeper",
".",
"get_ether_balance",
"(",
"account",
".",
"address",
")",
",",
"self",
".",
"_keeper",
".",
"token",
".",
"get_token_balance",
"(",
"account",
".",
"address",
")",
")"
]
| Return the balance, a tuple with the eth and ocn balance.
:param account: Account instance to return the balance of
:return: Balance tuple of (eth, ocn) | [
"Return",
"the",
"balance",
"a",
"tuple",
"with",
"the",
"eth",
"and",
"ocn",
"balance",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_accounts.py#L44-L52 |
oceanprotocol/squid-py | squid_py/agreements/register_service_agreement.py | register_service_agreement_consumer | def register_service_agreement_consumer(storage_path, publisher_address, agreement_id, did,
service_agreement, service_definition_id, price,
encrypted_files, consumer_account, condition_ids,
consume_callback=None, start_time=None):
"""
Registers the given service agreement in the local storage.
Subscribes to the service agreement events.
:param storage_path: storage path for the internal db, str
:param publisher_address: ethereum account address of publisher, hex str
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param service_agreement: ServiceAgreement instance
:param service_definition_id: identifier of the service inside the asset DDO, str
:param price: Asset price, int
:param encrypted_files: resutl of the files encrypted by the secret store, hex str
:param consumer_account: Account instance of the consumer
:param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32
:param consume_callback:
:param start_time: start time, int
"""
if start_time is None:
start_time = int(datetime.now().timestamp())
record_service_agreement(
storage_path, agreement_id, did, service_definition_id, price, encrypted_files, start_time)
process_agreement_events_consumer(
publisher_address, agreement_id, did, service_agreement,
price, consumer_account, condition_ids,
consume_callback
) | python | def register_service_agreement_consumer(storage_path, publisher_address, agreement_id, did,
service_agreement, service_definition_id, price,
encrypted_files, consumer_account, condition_ids,
consume_callback=None, start_time=None):
if start_time is None:
start_time = int(datetime.now().timestamp())
record_service_agreement(
storage_path, agreement_id, did, service_definition_id, price, encrypted_files, start_time)
process_agreement_events_consumer(
publisher_address, agreement_id, did, service_agreement,
price, consumer_account, condition_ids,
consume_callback
) | [
"def",
"register_service_agreement_consumer",
"(",
"storage_path",
",",
"publisher_address",
",",
"agreement_id",
",",
"did",
",",
"service_agreement",
",",
"service_definition_id",
",",
"price",
",",
"encrypted_files",
",",
"consumer_account",
",",
"condition_ids",
",",
"consume_callback",
"=",
"None",
",",
"start_time",
"=",
"None",
")",
":",
"if",
"start_time",
"is",
"None",
":",
"start_time",
"=",
"int",
"(",
"datetime",
".",
"now",
"(",
")",
".",
"timestamp",
"(",
")",
")",
"record_service_agreement",
"(",
"storage_path",
",",
"agreement_id",
",",
"did",
",",
"service_definition_id",
",",
"price",
",",
"encrypted_files",
",",
"start_time",
")",
"process_agreement_events_consumer",
"(",
"publisher_address",
",",
"agreement_id",
",",
"did",
",",
"service_agreement",
",",
"price",
",",
"consumer_account",
",",
"condition_ids",
",",
"consume_callback",
")"
]
| Registers the given service agreement in the local storage.
Subscribes to the service agreement events.
:param storage_path: storage path for the internal db, str
:param publisher_address: ethereum account address of publisher, hex str
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param service_agreement: ServiceAgreement instance
:param service_definition_id: identifier of the service inside the asset DDO, str
:param price: Asset price, int
:param encrypted_files: resutl of the files encrypted by the secret store, hex str
:param consumer_account: Account instance of the consumer
:param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32
:param consume_callback:
:param start_time: start time, int | [
"Registers",
"the",
"given",
"service",
"agreement",
"in",
"the",
"local",
"storage",
".",
"Subscribes",
"to",
"the",
"service",
"agreement",
"events",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/register_service_agreement.py#L20-L51 |
oceanprotocol/squid-py | squid_py/agreements/register_service_agreement.py | process_agreement_events_consumer | def process_agreement_events_consumer(publisher_address, agreement_id, did, service_agreement,
price, consumer_account, condition_ids,
consume_callback):
"""
Process the agreement events during the register of the service agreement for the consumer side.
:param publisher_address: ethereum account address of publisher, hex str
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param service_agreement: ServiceAgreement instance
:param price: Asset price, int
:param consumer_account: Account instance of the consumer
:param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32
:param consume_callback:
:return:
"""
conditions_dict = service_agreement.condition_by_name
events_manager = EventsManager.get_instance(Keeper.get_instance())
events_manager.watch_agreement_created_event(
agreement_id,
lock_reward_condition.fulfillLockRewardCondition,
None,
(agreement_id, price, consumer_account),
EVENT_WAIT_TIMEOUT,
)
if consume_callback:
def _refund_callback(_price, _publisher_address, _condition_ids):
def do_refund(_event, _agreement_id, _did, _service_agreement, _consumer_account, *_):
escrow_reward_condition.refund_reward(
_event, _agreement_id, _did, _service_agreement, _price,
_consumer_account, _publisher_address, _condition_ids
)
return do_refund
events_manager.watch_access_event(
agreement_id,
escrow_reward_condition.consume_asset,
_refund_callback(price, publisher_address, condition_ids),
(agreement_id, did, service_agreement, consumer_account, consume_callback),
conditions_dict['accessSecretStore'].timeout
) | python | def process_agreement_events_consumer(publisher_address, agreement_id, did, service_agreement,
price, consumer_account, condition_ids,
consume_callback):
conditions_dict = service_agreement.condition_by_name
events_manager = EventsManager.get_instance(Keeper.get_instance())
events_manager.watch_agreement_created_event(
agreement_id,
lock_reward_condition.fulfillLockRewardCondition,
None,
(agreement_id, price, consumer_account),
EVENT_WAIT_TIMEOUT,
)
if consume_callback:
def _refund_callback(_price, _publisher_address, _condition_ids):
def do_refund(_event, _agreement_id, _did, _service_agreement, _consumer_account, *_):
escrow_reward_condition.refund_reward(
_event, _agreement_id, _did, _service_agreement, _price,
_consumer_account, _publisher_address, _condition_ids
)
return do_refund
events_manager.watch_access_event(
agreement_id,
escrow_reward_condition.consume_asset,
_refund_callback(price, publisher_address, condition_ids),
(agreement_id, did, service_agreement, consumer_account, consume_callback),
conditions_dict['accessSecretStore'].timeout
) | [
"def",
"process_agreement_events_consumer",
"(",
"publisher_address",
",",
"agreement_id",
",",
"did",
",",
"service_agreement",
",",
"price",
",",
"consumer_account",
",",
"condition_ids",
",",
"consume_callback",
")",
":",
"conditions_dict",
"=",
"service_agreement",
".",
"condition_by_name",
"events_manager",
"=",
"EventsManager",
".",
"get_instance",
"(",
"Keeper",
".",
"get_instance",
"(",
")",
")",
"events_manager",
".",
"watch_agreement_created_event",
"(",
"agreement_id",
",",
"lock_reward_condition",
".",
"fulfillLockRewardCondition",
",",
"None",
",",
"(",
"agreement_id",
",",
"price",
",",
"consumer_account",
")",
",",
"EVENT_WAIT_TIMEOUT",
",",
")",
"if",
"consume_callback",
":",
"def",
"_refund_callback",
"(",
"_price",
",",
"_publisher_address",
",",
"_condition_ids",
")",
":",
"def",
"do_refund",
"(",
"_event",
",",
"_agreement_id",
",",
"_did",
",",
"_service_agreement",
",",
"_consumer_account",
",",
"*",
"_",
")",
":",
"escrow_reward_condition",
".",
"refund_reward",
"(",
"_event",
",",
"_agreement_id",
",",
"_did",
",",
"_service_agreement",
",",
"_price",
",",
"_consumer_account",
",",
"_publisher_address",
",",
"_condition_ids",
")",
"return",
"do_refund",
"events_manager",
".",
"watch_access_event",
"(",
"agreement_id",
",",
"escrow_reward_condition",
".",
"consume_asset",
",",
"_refund_callback",
"(",
"price",
",",
"publisher_address",
",",
"condition_ids",
")",
",",
"(",
"agreement_id",
",",
"did",
",",
"service_agreement",
",",
"consumer_account",
",",
"consume_callback",
")",
",",
"conditions_dict",
"[",
"'accessSecretStore'",
"]",
".",
"timeout",
")"
]
| Process the agreement events during the register of the service agreement for the consumer side.
:param publisher_address: ethereum account address of publisher, hex str
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param service_agreement: ServiceAgreement instance
:param price: Asset price, int
:param consumer_account: Account instance of the consumer
:param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32
:param consume_callback:
:return: | [
"Process",
"the",
"agreement",
"events",
"during",
"the",
"register",
"of",
"the",
"service",
"agreement",
"for",
"the",
"consumer",
"side",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/register_service_agreement.py#L54-L96 |
oceanprotocol/squid-py | squid_py/agreements/register_service_agreement.py | register_service_agreement_publisher | def register_service_agreement_publisher(storage_path, consumer_address, agreement_id, did,
service_agreement, service_definition_id, price,
publisher_account, condition_ids, start_time=None):
"""
Registers the given service agreement in the local storage.
Subscribes to the service agreement events.
:param storage_path:storage path for the internal db, str
:param consumer_address: ethereum account address of consumer, hex str
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param service_agreement: ServiceAgreement instance
:param service_definition_id: identifier of the service inside the asset DDO, str
:param price: Asset price, int
:param publisher_account: Account instance of the publisher
:param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32
:param start_time:
:return:
"""
if start_time is None:
start_time = int(datetime.now().timestamp())
record_service_agreement(
storage_path, agreement_id, did, service_definition_id, price, '', start_time)
process_agreement_events_publisher(
publisher_account, agreement_id, did, service_agreement,
price, consumer_address, condition_ids
) | python | def register_service_agreement_publisher(storage_path, consumer_address, agreement_id, did,
service_agreement, service_definition_id, price,
publisher_account, condition_ids, start_time=None):
if start_time is None:
start_time = int(datetime.now().timestamp())
record_service_agreement(
storage_path, agreement_id, did, service_definition_id, price, '', start_time)
process_agreement_events_publisher(
publisher_account, agreement_id, did, service_agreement,
price, consumer_address, condition_ids
) | [
"def",
"register_service_agreement_publisher",
"(",
"storage_path",
",",
"consumer_address",
",",
"agreement_id",
",",
"did",
",",
"service_agreement",
",",
"service_definition_id",
",",
"price",
",",
"publisher_account",
",",
"condition_ids",
",",
"start_time",
"=",
"None",
")",
":",
"if",
"start_time",
"is",
"None",
":",
"start_time",
"=",
"int",
"(",
"datetime",
".",
"now",
"(",
")",
".",
"timestamp",
"(",
")",
")",
"record_service_agreement",
"(",
"storage_path",
",",
"agreement_id",
",",
"did",
",",
"service_definition_id",
",",
"price",
",",
"''",
",",
"start_time",
")",
"process_agreement_events_publisher",
"(",
"publisher_account",
",",
"agreement_id",
",",
"did",
",",
"service_agreement",
",",
"price",
",",
"consumer_address",
",",
"condition_ids",
")"
]
| Registers the given service agreement in the local storage.
Subscribes to the service agreement events.
:param storage_path:storage path for the internal db, str
:param consumer_address: ethereum account address of consumer, hex str
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param service_agreement: ServiceAgreement instance
:param service_definition_id: identifier of the service inside the asset DDO, str
:param price: Asset price, int
:param publisher_account: Account instance of the publisher
:param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32
:param start_time:
:return: | [
"Registers",
"the",
"given",
"service",
"agreement",
"in",
"the",
"local",
"storage",
".",
"Subscribes",
"to",
"the",
"service",
"agreement",
"events",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/register_service_agreement.py#L99-L127 |
oceanprotocol/squid-py | squid_py/agreements/register_service_agreement.py | process_agreement_events_publisher | def process_agreement_events_publisher(publisher_account, agreement_id, did, service_agreement,
price, consumer_address, condition_ids):
"""
Process the agreement events during the register of the service agreement for the publisher side
:param publisher_account: Account instance of the publisher
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param service_agreement: ServiceAgreement instance
:param price: Asset price, int
:param consumer_address: ethereum account address of consumer, hex str
:param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32
:return:
"""
conditions_dict = service_agreement.condition_by_name
events_manager = EventsManager.get_instance(Keeper.get_instance())
events_manager.watch_lock_reward_event(
agreement_id,
access_secret_store_condition.fulfillAccessSecretStoreCondition,
None,
(agreement_id, did, service_agreement,
consumer_address, publisher_account),
conditions_dict['lockReward'].timeout
)
events_manager.watch_access_event(
agreement_id,
escrow_reward_condition.fulfillEscrowRewardCondition,
None,
(agreement_id, service_agreement,
price, consumer_address, publisher_account, condition_ids),
conditions_dict['accessSecretStore'].timeout
)
events_manager.watch_reward_event(
agreement_id,
verify_reward_condition.verifyRewardTokens,
None,
(agreement_id, did, service_agreement,
price, consumer_address, publisher_account),
conditions_dict['escrowReward'].timeout
) | python | def process_agreement_events_publisher(publisher_account, agreement_id, did, service_agreement,
price, consumer_address, condition_ids):
conditions_dict = service_agreement.condition_by_name
events_manager = EventsManager.get_instance(Keeper.get_instance())
events_manager.watch_lock_reward_event(
agreement_id,
access_secret_store_condition.fulfillAccessSecretStoreCondition,
None,
(agreement_id, did, service_agreement,
consumer_address, publisher_account),
conditions_dict['lockReward'].timeout
)
events_manager.watch_access_event(
agreement_id,
escrow_reward_condition.fulfillEscrowRewardCondition,
None,
(agreement_id, service_agreement,
price, consumer_address, publisher_account, condition_ids),
conditions_dict['accessSecretStore'].timeout
)
events_manager.watch_reward_event(
agreement_id,
verify_reward_condition.verifyRewardTokens,
None,
(agreement_id, did, service_agreement,
price, consumer_address, publisher_account),
conditions_dict['escrowReward'].timeout
) | [
"def",
"process_agreement_events_publisher",
"(",
"publisher_account",
",",
"agreement_id",
",",
"did",
",",
"service_agreement",
",",
"price",
",",
"consumer_address",
",",
"condition_ids",
")",
":",
"conditions_dict",
"=",
"service_agreement",
".",
"condition_by_name",
"events_manager",
"=",
"EventsManager",
".",
"get_instance",
"(",
"Keeper",
".",
"get_instance",
"(",
")",
")",
"events_manager",
".",
"watch_lock_reward_event",
"(",
"agreement_id",
",",
"access_secret_store_condition",
".",
"fulfillAccessSecretStoreCondition",
",",
"None",
",",
"(",
"agreement_id",
",",
"did",
",",
"service_agreement",
",",
"consumer_address",
",",
"publisher_account",
")",
",",
"conditions_dict",
"[",
"'lockReward'",
"]",
".",
"timeout",
")",
"events_manager",
".",
"watch_access_event",
"(",
"agreement_id",
",",
"escrow_reward_condition",
".",
"fulfillEscrowRewardCondition",
",",
"None",
",",
"(",
"agreement_id",
",",
"service_agreement",
",",
"price",
",",
"consumer_address",
",",
"publisher_account",
",",
"condition_ids",
")",
",",
"conditions_dict",
"[",
"'accessSecretStore'",
"]",
".",
"timeout",
")",
"events_manager",
".",
"watch_reward_event",
"(",
"agreement_id",
",",
"verify_reward_condition",
".",
"verifyRewardTokens",
",",
"None",
",",
"(",
"agreement_id",
",",
"did",
",",
"service_agreement",
",",
"price",
",",
"consumer_address",
",",
"publisher_account",
")",
",",
"conditions_dict",
"[",
"'escrowReward'",
"]",
".",
"timeout",
")"
]
| Process the agreement events during the register of the service agreement for the publisher side
:param publisher_account: Account instance of the publisher
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param service_agreement: ServiceAgreement instance
:param price: Asset price, int
:param consumer_address: ethereum account address of consumer, hex str
:param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32
:return: | [
"Process",
"the",
"agreement",
"events",
"during",
"the",
"register",
"of",
"the",
"service",
"agreement",
"for",
"the",
"publisher",
"side"
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/register_service_agreement.py#L130-L171 |
oceanprotocol/squid-py | squid_py/agreements/register_service_agreement.py | execute_pending_service_agreements | def execute_pending_service_agreements(storage_path, account, actor_type, did_resolver_fn):
"""
Iterates over pending service agreements recorded in the local storage,
fetches their service definitions, and subscribes to service agreement events.
:param storage_path: storage path for the internal db, str
:param account:
:param actor_type:
:param did_resolver_fn:
:return:
"""
keeper = Keeper.get_instance()
# service_agreement_id, did, service_definition_id, price, files, start_time, status
for (agreement_id, did, _,
price, files, start_time, _) in get_service_agreements(storage_path):
ddo = did_resolver_fn(did)
for service in ddo.services:
if service.type != 'Access':
continue
consumer_provider_tuple = keeper.escrow_access_secretstore_template.get_agreement_data(
agreement_id)
if not consumer_provider_tuple:
continue
consumer, provider = consumer_provider_tuple
did = ddo.did
service_agreement = ServiceAgreement.from_service_dict(service.as_dictionary())
condition_ids = service_agreement.generate_agreement_condition_ids(
agreement_id, did, consumer, provider, keeper)
if actor_type == 'consumer':
assert account.address == consumer
process_agreement_events_consumer(
provider, agreement_id, did, service_agreement,
price, account, condition_ids, None)
else:
assert account.address == provider
process_agreement_events_publisher(
account, agreement_id, did, service_agreement,
price, consumer, condition_ids) | python | def execute_pending_service_agreements(storage_path, account, actor_type, did_resolver_fn):
keeper = Keeper.get_instance()
for (agreement_id, did, _,
price, files, start_time, _) in get_service_agreements(storage_path):
ddo = did_resolver_fn(did)
for service in ddo.services:
if service.type != 'Access':
continue
consumer_provider_tuple = keeper.escrow_access_secretstore_template.get_agreement_data(
agreement_id)
if not consumer_provider_tuple:
continue
consumer, provider = consumer_provider_tuple
did = ddo.did
service_agreement = ServiceAgreement.from_service_dict(service.as_dictionary())
condition_ids = service_agreement.generate_agreement_condition_ids(
agreement_id, did, consumer, provider, keeper)
if actor_type == 'consumer':
assert account.address == consumer
process_agreement_events_consumer(
provider, agreement_id, did, service_agreement,
price, account, condition_ids, None)
else:
assert account.address == provider
process_agreement_events_publisher(
account, agreement_id, did, service_agreement,
price, consumer, condition_ids) | [
"def",
"execute_pending_service_agreements",
"(",
"storage_path",
",",
"account",
",",
"actor_type",
",",
"did_resolver_fn",
")",
":",
"keeper",
"=",
"Keeper",
".",
"get_instance",
"(",
")",
"# service_agreement_id, did, service_definition_id, price, files, start_time, status",
"for",
"(",
"agreement_id",
",",
"did",
",",
"_",
",",
"price",
",",
"files",
",",
"start_time",
",",
"_",
")",
"in",
"get_service_agreements",
"(",
"storage_path",
")",
":",
"ddo",
"=",
"did_resolver_fn",
"(",
"did",
")",
"for",
"service",
"in",
"ddo",
".",
"services",
":",
"if",
"service",
".",
"type",
"!=",
"'Access'",
":",
"continue",
"consumer_provider_tuple",
"=",
"keeper",
".",
"escrow_access_secretstore_template",
".",
"get_agreement_data",
"(",
"agreement_id",
")",
"if",
"not",
"consumer_provider_tuple",
":",
"continue",
"consumer",
",",
"provider",
"=",
"consumer_provider_tuple",
"did",
"=",
"ddo",
".",
"did",
"service_agreement",
"=",
"ServiceAgreement",
".",
"from_service_dict",
"(",
"service",
".",
"as_dictionary",
"(",
")",
")",
"condition_ids",
"=",
"service_agreement",
".",
"generate_agreement_condition_ids",
"(",
"agreement_id",
",",
"did",
",",
"consumer",
",",
"provider",
",",
"keeper",
")",
"if",
"actor_type",
"==",
"'consumer'",
":",
"assert",
"account",
".",
"address",
"==",
"consumer",
"process_agreement_events_consumer",
"(",
"provider",
",",
"agreement_id",
",",
"did",
",",
"service_agreement",
",",
"price",
",",
"account",
",",
"condition_ids",
",",
"None",
")",
"else",
":",
"assert",
"account",
".",
"address",
"==",
"provider",
"process_agreement_events_publisher",
"(",
"account",
",",
"agreement_id",
",",
"did",
",",
"service_agreement",
",",
"price",
",",
"consumer",
",",
"condition_ids",
")"
]
| Iterates over pending service agreements recorded in the local storage,
fetches their service definitions, and subscribes to service agreement events.
:param storage_path: storage path for the internal db, str
:param account:
:param actor_type:
:param did_resolver_fn:
:return: | [
"Iterates",
"over",
"pending",
"service",
"agreements",
"recorded",
"in",
"the",
"local",
"storage",
"fetches",
"their",
"service",
"definitions",
"and",
"subscribes",
"to",
"service",
"agreement",
"events",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/register_service_agreement.py#L174-L215 |
oceanprotocol/squid-py | squid_py/keeper/utils.py | generate_multi_value_hash | def generate_multi_value_hash(types, values):
"""
Return the hash of the given list of values.
This is equivalent to packing and hashing values in a solidity smart contract
hence the use of `soliditySha3`.
:param types: list of solidity types expressed as strings
:param values: list of values matching the `types` list
:return: bytes
"""
assert len(types) == len(values)
return Web3Provider.get_web3().soliditySha3(
types,
values
) | python | def generate_multi_value_hash(types, values):
assert len(types) == len(values)
return Web3Provider.get_web3().soliditySha3(
types,
values
) | [
"def",
"generate_multi_value_hash",
"(",
"types",
",",
"values",
")",
":",
"assert",
"len",
"(",
"types",
")",
"==",
"len",
"(",
"values",
")",
"return",
"Web3Provider",
".",
"get_web3",
"(",
")",
".",
"soliditySha3",
"(",
"types",
",",
"values",
")"
]
| Return the hash of the given list of values.
This is equivalent to packing and hashing values in a solidity smart contract
hence the use of `soliditySha3`.
:param types: list of solidity types expressed as strings
:param values: list of values matching the `types` list
:return: bytes | [
"Return",
"the",
"hash",
"of",
"the",
"given",
"list",
"of",
"values",
".",
"This",
"is",
"equivalent",
"to",
"packing",
"and",
"hashing",
"values",
"in",
"a",
"solidity",
"smart",
"contract",
"hence",
"the",
"use",
"of",
"soliditySha3",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/utils.py#L14-L28 |
oceanprotocol/squid-py | squid_py/keeper/utils.py | process_tx_receipt | def process_tx_receipt(tx_hash, event, event_name):
"""
Wait until the tx receipt is processed.
:param tx_hash: hash of the transaction
:param event: AttributeDict with the event data.
:param event_name: name of the event to subscribe, str
:return:
"""
web3 = Web3Provider.get_web3()
try:
web3.eth.waitForTransactionReceipt(tx_hash, timeout=20)
except Timeout:
logger.info('Waiting for transaction receipt timed out. Cannot verify receipt and event.')
return
receipt = web3.eth.getTransactionReceipt(tx_hash)
event = event().processReceipt(receipt)
if event:
logger.info(f'Success: got {event_name} event after fulfilling condition.')
logger.debug(
f'Success: got {event_name} event after fulfilling condition. {receipt}, ::: {event}')
else:
logger.debug(f'Something is not right, cannot find the {event_name} event after calling the'
f' fulfillment condition. This is the transaction receipt {receipt}')
if receipt and receipt.status == 0:
logger.warning(
f'Transaction failed: tx_hash {tx_hash}, tx event {event_name}, receipt {receipt}') | python | def process_tx_receipt(tx_hash, event, event_name):
web3 = Web3Provider.get_web3()
try:
web3.eth.waitForTransactionReceipt(tx_hash, timeout=20)
except Timeout:
logger.info('Waiting for transaction receipt timed out. Cannot verify receipt and event.')
return
receipt = web3.eth.getTransactionReceipt(tx_hash)
event = event().processReceipt(receipt)
if event:
logger.info(f'Success: got {event_name} event after fulfilling condition.')
logger.debug(
f'Success: got {event_name} event after fulfilling condition. {receipt}, ::: {event}')
else:
logger.debug(f'Something is not right, cannot find the {event_name} event after calling the'
f' fulfillment condition. This is the transaction receipt {receipt}')
if receipt and receipt.status == 0:
logger.warning(
f'Transaction failed: tx_hash {tx_hash}, tx event {event_name}, receipt {receipt}') | [
"def",
"process_tx_receipt",
"(",
"tx_hash",
",",
"event",
",",
"event_name",
")",
":",
"web3",
"=",
"Web3Provider",
".",
"get_web3",
"(",
")",
"try",
":",
"web3",
".",
"eth",
".",
"waitForTransactionReceipt",
"(",
"tx_hash",
",",
"timeout",
"=",
"20",
")",
"except",
"Timeout",
":",
"logger",
".",
"info",
"(",
"'Waiting for transaction receipt timed out. Cannot verify receipt and event.'",
")",
"return",
"receipt",
"=",
"web3",
".",
"eth",
".",
"getTransactionReceipt",
"(",
"tx_hash",
")",
"event",
"=",
"event",
"(",
")",
".",
"processReceipt",
"(",
"receipt",
")",
"if",
"event",
":",
"logger",
".",
"info",
"(",
"f'Success: got {event_name} event after fulfilling condition.'",
")",
"logger",
".",
"debug",
"(",
"f'Success: got {event_name} event after fulfilling condition. {receipt}, ::: {event}'",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"f'Something is not right, cannot find the {event_name} event after calling the'",
"f' fulfillment condition. This is the transaction receipt {receipt}'",
")",
"if",
"receipt",
"and",
"receipt",
".",
"status",
"==",
"0",
":",
"logger",
".",
"warning",
"(",
"f'Transaction failed: tx_hash {tx_hash}, tx event {event_name}, receipt {receipt}'",
")"
]
| Wait until the tx receipt is processed.
:param tx_hash: hash of the transaction
:param event: AttributeDict with the event data.
:param event_name: name of the event to subscribe, str
:return: | [
"Wait",
"until",
"the",
"tx",
"receipt",
"is",
"processed",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/utils.py#L31-L59 |
oceanprotocol/squid-py | squid_py/keeper/conditions/condition_manager.py | ConditionStoreManager.get_condition | def get_condition(self, condition_id):
"""Retrieve the condition for a condition_id.
:param condition_id: id of the condition, str
:return:
"""
condition = self.contract_concise.getCondition(condition_id)
if condition and len(condition) == 7:
return ConditionValues(*condition)
return None | python | def get_condition(self, condition_id):
condition = self.contract_concise.getCondition(condition_id)
if condition and len(condition) == 7:
return ConditionValues(*condition)
return None | [
"def",
"get_condition",
"(",
"self",
",",
"condition_id",
")",
":",
"condition",
"=",
"self",
".",
"contract_concise",
".",
"getCondition",
"(",
"condition_id",
")",
"if",
"condition",
"and",
"len",
"(",
"condition",
")",
"==",
"7",
":",
"return",
"ConditionValues",
"(",
"*",
"condition",
")",
"return",
"None"
]
| Retrieve the condition for a condition_id.
:param condition_id: id of the condition, str
:return: | [
"Retrieve",
"the",
"condition",
"for",
"a",
"condition_id",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/conditions/condition_manager.py#L19-L29 |
oceanprotocol/squid-py | squid_py/keeper/conditions/sign.py | SignCondition.fulfill | def fulfill(self, agreement_id, message, account_address, signature, from_account):
"""
Fulfill the sign conditon.
:param agreement_id: id of the agreement, hex str
:param message:
:param account_address: ethereum account address, hex str
:param signature: signed agreement hash, hex str
:param from_account: Account doing the transaction
:return:
"""
return self._fulfill(
agreement_id,
message,
account_address,
signature,
transact={'from': from_account.address,
'passphrase': from_account.password}
) | python | def fulfill(self, agreement_id, message, account_address, signature, from_account):
return self._fulfill(
agreement_id,
message,
account_address,
signature,
transact={'from': from_account.address,
'passphrase': from_account.password}
) | [
"def",
"fulfill",
"(",
"self",
",",
"agreement_id",
",",
"message",
",",
"account_address",
",",
"signature",
",",
"from_account",
")",
":",
"return",
"self",
".",
"_fulfill",
"(",
"agreement_id",
",",
"message",
",",
"account_address",
",",
"signature",
",",
"transact",
"=",
"{",
"'from'",
":",
"from_account",
".",
"address",
",",
"'passphrase'",
":",
"from_account",
".",
"password",
"}",
")"
]
| Fulfill the sign conditon.
:param agreement_id: id of the agreement, hex str
:param message:
:param account_address: ethereum account address, hex str
:param signature: signed agreement hash, hex str
:param from_account: Account doing the transaction
:return: | [
"Fulfill",
"the",
"sign",
"conditon",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/conditions/sign.py#L11-L29 |
oceanprotocol/squid-py | squid_py/ocean/ocean_agreements.py | OceanAgreements.send | def send(self, did, agreement_id, service_definition_id, signature,
consumer_account, auto_consume=False):
"""
Send a signed service agreement to the publisher Brizo instance to
consume/access the service.
:param did: str representation fo the asset DID. Use this to retrieve the asset DDO.
:param agreement_id: 32 bytes identifier created by the consumer and will be used
on-chain for the executed agreement.
:param service_definition_id: str identifies the specific service in
the ddo to use in this agreement.
:param signature: str the signed agreement message hash which includes
conditions and their parameters values and other details of the agreement.
:param consumer_account: Account instance of the consumer
:param auto_consume: boolean tells this function wether to automatically trigger
consuming the asset upon receiving access permission
:raises OceanInitializeServiceAgreementError: on failure
:return: bool
"""
asset = self._asset_resolver.resolve(did)
service_agreement = ServiceAgreement.from_ddo(service_definition_id, asset)
# subscribe to events related to this agreement_id before sending the request.
logger.debug(f'Registering service agreement with id: {agreement_id}')
publisher_address = self._keeper.did_registry.get_did_owner(asset.asset_id)
condition_ids = service_agreement.generate_agreement_condition_ids(
agreement_id, asset.asset_id, consumer_account.address, publisher_address, self._keeper)
register_service_agreement_consumer(
self._config.storage_path,
publisher_address,
agreement_id,
did,
service_agreement,
service_definition_id,
service_agreement.get_price(),
asset.encrypted_files,
consumer_account,
condition_ids,
self._asset_consumer.download if auto_consume else None,
)
return BrizoProvider.get_brizo().initialize_service_agreement(
did,
agreement_id,
service_definition_id,
signature,
consumer_account.address,
service_agreement.endpoints.service
) | python | def send(self, did, agreement_id, service_definition_id, signature,
consumer_account, auto_consume=False):
asset = self._asset_resolver.resolve(did)
service_agreement = ServiceAgreement.from_ddo(service_definition_id, asset)
logger.debug(f'Registering service agreement with id: {agreement_id}')
publisher_address = self._keeper.did_registry.get_did_owner(asset.asset_id)
condition_ids = service_agreement.generate_agreement_condition_ids(
agreement_id, asset.asset_id, consumer_account.address, publisher_address, self._keeper)
register_service_agreement_consumer(
self._config.storage_path,
publisher_address,
agreement_id,
did,
service_agreement,
service_definition_id,
service_agreement.get_price(),
asset.encrypted_files,
consumer_account,
condition_ids,
self._asset_consumer.download if auto_consume else None,
)
return BrizoProvider.get_brizo().initialize_service_agreement(
did,
agreement_id,
service_definition_id,
signature,
consumer_account.address,
service_agreement.endpoints.service
) | [
"def",
"send",
"(",
"self",
",",
"did",
",",
"agreement_id",
",",
"service_definition_id",
",",
"signature",
",",
"consumer_account",
",",
"auto_consume",
"=",
"False",
")",
":",
"asset",
"=",
"self",
".",
"_asset_resolver",
".",
"resolve",
"(",
"did",
")",
"service_agreement",
"=",
"ServiceAgreement",
".",
"from_ddo",
"(",
"service_definition_id",
",",
"asset",
")",
"# subscribe to events related to this agreement_id before sending the request.",
"logger",
".",
"debug",
"(",
"f'Registering service agreement with id: {agreement_id}'",
")",
"publisher_address",
"=",
"self",
".",
"_keeper",
".",
"did_registry",
".",
"get_did_owner",
"(",
"asset",
".",
"asset_id",
")",
"condition_ids",
"=",
"service_agreement",
".",
"generate_agreement_condition_ids",
"(",
"agreement_id",
",",
"asset",
".",
"asset_id",
",",
"consumer_account",
".",
"address",
",",
"publisher_address",
",",
"self",
".",
"_keeper",
")",
"register_service_agreement_consumer",
"(",
"self",
".",
"_config",
".",
"storage_path",
",",
"publisher_address",
",",
"agreement_id",
",",
"did",
",",
"service_agreement",
",",
"service_definition_id",
",",
"service_agreement",
".",
"get_price",
"(",
")",
",",
"asset",
".",
"encrypted_files",
",",
"consumer_account",
",",
"condition_ids",
",",
"self",
".",
"_asset_consumer",
".",
"download",
"if",
"auto_consume",
"else",
"None",
",",
")",
"return",
"BrizoProvider",
".",
"get_brizo",
"(",
")",
".",
"initialize_service_agreement",
"(",
"did",
",",
"agreement_id",
",",
"service_definition_id",
",",
"signature",
",",
"consumer_account",
".",
"address",
",",
"service_agreement",
".",
"endpoints",
".",
"service",
")"
]
| Send a signed service agreement to the publisher Brizo instance to
consume/access the service.
:param did: str representation fo the asset DID. Use this to retrieve the asset DDO.
:param agreement_id: 32 bytes identifier created by the consumer and will be used
on-chain for the executed agreement.
:param service_definition_id: str identifies the specific service in
the ddo to use in this agreement.
:param signature: str the signed agreement message hash which includes
conditions and their parameters values and other details of the agreement.
:param consumer_account: Account instance of the consumer
:param auto_consume: boolean tells this function wether to automatically trigger
consuming the asset upon receiving access permission
:raises OceanInitializeServiceAgreementError: on failure
:return: bool | [
"Send",
"a",
"signed",
"service",
"agreement",
"to",
"the",
"publisher",
"Brizo",
"instance",
"to",
"consume",
"/",
"access",
"the",
"service",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_agreements.py#L76-L124 |
oceanprotocol/squid-py | squid_py/ocean/ocean_agreements.py | OceanAgreements.create | def create(self, did, service_definition_id, agreement_id,
service_agreement_signature, consumer_address, account):
"""
Execute the service agreement on-chain using keeper's ServiceAgreement contract.
The on-chain executeAgreement method requires the following arguments:
templateId, signature, consumer, hashes, timeouts, serviceAgreementId, did.
`agreement_message_hash` is necessary to verify the signature.
The consumer `signature` includes the conditions timeouts and parameters values which
is usedon-chain to verify that the values actually match the signed hashes.
:param did: str representation fo the asset DID. Use this to retrieve the asset DDO.
:param service_definition_id: str identifies the specific service in
the ddo to use in this agreement.
:param agreement_id: 32 bytes identifier created by the consumer and will be used
on-chain for the executed agreement.
:param service_agreement_signature: str the signed agreement message hash which includes
conditions and their parameters values and other details of the agreement.
:param consumer_address: ethereum account address of consumer, hex str
:param account: Account instance creating the agreement. Can be either the
consumer, publisher or provider
:return: dict the `executeAgreement` transaction receipt
"""
assert consumer_address and Web3Provider.get_web3().isChecksumAddress(
consumer_address), f'Invalid consumer address {consumer_address}'
assert account.address in self._keeper.accounts, \
f'Unrecognized account address {account.address}'
agreement_template_approved = self._keeper.template_manager.is_template_approved(
self._keeper.escrow_access_secretstore_template.address)
if not agreement_template_approved:
msg = (f'The EscrowAccessSecretStoreTemplate contract at address '
f'{self._keeper.escrow_access_secretstore_template.address} is not '
f'approved and cannot be used for creating service agreements.')
logger.warning(msg)
raise OceanInvalidAgreementTemplate(msg)
asset = self._asset_resolver.resolve(did)
asset_id = asset.asset_id
service_agreement = ServiceAgreement.from_ddo(service_definition_id, asset)
agreement_template = self._keeper.escrow_access_secretstore_template
if agreement_template.get_agreement_consumer(agreement_id) is not None:
raise OceanServiceAgreementExists(
f'Service agreement {agreement_id} already exists, cannot reuse '
f'the same agreement id.')
if consumer_address != account.address:
if not self._verify_service_agreement_signature(
did, agreement_id, service_definition_id,
consumer_address, service_agreement_signature,
ddo=asset
):
raise OceanInvalidServiceAgreementSignature(
f'Verifying consumer signature failed: '
f'signature {service_agreement_signature}, '
f'consumerAddress {consumer_address}'
)
publisher_address = Web3Provider.get_web3().toChecksumAddress(asset.publisher)
condition_ids = service_agreement.generate_agreement_condition_ids(
agreement_id, asset_id, consumer_address, publisher_address, self._keeper)
time_locks = service_agreement.conditions_timelocks
time_outs = service_agreement.conditions_timeouts
success = agreement_template.create_agreement(
agreement_id,
asset_id,
condition_ids,
time_locks,
time_outs,
consumer_address,
account
)
if not success:
# success is based on tx receipt which is not reliable.
# So we check on-chain directly to see if agreement_id is there
consumer = self._keeper.escrow_access_secretstore_template.get_agreement_consumer(agreement_id)
if consumer:
success = True
else:
event_log = self._keeper.escrow_access_secretstore_template.subscribe_agreement_created(
agreement_id, 30, None, (), wait=True
)
success = event_log is not None
if success:
logger.info(f'Service agreement {agreement_id} created successfully.')
else:
logger.info(f'Create agreement "{agreement_id}" failed.')
self._log_agreement_info(
asset, service_agreement, agreement_id, service_agreement_signature,
consumer_address, account, condition_ids
)
if success:
# subscribe to events related to this agreement_id
if consumer_address == account.address:
register_service_agreement_consumer(
self._config.storage_path,
publisher_address,
agreement_id,
did,
service_agreement,
service_definition_id,
service_agreement.get_price(),
asset.encrypted_files,
account,
condition_ids,
None
)
else:
register_service_agreement_publisher(
self._config.storage_path,
consumer_address,
agreement_id,
did,
service_agreement,
service_definition_id,
service_agreement.get_price(),
account,
condition_ids
)
return success | python | def create(self, did, service_definition_id, agreement_id,
service_agreement_signature, consumer_address, account):
assert consumer_address and Web3Provider.get_web3().isChecksumAddress(
consumer_address), f'Invalid consumer address {consumer_address}'
assert account.address in self._keeper.accounts, \
f'Unrecognized account address {account.address}'
agreement_template_approved = self._keeper.template_manager.is_template_approved(
self._keeper.escrow_access_secretstore_template.address)
if not agreement_template_approved:
msg = (f'The EscrowAccessSecretStoreTemplate contract at address '
f'{self._keeper.escrow_access_secretstore_template.address} is not '
f'approved and cannot be used for creating service agreements.')
logger.warning(msg)
raise OceanInvalidAgreementTemplate(msg)
asset = self._asset_resolver.resolve(did)
asset_id = asset.asset_id
service_agreement = ServiceAgreement.from_ddo(service_definition_id, asset)
agreement_template = self._keeper.escrow_access_secretstore_template
if agreement_template.get_agreement_consumer(agreement_id) is not None:
raise OceanServiceAgreementExists(
f'Service agreement {agreement_id} already exists, cannot reuse '
f'the same agreement id.')
if consumer_address != account.address:
if not self._verify_service_agreement_signature(
did, agreement_id, service_definition_id,
consumer_address, service_agreement_signature,
ddo=asset
):
raise OceanInvalidServiceAgreementSignature(
f'Verifying consumer signature failed: '
f'signature {service_agreement_signature}, '
f'consumerAddress {consumer_address}'
)
publisher_address = Web3Provider.get_web3().toChecksumAddress(asset.publisher)
condition_ids = service_agreement.generate_agreement_condition_ids(
agreement_id, asset_id, consumer_address, publisher_address, self._keeper)
time_locks = service_agreement.conditions_timelocks
time_outs = service_agreement.conditions_timeouts
success = agreement_template.create_agreement(
agreement_id,
asset_id,
condition_ids,
time_locks,
time_outs,
consumer_address,
account
)
if not success:
consumer = self._keeper.escrow_access_secretstore_template.get_agreement_consumer(agreement_id)
if consumer:
success = True
else:
event_log = self._keeper.escrow_access_secretstore_template.subscribe_agreement_created(
agreement_id, 30, None, (), wait=True
)
success = event_log is not None
if success:
logger.info(f'Service agreement {agreement_id} created successfully.')
else:
logger.info(f'Create agreement "{agreement_id}" failed.')
self._log_agreement_info(
asset, service_agreement, agreement_id, service_agreement_signature,
consumer_address, account, condition_ids
)
if success:
if consumer_address == account.address:
register_service_agreement_consumer(
self._config.storage_path,
publisher_address,
agreement_id,
did,
service_agreement,
service_definition_id,
service_agreement.get_price(),
asset.encrypted_files,
account,
condition_ids,
None
)
else:
register_service_agreement_publisher(
self._config.storage_path,
consumer_address,
agreement_id,
did,
service_agreement,
service_definition_id,
service_agreement.get_price(),
account,
condition_ids
)
return success | [
"def",
"create",
"(",
"self",
",",
"did",
",",
"service_definition_id",
",",
"agreement_id",
",",
"service_agreement_signature",
",",
"consumer_address",
",",
"account",
")",
":",
"assert",
"consumer_address",
"and",
"Web3Provider",
".",
"get_web3",
"(",
")",
".",
"isChecksumAddress",
"(",
"consumer_address",
")",
",",
"f'Invalid consumer address {consumer_address}'",
"assert",
"account",
".",
"address",
"in",
"self",
".",
"_keeper",
".",
"accounts",
",",
"f'Unrecognized account address {account.address}'",
"agreement_template_approved",
"=",
"self",
".",
"_keeper",
".",
"template_manager",
".",
"is_template_approved",
"(",
"self",
".",
"_keeper",
".",
"escrow_access_secretstore_template",
".",
"address",
")",
"if",
"not",
"agreement_template_approved",
":",
"msg",
"=",
"(",
"f'The EscrowAccessSecretStoreTemplate contract at address '",
"f'{self._keeper.escrow_access_secretstore_template.address} is not '",
"f'approved and cannot be used for creating service agreements.'",
")",
"logger",
".",
"warning",
"(",
"msg",
")",
"raise",
"OceanInvalidAgreementTemplate",
"(",
"msg",
")",
"asset",
"=",
"self",
".",
"_asset_resolver",
".",
"resolve",
"(",
"did",
")",
"asset_id",
"=",
"asset",
".",
"asset_id",
"service_agreement",
"=",
"ServiceAgreement",
".",
"from_ddo",
"(",
"service_definition_id",
",",
"asset",
")",
"agreement_template",
"=",
"self",
".",
"_keeper",
".",
"escrow_access_secretstore_template",
"if",
"agreement_template",
".",
"get_agreement_consumer",
"(",
"agreement_id",
")",
"is",
"not",
"None",
":",
"raise",
"OceanServiceAgreementExists",
"(",
"f'Service agreement {agreement_id} already exists, cannot reuse '",
"f'the same agreement id.'",
")",
"if",
"consumer_address",
"!=",
"account",
".",
"address",
":",
"if",
"not",
"self",
".",
"_verify_service_agreement_signature",
"(",
"did",
",",
"agreement_id",
",",
"service_definition_id",
",",
"consumer_address",
",",
"service_agreement_signature",
",",
"ddo",
"=",
"asset",
")",
":",
"raise",
"OceanInvalidServiceAgreementSignature",
"(",
"f'Verifying consumer signature failed: '",
"f'signature {service_agreement_signature}, '",
"f'consumerAddress {consumer_address}'",
")",
"publisher_address",
"=",
"Web3Provider",
".",
"get_web3",
"(",
")",
".",
"toChecksumAddress",
"(",
"asset",
".",
"publisher",
")",
"condition_ids",
"=",
"service_agreement",
".",
"generate_agreement_condition_ids",
"(",
"agreement_id",
",",
"asset_id",
",",
"consumer_address",
",",
"publisher_address",
",",
"self",
".",
"_keeper",
")",
"time_locks",
"=",
"service_agreement",
".",
"conditions_timelocks",
"time_outs",
"=",
"service_agreement",
".",
"conditions_timeouts",
"success",
"=",
"agreement_template",
".",
"create_agreement",
"(",
"agreement_id",
",",
"asset_id",
",",
"condition_ids",
",",
"time_locks",
",",
"time_outs",
",",
"consumer_address",
",",
"account",
")",
"if",
"not",
"success",
":",
"# success is based on tx receipt which is not reliable.",
"# So we check on-chain directly to see if agreement_id is there",
"consumer",
"=",
"self",
".",
"_keeper",
".",
"escrow_access_secretstore_template",
".",
"get_agreement_consumer",
"(",
"agreement_id",
")",
"if",
"consumer",
":",
"success",
"=",
"True",
"else",
":",
"event_log",
"=",
"self",
".",
"_keeper",
".",
"escrow_access_secretstore_template",
".",
"subscribe_agreement_created",
"(",
"agreement_id",
",",
"30",
",",
"None",
",",
"(",
")",
",",
"wait",
"=",
"True",
")",
"success",
"=",
"event_log",
"is",
"not",
"None",
"if",
"success",
":",
"logger",
".",
"info",
"(",
"f'Service agreement {agreement_id} created successfully.'",
")",
"else",
":",
"logger",
".",
"info",
"(",
"f'Create agreement \"{agreement_id}\" failed.'",
")",
"self",
".",
"_log_agreement_info",
"(",
"asset",
",",
"service_agreement",
",",
"agreement_id",
",",
"service_agreement_signature",
",",
"consumer_address",
",",
"account",
",",
"condition_ids",
")",
"if",
"success",
":",
"# subscribe to events related to this agreement_id",
"if",
"consumer_address",
"==",
"account",
".",
"address",
":",
"register_service_agreement_consumer",
"(",
"self",
".",
"_config",
".",
"storage_path",
",",
"publisher_address",
",",
"agreement_id",
",",
"did",
",",
"service_agreement",
",",
"service_definition_id",
",",
"service_agreement",
".",
"get_price",
"(",
")",
",",
"asset",
".",
"encrypted_files",
",",
"account",
",",
"condition_ids",
",",
"None",
")",
"else",
":",
"register_service_agreement_publisher",
"(",
"self",
".",
"_config",
".",
"storage_path",
",",
"consumer_address",
",",
"agreement_id",
",",
"did",
",",
"service_agreement",
",",
"service_definition_id",
",",
"service_agreement",
".",
"get_price",
"(",
")",
",",
"account",
",",
"condition_ids",
")",
"return",
"success"
]
| Execute the service agreement on-chain using keeper's ServiceAgreement contract.
The on-chain executeAgreement method requires the following arguments:
templateId, signature, consumer, hashes, timeouts, serviceAgreementId, did.
`agreement_message_hash` is necessary to verify the signature.
The consumer `signature` includes the conditions timeouts and parameters values which
is usedon-chain to verify that the values actually match the signed hashes.
:param did: str representation fo the asset DID. Use this to retrieve the asset DDO.
:param service_definition_id: str identifies the specific service in
the ddo to use in this agreement.
:param agreement_id: 32 bytes identifier created by the consumer and will be used
on-chain for the executed agreement.
:param service_agreement_signature: str the signed agreement message hash which includes
conditions and their parameters values and other details of the agreement.
:param consumer_address: ethereum account address of consumer, hex str
:param account: Account instance creating the agreement. Can be either the
consumer, publisher or provider
:return: dict the `executeAgreement` transaction receipt | [
"Execute",
"the",
"service",
"agreement",
"on",
"-",
"chain",
"using",
"keeper",
"s",
"ServiceAgreement",
"contract",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_agreements.py#L126-L252 |
oceanprotocol/squid-py | squid_py/ocean/ocean_agreements.py | OceanAgreements.is_access_granted | def is_access_granted(self, agreement_id, did, consumer_address):
"""
Check permission for the agreement.
Verify on-chain that the `consumer_address` has permission to access the given asset `did`
according to the `agreement_id`.
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param consumer_address: ethereum account address of consumer, hex str
:return: bool True if user has permission
"""
agreement_consumer = self._keeper.escrow_access_secretstore_template.get_agreement_consumer(
agreement_id)
if agreement_consumer != consumer_address:
logger.warning(f'Invalid consumer address {consumer_address} and/or '
f'service agreement id {agreement_id} (did {did})'
f', agreement consumer is {agreement_consumer}')
return False
document_id = did_to_id(did)
return self._keeper.access_secret_store_condition.check_permissions(
document_id, consumer_address
) | python | def is_access_granted(self, agreement_id, did, consumer_address):
agreement_consumer = self._keeper.escrow_access_secretstore_template.get_agreement_consumer(
agreement_id)
if agreement_consumer != consumer_address:
logger.warning(f'Invalid consumer address {consumer_address} and/or '
f'service agreement id {agreement_id} (did {did})'
f', agreement consumer is {agreement_consumer}')
return False
document_id = did_to_id(did)
return self._keeper.access_secret_store_condition.check_permissions(
document_id, consumer_address
) | [
"def",
"is_access_granted",
"(",
"self",
",",
"agreement_id",
",",
"did",
",",
"consumer_address",
")",
":",
"agreement_consumer",
"=",
"self",
".",
"_keeper",
".",
"escrow_access_secretstore_template",
".",
"get_agreement_consumer",
"(",
"agreement_id",
")",
"if",
"agreement_consumer",
"!=",
"consumer_address",
":",
"logger",
".",
"warning",
"(",
"f'Invalid consumer address {consumer_address} and/or '",
"f'service agreement id {agreement_id} (did {did})'",
"f', agreement consumer is {agreement_consumer}'",
")",
"return",
"False",
"document_id",
"=",
"did_to_id",
"(",
"did",
")",
"return",
"self",
".",
"_keeper",
".",
"access_secret_store_condition",
".",
"check_permissions",
"(",
"document_id",
",",
"consumer_address",
")"
]
| Check permission for the agreement.
Verify on-chain that the `consumer_address` has permission to access the given asset `did`
according to the `agreement_id`.
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param consumer_address: ethereum account address of consumer, hex str
:return: bool True if user has permission | [
"Check",
"permission",
"for",
"the",
"agreement",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_agreements.py#L273-L296 |
oceanprotocol/squid-py | squid_py/ocean/ocean_agreements.py | OceanAgreements._verify_service_agreement_signature | def _verify_service_agreement_signature(self, did, agreement_id, service_definition_id,
consumer_address, signature, ddo=None):
"""
Verify service agreement signature.
Verify that the given signature is truly signed by the `consumer_address`
and represents this did's service agreement..
:param did: DID, str
:param agreement_id: id of the agreement, hex str
:param service_definition_id: identifier of the service inside the asset DDO, str
:param consumer_address: ethereum account address of consumer, hex str
:param signature: Signature, str
:param ddo: DDO instance
:return: True if signature is legitimate, False otherwise
:raises: ValueError if service is not found in the ddo
:raises: AssertionError if conditions keys do not match the on-chain conditions keys
"""
if not ddo:
ddo = self._asset_resolver.resolve(did)
service_agreement = ServiceAgreement.from_ddo(service_definition_id, ddo)
agreement_hash = service_agreement.get_service_agreement_hash(
agreement_id, ddo.asset_id, consumer_address,
Web3Provider.get_web3().toChecksumAddress(ddo.proof['creator']), self._keeper)
prefixed_hash = prepare_prefixed_hash(agreement_hash)
recovered_address = Web3Provider.get_web3().eth.account.recoverHash(
prefixed_hash, signature=signature
)
is_valid = (recovered_address == consumer_address)
if not is_valid:
logger.warning(f'Agreement signature failed: agreement hash is {agreement_hash.hex()}')
return is_valid | python | def _verify_service_agreement_signature(self, did, agreement_id, service_definition_id,
consumer_address, signature, ddo=None):
if not ddo:
ddo = self._asset_resolver.resolve(did)
service_agreement = ServiceAgreement.from_ddo(service_definition_id, ddo)
agreement_hash = service_agreement.get_service_agreement_hash(
agreement_id, ddo.asset_id, consumer_address,
Web3Provider.get_web3().toChecksumAddress(ddo.proof['creator']), self._keeper)
prefixed_hash = prepare_prefixed_hash(agreement_hash)
recovered_address = Web3Provider.get_web3().eth.account.recoverHash(
prefixed_hash, signature=signature
)
is_valid = (recovered_address == consumer_address)
if not is_valid:
logger.warning(f'Agreement signature failed: agreement hash is {agreement_hash.hex()}')
return is_valid | [
"def",
"_verify_service_agreement_signature",
"(",
"self",
",",
"did",
",",
"agreement_id",
",",
"service_definition_id",
",",
"consumer_address",
",",
"signature",
",",
"ddo",
"=",
"None",
")",
":",
"if",
"not",
"ddo",
":",
"ddo",
"=",
"self",
".",
"_asset_resolver",
".",
"resolve",
"(",
"did",
")",
"service_agreement",
"=",
"ServiceAgreement",
".",
"from_ddo",
"(",
"service_definition_id",
",",
"ddo",
")",
"agreement_hash",
"=",
"service_agreement",
".",
"get_service_agreement_hash",
"(",
"agreement_id",
",",
"ddo",
".",
"asset_id",
",",
"consumer_address",
",",
"Web3Provider",
".",
"get_web3",
"(",
")",
".",
"toChecksumAddress",
"(",
"ddo",
".",
"proof",
"[",
"'creator'",
"]",
")",
",",
"self",
".",
"_keeper",
")",
"prefixed_hash",
"=",
"prepare_prefixed_hash",
"(",
"agreement_hash",
")",
"recovered_address",
"=",
"Web3Provider",
".",
"get_web3",
"(",
")",
".",
"eth",
".",
"account",
".",
"recoverHash",
"(",
"prefixed_hash",
",",
"signature",
"=",
"signature",
")",
"is_valid",
"=",
"(",
"recovered_address",
"==",
"consumer_address",
")",
"if",
"not",
"is_valid",
":",
"logger",
".",
"warning",
"(",
"f'Agreement signature failed: agreement hash is {agreement_hash.hex()}'",
")",
"return",
"is_valid"
]
| Verify service agreement signature.
Verify that the given signature is truly signed by the `consumer_address`
and represents this did's service agreement..
:param did: DID, str
:param agreement_id: id of the agreement, hex str
:param service_definition_id: identifier of the service inside the asset DDO, str
:param consumer_address: ethereum account address of consumer, hex str
:param signature: Signature, str
:param ddo: DDO instance
:return: True if signature is legitimate, False otherwise
:raises: ValueError if service is not found in the ddo
:raises: AssertionError if conditions keys do not match the on-chain conditions keys | [
"Verify",
"service",
"agreement",
"signature",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_agreements.py#L298-L332 |
oceanprotocol/squid-py | squid_py/ocean/ocean_agreements.py | OceanAgreements.status | def status(self, agreement_id):
"""
Get the status of a service agreement.
:param agreement_id: id of the agreement, hex str
:return: dict with condition status of each of the agreement's conditions or None if the
agreement is invalid.
"""
condition_ids = self._keeper.agreement_manager.get_agreement(agreement_id).condition_ids
result = {"agreementId": agreement_id}
conditions = dict()
for i in condition_ids:
conditions[self._keeper.get_condition_name_by_address(
self._keeper.condition_manager.get_condition(
i).type_ref)] = self._keeper.condition_manager.get_condition_state(i)
result["conditions"] = conditions
return result | python | def status(self, agreement_id):
condition_ids = self._keeper.agreement_manager.get_agreement(agreement_id).condition_ids
result = {"agreementId": agreement_id}
conditions = dict()
for i in condition_ids:
conditions[self._keeper.get_condition_name_by_address(
self._keeper.condition_manager.get_condition(
i).type_ref)] = self._keeper.condition_manager.get_condition_state(i)
result["conditions"] = conditions
return result | [
"def",
"status",
"(",
"self",
",",
"agreement_id",
")",
":",
"condition_ids",
"=",
"self",
".",
"_keeper",
".",
"agreement_manager",
".",
"get_agreement",
"(",
"agreement_id",
")",
".",
"condition_ids",
"result",
"=",
"{",
"\"agreementId\"",
":",
"agreement_id",
"}",
"conditions",
"=",
"dict",
"(",
")",
"for",
"i",
"in",
"condition_ids",
":",
"conditions",
"[",
"self",
".",
"_keeper",
".",
"get_condition_name_by_address",
"(",
"self",
".",
"_keeper",
".",
"condition_manager",
".",
"get_condition",
"(",
"i",
")",
".",
"type_ref",
")",
"]",
"=",
"self",
".",
"_keeper",
".",
"condition_manager",
".",
"get_condition_state",
"(",
"i",
")",
"result",
"[",
"\"conditions\"",
"]",
"=",
"conditions",
"return",
"result"
]
| Get the status of a service agreement.
:param agreement_id: id of the agreement, hex str
:return: dict with condition status of each of the agreement's conditions or None if the
agreement is invalid. | [
"Get",
"the",
"status",
"of",
"a",
"service",
"agreement",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_agreements.py#L343-L359 |
oceanprotocol/squid-py | squid_py/keeper/templates/access_secret_store_template.py | EscrowAccessSecretStoreTemplate.create_agreement | def create_agreement(self, agreement_id, did, condition_ids, time_locks, time_outs,
consumer_address, account):
"""
Create the service agreement. Return true if it is created successfully.
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32
:param time_locks: is a list of uint time lock values associated to each Condition, int
:param time_outs: is a list of uint time out values associated to each Condition, int
:param consumer_address: ethereum account address of consumer, hex str
:param account: Account instance creating the agreement
:return: bool
"""
logger.info(
f'Creating agreement {agreement_id} with did={did}, consumer={consumer_address}.')
tx_hash = self.send_transaction(
'createAgreement',
(agreement_id,
did,
condition_ids,
time_locks,
time_outs,
consumer_address),
transact={'from': account.address,
'passphrase': account.password}
)
receipt = self.get_tx_receipt(tx_hash)
return receipt and receipt.status == 1 | python | def create_agreement(self, agreement_id, did, condition_ids, time_locks, time_outs,
consumer_address, account):
logger.info(
f'Creating agreement {agreement_id} with did={did}, consumer={consumer_address}.')
tx_hash = self.send_transaction(
'createAgreement',
(agreement_id,
did,
condition_ids,
time_locks,
time_outs,
consumer_address),
transact={'from': account.address,
'passphrase': account.password}
)
receipt = self.get_tx_receipt(tx_hash)
return receipt and receipt.status == 1 | [
"def",
"create_agreement",
"(",
"self",
",",
"agreement_id",
",",
"did",
",",
"condition_ids",
",",
"time_locks",
",",
"time_outs",
",",
"consumer_address",
",",
"account",
")",
":",
"logger",
".",
"info",
"(",
"f'Creating agreement {agreement_id} with did={did}, consumer={consumer_address}.'",
")",
"tx_hash",
"=",
"self",
".",
"send_transaction",
"(",
"'createAgreement'",
",",
"(",
"agreement_id",
",",
"did",
",",
"condition_ids",
",",
"time_locks",
",",
"time_outs",
",",
"consumer_address",
")",
",",
"transact",
"=",
"{",
"'from'",
":",
"account",
".",
"address",
",",
"'passphrase'",
":",
"account",
".",
"password",
"}",
")",
"receipt",
"=",
"self",
".",
"get_tx_receipt",
"(",
"tx_hash",
")",
"return",
"receipt",
"and",
"receipt",
".",
"status",
"==",
"1"
]
| Create the service agreement. Return true if it is created successfully.
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32
:param time_locks: is a list of uint time lock values associated to each Condition, int
:param time_outs: is a list of uint time out values associated to each Condition, int
:param consumer_address: ethereum account address of consumer, hex str
:param account: Account instance creating the agreement
:return: bool | [
"Create",
"the",
"service",
"agreement",
".",
"Return",
"true",
"if",
"it",
"is",
"created",
"successfully",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/templates/access_secret_store_template.py#L17-L45 |
oceanprotocol/squid-py | squid_py/keeper/templates/access_secret_store_template.py | EscrowAccessSecretStoreTemplate.subscribe_agreement_created | def subscribe_agreement_created(self, agreement_id, timeout, callback, args, wait=False):
"""
Subscribe to an agreement created.
:param agreement_id: id of the agreement, hex str
:param timeout:
:param callback:
:param args:
:param wait: if true block the listener until get the event, bool
:return:
"""
logger.info(
f'Subscribing {self.AGREEMENT_CREATED_EVENT} event with agreement id {agreement_id}.')
return self.subscribe_to_event(
self.AGREEMENT_CREATED_EVENT,
timeout,
{'_agreementId': Web3Provider.get_web3().toBytes(hexstr=agreement_id)},
callback=callback,
args=args,
wait=wait
) | python | def subscribe_agreement_created(self, agreement_id, timeout, callback, args, wait=False):
logger.info(
f'Subscribing {self.AGREEMENT_CREATED_EVENT} event with agreement id {agreement_id}.')
return self.subscribe_to_event(
self.AGREEMENT_CREATED_EVENT,
timeout,
{'_agreementId': Web3Provider.get_web3().toBytes(hexstr=agreement_id)},
callback=callback,
args=args,
wait=wait
) | [
"def",
"subscribe_agreement_created",
"(",
"self",
",",
"agreement_id",
",",
"timeout",
",",
"callback",
",",
"args",
",",
"wait",
"=",
"False",
")",
":",
"logger",
".",
"info",
"(",
"f'Subscribing {self.AGREEMENT_CREATED_EVENT} event with agreement id {agreement_id}.'",
")",
"return",
"self",
".",
"subscribe_to_event",
"(",
"self",
".",
"AGREEMENT_CREATED_EVENT",
",",
"timeout",
",",
"{",
"'_agreementId'",
":",
"Web3Provider",
".",
"get_web3",
"(",
")",
".",
"toBytes",
"(",
"hexstr",
"=",
"agreement_id",
")",
"}",
",",
"callback",
"=",
"callback",
",",
"args",
"=",
"args",
",",
"wait",
"=",
"wait",
")"
]
| Subscribe to an agreement created.
:param agreement_id: id of the agreement, hex str
:param timeout:
:param callback:
:param args:
:param wait: if true block the listener until get the event, bool
:return: | [
"Subscribe",
"to",
"an",
"agreement",
"created",
"."
]
| train | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/templates/access_secret_store_template.py#L72-L92 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.