Skip to content

Commit

Permalink
Merge pull request openwallet-foundation#2516 from dbluhm/fix/mediati…
Browse files Browse the repository at this point in the history
…on-routing-keys-as-did-key

fix: mediation routing keys as did key
  • Loading branch information
swcurran authored Oct 20, 2023
2 parents 2c901a9 + 6017f1c commit 900b1d8
Show file tree
Hide file tree
Showing 27 changed files with 416 additions and 687 deletions.
66 changes: 10 additions & 56 deletions aries_cloudagent/connections/base_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,15 +80,13 @@ def __init__(self, profile: Profile):
async def create_did_document(
self,
did_info: DIDInfo,
inbound_connection_id: Optional[str] = None,
svc_endpoints: Optional[Sequence[str]] = None,
mediation_records: Optional[List[MediationRecord]] = None,
) -> DIDDoc:
"""Create our DID doc for a given DID.
Args:
did_info: The DID information (DID and verkey) used in the connection
inbound_connection_id: The ID of the inbound routing connection to use
svc_endpoints: Custom endpoints for the DID Document
mediation_record: The record for mediation that contains routing_keys and
service endpoint
Expand All @@ -111,61 +109,18 @@ async def create_did_document(
)
did_doc.set(pk)

router_id = inbound_connection_id
routing_keys = []
router_idx = 1
while router_id:
# look up routing connection information
async with self._profile.session() as session:
router = await ConnRecord.retrieve_by_id(session, router_id)
if ConnRecord.State.get(router.state) != ConnRecord.State.COMPLETED:
raise BaseConnectionManagerError(
f"Router connection not completed: {router_id}"
)
routing_doc, _ = await self.fetch_did_document(router.their_did)
assert isinstance(routing_doc, DIDDoc)
if not routing_doc.service:
raise BaseConnectionManagerError(
f"No services defined by routing DIDDoc: {router_id}"
)
for service in routing_doc.service.values():
if not service.endpoint:
raise BaseConnectionManagerError(
"Routing DIDDoc service has no service endpoint"
)
if not service.recip_keys:
raise BaseConnectionManagerError(
"Routing DIDDoc service has no recipient key(s)"
)
rk = PublicKey(
did_info.did,
f"routing-{router_idx}",
service.recip_keys[0].value,
PublicKeyType.ED25519_SIG_2018,
did_controller,
True,
)
routing_keys.append(rk)
svc_endpoints = [service.endpoint]
break
router_id = router.inbound_connection_id

routing_keys: List[str] = []
if mediation_records:
for mediation_record in mediation_records:
mediator_routing_keys = [
PublicKey(
did_info.did,
f"routing-{idx}",
key,
PublicKeyType.ED25519_SIG_2018,
did_controller, # TODO: get correct controller did_info
True, # TODO: should this be true?
)
for idx, key in enumerate(mediation_record.routing_keys)
]

routing_keys = [*routing_keys, *mediator_routing_keys]
svc_endpoints = [mediation_record.endpoint]
(
mediator_routing_keys,
endpoint,
) = await self._route_manager.routing_info(
self._profile, mediation_record
)
routing_keys = [*routing_keys, *(mediator_routing_keys or [])]
if endpoint:
svc_endpoints = [endpoint]

for endpoint_index, svc_endpoint in enumerate(svc_endpoints or []):
endpoint_ident = "indy" if endpoint_index == 0 else f"indy{endpoint_index}"
Expand Down Expand Up @@ -938,7 +893,6 @@ async def create_static_connection(
# Synthesize their DID doc
did_doc = await self.create_did_document(
their_info,
None,
[their_endpoint or ""],
mediation_records=list(
filter(None, [base_mediation_record, mediation_record])
Expand Down
31 changes: 28 additions & 3 deletions aries_cloudagent/connections/models/diddoc/diddoc.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@

from typing import List, Sequence, Union

from ....did.did_key import DIDKey

from .publickey import PublicKey, PublicKeyType
from .service import Service
from .util import canon_did, canon_ref, ok_did, resource
Expand Down Expand Up @@ -116,13 +118,36 @@ def set(self, item: Union[Service, PublicKey]) -> "DIDDoc":
"Cannot add item {} to DIDDoc on DID {}".format(item, self.did)
)

def serialize(self) -> dict:
@staticmethod
def _normalize_routing_keys(service: dict) -> dict:
"""Normalize routing keys in service.
Args:
service: service dict
Returns: service dict with routing keys normalized
"""
routing_keys = service.get("routingKeys")
if routing_keys:
routing_keys = [
DIDKey.from_did(key).public_key_b58
if key.startswith("did:key:")
else key
for key in routing_keys
]
service["routingKeys"] = routing_keys
return service

def serialize(self, normalize_routing_keys: bool = False) -> dict:
"""Dump current object to a JSON-compatible dictionary.
Returns:
dict representation of current DIDDoc
"""
service = [service.to_dict() for service in self.service.values()]
if normalize_routing_keys:
service = [self._normalize_routing_keys(s) for s in service]

return {
"@context": DIDDoc.CONTEXT,
Expand All @@ -136,7 +161,7 @@ def serialize(self) -> dict:
for pubkey in self.pubkey.values()
if pubkey.authn
],
"service": [service.to_dict() for service in self.service.values()],
"service": service,
}

def to_json(self) -> str:
Expand Down Expand Up @@ -285,7 +310,7 @@ def deserialize(cls, did_doc: dict) -> "DIDDoc":
),
service["type"],
rv.add_service_pubkeys(service, "recipientKeys"),
rv.add_service_pubkeys(service, ["mediatorKeys", "routingKeys"]),
service.get("routingKeys", []),
canon_ref(rv.did, endpoint, ";") if ";" in endpoint else endpoint,
service.get("priority", None),
)
Expand Down
14 changes: 4 additions & 10 deletions aries_cloudagent/connections/models/diddoc/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def __init__(
ident: str,
typ: str,
recip_keys: Union[Sequence, PublicKey],
routing_keys: Union[Sequence, PublicKey],
routing_keys: List[str],
endpoint: str,
priority: int = 0,
):
Expand Down Expand Up @@ -69,13 +69,7 @@ def __init__(
if recip_keys
else None
)
self._routing_keys = (
[routing_keys]
if isinstance(routing_keys, PublicKey)
else list(routing_keys)
if routing_keys
else None
)
self._routing_keys = routing_keys or []
self._endpoint = endpoint
self._priority = priority

Expand Down Expand Up @@ -104,7 +98,7 @@ def recip_keys(self) -> List[PublicKey]:
return self._recip_keys

@property
def routing_keys(self) -> List[PublicKey]:
def routing_keys(self) -> List[str]:
"""Accessor for the routing keys."""

return self._routing_keys
Expand All @@ -128,7 +122,7 @@ def to_dict(self) -> dict:
if self.recip_keys:
rv["recipientKeys"] = [k.value for k in self.recip_keys]
if self.routing_keys:
rv["routingKeys"] = [k.value for k in self.routing_keys]
rv["routingKeys"] = self.routing_keys
rv["serviceEndpoint"] = self.endpoint

return rv
Loading

0 comments on commit 900b1d8

Please sign in to comment.