-
Notifications
You must be signed in to change notification settings - Fork 516
/
manager.py
846 lines (743 loc) · 32.1 KB
/
manager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
"""Classes to manage connection establishment under RFC 23 (DID exchange)."""
import json
import logging
from ....connections.models.conn_record import ConnRecord
from ....connections.models.diddoc import DIDDoc
from ....connections.base_manager import BaseConnectionManager
from ....connections.util import mediation_record_if_id
from ....core.error import BaseError
from ....core.profile import Profile
from ....messaging.decorators.attach_decorator import AttachDecorator
from ....messaging.responder import BaseResponder
from ....multitenant.base import BaseMultitenantManager
from ....storage.error import StorageNotFoundError
from ....transport.inbound.receipt import MessageReceipt
from ....wallet.base import BaseWallet
from ....wallet.error import WalletError
from ....wallet.key_type import KeyType
from ....wallet.did_method import DIDMethod
from ....wallet.did_posture import DIDPosture
from ....did.did_key import DIDKey
from ...coordinate_mediation.v1_0.manager import MediationManager
from ...discovery.v2_0.manager import V20DiscoveryMgr
from ...out_of_band.v1_0.messages.invitation import (
InvitationMessage as OOBInvitationMessage,
)
from ...out_of_band.v1_0.messages.service import Service as OOBService
from .message_types import ARIES_PROTOCOL as DIDX_PROTO
from .messages.complete import DIDXComplete
from .messages.request import DIDXRequest
from .messages.response import DIDXResponse
from .messages.problem_report_reason import ProblemReportReason
class DIDXManagerError(BaseError):
"""Connection error."""
class DIDXManager(BaseConnectionManager):
"""Class for managing connections under RFC 23 (DID exchange)."""
def __init__(self, profile: Profile):
"""
Initialize a DIDXManager.
Args:
profile: The profile for this did exchange manager
"""
self._profile = profile
self._logger = logging.getLogger(__name__)
super().__init__(self._profile)
@property
def profile(self) -> Profile:
"""
Accessor for the current profile.
Returns:
The profile for this did exchange manager
"""
return self._profile
async def receive_invitation(
self,
invitation: OOBInvitationMessage,
their_public_did: str = None,
auto_accept: bool = None,
alias: str = None,
mediation_id: str = None,
) -> ConnRecord: # leave in didexchange as it uses a responder: not out-of-band
"""
Create a new connection record to track a received invitation.
Args:
invitation: invitation to store
their_public_did: their public DID
auto_accept: set to auto-accept invitation (None to use config)
alias: optional alias to set on record
mediation_id: record id for mediation with routing_keys, service endpoint
Returns:
The new `ConnRecord` instance
"""
if not invitation.services:
raise DIDXManagerError(
"Invitation must contain service blocks or service DIDs"
)
else:
for s in invitation.services:
if isinstance(s, OOBService):
if not s.recipient_keys or not s.service_endpoint:
raise DIDXManagerError(
"All service blocks in invitation with no service DIDs "
"must contain recipient key(s) and service endpoint(s)"
)
accept = (
ConnRecord.ACCEPT_AUTO
if (
auto_accept
or (
auto_accept is None
and self.profile.settings.get("debug.auto_accept_invites")
)
)
else ConnRecord.ACCEPT_MANUAL
)
service_item = invitation.services[0]
# Create connection record
conn_rec = ConnRecord(
invitation_key=(
DIDKey.from_did(service_item.recipient_keys[0]).public_key_b58
if isinstance(service_item, OOBService)
else None
),
invitation_msg_id=invitation._id,
their_label=invitation.label,
their_role=ConnRecord.Role.RESPONDER.rfc23,
state=ConnRecord.State.INVITATION.rfc23,
accept=accept,
alias=alias,
their_public_did=their_public_did,
connection_protocol=DIDX_PROTO,
)
async with self.profile.session() as session:
await conn_rec.save(
session,
reason="Created new connection record from invitation",
log_params={
"invitation": invitation,
"their_role": ConnRecord.Role.RESPONDER.rfc23,
},
)
# Save the invitation for later processing
await conn_rec.attach_invitation(session, invitation)
if conn_rec.accept == ConnRecord.ACCEPT_AUTO:
request = await self.create_request(conn_rec, mediation_id=mediation_id)
responder = self.profile.inject_or(BaseResponder)
if responder:
await responder.send_reply(
request,
connection_id=conn_rec.connection_id,
)
conn_rec.state = ConnRecord.State.REQUEST.rfc23
async with self.profile.session() as session:
await conn_rec.save(session, reason="Sent connection request")
else:
self._logger.debug("Connection invitation will await acceptance")
return conn_rec
async def create_request_implicit(
self,
their_public_did: str,
my_label: str = None,
my_endpoint: str = None,
mediation_id: str = None,
use_public_did: bool = False,
alias: str = None,
) -> ConnRecord:
"""
Create and send a request against a public DID only (no explicit invitation).
Args:
their_public_did: public DID to which to request a connection
my_label: my label for request
my_endpoint: my endpoint
mediation_id: record id for mediation with routing_keys, service endpoint
use_public_did: use my public DID for this connection
Returns:
The new `ConnRecord` instance
"""
my_public_info = None
if use_public_did:
async with self.profile.session() as session:
wallet = session.inject(BaseWallet)
my_public_info = await wallet.get_public_did()
if not my_public_info:
raise WalletError("No public DID configured")
conn_rec = ConnRecord(
my_did=my_public_info.did
if my_public_info
else None, # create-request will fill in on local DID creation
their_did=their_public_did,
their_label=None,
their_role=ConnRecord.Role.RESPONDER.rfc23,
invitation_key=None,
invitation_msg_id=None,
accept=None,
alias=alias,
their_public_did=their_public_did,
connection_protocol=DIDX_PROTO,
)
request = await self.create_request( # saves and updates conn_rec
conn_rec=conn_rec,
my_label=my_label,
my_endpoint=my_endpoint,
mediation_id=mediation_id,
)
conn_rec.request_id = request._id
conn_rec.state = ConnRecord.State.REQUEST.rfc23
async with self.profile.session() as session:
await conn_rec.save(session, reason="Created connection request")
responder = self.profile.inject_or(BaseResponder)
if responder:
await responder.send(request, connection_id=conn_rec.connection_id)
return conn_rec
async def create_request(
self,
conn_rec: ConnRecord,
my_label: str = None,
my_endpoint: str = None,
mediation_id: str = None,
) -> DIDXRequest:
"""
Create a new connection request for a previously-received invitation.
Args:
conn_rec: The `ConnRecord` representing the invitation to accept
my_label: My label for request
my_endpoint: My endpoint
mediation_id: The record id for mediation that contains routing_keys and
service endpoint
Returns:
A new `DIDXRequest` message to send to the other agent
"""
# Mediation Support
mediation_mgr = MediationManager(self.profile)
keylist_updates = None
mediation_record = await mediation_record_if_id(
self.profile,
mediation_id,
or_default=True,
)
base_mediation_record = None
# Multitenancy setup
multitenant_mgr = self.profile.inject_or(BaseMultitenantManager)
wallet_id = self.profile.settings.get("wallet.id")
if multitenant_mgr and wallet_id:
base_mediation_record = await multitenant_mgr.get_default_mediator()
my_info = None
if conn_rec.my_did:
async with self.profile.session() as session:
wallet = session.inject(BaseWallet)
my_info = await wallet.get_local_did(conn_rec.my_did)
else:
# Create new DID for connection
async with self.profile.session() as session:
wallet = session.inject(BaseWallet)
my_info = await wallet.create_local_did(
method=DIDMethod.SOV,
key_type=KeyType.ED25519,
)
conn_rec.my_did = my_info.did
keylist_updates = await mediation_mgr.add_key(
my_info.verkey, keylist_updates
)
# Add mapping for multitenant relay
if multitenant_mgr and wallet_id:
await multitenant_mgr.add_key(wallet_id, my_info.verkey)
# Create connection request message
if my_endpoint:
my_endpoints = [my_endpoint]
else:
my_endpoints = []
default_endpoint = self.profile.settings.get("default_endpoint")
if default_endpoint:
my_endpoints.append(default_endpoint)
my_endpoints.extend(self.profile.settings.get("additional_endpoints", []))
did_doc = await self.create_did_document(
my_info,
conn_rec.inbound_connection_id,
my_endpoints,
mediation_records=list(
filter(None, [base_mediation_record, mediation_record])
),
)
if (
conn_rec.their_public_did is not None
and conn_rec.their_public_did.startswith("did:")
):
qualified_did = conn_rec.their_public_did
else:
qualified_did = f"did:sov:{conn_rec.their_public_did}"
pthid = conn_rec.invitation_msg_id or qualified_did
attach = AttachDecorator.data_base64(did_doc.serialize())
async with self.profile.session() as session:
wallet = session.inject(BaseWallet)
await attach.data.sign(my_info.verkey, wallet)
if not my_label:
my_label = self.profile.settings.get("default_label")
request = DIDXRequest(
label=my_label,
did=conn_rec.my_did,
did_doc_attach=attach,
)
request.assign_thread_id(thid=request._id, pthid=pthid)
# Update connection state
conn_rec.request_id = request._id
conn_rec.state = ConnRecord.State.REQUEST.rfc23
async with self.profile.session() as session:
await conn_rec.save(session, reason="Created connection request")
# Notify Mediator
if keylist_updates and mediation_record:
responder = self.profile.inject_or(BaseResponder)
await responder.send(
keylist_updates, connection_id=mediation_record.connection_id
)
return request
async def receive_request(
self,
request: DIDXRequest,
recipient_did: str,
recipient_verkey: str = None,
my_endpoint: str = None,
alias: str = None,
auto_accept_implicit: bool = None,
mediation_id: str = None,
) -> ConnRecord:
"""
Receive and store a connection request.
Args:
request: The `DIDXRequest` to accept
recipient_did: The (unqualified) recipient DID
recipient_verkey: The recipient verkey: None for public recipient DID
my_endpoint: My endpoint
alias: Alias for the connection
auto_accept: Auto-accept request against implicit invitation
mediation_id: The record id for mediation that contains routing_keys and
service endpoint
Returns:
The new or updated `ConnRecord` instance
"""
ConnRecord.log_state(
"Receiving connection request",
{"request": request},
settings=self.profile.settings,
)
mediation_mgr = MediationManager(self.profile)
keylist_updates = None
conn_rec = None
connection_key = None
my_info = None
# Multitenancy setup
multitenant_mgr = self.profile.inject_or(BaseMultitenantManager)
wallet_id = self.profile.settings.get("wallet.id")
# Determine what key will need to sign the response
if recipient_verkey: # peer DID
connection_key = recipient_verkey
try:
async with self.profile.session() as session:
conn_rec = await ConnRecord.retrieve_by_invitation_key(
session=session,
invitation_key=connection_key,
their_role=ConnRecord.Role.REQUESTER.rfc23,
)
except StorageNotFoundError:
if recipient_verkey:
raise DIDXManagerError(
"No explicit invitation found for pairwise connection "
f"in state {ConnRecord.State.INVITATION.rfc23}: "
"a prior connection request may have updated the connection state"
)
else:
if not self.profile.settings.get("public_invites"):
raise DIDXManagerError(
"Public invitations are not enabled: connection request refused"
)
async with self.profile.session() as session:
wallet = session.inject(BaseWallet)
my_info = await wallet.get_local_did(recipient_did)
if DIDPosture.get(my_info.metadata) not in (
DIDPosture.PUBLIC,
DIDPosture.POSTED,
):
raise DIDXManagerError(f"Request DID {recipient_did} is not public")
connection_key = my_info.verkey
async with self.profile.session() as session:
conn_rec = await ConnRecord.retrieve_by_invitation_msg_id(
session=session,
invitation_msg_id=request._thread.pthid,
their_role=ConnRecord.Role.REQUESTER.rfc23,
)
if conn_rec: # invitation was explicit
connection_key = conn_rec.invitation_key
if conn_rec.is_multiuse_invitation:
async with self.profile.session() as session:
wallet = session.inject(BaseWallet)
my_info = await wallet.create_local_did(
method=DIDMethod.SOV,
key_type=KeyType.ED25519,
)
keylist_updates = await mediation_mgr.add_key(
my_info.verkey, keylist_updates
)
new_conn_rec = ConnRecord(
invitation_key=connection_key,
my_did=my_info.did,
state=ConnRecord.State.REQUEST.rfc23,
accept=conn_rec.accept,
their_role=conn_rec.their_role,
connection_protocol=DIDX_PROTO,
)
async with self.profile.session() as session:
await new_conn_rec.save(
session,
reason=(
"Received connection request from multi-use invitation DID"
),
)
# Transfer metadata from multi-use to new connection
# Must come after save so there's an ID to associate with metadata
async with self.profile.session() as session:
for key, value in (
await conn_rec.metadata_get_all(session)
).items():
await new_conn_rec.metadata_set(session, key, value)
conn_rec = new_conn_rec
# Add mapping for multitenant relay
if multitenant_mgr and wallet_id:
await multitenant_mgr.add_key(wallet_id, my_info.verkey)
else:
keylist_updates = await mediation_mgr.remove_key(
connection_key, keylist_updates
)
# request DID doc describes requester DID
if not (request.did_doc_attach and request.did_doc_attach.data):
raise DIDXManagerError(
"DID Doc attachment missing or has no data: "
"cannot connect to public DID"
)
async with self.profile.session() as session:
wallet = session.inject(BaseWallet)
if not await request.did_doc_attach.data.verify(wallet):
raise DIDXManagerError("DID Doc signature failed verification")
conn_did_doc = DIDDoc.from_json(request.did_doc_attach.data.signed.decode())
if request.did != conn_did_doc.did:
raise DIDXManagerError(
(
f"Connection DID {request.did} does not match "
f"DID Doc id {conn_did_doc.did}"
),
error_code=ProblemReportReason.REQUEST_NOT_ACCEPTED.value,
)
await self.store_did_document(conn_did_doc)
if conn_rec: # request is against explicit invitation
auto_accept = (
conn_rec.accept == ConnRecord.ACCEPT_AUTO
) # null=manual; oob-manager calculated at conn rec creation
conn_rec.their_label = request.label
if alias:
conn_rec.alias = alias
conn_rec.their_did = request.did
conn_rec.state = ConnRecord.State.REQUEST.rfc23
conn_rec.request_id = request._id
async with self.profile.session() as session:
await conn_rec.save(
session, reason="Received connection request from invitation"
)
else:
# request is against implicit invitation on public DID
async with self.profile.session() as session:
wallet = session.inject(BaseWallet)
my_info = await wallet.create_local_did(
method=DIDMethod.SOV,
key_type=KeyType.ED25519,
)
keylist_updates = await mediation_mgr.add_key(
my_info.verkey, keylist_updates
)
# Add mapping for multitenant relay
if multitenant_mgr and wallet_id:
await multitenant_mgr.add_key(wallet_id, my_info.verkey)
auto_accept = bool(
auto_accept_implicit
or (
auto_accept_implicit is None
and self.profile.settings.get("debug.auto_accept_requests", False)
)
)
conn_rec = ConnRecord(
my_did=my_info.did,
accept=(
ConnRecord.ACCEPT_AUTO if auto_accept else ConnRecord.ACCEPT_MANUAL
),
their_did=request.did,
their_label=request.label,
alias=alias,
their_role=ConnRecord.Role.REQUESTER.rfc23,
invitation_key=connection_key,
invitation_msg_id=None,
request_id=request._id,
state=ConnRecord.State.REQUEST.rfc23,
connection_protocol=DIDX_PROTO,
)
async with self.profile.session() as session:
await conn_rec.save(
session, reason="Received connection request from public DID"
)
async with self.profile.session() as session:
# Attach the connection request so it can be found and responded to
await conn_rec.attach_request(session, request)
# Send keylist updates to mediator
mediation_record = await mediation_record_if_id(self.profile, mediation_id)
if keylist_updates and mediation_record:
responder = self.profile.inject(BaseResponder)
await responder.send(
keylist_updates, connection_id=mediation_record.connection_id
)
return conn_rec
async def create_response(
self,
conn_rec: ConnRecord,
my_endpoint: str = None,
mediation_id: str = None,
) -> DIDXResponse:
"""
Create a connection response for a received connection request.
Args:
conn_rec: The `ConnRecord` with a pending connection request
my_endpoint: Current agent endpoint
mediation_id: The record id for mediation that contains routing_keys and
service endpoint
Returns:
New `DIDXResponse` message
"""
ConnRecord.log_state(
"Creating connection response",
{"connection_id": conn_rec.connection_id},
settings=self.profile.settings,
)
mediation_mgr = MediationManager(self.profile)
keylist_updates = None
mediation_record = await mediation_record_if_id(self.profile, mediation_id)
base_mediation_record = None
# Multitenancy setup
multitenant_mgr = self.profile.inject_or(BaseMultitenantManager)
wallet_id = self.profile.settings.get("wallet.id")
if multitenant_mgr and wallet_id:
base_mediation_record = await multitenant_mgr.get_default_mediator()
if ConnRecord.State.get(conn_rec.state) is not ConnRecord.State.REQUEST:
raise DIDXManagerError(
f"Connection not in state {ConnRecord.State.REQUEST.rfc23}"
)
async with self.profile.session() as session:
request = await conn_rec.retrieve_request(session)
if conn_rec.my_did:
async with self.profile.session() as session:
wallet = session.inject(BaseWallet)
my_info = await wallet.get_local_did(conn_rec.my_did)
else:
async with self.profile.session() as session:
wallet = session.inject(BaseWallet)
my_info = await wallet.create_local_did(
method=DIDMethod.SOV,
key_type=KeyType.ED25519,
)
conn_rec.my_did = my_info.did
keylist_updates = await mediation_mgr.add_key(
my_info.verkey, keylist_updates
)
# Add mapping for multitenant relay
if multitenant_mgr and wallet_id:
await multitenant_mgr.add_key(wallet_id, my_info.verkey)
# Create connection response message
if my_endpoint:
my_endpoints = [my_endpoint]
else:
my_endpoints = []
default_endpoint = self.profile.settings.get("default_endpoint")
if default_endpoint:
my_endpoints.append(default_endpoint)
my_endpoints.extend(self.profile.settings.get("additional_endpoints", []))
did_doc = await self.create_did_document(
my_info,
conn_rec.inbound_connection_id,
my_endpoints,
mediation_records=list(
filter(None, [base_mediation_record, mediation_record])
),
)
attach = AttachDecorator.data_base64(did_doc.serialize())
async with self.profile.session() as session:
wallet = session.inject(BaseWallet)
await attach.data.sign(conn_rec.invitation_key, wallet)
response = DIDXResponse(did=my_info.did, did_doc_attach=attach)
# Assign thread information
response.assign_thread_from(request)
response.assign_trace_from(request)
# Update connection state
conn_rec.state = ConnRecord.State.RESPONSE.rfc23
async with self.profile.session() as session:
await conn_rec.save(
session,
reason="Created connection response",
log_params={"response": response},
)
# Update Mediator if necessary
if keylist_updates and mediation_record:
responder = self.profile.inject_or(BaseResponder)
await responder.send(
keylist_updates, connection_id=mediation_record.connection_id
)
async with self.profile.session() as session:
send_mediation_request = await conn_rec.metadata_get(
session, MediationManager.SEND_REQ_AFTER_CONNECTION
)
if send_mediation_request:
temp_mediation_mgr = MediationManager(self.profile)
_record, request = await temp_mediation_mgr.prepare_request(
conn_rec.connection_id
)
responder = self.profile.inject(BaseResponder)
await responder.send(request, connection_id=conn_rec.connection_id)
return response
async def accept_response(
self,
response: DIDXResponse,
receipt: MessageReceipt,
) -> ConnRecord:
"""
Accept a connection response under RFC 23 (DID exchange).
Process a `DIDXResponse` message by looking up
the connection request and setting up the pairwise connection.
Args:
response: The `DIDXResponse` to accept
receipt: The message receipt
Returns:
The updated `ConnRecord` representing the connection
Raises:
DIDXManagerError: If there is no DID associated with the
connection response
DIDXManagerError: If the corresponding connection is not
in the request-sent state
"""
conn_rec = None
if response._thread:
# identify the request by the thread ID
try:
async with self.profile.session() as session:
conn_rec = await ConnRecord.retrieve_by_request_id(
session, response._thread_id
)
except StorageNotFoundError:
pass
if not conn_rec and receipt.sender_did:
# identify connection by the DID they used for us
try:
async with self.profile.session() as session:
conn_rec = await ConnRecord.retrieve_by_did(
session=session,
their_did=receipt.sender_did,
my_did=receipt.recipient_did,
their_role=ConnRecord.Role.RESPONDER.rfc23,
)
except StorageNotFoundError:
pass
if not conn_rec:
raise DIDXManagerError(
"No corresponding connection request found",
error_code=ProblemReportReason.RESPONSE_NOT_ACCEPTED.value,
)
if ConnRecord.State.get(conn_rec.state) is not ConnRecord.State.REQUEST:
raise DIDXManagerError(
"Cannot accept connection response for connection"
f" in state: {conn_rec.state}"
)
their_did = response.did
if not response.did_doc_attach:
raise DIDXManagerError("No DIDDoc attached; cannot connect to public DID")
async with self.profile.session() as session:
wallet = session.inject(BaseWallet)
conn_did_doc = await self.verify_diddoc(wallet, response.did_doc_attach)
if their_did != conn_did_doc.did:
raise DIDXManagerError(
f"Connection DID {their_did} "
f"does not match DID doc id {conn_did_doc.did}"
)
await self.store_did_document(conn_did_doc)
conn_rec.their_did = their_did
conn_rec.state = ConnRecord.State.RESPONSE.rfc23
async with self.profile.session() as session:
await conn_rec.save(session, reason="Accepted connection response")
async with self.profile.session() as session:
send_mediation_request = await conn_rec.metadata_get(
session, MediationManager.SEND_REQ_AFTER_CONNECTION
)
if send_mediation_request:
temp_mediation_mgr = MediationManager(self.profile)
_record, request = await temp_mediation_mgr.prepare_request(
conn_rec.connection_id
)
responder = self.profile.inject(BaseResponder)
await responder.send(request, connection_id=conn_rec.connection_id)
# create and send connection-complete message
complete = DIDXComplete()
complete.assign_thread_from(response)
responder = self.profile.inject_or(BaseResponder)
if responder:
await responder.send_reply(complete, connection_id=conn_rec.connection_id)
conn_rec.state = ConnRecord.State.COMPLETED.rfc23
async with self.profile.session() as session:
await conn_rec.save(session, reason="Sent connection complete")
if session.settings.get("auto_disclose_features"):
discovery_mgr = V20DiscoveryMgr(self._profile)
await discovery_mgr.proactive_disclose_features(
connection_id=conn_rec.connection_id
)
return conn_rec
async def accept_complete(
self,
complete: DIDXComplete,
receipt: MessageReceipt,
) -> ConnRecord:
"""
Accept a connection complete message under RFC 23 (DID exchange).
Process a `DIDXComplete` message by looking up
the connection record and marking the exchange complete.
Args:
complete: The `DIDXComplete` to accept
receipt: The message receipt
Returns:
The updated `ConnRecord` representing the connection
Raises:
DIDXManagerError: If the corresponding connection does not exist
or is not in the response-sent state
"""
conn_rec = None
# identify the request by the thread ID
try:
async with self.profile.session() as session:
conn_rec = await ConnRecord.retrieve_by_request_id(
session, complete._thread_id
)
except StorageNotFoundError:
raise DIDXManagerError(
"No corresponding connection request found",
error_code=ProblemReportReason.COMPLETE_NOT_ACCEPTED.value,
)
conn_rec.state = ConnRecord.State.COMPLETED.rfc23
async with self.profile.session() as session:
await conn_rec.save(session, reason="Received connection complete")
if session.settings.get("auto_disclose_features"):
discovery_mgr = V20DiscoveryMgr(self._profile)
await discovery_mgr.proactive_disclose_features(
connection_id=conn_rec.connection_id
)
return conn_rec
async def verify_diddoc(
self,
wallet: BaseWallet,
attached: AttachDecorator,
) -> DIDDoc:
"""Verify DIDDoc attachment and return signed data."""
signed_diddoc_bytes = attached.data.signed
if not signed_diddoc_bytes:
raise DIDXManagerError("DID doc attachment is not signed.")
if not await attached.data.verify(wallet):
raise DIDXManagerError("DID doc attachment signature failed verification")
return DIDDoc.deserialize(json.loads(signed_diddoc_bytes.decode()))