Skip to content

Commit d80b37c

Browse files
feat(mercury): fix mercury issues
1 parent a274967 commit d80b37c

File tree

20 files changed

+188
-156
lines changed

20 files changed

+188
-156
lines changed

AtalaPrismSDK/Domain/Sources/Models/Errors.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -383,6 +383,13 @@ public enum MercuryError: KnownPrismError {
383383

384384
/// An error case representing invalid body data in a message.
385385
case messageInvalidBodyDataError
386+
387+
/**
388+
An error case representing a DIDComm error.
389+
- Parameters:
390+
- msg: The message describing the error.
391+
- underlyingErrors: An array of underlying errors that may have contributed to this error, if provided.
392+
*/
386393
case didcommError(msg: String, underlyingErrors: [Error]? = nil)
387394

388395
/// The error code returned by the server.

AtalaPrismSDK/Mercury/Sources/DIDCommWrappers/PackEncryptedOperation.swift

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,10 @@ final class PackEncryptedOperation: OnPackEncryptedResult {
4444
continuation.resume(returning: result)
4545
})
4646
do {
47-
print("Packing message \(message.piuri) sender:\(fromDID) \nto:\(toDID)")
47+
logger.debug(message: "Packing message \(message.piuri)", metadata: [
48+
.maskedMetadataByLevel(key: "Sender", value: fromDID.string, level: .debug),
49+
.maskedMetadataByLevel(key: "Receiver", value: toDID.string, level: .debug)
50+
])
4851
let status = didcomm.packEncrypted(
4952
msg: try DIDCommxSwift.Message(domain: message, mediaType: .contentTypePlain),
5053
to: toDID.string,

AtalaPrismSDK/Mercury/Sources/DIDCommWrappers/UnpackOperation.swift

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,6 @@ Error on parsing DIDComm library model message to Domain message : \(error.local
8484
}
8585

8686
func error(err: DIDCommxSwift.ErrorKind, msg: String) {
87-
print(err.localizedDescription)
8887
let error = MercuryError.didcommError(
8988
msg:
9089
"""

AtalaPrismSDK/Mercury/Sources/MecuryImpl+SendMessage.swift

Lines changed: 39 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ extension MercuryImpl {
1010
public func sendMessage(_ msg: Message) async throws -> Data? {
1111
guard let toDID = msg.to else { throw MercuryError.noRecipientDIDSetError }
1212
guard let fromDID = msg.from else { throw MercuryError.noRecipientDIDSetError }
13-
print("Send message \(msg.piuri) sender:\(fromDID.string) \nto:\(toDID.string)")
1413
let document = try await castor.resolveDID(did: toDID)
1514

1615
let originalPackedMessage = try await packMessage(msg: msg)
@@ -24,8 +23,23 @@ extension MercuryImpl {
2423
encrypted: encryptedData,
2524
mediatorDID: mediatorDID
2625
)
27-
print("Send message \(forwardMessage.piuri) sender:\(forwardMessage.from?.string) \nto:\(forwardMessage.to?.string)")
28-
let forwardPackedMessage = try await packMessage(msg: forwardMessage)
26+
27+
logger.debug(
28+
message: "Sending forward message with internal message type \(msg.piuri)",
29+
metadata: [
30+
.maskedMetadataByLevel(
31+
key: "Sender",
32+
value: forwardMessage.from.string,
33+
level: .debug
34+
),
35+
.maskedMetadataByLevel(
36+
key: "Receiver",
37+
value: forwardMessage.to.string,
38+
level: .debug
39+
)
40+
]
41+
)
42+
let forwardPackedMessage = try await packMessage(msg: forwardMessage.makeMessage())
2943
let mediatorDocument = try await castor.resolveDID(did: mediatorDID)
3044
guard
3145
let url = getDIDCommURL(document: mediatorDocument),
@@ -41,6 +55,21 @@ extension MercuryImpl {
4155
else {
4256
throw MercuryError.noValidServiceFoundError(did: toDID.string)
4357
}
58+
logger.debug(
59+
message: "Sending message with type \(msg.piuri)",
60+
metadata: [
61+
.maskedMetadataByLevel(
62+
key: "Sender",
63+
value: fromDID.string,
64+
level: .debug
65+
),
66+
.maskedMetadataByLevel(
67+
key: "Receiver",
68+
value: toDID.string,
69+
level: .debug
70+
)
71+
]
72+
)
4473
return try await sendHTTPMessage(url: url, packedMessage: data)
4574
}
4675
}
@@ -56,7 +85,6 @@ extension MercuryImpl {
5685
let msgStr = String(data: msgData, encoding: .utf8),
5786
msgStr != "null"
5887
else { return nil }
59-
print("Data returned: \(msgStr)")
6088
return try? await self.unpackMessage(msg: msgStr)
6189
}
6290

@@ -67,15 +95,19 @@ extension MercuryImpl {
6795
headers: ["content-type": MediaType.contentTypeEncrypted.rawValue]
6896
)
6997
}
70-
private func prepareForwardMessage(msg: Message, encrypted: Data, mediatorDID: DID) throws -> Message {
98+
private func prepareForwardMessage(
99+
msg: Message,
100+
encrypted: Data,
101+
mediatorDID: DID
102+
) throws -> ForwardMessage {
71103
guard let fromDID = msg.from else { throw MercuryError.noSenderDIDSetError }
72104
guard let toDID = msg.to else { throw MercuryError.noRecipientDIDSetError }
73-
return try ForwardMessage(
105+
return ForwardMessage(
74106
from: fromDID,
75107
to: mediatorDID,
76108
body: .init(next: toDID.string),
77109
encryptedJsonMessage: encrypted
78-
).makeMessage()
110+
)
79111
}
80112

81113
private func getDIDCommURL(document: DIDDocument) -> URL? {

AtalaPrismSDK/Mercury/Sources/MercuryImpl+Public.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ extension MercuryImpl: Mercury {
1010
/// - Returns: The string representation of the packed message
1111
/// - Throws: An error if the message object is invalid
1212
public func packMessage(msg: Domain.Message) async throws -> String {
13-
try await PackEncryptedOperation(didcomm: didcomm, message: msg, logger: logger).packEncrypted()
13+
try await PackEncryptedOperation(didcomm: getDidcomm(), message: msg, logger: logger).packEncrypted()
1414
}
1515

1616
/// unpackMessage asynchronously unpacks a given string representation of a message into a message object. This function may throw an error if the string is not a valid message representation.
@@ -19,6 +19,6 @@ extension MercuryImpl: Mercury {
1919
/// - Returns: The message object
2020
/// - Throws: An error if the string is not a valid message representation
2121
public func unpackMessage(msg: String) async throws -> Domain.Message {
22-
try await UnpackOperation(didcomm: didcomm, castor: castor, logger: logger).unpackEncrypted(messageString: msg)
22+
try await UnpackOperation(didcomm: getDidcomm(), castor: castor, logger: logger).unpackEncrypted(messageString: msg)
2323
}
2424
}

AtalaPrismSDK/Mercury/Sources/MercuryImpl.swift

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ public struct MercuryImpl {
88
let castor: Castor
99
let apollo: Apollo
1010
let pluto: Pluto
11-
let didcomm: DidComm
1211
let logger: PrismLogger
1312

1413
public init(
@@ -24,14 +23,17 @@ public struct MercuryImpl {
2423
self.castor = castor
2524
self.apollo = apollo
2625
self.pluto = pluto
26+
}
27+
28+
func getDidcomm() -> DidComm {
2729
let didResolver = DIDCommDIDResolverWrapper(castor: castor, logger: logger)
2830
let secretsResolver = DIDCommSecretsResolverWrapper(
2931
apollo: apollo,
3032
pluto: pluto,
3133
castor: castor,
3234
logger: logger
3335
)
34-
self.didcomm = DidComm(
36+
return DidComm(
3537
didResolver: didResolver,
3638
secretResolver: secretsResolver
3739
)

AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDDIDPrivateKeyDAO+DIDPrivateKeyStore.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ extension CDDIDPrivateKeyDAO: DIDPrivateKeyStore {
2121

2222
private extension CDDIDPrivateKey {
2323
func parseFrom(did: DID, privateKeys: [PrivateKey], alias: String?) {
24+
self.alias = alias
2425
self.did = did.string
2526
self.schema = did.schema
2627
self.method = did.method
@@ -37,7 +38,6 @@ private extension CDDIDPrivateKey {
3738
break
3839
}
3940
}
40-
self.alias = alias
4141
}
4242
}
4343

AtalaPrismSDK/Pluto/Sources/Resources/PrismPluto.xcdatamodeld/Model.xcdatamodel/contents

Lines changed: 0 additions & 2 deletions
This file was deleted.

AtalaPrismSDK/PrismAgent/Sources/PrismAgent+DIDHigherFucntions.swift

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -231,12 +231,6 @@ Could not find key in storage please use Castor instead and provide the private
231231
}
232232
}
233233

234-
func getAllRegisteredPeerDIDs() -> AnyPublisher<[(did: DID, alias: String?)], Error> {
235-
pluto.getAllPeerDIDs()
236-
.map { $0.map { ($0.did, $0.alias) } }
237-
.eraseToAnyPublisher()
238-
}
239-
240234
/// This function registers a DID pair in the `pluto` store
241235
///
242236
/// - Parameter pair: The DID pair to register
@@ -253,4 +247,13 @@ Could not find key in storage please use Castor instead and provide the private
253247
func getAllDIDPairs() -> AnyPublisher<[DIDPair], Error> {
254248
pluto.getAllDidPairs()
255249
}
250+
251+
/// This function gets all the DID peers from the `pluto` store
252+
///
253+
/// - Returns: A publisher that emits an array of tuples (`DID`, `String?`) objects, or an error if there was a problem getting the dids
254+
func getAllRegisteredPeerDIDs() -> AnyPublisher<[(did: DID, alias: String?)], Error> {
255+
pluto.getAllPeerDIDs()
256+
.map { $0.map { ($0.did, $0.alias) } }
257+
.eraseToAnyPublisher()
258+
}
256259
}

AtalaPrismSDK/PrismAgent/Sources/PrismAgent+MessageEvents.swift

Lines changed: 3 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ import Foundation
55
// MARK: Messaging events funcionalities
66
public extension PrismAgent {
77
/// Start fetching the messages from the mediator
8-
func startFetchingMessages() {
9-
// Check if messagesStreamTask is nil
8+
func startFetchingMessages(timeBetweenRequests: Int = 5) {
9+
let timeInterval = max(timeBetweenRequests, 5)
1010
guard messagesStreamTask == nil else { return }
1111

1212
logger.info(message: "Start streaming new unread messages")
@@ -22,7 +22,7 @@ public extension PrismAgent {
2222
// Handle errors that occur during the message fetching process
2323
logger.error(error: error)
2424
}
25-
sleep(90)
25+
sleep(UInt32(timeInterval))
2626
}
2727
}
2828
}
@@ -56,39 +56,6 @@ public extension PrismAgent {
5656
func handleReceivedMessagesEvents() -> AnyPublisher<Message, Error> {
5757
pluto.getAllMessagesReceived()
5858
.flatMap { $0.publisher }
59-
.print()
6059
.eraseToAnyPublisher()
61-
// .flatMap { message -> AnyPublisher<Message, Error> in
62-
// if let issueCredential = try? IssueCredential(fromMessage: message) {
63-
// let credentials = try? issueCredential.getCredentialStrings().map {
64-
// try pollux.parseVerifiableCredential(jwtString: $0)
65-
// }
66-
// guard let credential = credentials?.first else {
67-
// return Just(message)
68-
// .tryMap { $0 }
69-
// .eraseToAnyPublisher()
70-
// }
71-
// return pluto
72-
// .storeCredential(credential: credential)
73-
// .map { message }
74-
// .eraseToAnyPublisher()
75-
// }
76-
// return Just(message)
77-
// .tryMap { $0 }
78-
// .eraseToAnyPublisher()
79-
// }
80-
// .flatMap { [weak self] message -> AnyPublisher<Message, Error> in
81-
// if
82-
// let self,
83-
// let request = try? RequestPresentation(fromMessage: message),
84-
// !self.requestedPresentations.value.contains(where: { $0.0.id == request.id })
85-
// {
86-
// self.requestedPresentations.value = self.requestedPresentations.value + [(request, false)]
87-
// }
88-
// return Just(message)
89-
// .tryMap { $0 }
90-
// .eraseToAnyPublisher()
91-
// }
92-
// .eraseToAnyPublisher()
9360
}
9461
}

AtalaPrismSDK/PrismAgent/Sources/PrismAgent.swift

Lines changed: 42 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -160,48 +160,48 @@ public class PrismAgent {
160160
logger.info(message: "Agent not running")
161161
}
162162

163-
// TODO: This is to be deleted in the future. For now it helps with proof of request logic
164-
public func presentCredentialProof(
165-
request: RequestPresentation,
166-
credential: VerifiableCredential
167-
) async throws {
168-
guard let jwtBase64 = credential.id.data(using: .utf8)?.base64UrlEncodedString() else {
169-
throw UnknownError.somethingWentWrongError(
170-
customMessage: "Could not decode JWT Credential",
171-
underlyingErrors: nil
172-
)
173-
}
174-
let presentation = Presentation(
175-
body: .init(goalCode: request.body.goalCode, comment: request.body.comment),
176-
attachments: [try .build(
177-
payload: AttachmentBase64(base64: jwtBase64),
178-
mediaType: "prism/jwt"
179-
)],
180-
thid: request.id,
181-
from: request.to,
182-
to: request.from
183-
)
184-
_ = try await connectionManager.sendMessage(presentation.makeMessage())
185-
}
186-
187-
// TODO: This is to be deleted in the future. For now it helps with issue credentials logic
188-
public func issueCredentialProtocol() {
189-
startFetchingMessages()
190-
Task {
191-
do {
192-
for try await offer in handleReceivedMessagesEvents()
193-
.drop(while: { (try? OfferCredential(fromMessage: $0)) != nil })
194-
.values
195-
{
196-
if let issueProtocol = try? IssueCredentialProtocol(offer, connector: connectionManager) {
197-
try? await issueProtocol.nextStage()
198-
}
199-
}
200-
} catch {
201-
print(error.localizedDescription)
202-
}
203-
}
204-
}
163+
// // TODO: This is to be deleted in the future. For now it helps with proof of request logic
164+
// public func presentCredentialProof(
165+
// request: RequestPresentation,
166+
// credential: VerifiableCredential
167+
// ) async throws {
168+
// guard let jwtBase64 = credential.id.data(using: .utf8)?.base64UrlEncodedString() else {
169+
// throw UnknownError.somethingWentWrongError(
170+
// customMessage: "Could not decode JWT Credential",
171+
// underlyingErrors: nil
172+
// )
173+
// }
174+
// let presentation = Presentation(
175+
// body: .init(goalCode: request.body.goalCode, comment: request.body.comment),
176+
// attachments: [try .build(
177+
// payload: AttachmentBase64(base64: jwtBase64),
178+
// mediaType: "prism/jwt"
179+
// )],
180+
// thid: request.id,
181+
// from: request.to,
182+
// to: request.from
183+
// )
184+
// _ = try await connectionManager.sendMessage(presentation.makeMessage())
185+
// }
186+
//
187+
// // TODO: This is to be deleted in the future. For now it helps with issue credentials logic
188+
// public func issueCredentialProtocol() {
189+
// startFetchingMessages()
190+
// Task {
191+
// do {
192+
// for try await offer in handleReceivedMessagesEvents()
193+
// .drop(while: { (try? OfferCredential(fromMessage: $0)) != nil })
194+
// .values
195+
// {
196+
// if let issueProtocol = try? IssueCredentialProtocol(offer, connector: connectionManager) {
197+
// try? await issueProtocol.nextStage()
198+
// }
199+
// }
200+
// } catch {
201+
// print(error.localizedDescription)
202+
// }
203+
// }
204+
// }
205205
}
206206

207207
extension DID {

AtalaPrismSDK/PrismAgent/Sources/Protocols/Mediation/MediationKeysUpdateList.swift

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@ struct MediationKeysUpdateList {
2626
self.id = id
2727
self.from = from
2828
self.to = to
29-
print(recipientDids.map { $0.string })
3029
self.body = .init(
3130
updates: recipientDids.map {
3231
Body.Update(recipientDid: $0.string)

0 commit comments

Comments
 (0)