Skip to content

Commit

Permalink
feat(sample): Forth batch of sample app code
Browse files Browse the repository at this point in the history
  • Loading branch information
goncalo-frade-iohk committed Jan 10, 2023
1 parent b79e11f commit d55b511
Show file tree
Hide file tree
Showing 62 changed files with 836 additions and 303 deletions.
22 changes: 22 additions & 0 deletions Apollo/Sources/ApolloImpl+Public.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Domain
import Foundation
import SwiftJWT

extension ApolloImpl: Apollo {
public func createRandomMnemonics() -> [String] {
Expand Down Expand Up @@ -94,4 +95,25 @@ returns random mnemonics nerver returns invalid mnemonics
else { throw CommonError.somethingWentWrongError }
return jsonString
}

public func verifyJWT(jwk: String, publicKey: PublicKey) throws -> String {
switch publicKey.curve {
case "secp256k1":
let verifier = JWTVerifier.es256(publicKey: publicKey.value)
let decoder = JWTDecoder.init(jwtVerifier: verifier)
let jwt = try decoder.decode(JWT<MyClaims>.self, fromString: jwk)
return jwk
default:
let verifier = JWTVerifier.none
let decoder = JWTDecoder.init(jwtVerifier: verifier)
let jwt = try decoder.decode(JWT<MyClaims>.self, fromString: jwk)
return jwk
}
}
}

struct MyClaims: Claims {
let iss: String
let sub: String
let exp: Date
}
14 changes: 14 additions & 0 deletions Builders/Sources/PolluxBuilder.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import Pollux
import Domain

public struct PolluxBuilder {
let castor: Castor

public init(castor: Castor) {
self.castor = castor
}

public func build() -> Pollux {
PolluxImpl(castor: castor)
}
}
3 changes: 2 additions & 1 deletion Castor/Tests/PeerDIDCreationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,12 @@ final class PeerDIDCreationTests: XCTestCase {
let mypeerDID = DID(
schema: "did",
method: "peer",
methodId: "2.Ez6LSfuJvTtcmcFrjNYYSAuD32tMZWQUD2HYDfXrJqy3ui6MQ.Vz6MkoPyvuxAecSezqmL4ERE7eW2XPbiUEHRH9aqay6LA8Eqr.SeyJ0IjoiZG0iLCJzIjoiaHR0cDovL2hvc3QuZG9ja2VyLmludGVybmFsOjgwL2RpZGNvbW0vIiwiciI6W10sImEiOlsiZGlkY29tbS92MiJdfQ"
methodId: "2.Ez6LSms555YhFthn1WV8ciDBpZm86hK9tp83WojJUmxPGk1hZ.Vz6MkmdBjMyB4TS5UbbQw54szm8yvMMf1ftGV2sQVYAxaeWhE.SeyJpZCI6Im5ldy1pZCIsInQiOiJkbSIsInMiOiJodHRwczovL21lZGlhdG9yLnJvb3RzaWQuY2xvdWQiLCJhIjpbImRpZGNvbW0vdjIiXX0"
)

let apollo = ApolloImpl()
let castor = CastorImpl(apollo: apollo)
let document = try await castor.resolveDID(did: mypeerDID)
print(document)
}
}
9 changes: 9 additions & 0 deletions Core/Sources/Helpers/First+AsyncAwait.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,12 @@ public extension Publishers.First where Failure == Error {
throw Publishers.MissingOutputError()
}
}

public extension Publishers.FirstWhere where Failure == Error {
func await() async throws -> Output {
for try await output in values {
return output
}
throw Publishers.MissingOutputError()
}
}
2 changes: 1 addition & 1 deletion Domain/Sources/BBs/Pollux.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Foundation

