Skip to content

Commit

Permalink
feat(mercury): fix mercury issues
Browse files Browse the repository at this point in the history
  • Loading branch information
goncalo-frade-iohk committed Mar 6, 2023
1 parent cf195d6 commit 62654fd
Show file tree
Hide file tree
Showing 20 changed files with 188 additions and 156 deletions.
7 changes: 7 additions & 0 deletions AtalaPrismSDK/Domain/Sources/Models/Errors.swift
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,13 @@ public enum MercuryError: KnownPrismError {

/// An error case representing invalid body data in a message.
case messageInvalidBodyDataError

/**
An error case representing a DIDComm error.
- Parameters:
- msg: The message describing the error.
- underlyingErrors: An array of underlying errors that may have contributed to this error, if provided.
*/
case didcommError(msg: String, underlyingErrors: [Error]? = nil)

/// The error code returned by the server.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,10 @@ final class PackEncryptedOperation: OnPackEncryptedResult {
continuation.resume(returning: result)
})
do {
print("Packing message \(message.piuri) sender:\(fromDID) \nto:\(toDID)")
logger.debug(message: "Packing message \(message.piuri)", metadata: [
.maskedMetadataByLevel(key: "Sender", value: fromDID.string, level: .debug),
.maskedMetadataByLevel(key: "Receiver", value: toDID.string, level: .debug)
])
let status = didcomm.packEncrypted(
msg: try DIDCommxSwift.Message(domain: message, mediaType: .contentTypePlain),
to: toDID.string,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@ Error on parsing DIDComm library model message to Domain message : \(error.local
}

func error(err: DIDCommxSwift.ErrorKind, msg: String) {
print(err.localizedDescription)
let error = MercuryError.didcommError(
msg:
"""
Expand Down
46 changes: 39 additions & 7 deletions AtalaPrismSDK/Mercury/Sources/MecuryImpl+SendMessage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ extension MercuryImpl {
public func sendMessage(_ msg: Message) async throws -> Data? {
guard let toDID = msg.to else { throw MercuryError.noRecipientDIDSetError }
guard let fromDID = msg.from else { throw MercuryError.noRecipientDIDSetError }
print("Send message \(msg.piuri) sender:\(fromDID.string) \nto:\(toDID.string)")
let document = try await castor.resolveDID(did: toDID)

let originalPackedMessage = try await packMessage(msg: msg)
Expand All @@ -24,8 +23,23 @@ extension MercuryImpl {
encrypted: encryptedData,
mediatorDID: mediatorDID
)
print("Send message \(forwardMessage.piuri) sender:\(forwardMessage.from?.string) \nto:\(forwardMessage.to?.string)")
let forwardPackedMessage = try await packMessage(msg: forwardMessage)

logger.debug(
message: "Sending forward message with internal message type \(msg.piuri)",
metadata: [
.maskedMetadataByLevel(
key: "Sender",
value: forwardMessage.from.string,
level: .debug
),
.maskedMetadataByLevel(
key: "Receiver",
value: forwardMessage.to.string,
level: .debug
)
]
)
let forwardPackedMessage = try await packMessage(msg: forwardMessage.makeMessage())
let mediatorDocument = try await castor.resolveDID(did: mediatorDID)
guard
let url = getDIDCommURL(document: mediatorDocument),
Expand All @@ -41,6 +55,21 @@ extension MercuryImpl {
else {
throw MercuryError.noValidServiceFoundError(did: toDID.string)
}
logger.debug(
message: "Sending message with type \(msg.piuri)",
metadata: [
.maskedMetadataByLevel(
key: "Sender",
value: fromDID.string,
level: .debug
),
.maskedMetadataByLevel(
key: "Receiver",
value: toDID.string,
level: .debug
)
]
)
return try await sendHTTPMessage(url: url, packedMessage: data)
}
}
Expand All @@ -56,7 +85,6 @@ extension MercuryImpl {
let msgStr = String(data: msgData, encoding: .utf8),
msgStr != "null"
else { return nil }
print("Data returned: \(msgStr)")
return try? await self.unpackMessage(msg: msgStr)
}

Expand All @@ -67,15 +95,19 @@ extension MercuryImpl {
headers: ["content-type": MediaType.contentTypeEncrypted.rawValue]
)
}
private func prepareForwardMessage(msg: Message, encrypted: Data, mediatorDID: DID) throws -> Message {
private func prepareForwardMessage(
msg: Message,
encrypted: Data,
mediatorDID: DID
) throws -> ForwardMessage {
guard let fromDID = msg.from else { throw MercuryError.noSenderDIDSetError }
guard let toDID = msg.to else { throw MercuryError.noRecipientDIDSetError }
return try ForwardMessage(
return ForwardMessage(
from: fromDID,
to: mediatorDID,
body: .init(next: toDID.string),
encryptedJsonMessage: encrypted
).makeMessage()
)
}

private func getDIDCommURL(document: DIDDocument) -> URL? {
Expand Down
4 changes: 2 additions & 2 deletions AtalaPrismSDK/Mercury/Sources/MercuryImpl+Public.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ extension MercuryImpl: Mercury {
/// - Returns: The string representation of the packed message
/// - Throws: An error if the message object is invalid
public func packMessage(msg: Domain.Message) async throws -> String {
try await PackEncryptedOperation(didcomm: didcomm, message: msg, logger: logger).packEncrypted()
try await PackEncryptedOperation(didcomm: getDidcomm(), message: msg, logger: logger).packEncrypted()
}

/// 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.
Expand All @@ -19,6 +19,6 @@ extension MercuryImpl: Mercury {
/// - Returns: The message object
/// - Throws: An error if the string is not a valid message representation
public func unpackMessage(msg: String) async throws -> Domain.Message {
try await UnpackOperation(didcomm: didcomm, castor: castor, logger: logger).unpackEncrypted(messageString: msg)
try await UnpackOperation(didcomm: getDidcomm(), castor: castor, logger: logger).unpackEncrypted(messageString: msg)
}
}
6 changes: 4 additions & 2 deletions AtalaPrismSDK/Mercury/Sources/MercuryImpl.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ public struct MercuryImpl {
let castor: Castor
let apollo: Apollo
let pluto: Pluto
let didcomm: DidComm
let logger: PrismLogger

public init(
Expand All @@ -24,14 +23,17 @@ public struct MercuryImpl {
self.castor = castor
self.apollo = apollo
self.pluto = pluto
}

func getDidcomm() -> DidComm {
let didResolver = DIDCommDIDResolverWrapper(castor: castor, logger: logger)
let secretsResolver = DIDCommSecretsResolverWrapper(
apollo: apollo,
pluto: pluto,
castor: castor,
logger: logger
)
self.didcomm = DidComm(
return DidComm(
didResolver: didResolver,
secretResolver: secretsResolver
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ extension CDDIDPrivateKeyDAO: DIDPrivateKeyStore {

private extension CDDIDPrivateKey {
func parseFrom(did: DID, privateKeys: [PrivateKey], alias: String?) {
self.alias = alias
self.did = did.string
self.schema = did.schema
self.method = did.method
Expand All @@ -37,7 +38,6 @@ private extension CDDIDPrivateKey {
break
}
}
self.alias = alias
}
}

Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -231,12 +231,6 @@ Could not find key in storage please use Castor instead and provide the private
}
}

func getAllRegisteredPeerDIDs() -> AnyPublisher<[(did: DID, alias: String?)], Error> {
pluto.getAllPeerDIDs()
.map { $0.map { ($0.did, $0.alias) } }
.eraseToAnyPublisher()
}

/// This function registers a DID pair in the `pluto` store
///
/// - Parameter pair: The DID pair to register
Expand All @@ -253,4 +247,13 @@ Could not find key in storage please use Castor instead and provide the private
func getAllDIDPairs() -> AnyPublisher<[DIDPair], Error> {
pluto.getAllDidPairs()
}

/// This function gets all the DID peers from the `pluto` store
///
/// - Returns: A publisher that emits an array of tuples (`DID`, `String?`) objects, or an error if there was a problem getting the dids
func getAllRegisteredPeerDIDs() -> AnyPublisher<[(did: DID, alias: String?)], Error> {
pluto.getAllPeerDIDs()
.map { $0.map { ($0.did, $0.alias) } }
.eraseToAnyPublisher()
}
}
39 changes: 3 additions & 36 deletions AtalaPrismSDK/PrismAgent/Sources/PrismAgent+MessageEvents.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import Foundation
// MARK: Messaging events funcionalities
public extension PrismAgent {
/// Start fetching the messages from the mediator
func startFetchingMessages() {
// Check if messagesStreamTask is nil
func startFetchingMessages(timeBetweenRequests: Int = 5) {
let timeInterval = max(timeBetweenRequests, 5)
guard messagesStreamTask == nil else { return }

logger.info(message: "Start streaming new unread messages")
Expand All @@ -22,7 +22,7 @@ public extension PrismAgent {
// Handle errors that occur during the message fetching process
logger.error(error: error)
}
sleep(90)
sleep(UInt32(timeInterval))
}
}
}
Expand Down Expand Up @@ -56,39 +56,6 @@ public extension PrismAgent {
func handleReceivedMessagesEvents() -> AnyPublisher<Message, Error> {
pluto.getAllMessagesReceived()
.flatMap { $0.publisher }
.print()
.eraseToAnyPublisher()
// .flatMap { message -> AnyPublisher<Message, Error> in
// if let issueCredential = try? IssueCredential(fromMessage: message) {
// let credentials = try? issueCredential.getCredentialStrings().map {
// try pollux.parseVerifiableCredential(jwtString: $0)
// }
// guard let credential = credentials?.first else {
// return Just(message)
// .tryMap { $0 }
// .eraseToAnyPublisher()
// }
// return pluto
// .storeCredential(credential: credential)
// .map { message }
// .eraseToAnyPublisher()
// }
// return Just(message)
// .tryMap { $0 }
// .eraseToAnyPublisher()
// }
// .flatMap { [weak self] message -> AnyPublisher<Message, Error> in
// if
// let self,
// let request = try? RequestPresentation(fromMessage: message),
// !self.requestedPresentations.value.contains(where: { $0.0.id == request.id })
// {
// self.requestedPresentations.value = self.requestedPresentations.value + [(request, false)]
// }
// return Just(message)
// .tryMap { $0 }
// .eraseToAnyPublisher()
// }
// .eraseToAnyPublisher()
}
}
84 changes: 42 additions & 42 deletions AtalaPrismSDK/PrismAgent/Sources/PrismAgent.swift
Original file line number Diff line number Diff line change
Expand Up @@ -160,48 +160,48 @@ public class PrismAgent {
logger.info(message: "Agent not running")
}

// TODO: This is to be deleted in the future. For now it helps with proof of request logic
public func presentCredentialProof(
request: RequestPresentation,
credential: VerifiableCredential
) async throws {
guard let jwtBase64 = credential.id.data(using: .utf8)?.base64UrlEncodedString() else {
throw UnknownError.somethingWentWrongError(
customMessage: "Could not decode JWT Credential",
underlyingErrors: nil
)
}
let presentation = Presentation(
body: .init(goalCode: request.body.goalCode, comment: request.body.comment),
attachments: [try .build(
payload: AttachmentBase64(base64: jwtBase64),
mediaType: "prism/jwt"
)],
thid: request.id,
from: request.to,
to: request.from
)
_ = try await connectionManager.sendMessage(presentation.makeMessage())
}

// TODO: This is to be deleted in the future. For now it helps with issue credentials logic
public func issueCredentialProtocol() {
startFetchingMessages()
Task {
do {
for try await offer in handleReceivedMessagesEvents()
.drop(while: { (try? OfferCredential(fromMessage: $0)) != nil })
.values
{
if let issueProtocol = try? IssueCredentialProtocol(offer, connector: connectionManager) {
try? await issueProtocol.nextStage()
}
}
} catch {
print(error.localizedDescription)
}
}
}
// // TODO: This is to be deleted in the future. For now it helps with proof of request logic
// public func presentCredentialProof(
// request: RequestPresentation,
// credential: VerifiableCredential
// ) async throws {
// guard let jwtBase64 = credential.id.data(using: .utf8)?.base64UrlEncodedString() else {
// throw UnknownError.somethingWentWrongError(
// customMessage: "Could not decode JWT Credential",
// underlyingErrors: nil
// )
// }
// let presentation = Presentation(
// body: .init(goalCode: request.body.goalCode, comment: request.body.comment),
// attachments: [try .build(
// payload: AttachmentBase64(base64: jwtBase64),
// mediaType: "prism/jwt"
// )],
// thid: request.id,
// from: request.to,
// to: request.from
// )
// _ = try await connectionManager.sendMessage(presentation.makeMessage())
// }
//
// // TODO: This is to be deleted in the future. For now it helps with issue credentials logic
// public func issueCredentialProtocol() {
// startFetchingMessages()
// Task {
// do {
// for try await offer in handleReceivedMessagesEvents()
// .drop(while: { (try? OfferCredential(fromMessage: $0)) != nil })
// .values
// {
// if let issueProtocol = try? IssueCredentialProtocol(offer, connector: connectionManager) {
// try? await issueProtocol.nextStage()
// }
// }
// } catch {
// print(error.localizedDescription)
// }
// }
// }
}

extension DID {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ struct MediationKeysUpdateList {
self.id = id
self.from = from
self.to = to
print(recipientDids.map { $0.string })
self.body = .init(
updates: recipientDids.map {
Body.Update(recipientDid: $0.string)
Expand Down
Loading

0 comments on commit 62654fd

Please sign in to comment.