Compare commits

...

2 commits

Author SHA1 Message Date
Cayo Puigdefabregas d0d4ac8d6c fix READMES 2024-06-03 17:53:58 +02:00
Cayo Puigdefabregas 4c876e56c7 add cache to document loader 2024-06-03 17:51:52 +02:00
5 changed files with 148 additions and 16 deletions

View file

@ -25,47 +25,47 @@ The mode of use under the command line would be the following:
## generate a key pair: ## generate a key pair:
```sh ```sh
python did.py -n keys > keypair.json python pyvckit/did.py -n keys > keypair.json
``` ```
## generate a did identifier: ## generate a did identifier:
### did key ### did key
```sh ```sh
python did.py -n did -k keypair.json python pyvckit/did.py -n did -k keypair.json
``` ```
### did web ### did web
```sh ```sh
python did.py -n did -k keypair.json -u https://localhost/user1/dids/ python pyvckit/did.py -n did -k keypair.json -u https://localhost/user1/dids/
``` ```
## generate an example signed credential: ## generate an example signed credential:
An example of a credential is generated, which is the one that appears in the credential_tmpl template in the file [templates.py](templates.py) An example of a credential is generated, which is the one that appears in the credential_tmpl template in the file [templates.py](templates.py)
```sh ```sh
python sign_vc.py -k keypair.json > credential_signed.json python pyvckit/sign_vc.py -k keypair.json > credential_signed.json
``` ```
## verify a signed credential: ## verify a signed credential:
```sh ```sh
python verify_vc.py credential_signed.json python pyvckit/verify_vc.py credential_signed.json
``` ```
## generate a verifiable presentation: ## generate a verifiable presentation:
```sh ```sh
python sign_vp.py -k keypair.json -c credential_signed.json > presentation_signed.json python pyvckit/sign_vp.py -k keypair.json -c credential_signed.json > presentation_signed.json
``` ```
## verify a verifiable presentation: ## verify a verifiable presentation:
```sh ```sh
python verify_vp.py presentation_signed.json python pyvckit/verify_vp.py presentation_signed.json
``` ```
## creation of did document: ## creation of did document:
This command will create a json document and a url path where to place this document. The did must be a web did. This command will create a json document and a url path where to place this document. The did must be a web did.
This document is an example and in production it must be adapted to contain the revoked verifiable credentials. This document is an example and in production it must be adapted to contain the revoked verifiable credentials.
```sh ```sh
python did.py -k keypair.json -g did:web:localhost:did-registry:z6MkiNc8xqJLcG7QR1wzD9HPs5oPQEaWNcVf92QsbppNiB7C python pyvckit/did.py -k keypair.json -g did:web:localhost:did-registry:z6MkiNc8xqJLcG7QR1wzD9HPs5oPQEaWNcVf92QsbppNiB7C
``` ```
# Use as a library # Use as a library

View file

@ -25,47 +25,47 @@ El modo de uso bajo la linea de comandos seria el siguiente:
## generar un par de claves: ## generar un par de claves:
```sh ```sh
python did.py -n keys > keypair.json python pyvckit/did.py -n keys > keypair.json
``` ```
## generar un identificador did: ## generar un identificador did:
### did key ### did key
```sh ```sh
python did.py -n did -k keypair.json python pyvckit/did.py -n did -k keypair.json
``` ```
### did web ### did web
```sh ```sh
python did.py -n did -k keypair.json -u https://localhost/user1/dids/ python pyvckit/did.py -n did -k keypair.json -u https://localhost/user1/dids/
``` ```
## generar una credencial firmada de ejemplo: ## generar una credencial firmada de ejemplo:
Se genera un ejemplo de credencial que es el que aparece en la plantilla credential_tmpl del fichero [templates.py](templates.py) Se genera un ejemplo de credencial que es el que aparece en la plantilla credential_tmpl del fichero [templates.py](templates.py)
```sh ```sh
python sign_vc.py -k keypair.json > credential_signed.json python pyvckit/sign_vc.py -k keypair.json > credential_signed.json
``` ```
## verificar una credencial firmada: ## verificar una credencial firmada:
```sh ```sh
python verify_vc.py credential_signed.json python pyvckit/verify_vc.py credential_signed.json
``` ```
## generar una presentación verificable: ## generar una presentación verificable:
```sh ```sh
python sign_vp.py -k keypair.json -c credential_signed.json > presentation_signed.json python pyvckit/sign_vp.py -k keypair.json -c credential_signed.json > presentation_signed.json
``` ```
## verificar una presentación verificable: ## verificar una presentación verificable:
```sh ```sh
python verify_vp.py presentation_signed.json python pyvckit/verify_vp.py presentation_signed.json
``` ```
## creación del documento did: ## creación del documento did:
Este comando creara un documento json y una ruta url donde colocar este documento. El did tiene que ser un did web. Este comando creara un documento json y una ruta url donde colocar este documento. El did tiene que ser un did web.
Este documento es un ejemplo y en producción hay que adaptarlo para contener las credenciales verificables revocadas. Este documento es un ejemplo y en producción hay que adaptarlo para contener las credenciales verificables revocadas.
```sh ```sh
python did.py -k keypair.json -g did:web:localhost:did-registry:z6MkiNc8xqJLcG7QR1wzD9HPs5oPQEaWNcVf92QsbppNiB7C python pyvckit/did.py -k keypair.json -g did:web:localhost:did-registry:z6MkiNc8xqJLcG7QR1wzD9HPs5oPQEaWNcVf92QsbppNiB7C
``` ```
# Uso como librería # Uso como librería