public protocol Pollux {
func parseVerifiableCredential(jsonString: String) throws -> VerifiableCredential
func parseVerifiableCredential(jwtString: String) throws -> VerifiableCredential
}
2 changes: 1 addition & 1 deletion Domain/Sources/Logging.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,5 @@ public enum LogComponent: String {
case mercury
case pluto
case pollux
case experiences
case prismAgent
}
1 change: 1 addition & 0 deletions Domain/Sources/Models/Errors.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,5 @@ public enum PlutoError: Error {

public enum PolluxError: Error {
case invalidCredentialError
case invalidJWTString
}
12 changes: 6 additions & 6 deletions Domain/Sources/Models/JWTVerifiableCredential+Codable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ extension JWTCredentialPayload.JWTVerfiableCredential: Codable {

public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.context, forKey: .context)
try? container.encode(self.context, forKey: .context)
if self.type.count != 1 {
try container.encode(self.type, forKey: .type)
} else if let value = self.type.first {
Expand All @@ -30,14 +30,14 @@ extension JWTCredentialPayload.JWTVerfiableCredential: Codable {

public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let context = try container.decode(Set<String>.self, forKey: .context)
let context = (try? container.decode(Set<String>.self, forKey: .context)) ?? Set<String>()
let type: Set<String>
if let value = try? container.decode(String.self, forKey: .type) {
type = Set([value])
} else {
type = try container.decode(Set<String>.self, forKey: .type)
type = (try? container.decode(Set<String>.self, forKey: .type)) ?? Set<String>()
}
let credentialSubject = try container.decode(String.self, forKey: .credentialSubject)
let credentialSubject = try container.decode([String: String].self, forKey: .credentialSubject)
let credentialStatus = try? container.decode(
VerifiableCredentialTypeContainer.self,
forKey: .credentialStatus
Expand Down Expand Up @@ -107,10 +107,10 @@ extension JWTCredentialPayload: Codable {
Date.self,
forKey: .exp
)
let jti = try container.decode(
let jti = (try? container.decode(
String.self,
forKey: .jti
)
)) ?? ""
let aud = (try? container.decode(
Set<String>.self,
forKey: .aud
Expand Down
6 changes: 3 additions & 3 deletions Domain/Sources/Models/JWTVerifiableCredential.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ public struct JWTCredentialPayload {
public let context: Set<String>
public let type: Set<String>
public let credentialSchema: VerifiableCredentialTypeContainer?
public let credentialSubject: String
public let credentialSubject: [String: String]
public let credentialStatus: VerifiableCredentialTypeContainer?
public let refreshService: VerifiableCredentialTypeContainer?
public let evidence: VerifiableCredentialTypeContainer?
Expand All @@ -15,7 +15,7 @@ public struct JWTCredentialPayload {
context: Set<String> = Set(),
type: Set<String> = Set(),
credentialSchema: VerifiableCredentialTypeContainer? = nil,
credentialSubject: String,
credentialSubject: [String: String],
credentialStatus: VerifiableCredentialTypeContainer? = nil,
refreshService: VerifiableCredentialTypeContainer? = nil,
evidence: VerifiableCredentialTypeContainer? = nil,
Expand Down Expand Up @@ -67,7 +67,7 @@ extension JWTCredentialPayload: VerifiableCredential {
public var issuanceDate: Date { nbf }
public var expirationDate: Date? { exp }
public var credentialSchema: VerifiableCredentialTypeContainer? { verifiableCredential.credentialSchema }
public var credentialSubject: String { verifiableCredential.credentialSubject }
public var credentialSubject: [String: String] { verifiableCredential.credentialSubject }
public var credentialStatus: VerifiableCredentialTypeContainer? { verifiableCredential.credentialStatus }
public var refreshService: VerifiableCredentialTypeContainer? { verifiableCredential.refreshService }
public var evidence: Domain.VerifiableCredentialTypeContainer? { verifiableCredential.evidence }
Expand Down
2 changes: 1 addition & 1 deletion Domain/Sources/Models/VerifiableCredential.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public protocol VerifiableCredential {
var issuanceDate: Date { get }
var expirationDate: Date? { get }
var credentialSchema: VerifiableCredentialTypeContainer? { get }
var credentialSubject: String { get }
var credentialSubject: [String: String] { get }
var credentialStatus: VerifiableCredentialTypeContainer? { get }
var refreshService: VerifiableCredentialTypeContainer? { get }
var evidence: VerifiableCredentialTypeContainer? { get }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ extension W3CVerifiableCredential: Codable {
let validUntil = try? container.decode(VerifiableCredentialTypeContainer.self, forKey: .validUntil)
let proof = try? container.decode(String.self, forKey: .proof)
let aud = (try? container.decode(Set<String>.self, forKey: .proof)) ?? Set()
let credentialSubject = try container.decode(String.self, forKey: .credentialSubject)
let credentialSubject = try container.decode([String: String].self, forKey: .credentialSubject)
let credentialStatus = try? container.decode(
VerifiableCredentialTypeContainer.self,
forKey: .credentialStatus
Expand Down
4 changes: 2 additions & 2 deletions Domain/Sources/Models/W3CVerifiableCredential.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public struct W3CVerifiableCredential: VerifiableCredential {
public let issuanceDate: Date
public let expirationDate: Date?
public let credentialSchema: VerifiableCredentialTypeContainer?
public let credentialSubject: String
public let credentialSubject: [String: String]
public let credentialStatus: VerifiableCredentialTypeContainer?
public let refreshService: VerifiableCredentialTypeContainer?
public let evidence: VerifiableCredentialTypeContainer?
Expand All @@ -27,7 +27,7 @@ public struct W3CVerifiableCredential: VerifiableCredential {
issuanceDate: Date,
expirationDate: Date? = nil,
credentialSchema: VerifiableCredentialTypeContainer? = nil,
credentialSubject: String,
credentialSubject: [String: String],
credentialStatus: VerifiableCredentialTypeContainer? = nil,
refreshService: VerifiableCredentialTypeContainer? = nil,
evidence: VerifiableCredentialTypeContainer? = nil,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,9 @@ extension DIDCommSecretsResolverWrapper: SecretsResolver {
.map { $0.first { $0.id == secretid } }
.sink {
do {
if $0 == nil {
print("Secret not found: \(secretid)")
}
try cb.success(result: $0.map { DIDCommxSwift.Secret(from: $0) })
} catch {
print(error.localizedDescription)
Expand All @@ -92,6 +95,9 @@ extension DIDCommSecretsResolverWrapper: SecretsResolver {
}
.sink {
do {
if $0.isEmpty {
print("Secrets not found: \(secretids)")
}
try cb.success(result: $0)
} catch {
print(error.localizedDescription)
Expand Down
8 changes: 6 additions & 2 deletions Mercury/Sources/DIDCommWrappers/PackEncryptedOperation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ final class PackEncryptedOperation: OnPackEncryptedResult {
case .finished:
break
case let .failure(error):
print("Error packing message type:\(msg.piuri)")
print("Error packing message from:\(fromDID.string)")
print("Error packing message to:\(toDID.string)")
continuation.resume(throwing: error)
}
}, receiveValue: {
Expand All @@ -41,8 +44,8 @@ final class PackEncryptedOperation: OnPackEncryptedResult {
signBy: nil,
options: .init(
protectSender: false,
forward: true,
forwardHeaders: [:],
forward: false,
forwardHeaders: nil,
messagingService: nil,
encAlgAuth: .a256cbcHs512Ecdh1puA256kw,
encAlgAnon: .xc20pEcdhEsA256kw
Expand All @@ -68,6 +71,7 @@ final class PackEncryptedOperation: OnPackEncryptedResult {
}

func error(err: DIDCommxSwift.ErrorKind, msg: String) {
print("Error packing message: \(msg)")
published.send(completion: .failure(MercuryError.didcommError(msg: msg)))
}
}
1 change: 1 addition & 0 deletions Mercury/Sources/Helpers/Session.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ struct SessionManager {
let (data, response) = try await session.data(for: request)
if let urlResponse = response as? HTTPURLResponse {
guard 200...299 ~= urlResponse.statusCode else {
print("HTTP Error: \(urlResponse.statusCode)")
throw MercuryError.urlSessionError(
statusCode: urlResponse.statusCode,
error: nil,
Expand Down
7 changes: 5 additions & 2 deletions Mercury/Sources/MercuryImpl+Public.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,17 @@ extension MercuryImpl: Mercury {
}

public func sendMessage(msg: Domain.Message) async throws -> Data? {
print("Preparing message of type: \(msg.piuri)")
print("From: \(msg.from?.string)")
print("to: \(msg.to?.string)")
guard let toDID = msg.to else { throw MercuryError.noDIDReceiverSetError }
let document = try await castor.resolveDID(did: toDID)
guard
let urlString = document.services.first?.serviceEndpoint.uri,
let url = URL(string: urlString)
else { throw MercuryError.noValidServiceFoundError }
let packedMessage = try await packMessage(msg: msg)

print("Sending message of type: \(msg.piuri)")
return try await session.post(
url: url,
body: packedMessage.data(using: .utf8),
Expand All @@ -33,6 +36,6 @@ extension MercuryImpl: Mercury {
let msgData = try await sendMessage(msg: msg),
let msgStr = String(data: msgData, encoding: .utf8)
else { return nil }
return try await self.unpackMessage(msg: msgStr)
return try? await self.unpackMessage(msg: msgStr)
}
}
2 changes: 1 addition & 1 deletion Mercury/Sources/MercuryImpl.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public struct MercuryImpl {

public init(
session: URLSession = .shared,
timeout: TimeInterval = 30,
timeout: TimeInterval = 999,
apollo: Apollo,
castor: Castor,
pluto: Pluto
Expand Down
6 changes: 4 additions & 2 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ let package = Package(
.package(url: "https://github.com/antlr/antlr4", branch: "master"),
.package(url: "https://github.com/input-output-hk/atala-prism-didcomm-swift", from: "0.3.4"),
.package(url: "https://github.com/input-output-hk/atala-prism-crypto-sdk-sp", from: "1.4.1"),
.package(url: "https://github.com/swift-libp2p/swift-multibase", branch: "main")
.package(url: "https://github.com/swift-libp2p/swift-multibase", branch: "main"),
.package(url:"https://github.com/IBM-Swift/Swift-JWT", from: "4.0.0")
],
targets: [
.target(
Expand All @@ -72,7 +73,8 @@ let package = Package(
dependencies: [
"Domain",
"Core",
.product(name: "PrismAPI", package: "atala-prism-crypto-sdk-sp")
.product(name: "PrismAPI", package: "atala-prism-crypto-sdk-sp"),
.product(name: "SwiftJWT", package: "Swift-JWT")
],
path: "Apollo/Sources"
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import Domain
extension CDVerifiableCredentialDAO: VerifiableCredentialProvider {
func getAll() -> AnyPublisher<[VerifiableCredential], Error> {
fetchController(context: readContext)
.tryMap { try $0.map { try $0.toDomain() } }
.tryMap {
try $0.map { try $0.toDomain() }
}
.eraseToAnyPublisher()
}

Expand All @@ -24,7 +26,7 @@ extension CDVerifiableCredentialDAO: VerifiableCredentialProvider {

extension CDVerifiableCredential {
func toDomain() throws -> VerifiableCredential {
switch self.credentialId {
switch self.credentialType {
case "jwt":
return try JSONDecoder()
.decode(JWTCredentialPayload.self, from: self.verifiableCredetialJson)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import CoreData
import Foundation

@objc(CDIssueCredentialProtocol)
class CDIssueCredentialProtocol: NSManagedObject {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import CoreData
import Foundation

extension CDIssueCredentialProtocol {
@nonobjc class func createFetchRequest() -> NSFetchRequest<CDIssueCredentialProtocol> {
return NSFetchRequest<CDIssueCredentialProtocol>(entityName: "CDIssueCredentialProtocol")
}

@NSManaged var protocolId: String
@NSManaged var threadId: String?
@NSManaged var credential: CDVerifiableCredential?
@NSManaged var issue: CDMessage?
@NSManaged var offer: CDMessage?
@NSManaged var propose: CDMessage?
@NSManaged var request: CDMessage?
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import CoreData
import Foundation

@objc(CDProofProtocol)
class CDProofProtocol: NSManagedObject {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import CoreData
import Foundation

extension CDProofProtocol {
@nonobjc class func createFetchRequest() -> NSFetchRequest<CDProofProtocol> {
return NSFetchRequest<CDProofProtocol>(entityName: "CDProofProtocol")
}

@NSManaged var protocolId: String
@NSManaged var threadId: String?
@NSManaged var presentation: CDMessage?
@NSManaged var propose: CDMessage?
@NSManaged var request: CDMessage?
}
Loading

0 comments on commit d55b511

Please sign in to comment.