Skip to content

Commit

Permalink
Merge pull request #2687 from Jsyro/feature/did-peer-2-did-exchange-t…
Browse files Browse the repository at this point in the history
…ested

Emit did:peer:2 for didexchange
  • Loading branch information
dbluhm authored Dec 29, 2023
2 parents b06c2c5 + c7e01e2 commit 4d7bc80
Show file tree
Hide file tree
Showing 19 changed files with 572 additions and 132 deletions.
10 changes: 10 additions & 0 deletions aries_cloudagent/config/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1170,6 +1170,12 @@ def add_arguments(self, parser: ArgumentParser):
"using unencrypted rather than encrypted tags"
),
)
parser.add_argument(
"--emit-did-peer-2",
action="store_true",
env_var="ACAPY_EMIT_DID_PEER_2",
help=("Emit did:peer:2 DIDs in DID Exchange Protocol"),
)

def get_settings(self, args: Namespace) -> dict:
"""Get protocol settings."""
Expand Down Expand Up @@ -1236,6 +1242,10 @@ def get_settings(self, args: Namespace) -> dict:
if args.exch_use_unencrypted_tags:
settings["exch_use_unencrypted_tags"] = True
environ["EXCH_UNENCRYPTED_TAGS"] = "True"

if args.emit_did_peer_2:
settings["emit_did_peer_2"] = True

return settings


Expand Down
29 changes: 15 additions & 14 deletions aries_cloudagent/config/default_per_tenant_logging_config.ini
Original file line number Diff line number Diff line change
@@ -1,27 +1,28 @@
[loggers]
keys=root
keys = root

[handlers]
keys=stream_handler, timed_file_handler
keys = stream_handler, timed_file_handler

[formatters]
keys=formatter
keys = formatter

[logger_root]
level=ERROR
handlers=stream_handler, timed_file_handler
level = ERROR
handlers = stream_handler, timed_file_handler

[handler_stream_handler]
class=StreamHandler
level=DEBUG
formatter=formatter
args=(sys.stderr,)
class = StreamHandler
level = DEBUG
formatter = formatter
args = (sys.stderr,)

[handler_timed_file_handler]
class=logging.handlers.TimedRotatingFileMultiProcessHandler
level=DEBUG
formatter=formatter
args=('/home/aries/log/acapy-agent.log', 'd', 7, 1,)
class = logging.handlers.TimedRotatingFileMultiProcessHandler
level = DEBUG
formatter = formatter
args = ('test.log', 'd', 7, 1)

[formatter_formatter]
format=%(asctime)s %(wallet_id)s %(levelname)s %(pathname)s:%(lineno)d %(message)s
format = %(asctime)s %(wallet_id)s %(levelname)s %(pathname)s:%(lineno)d %(message)s

20 changes: 10 additions & 10 deletions aries_cloudagent/config/default_per_tenant_logging_config.yml
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
version: 1
formatters:
default:
format: '%(asctime)s %(wallet_id)s %(levelname)s %(pathname)s:%(lineno)d %(message)s'
handlers:
console:
class: logging.StreamHandler
level: DEBUG
formatter: default
level: DEBUG
stream: ext://sys.stderr
rotating_file:
class: logging.handlers.TimedRotatingFileMultiProcessHandler
level: DEBUG
filename: '/home/aries/log/acapy-agent.log'
when: 'd'
interval: 7
backupCount: 1
class: logging.handlers.TimedRotatingFileMultiProcessHandler
filename: test.log
formatter: default
interval: 7
level: DEBUG
when: d
root:
level: INFO
handlers:
- console
- rotating_file
- console
- rotating_file
level: INFO
version: 1
77 changes: 75 additions & 2 deletions aries_cloudagent/connections/base_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import logging
from typing import List, Optional, Sequence, Text, Tuple, Union

from base58 import b58decode
from did_peer_2 import KeySpec, generate
from pydid import (
BaseDIDDocument as ResolvedDocument,
DIDCommService,
Expand All @@ -17,6 +19,7 @@
Ed25519VerificationKey2018,
Ed25519VerificationKey2020,
JsonWebKey2020,
Multikey,
)

