Skip to content

Commit

Permalink
Merge pull request #51 from Indicio-tech/feature/json-ld-example
Browse files Browse the repository at this point in the history
Add json-ld example
  • Loading branch information
dbluhm authored Jul 26, 2023
2 parents f4c5c2e + af56f14 commit b46dd3e
Show file tree
Hide file tree
Showing 10 changed files with 1,281 additions and 621 deletions.
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
FROM python:3.10
WORKDIR /usr/src/app/

ENV POETRY_VERSION=1.1.11
ENV POETRY_VERSION=1.5.1
ENV POETRY_HOME=/opt/poetry
RUN curl -sSL https://install.python-poetry.org | python -

Expand Down
4 changes: 1 addition & 3 deletions conftest.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
from pathlib import Path
import subprocess
from typing import Union

from py._path.local import LocalPath
import pytest
from pytest import Session

Expand Down Expand Up @@ -62,7 +60,7 @@ def handle_run(self, *command: str):
self.cleanup()


def pytest_collect_file(parent: Session, path: Union[LocalPath, Path]):
def pytest_collect_file(parent: Session, path):
"""Pytest collection hook.
This will collect the docker-compose.yml files from the examples and create
Expand Down
2 changes: 1 addition & 1 deletion controller/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ def _header_filter(headers: Mapping[str, str]):
if resp.ok and resp.content_type == "application/json":
body = await resp.json()
response_out = dumps(body, indent=2, sort_keys=True)
if response_out.count("\n") > 50:
if response_out.count("\n") > 200:
response_out = dumps(body, sort_keys=True)
LOGGER.info("Response: %s", response_out)
return body
Expand Down
25 changes: 22 additions & 3 deletions controller/logging.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
"""Logging utilities."""

from contextlib import contextmanager
import logging
from os import getenv, get_terminal_size
from os import get_terminal_size, getenv
import sys
from contextlib import contextmanager
from typing import Optional, TextIO


from blessings import Terminal


Expand All @@ -13,7 +14,10 @@


class ColorFormatter(logging.Formatter):
"""Colorizer for logging output."""

def __init__(self, fmt: str):
"""Init formatter."""
self.default = logging.Formatter(fmt)
term = Terminal()
self.formats = {
Expand All @@ -22,11 +26,14 @@ def __init__(self, fmt: str):
}

def format(self, record):
"""Format log record."""
formatter = self.formats.get(record.levelno, self.default)
return formatter.format(record)


def logging_to_stdout():
"""Set up logging to stdout."""

global LOGGING_SET
if LOGGING_SET:
return
Expand Down Expand Up @@ -69,3 +76,15 @@ def section(
else:
print(title, file=file)
yield


def pause_for_input(
prompt: Optional[str] = None,
file: TextIO = sys.stdout,
):
if file == sys.stdout and sys.stdout.isatty():
term = Terminal()
prompt = prompt or "Press Enter to continue..."
print(f"{term.blue}{term.bold}", end="")
input(prompt)
print(f"{term.normal}", end="")
4 changes: 1 addition & 3 deletions controller/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -760,7 +760,6 @@ class Config:
...,
description="Public verification key",
example="H3C2AVvLMv6gmMNam3uVAjZpfkcJCwDwnZn6z3wXmqPV",
regex="^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{43,44}$",
)


Expand Down Expand Up @@ -2185,8 +2184,7 @@ class SchemasInputDescriptorFilter(BaseModel):
class Config:
allow_population_by_field_name = True

oneof_filter: Optional[bool] = Field(None, description="oneOf")
uri_groups: Optional[List[List[SchemaInputDescriptor]]] = None
__root__: Union[List[Dict[str, str]], Dict[str, Any]]


class SendMessage(BaseModel):
Expand Down
187 changes: 186 additions & 1 deletion controller/protocols.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,25 @@
from dataclasses import dataclass
import json
import logging
from secrets import randbelow, token_hex
from typing import Any, List, Mapping, Optional, Tuple, Union
from uuid import uuid4
from secrets import token_hex, randbelow

from .controller import Controller, ControllerError
from .models import (
AdminConfig,
ConnRecord,
ConnectionList,
CredAttrSpec,
Credential,
CredentialDefinitionSendRequest,
CredentialDefinitionSendResult,
CredentialPreview,
DIDCreate,
DIDCreateOptions,
DIDResult,
DIFOptions,
DIFProofRequest,
IndyCredPrecis,
IndyPresSpec,
IndyProofReqAttrSpec,
Expand All @@ -29,8 +32,11 @@
InvitationMessage,
InvitationRecord,
InvitationResult,
LDProofVCDetail,
LDProofVCDetailOptions,
MediationRecord,
PingRequest,
PresentationDefinition,
ReceiveInvitationRequest,
SchemaSendRequest,
SchemaSendResult,
Expand Down Expand Up @@ -878,3 +884,182 @@ async def indy_anoncreds_publish_revocation(
"Expected cred_ex to be V10CredentialExchange or V20CredExRecordDetail; "
f"got {type(cred_ex).__name__}"
)


async def jsonld_issue_credential(
issuer: Controller,
holder: Controller,
issuer_connection_id: str,
holder_connection_id: str,
credential: Union[Credential, Mapping[str, Any]],
options: Union[LDProofVCDetailOptions, Mapping[str, Any]],
):
"""Issue a JSON-LD Credential."""
credential = (
credential
if isinstance(credential, Credential)
else Credential.parse_obj(credential)
)
options = (
options
if isinstance(options, LDProofVCDetailOptions)
else LDProofVCDetailOptions.parse_obj(options)
)
issuer_cred_ex = await issuer.post(
"/issue-credential-2.0/send-offer",
json=V20CredOfferRequest(
auto_issue=False,
auto_remove=False,
comment="Credential from minimal example",
trace=False,
connection_id=issuer_connection_id,
filter=V20CredFilter( # pyright: ignore
ld_proof=LDProofVCDetail(
credential=credential,
options=options,
)
),
),
response=V20CredExRecord,
)
issuer_cred_ex_id = issuer_cred_ex.cred_ex_id

holder_cred_ex = await holder.record_with_values(
topic="issue_credential_v2_0",
record_type=V20CredExRecord,
connection_id=holder_connection_id,
state="offer-received",
)
holder_cred_ex_id = holder_cred_ex.cred_ex_id

holder_cred_ex = await holder.post(
f"/issue-credential-2.0/records/{holder_cred_ex_id}/send-request",
response=V20CredExRecord,
)

await issuer.record_with_values(
topic="issue_credential_v2_0",
cred_ex_id=issuer_cred_ex_id,
state="request-received",
)

issuer_cred_ex = await issuer.post(
f"/issue-credential-2.0/records/{issuer_cred_ex_id}/issue",
json={},
response=V20CredExRecordDetail,
)

await holder.record_with_values(
topic="issue_credential_v2_0",
cred_ex_id=holder_cred_ex_id,
state="credential-received",
)

holder_cred_ex = await holder.post(
f"/issue-credential-2.0/records/{holder_cred_ex_id}/store",
json={},
response=V20CredExRecordDetail,
)
issuer_cred_ex = await issuer.record_with_values(
topic="issue_credential_v2_0",
record_type=V20CredExRecord,
cred_ex_id=issuer_cred_ex_id,
state="done",
)

holder_cred_ex = await holder.record_with_values(
topic="issue_credential_v2_0",
record_type=V20CredExRecord,
cred_ex_id=holder_cred_ex_id,
state="done",
)

return issuer_cred_ex, holder_cred_ex


async def jsonld_present_proof(
verifier: Controller,
holder: Controller,
verifier_connection_id: str,
holder_connection_id: str,
presentation_definition: Union[Mapping[str, Any], PresentationDefinition],
domain: str,
*,
comment: Optional[str] = None,
):
"""Present an Indy credential using present proof v1."""
presentation_definition = (
presentation_definition
if isinstance(presentation_definition, PresentationDefinition)
else PresentationDefinition.parse_obj(presentation_definition)
)
verifier_pres_ex = await verifier.post(
"/present-proof-2.0/send-request",
json=V20PresSendRequestRequest(
auto_verify=False,
comment=comment or "Presentation request from minimal",
connection_id=verifier_connection_id,
presentation_request=V20PresRequestByFormat( # pyright: ignore
dif=DIFProofRequest(
presentation_definition=presentation_definition,
options=DIFOptions(challenge=str(uuid4()), domain=domain),
),
),
trace=False,
),
response=V20PresExRecord,
)
verifier_pres_ex_id = verifier_pres_ex.pres_ex_id

holder_pres_ex = await holder.record_with_values(
topic="present_proof_v2_0",
record_type=V20PresExRecord,
connection_id=holder_connection_id,
state="request-received",
)
assert holder_pres_ex.pres_request
assert holder_pres_ex.pres_request.request_presentations_attach
assert holder_pres_ex.pres_request.request_presentations_attach[0].data
assert holder_pres_ex.pres_request.request_presentations_attach[0].data.json_
holder_pres_ex_id = holder_pres_ex.pres_ex_id

holder_pres_ex = await holder.post(
f"/present-proof-2.0/records/{holder_pres_ex_id}/send-presentation",
json=V20PresRequestByFormat(
dif=DIFProofRequest( # pyright: ignore
presentation_definition=(
holder_pres_ex.pres_request.request_presentations_attach[
0
].data.json_["presentation_definition"]
)
)
),
response=V20PresExRecord,
)

await verifier.record_with_values(
topic="present_proof_v2_0",
record_type=V20PresExRecord,
pres_ex_id=verifier_pres_ex_id,
state="presentation-received",
)
verifier_pres_ex = await verifier.post(
f"/present-proof-2.0/records/{verifier_pres_ex_id}/verify-presentation",
json={},
response=V20PresExRecord,
)
verifier_pres_ex = await verifier.record_with_values(
topic="present_proof_v2_0",
record_type=V20PresExRecord,
pres_ex_id=verifier_pres_ex_id,
state="done",
)

holder_pres_ex = await holder.record_with_values(
topic="present_proof_v2_0",
record_type=V20PresExRecord,
pres_ex_id=holder_pres_ex_id,
state="done",
)

return verifier_pres_ex, holder_pres_ex
10 changes: 0 additions & 10 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ version: "3"
services:
alice:
image: ghcr.io/hyperledger/aries-cloudagent-python:py3.9-0.9.0
#image: bcgovimages/aries-cloudagent:py36-1.16-1_0.7.5
#image: bcgovimages/aries-cloudagent:py36-1.16-1_1.0.0-rc0
# image: acapy-test-image
# build:
# context: .
Expand Down Expand Up @@ -46,8 +44,6 @@ services:

bob:
image: ghcr.io/hyperledger/aries-cloudagent-python:py3.9-0.9.0
#image: bcgovimages/aries-cloudagent:py36-1.16-1_0.7.5
#image: bcgovimages/aries-cloudagent:py36-1.16-1_1.0.0-rc0
# image: acapy-test-image
# build:
# context: .
Expand Down Expand Up @@ -122,9 +118,3 @@ services:
condition: service_healthy
bob:
condition: service_healthy

configs:
alice-config:
file: ./configs/alice.yml
bob-config:
file: ./configs/bob.yml
Loading

0 comments on commit b46dd3e

Please sign in to comment.