Skip to content

Commit 1f840fd

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

File tree

19 files changed

+146
-82
lines changed

19 files changed

+146
-82
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 & 4 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,7 +56,6 @@ public extension PrismAgent {
5656
func handleReceivedMessagesEvents() -> AnyPublisher<Message, Error> {
5757
pluto.getAllMessagesReceived()
5858
.flatMap { $0.publisher }
59-
.print()
6059
.eraseToAnyPublisher()
6160
// .flatMap { message -> AnyPublisher<Message, Error> in
6261
// if let issueCredential = try? IssueCredential(fromMessage: message) {

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)
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import Core
2+
import Domain
3+
import Foundation
4+
5+
public struct BasicMessage {
6+
7+
public struct Body: Codable {
8+
public let content: String
9+
10+
public init(content: String) {
11+
self.content = content
12+
}
13+
}
14+
15+
public let id: String
16+
public let type = ProtocolTypes.didcommBasicMessage.rawValue
17+
public let from: DID
18+
public let to: DID
19+
public let date: Date
20+
public let body: Body
21+
22+
public init(
23+
id: String = UUID().uuidString,
24+
from: DID,
25+
to: DID,
26+
body: Body,
27+
date: Date = Date()
28+
) {
29+
self.id = id
30+
self.from = from
31+
self.to = to
32+
self.body = body
33+
self.date = date
34+
}
35+
36+
public init?(fromMessage: Message) throws {
37+
guard
38+
fromMessage.piuri == ProtocolTypes.didcommBasicMessage.rawValue,
39+
let from = fromMessage.from,
40+
let to = fromMessage.to
41+
else {
42+
return nil
43+
}
44+
self.id = fromMessage.id
45+
self.from = from
46+
self.to = to
47+
self.body = try JSONDecoder.didComm().decode(Body.self, from: fromMessage.body)
48+
self.date = fromMessage.createdTime
49+
}
50+
51+
public func makeMessage() throws -> Message {
52+
return Message(
53+
id: id,
54+
piuri: type,
55+
from: from,
56+
to: to,
57+
body: try JSONEncoder.didComm().encode(body),
58+
createdTime: date
59+
)
60+
}
61+
}

AtalaPrismSDK/PrismAgent/Sources/Protocols/ProtocolTypes.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import Foundation
22

33
enum ProtocolTypes: String {
4+
case didcommBasicMessage = "https://didcomm.org/basicmessage/2.0/message"
45
case didcommMediationRequest = "https://didcomm.org/coordinate-mediation/2.0/mediate-request"
56
case didcommMediationGrant = "https://didcomm.org/coordinate-mediation/2.0/mediate-grant"
67
case didcommMediationDeny = "https://didcomm.org/coordinate-mediation/2.0/mediate-deny"

Sample/DIDChat/DIDChat/Modules/ChatView/ChatView.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ struct ChatView<ViewModel: ChatViewModel>: View {
2424
MessageView(text: message.text, isSent: message.sent)
2525
}
2626
}
27+
.padding()
2728

2829
HStack {
2930
TextField("Type your message...", text: $viewModel.sendingText)

Sample/DIDChat/DIDChat/Modules/ChatView/ChatViewModel.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ final class ChatViewModelImpl: ChatViewModel {
6161
))
6262

6363
self.messages = self.messageList.sorted { $0.date < $1.date }
64+
self.sendingText = ""
6465
}
6566
}
6667
}

Sample/DIDChat/DIDChat/Modules/ContactsView/ContactsView.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ struct AddContactView<ViewModel: ContactsViewModel>: View {
6262
@EnvironmentObject var viewModel: ViewModel
6363
@Environment(\.presentationMode) var presentationMode
6464
@State var newContactName: String = "Bob"
65-
@State var newContactPeerDID: String = "did:peer:2.Ez6LSpAMSF7BxhxJEqWApn258toZ3RYFD5Bp6TaCCE1JkSNZW.Vz6MkmSoU3wZ1TfXEmrC8nzm5WvHvxrg8mmxe1BnGAZPXzTpR.SeyJyIjpbXSwicyI6ImRpZDpwZWVyOjIuRXo2TFNtaWJDSkxkeHFTc21hYUJ1c1NrUXdYek1ZUnFVTHRCWEdaWDd1dERKSE5HbS5WejZNa293a0Vxd1dEVVM0TUNOTG50UFpHVGV0YWM3dGtKbk1HWVB2eDlnZmh1N2RyLlNleUpwWkNJNkltNWxkeTFwWkNJc0luUWlPaUprYlNJc0luTWlPaUpvZEhSd2N6b3ZMMjFsWkdsaGRHOXlMbkp2YjNSemFXUXVZMnh2ZFdRaUxDSmhJanBiSW1ScFpHTnZiVzB2ZGpJaVhYMCIsImEiOltdLCJ0IjoiZG0ifQ"
65+
@State var newContactPeerDID: String = "did:peer:2.Ez6LSc9cZDE5ioLyEV9WKtcpejzr7GvzcWHHP8rwnWeZwYyaV.Vz6MkkbB59SstKEkTLfLhGmc5iyesyMzCgmNuZqgMz3c4sLgy.SeyJyIjpbXSwicyI6ImRpZDpwZWVyOjIuRXo2TFNjUGI0ZG1GbUR3RXd2aGpLTXphN1p0TnhDRlVGeWkxb0xKSHF0REZDWWhTVC5WejZNa3J2TWFjV0daa3RiWk16UFdDQ2dCYUs1VEdYdGJSUlNWZk1rZmtROWlrTER0LlNleUpwWkNJNkltNWxkeTFwWkNJc0luUWlPaUprYlNJc0luTWlPaUpvZEhSd2N6b3ZMMjFsWkdsaGRHOXlMbkp2YjNSemFXUXVZMnh2ZFdRaUxDSmhJanBiSW1ScFpHTnZiVzB2ZGpJaVhYMCIsImEiOltdLCJ0IjoiZG0ifQ"
6666
@State var newPeerDIDAlias: String = ""
6767

6868
var body: some View {

Sample/DIDChat/DIDChat/Modules/ContactsView/ContactsViewState.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,14 @@ struct ContactsViewState {
1212
hasher.combine(name)
1313
}
1414
}
15+
16+
struct PossibleContact: Identifiable, Hashable {
17+
let id: String
18+
let name: String
19+
20+
func hash(into hasher: inout Hasher) {
21+
hasher.combine(id)
22+
hasher.combine(name)
23+
}
24+
}
1525
}

Sample/DIDChat/DIDChat/Modules/MediatorView/MediatorViewModel.swift

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,8 @@ class MediatorViewModelImpl: MediatorViewModel {
2929
do {
3030
PrismAgent.setupLogging(logLevels: [
3131
.prismAgent: .debug,
32-
.mercury: .debug
32+
.mercury: .debug,
33+
.castor: .debug
3334
])
3435
let agent = PrismAgent(mediatorDID: did)
3536
try await agent.start()

0 commit comments

Comments
 (0)