from ..cache.base import BaseCache
Expand Down Expand Up @@ -44,8 +47,8 @@
from ..utils.multiformats import multibase, multicodec
from ..wallet.base import BaseWallet
from ..wallet.crypto import create_keypair, seed_to_did
from ..wallet.did_info import DIDInfo
from ..wallet.did_method import SOV
from ..wallet.did_info import DIDInfo, KeyInfo
from ..wallet.did_method import PEER2, SOV
from ..wallet.error import WalletNotFoundError
from ..wallet.key_type import ED25519
from ..wallet.util import b64_to_bytes, bytes_to_b58
Expand Down Expand Up @@ -74,6 +77,69 @@ def __init__(self, profile: Profile):
self._route_manager = profile.inject(RouteManager)
self._logger = logging.getLogger(__name__)

@staticmethod
def _key_info_to_multikey(key_info: KeyInfo) -> str:
"""Convert a KeyInfo to a multikey."""
return multibase.encode(
multicodec.wrap("ed25519-pub", b58decode(key_info.verkey)), "base58btc"
)

async def create_did_peer_2(
self,
svc_endpoints: Optional[Sequence[str]] = None,
mediation_records: Optional[List[MediationRecord]] = None,
) -> DIDInfo:
"""Create a did:peer:2 DID for a connection.
Args:
svc_endpoints: Custom endpoints for the DID Document
mediation_record: The record for mediation that contains routing_keys and
service endpoint
Returns:
The new `DIDInfo` instance
"""
routing_keys: List[str] = []
if mediation_records:
for mediation_record in mediation_records:
(
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]

services = []
for index, endpoint in enumerate(svc_endpoints or []):
services.append(
{
"id": f"#didcomm-{index}",
"type": "did-communication",
"priority": index,
"recipientKeys": ["#key-1"],
"routingKeys": routing_keys,
"serviceEndpoint": endpoint,
}
)

async with self._profile.session() as session:
wallet = session.inject(BaseWallet)
key = await wallet.create_key(ED25519)

did = generate(
[KeySpec.verification(self._key_info_to_multikey(key))], services
)

did_info = DIDInfo(
did=did, method=PEER2, verkey=key.verkey, metadata={}, key_type=ED25519
)
await wallet.store_did(did_info)

return did_info

async def create_did_document(
self,
did_info: DIDInfo,
Expand Down Expand Up @@ -375,6 +441,13 @@ def _extract_key_material_in_base58_format(method: VerificationMethod) -> str:
f"Key type {type(method).__name__} "
f"with kty {method.public_key_jwk.get('kty')} is not supported"
)
elif isinstance(method, Multikey):
codec, key = multicodec.unwrap(multibase.decode(method.material))
if codec != multicodec.multicodec("ed25519-pub"):
raise BaseConnectionManagerError(
"Expected ed25519 multicodec, got: %s", codec
)
return bytes_to_b58(key)
else:
raise BaseConnectionManagerError(
f"Key type {type(method).__name__} is not supported"
Expand Down
34 changes: 34 additions & 0 deletions aries_cloudagent/messaging/decorators/attach_decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -597,6 +597,40 @@ def content(self) -> Union[Mapping, Tuple[Sequence[str], str]]:
else:
return None

@classmethod
def data_base64_string(
cls,
content: str,
*,
ident: str = None,
description: str = None,
filename: str = None,
lastmod_time: str = None,
byte_count: int = None,
):
"""Create `AttachDecorator` instance on base64-encoded string data.
Given string content, base64-encode, and embed it as data; mark
`text/string` MIME type.
Args:
content: string content
ident: optional attachment identifier (default random UUID4)
description: optional attachment description
filename: optional attachment filename
lastmod_time: optional attachment last modification time
byte_count: optional attachment byte count
"""
return AttachDecorator(
ident=ident or str(uuid.uuid4()),
description=description,
filename=filename,
mime_type="text/string",
lastmod_time=lastmod_time,
byte_count=byte_count,
data=AttachDecoratorData(base64_=bytes_to_b64(content.encode())),
)

@classmethod
def data_base64(
cls,
Expand Down
Loading

0 comments on commit 4d7bc80

Please sign in to comment.