1
cache_context.json Normal file

File diff suppressed because one or more lines are too long

127
pyvckit/document_loader.py Normal file
View file

@ -0,0 +1,127 @@
"""
Remote document loader using Requests.
.. module:: jsonld.documentloader.requests
:synopsis: Remote document loader using Requests
.. moduleauthor:: Dave Longley
.. moduleauthor:: Mike Johnson
.. moduleauthor:: Tim McNamara <tim.mcnamara@okfn.org>
.. moduleauthor:: Olaf Conradi <olaf@conradi.org>
"""
import string
import json
import urllib.parse as urllib_parse
from pyld.jsonld import (JsonLdError, parse_link_header, LINK_HEADER_REL)
def get_cache():
with open("cache_context.json") as f:
doc_str = f.read()
if doc_str:
# import pdb; pdb.set_trace()
return json.loads(doc_str)
return {}
def requests_document_loader(secure=False, **kwargs):
"""
Create a Requests document loader.
Can be used to setup extra Requests args such as verify, cert, timeout,
or others.
:param secure: require all requests to use HTTPS (default: False).
:param **kwargs: extra keyword args for Requests get() call.
:return: the RemoteDocument loader function.
"""
import requests
def loader(url, options={}):
"""
Retrieves JSON-LD at the given URL.
:param url: the URL to retrieve.
:return: the RemoteDocument.
"""
# import pdb; pdb.set_trace()
cache = get_cache()
if cache.get(url):
return cache[url]
try:
# validate URL
pieces = urllib_parse.urlparse(url)
if (not all([pieces.scheme, pieces.netloc]) or
pieces.scheme not in ['http', 'https'] or
set(pieces.netloc) > set(
string.ascii_letters + string.digits + '-.:')):
raise JsonLdError(
'URL could not be dereferenced; only "http" and "https" '
'URLs are supported.',
'jsonld.InvalidUrl', {'url': url},
code='loading document failed')
if secure and pieces.scheme != 'https':
raise JsonLdError(
'URL could not be dereferenced; secure mode enabled and '
'the URL\'s scheme is not "https".',
'jsonld.InvalidUrl', {'url': url},
code='loading document failed')
headers = options.get('headers')
if headers is None:
headers = {
'Accept': 'application/ld+json, application/json'
}
response = requests.get(url, headers=headers, **kwargs)
content_type = response.headers.get('content-type')
if not content_type:
content_type = 'application/octet-stream'
doc = {
'contentType': content_type,
'contextUrl': None,
'documentUrl': response.url,
'document': response.json()
}
link_header = response.headers.get('link')
if link_header:
linked_context = parse_link_header(link_header).get(
LINK_HEADER_REL)
# only 1 related link header permitted
if linked_context and content_type != 'application/ld+json':
if isinstance(linked_context, list):
raise JsonLdError(
'URL could not be dereferenced, '
'it has more than one '
'associated HTTP Link Header.',
'jsonld.LoadDocumentError',
{'url': url},
code='multiple context link headers')
doc['contextUrl'] = linked_context['target']
linked_alternate = parse_link_header(link_header).get('alternate')
# if not JSON-LD, alternate may point there
if (linked_alternate and
linked_alternate.get('type') == 'application/ld+json' and
not re.match(r'^application\/(\w*\+)?json$', content_type)):
doc['contentType'] = 'application/ld+json'
doc['documentUrl'] = jsonld.prepend_base(url, linked_alternate['target'])
# import pdb; pdb.set_trace()
cache[url] = doc
f = open("cache_context.json", "w")
f.write(json.dumps(cache))
f.close()
return doc
except JsonLdError as e:
raise e
except Exception as cause:
raise JsonLdError(
'Could not retrieve a JSON-LD document from the URL.',
'jsonld.LoadDocumentError', code='loading document failed',
cause=cause)
return loader

View file

@ -2,6 +2,10 @@ import hashlib
import nacl.signing import nacl.signing
import nacl.encoding import nacl.encoding
from pyld import jsonld from pyld import jsonld
from pyvckit.document_loader import requests_document_loader
jsonld.set_document_loader(requests_document_loader())
# https://github.com/spruceid/ssi/blob/main/ssi-jws/src/lib.rs#L75 # https://github.com/spruceid/ssi/blob/main/ssi-jws/src/lib.rs#L75