diff --git a/.swiftlint.yml b/.swiftlint.yml index 1877b1ed..8ed716d4 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -80,19 +80,19 @@ excluded: - PrismAPISDK - Sources/PrismSwiftSDK/protobuf/* - Tests/PrismSwiftSDKTests - - Castor/Sources/DIDParser/DIDGrammar/* - - Castor/Tests - - Castor/Sources/protobuf - - Apollo/Tests - - Domain/Tests - - Authenticate/Tests - - Builders/Tests + - AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/* + - AtalaPrismSDK/Castor/Tests + - AtalaPrismSDK/Castor/Sources/protobuf + - AtalaPrismSDK/Apollo/Tests + - AtalaPrismSDK/Domain/Tests + - AtalaPrismSDK/Authenticate/Tests + - AtalaPrismSDK/Builders/Tests - Core/Tests - - Mercury/Tests - - Pluto/Tests - - Pollux/Tests - - PrismAgent/Tests - - Mercury/Sources/TestingConstants/* + - AtalaPrismSDK/Mercury/Tests + - AtalaPrismSDK/Pluto/Tests + - AtalaPrismSDK/Pollux/Tests + - AtalaPrismSDK/PrismAgent/Tests + - AtalaPrismSDK/Mercury/Sources/TestingConstants/* - Sample line_length: ignores_comments: true diff --git a/Apollo/Sources/ApolloImpl+Public.swift b/Apollo/Sources/ApolloImpl+Public.swift deleted file mode 100644 index ebd3b7a3..00000000 --- a/Apollo/Sources/ApolloImpl+Public.swift +++ /dev/null @@ -1,117 +0,0 @@ -import Domain -import Foundation -import SwiftJWT - -extension ApolloImpl: Apollo { - public func createRandomMnemonics() -> [String] { - RandomMnemonicsOperation(logger: ApolloImpl.logger).compute() - } - - public func createSeed(mnemonics: [String], passphrase: String) throws -> Seed { - try CreateSeedOperation(logger: ApolloImpl.logger, words: mnemonics, passphrase: passphrase).compute() - } - - public func createRandomSeed() -> (mnemonic: [String], seed: Seed) { - let words = createRandomMnemonics() - guard let seed = try? createSeed(mnemonics: words, passphrase: "") else { - fatalError(""" -This should never happen since the function that -returns random mnemonics nerver returns invalid mnemonics -""") - } - return (words, seed) - } - - public func createKeyPair(seed: Seed, curve: KeyCurve) -> KeyPair { - switch curve { - case .x25519: - return CreateX25519KeyPairOperation(logger: ApolloImpl.logger) - .compute() - case .ed25519: - return CreateEd25519KeyPairOperation(logger: ApolloImpl.logger) - .compute() - case let .secp256k1(index): - return CreateSec256k1KeyPairOperation( - logger: ApolloImpl.logger, - seed: seed, - keyPath: .init(index: index) - ).compute() - } - } - - public func createKeyPair(seed: Seed, privateKey: PrivateKey) throws -> KeyPair { - switch privateKey.curve { - case .secp256k1: - return createKeyPair(seed: seed, curve: privateKey.curve) - case .x25519: - return try CreateX25519KeyPairOperation(logger: ApolloImpl.logger) - .compute(fromPrivateKey: privateKey) - case .ed25519: - return try CreateEd25519KeyPairOperation(logger: ApolloImpl.logger) - .compute(fromPrivateKey: privateKey) - } - } - - public func compressedPublicKey(publicKey: PublicKey) -> CompressedPublicKey { - publicKey.compressed() - } - - public func compressedPublicKey(compressedData: Data) -> CompressedPublicKey { - CompressedPublicKey(compressedData: compressedData) - } - - public func signMessage(privateKey: PrivateKey, message: Data) -> Signature { - return SignMessageOperation( - logger: ApolloImpl.logger, - privateKey: privateKey, - message: message - ).compute() - } - - public func signMessage(privateKey: PrivateKey, message: String) throws -> Signature { - guard let data = message.data(using: .utf8) else { throw ApolloError.couldNotParseMessageString } - return signMessage(privateKey: privateKey, message: data) - } - - public func verifySignature(publicKey: PublicKey, challenge: Data, signature: Signature) -> Bool { - return VerifySignatureOperation( - logger: ApolloImpl.logger, - publicKey: publicKey, - challenge: challenge, - signature: signature - ).compute() - } - - public func getPrivateJWKJson(id: String, keyPair: KeyPair) throws -> String { - guard - let jsonString = try OctetKeyPair(id: id, from: keyPair).privateJson - else { throw CommonError.somethingWentWrongError } - return jsonString - } - - public func getPublicJWKJson(id: String, keyPair: KeyPair) throws -> String { - guard - let jsonString = try OctetKeyPair(id: id, from: keyPair).privateJson - 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(jwtVerifier: verifier) - return jwk - default: - let verifier = JWTVerifier.none - let decoder = JWTDecoder(jwtVerifier: verifier) - return jwk - } - } -} - -struct MyClaims: Claims { - let iss: String - let sub: String - let exp: Date -} diff --git a/AtalaPrismSDK/Apollo/Sources/Apollo.docc/Apollo.md b/AtalaPrismSDK/Apollo/Sources/Apollo.docc/Apollo.md new file mode 100644 index 00000000..d3b382da --- /dev/null +++ b/AtalaPrismSDK/Apollo/Sources/Apollo.docc/Apollo.md @@ -0,0 +1,41 @@ +# ``Apollo`` + +Apollo is a suite of cryptographic primitives designed to ensure the integrity, authenticity, and confidentiality of any data that is stored and processed. These primitives provide a provably secure way to protect sensitive information, and they can be used in a wide range of applications. + +## Cryptographic Primitives for Data Security + +### Hashing + +One of the basic building blocks of cryptography is the cryptographic hash, which is used to ensure the integrity of data. Hashing is frequently used to build more complex schemes, such as Merkle trees or digital signatures. Hashes can be used on their own to ensure the integrity of large chunks of data or as a basic commitment scheme. + +### Digital Signatures + +Digital signatures are the equivalent of handwritten signatures in the digital world. Owners of private signing keys create signatures, and anyone can check their validity with the corresponding public verification key. Most credentials carry a signature by their issuer. Digital signatures are used to ensure the authenticity and integrity of data. + +### Symmetric Encryption + +Symmetric encryption allows parties to exchange information while maintaining its secrecy. Given a symmetric key shared between parties, they can communicate securely. Symmetric encryption is a basic component for building secure communication channels. + +### Public-Key Encryption + +Public-key encryption uses a public encryption key to encrypt data so that only the owner of the corresponding private key can decrypt it. Public-key encryption is mostly used to encrypt symmetric keys or other (short) cryptographic values because of the high computational costs. + +### Accumulators + +Cryptographic accumulators allow for the accumulation of multiple values into one. Merkle trees are the most common type of accumulators used in the cryptocurrency domain. Accumulators make it possible to check (and prove) whether a given value has been accumulated or not. + +### MAC + +Message Authentication Codes are a type of symmetric equivalent of digital signatures. If two users share a symmetric key, they can use MAC algorithms to ensure the authenticity of the messages they exchange. The main difference between MACs and digital signatures is that MACs do not provide non-repudiation. + +### Key Exchange + +Key exchange protocols enable two or more parties to securely negotiate a symmetric key, even if they only know each other’s public keys. Key exchange protocols are used to establish secure communication channels. + +By using the Apollo suite of cryptographic primitives, developers can build secure and provably secure applications that protect sensitive data from unauthorized access, tampering, or theft. + +## Topics + +### Group + +- ``Symbol`` diff --git a/AtalaPrismSDK/Apollo/Sources/Apollo.docc/ApolloHowTo.md b/AtalaPrismSDK/Apollo/Sources/Apollo.docc/ApolloHowTo.md new file mode 100644 index 00000000..7bafb721 --- /dev/null +++ b/AtalaPrismSDK/Apollo/Sources/Apollo.docc/ApolloHowTo.md @@ -0,0 +1,103 @@ +# Apollo API Tutorial + +The Apollo protocol defines a set of functions for working with cryptography and key pairs. Here's a brief explanation of each function: + +- `createRandomMnemonics`: This function creates a random set of mnemonic phrases that can be used as a seed for generating a private key. + +```swift +// Example usage: +let mnemonics = ApolloImpl().createRandomMnemonics() +``` + +- `createSeed`: This function takes in a set of mnemonics and a passphrase, and returns a seed object used to generate a private key. It may throw an error if the mnemonics or passphrase are invalid. + +```swift +// Example usage: +do { + let apollo = ApolloImpl() + let mnemonics = ["word1", "word2", "word3", ...] + let passphrase = "passphrase" + let seed = try apollo.createSeed(mnemonics: mnemonics, passphrase: passphrase) +} catch { + // Handle error +} +``` + +- `createRandomSeed`: This function creates a random seed and a corresponding set of mnemonic phrases. + +```swift +// Example usage: +let (mnemonics, seed) = ApolloImpl().createRandomSeed() +``` + +- `createKeyPair`: This function creates a key pair (a private and public key) using a given seed and key curve. + +```swift +// Example usage: +let seed = Seed(...) +let curve = KeyCurve.secp256k1 +let keyPair = ApolloImpl().createKeyPair(seed: seed, curve: curve) +``` + +- `createKeyPair`: This function creates a key pair using a given seed and a specified private key. It may throw an error if the private key is invalid. + +```swift +// Example usage: +do { + let apollo = ApolloImpl() + let seed = Seed(...) + let privateKey = PrivateKey(...) + let keyPair = try apollo.createKeyPair(seed: seed, privateKey: privateKey) +} catch { + // Handle error +} +``` + +- `compressedPublicKey`: This function compresses a given public key into a shorter, more efficient form. + +```swift +// Example usage: +let publicKey = PublicKey(...) +let compressedPublicKey = ApolloImpl().compressedPublicKey(publicKey: publicKey) +``` + +- `compressedPublicKey`: This function decompresses a given compressed public key into its original form. + +```swift +// Example usage: +let compressedData = Data(...) +let decompressedPublicKey = ApolloImpl().compressedPublicKey(compressedData: compressedData) +``` + +- `signMessage`: This function signs a message using a given private key, returning the signature. + +```swift +// Example usage: +let privateKey = PrivateKey(...) +let message = Data(...) +let signature = ApolloImpl().signMessage(privateKey: privateKey, message: message) +``` + +- `signMessage`: This function signs a message using a given private key, returning the signature. It may throw an error if the message is invalid. + +```swift +// Example usage: +do { + let apollo = ApolloImpl() + let privateKey = PrivateKey(...) + let message = "hello world" + let signature = try apollo.signMessage(privateKey: privateKey, message: message) +} catch { + // Handle error +} +``` + +- `verifySignature`: This function verifies the authenticity of a signature using the corresponding public key, challenge, and signature. It returns a boolean value indicating whether the signature is valid or not. + +```swift +// Example usage: +let publicKey = PublicKey(...) +let challenge = Data(...) +let signature = Signature(...) +let isValid = ApolloImpl().verifySignature(publicKey: publicKey, challenge: challenge, signature: signature) +``` diff --git a/AtalaPrismSDK/Apollo/Sources/ApolloImpl+Public.swift b/AtalaPrismSDK/Apollo/Sources/ApolloImpl+Public.swift new file mode 100644 index 00000000..07631178 --- /dev/null +++ b/AtalaPrismSDK/Apollo/Sources/ApolloImpl+Public.swift @@ -0,0 +1,186 @@ +import Domain +import Foundation +import SwiftJWT + +extension ApolloImpl: Apollo { + /// createRandomMnemonics creates a random set of mnemonic phrases that can be used as a seed for generating a private key. + /// + /// - Returns: An array of mnemonic phrases + public func createRandomMnemonics() -> [String] { + RandomMnemonicsOperation(logger: ApolloImpl.logger).compute() + } + + /// createSeed takes in a set of mnemonics and a passphrase, and returns a seed object used to generate a private key. + /// This function may throw an error if the mnemonics or passphrase are invalid. + /// + /// - Parameters: + /// - mnemonics: An array of mnemonic phrases + /// - passphrase: A passphrase used to enhance the security of the seed + /// - Returns: A seed object + /// - Throws: An error if the mnemonics or passphrase are invalid + public func createSeed(mnemonics: [String], passphrase: String) throws -> Seed { + try CreateSeedOperation(logger: ApolloImpl.logger, words: mnemonics, passphrase: passphrase).compute() + } + + /// createRandomSeed creates a random seed and a corresponding set of mnemonic phrases. + /// + /// - Returns: A tuple containing an array of mnemonic phrases and a seed object + public func createRandomSeed() -> (mnemonic: [String], seed: Seed) { + let words = createRandomMnemonics() + guard let seed = try? createSeed(mnemonics: words, passphrase: "") else { + fatalError(""" +This should never happen since the function that +returns random mnemonics nerver returns invalid mnemonics +""") + } + return (words, seed) + } + + /// createKeyPair creates a key pair (a private and public key) using a given seed and key curve. + /// + /// - Parameters: + /// - seed: A seed object used to generate the key pair + /// - curve: The key curve to use for generating the key pair + /// - Returns: A key pair object containing a private and public key + public func createKeyPair(seed: Seed, curve: KeyCurve) -> KeyPair { + switch curve { + case .x25519: + return CreateX25519KeyPairOperation(logger: ApolloImpl.logger) + .compute() + case .ed25519: + return CreateEd25519KeyPairOperation(logger: ApolloImpl.logger) + .compute() + case let .secp256k1(index): + return CreateSec256k1KeyPairOperation( + logger: ApolloImpl.logger, + seed: seed, + keyPath: .init(index: index) + ).compute() + } + } + + /// createKeyPair creates a key pair using a given seed and a specified private key. This function may throw an error if the private key is invalid. + /// + /// - Parameters: + /// - seed: A seed object used to generate the key pair + /// - privateKey: The private key to use for generating the key pair + /// - Returns: A key pair object containing a private and public key + /// - Throws: An error if the private key is invalid + public func createKeyPair(seed: Seed, privateKey: PrivateKey) throws -> KeyPair { + switch privateKey.curve { + case .secp256k1: + return createKeyPair(seed: seed, curve: privateKey.curve) + case .x25519: + return try CreateX25519KeyPairOperation(logger: ApolloImpl.logger) + .compute(fromPrivateKey: privateKey) + case .ed25519: + return try CreateEd25519KeyPairOperation(logger: ApolloImpl.logger) + .compute(fromPrivateKey: privateKey) + } + } + + /// compressedPublicKey compresses a given public key into a shorter, more efficient form. + /// + /// - Parameter publicKey: The public key to compress + /// - Returns: The compressed public key + public func compressedPublicKey(publicKey: PublicKey) -> CompressedPublicKey { + publicKey.compressed() + } + + /// compressedPublicKey decompresses a given compressed public key into its original form. + /// + /// - Parameter compressedData: The compressed public key data + /// - Returns: The decompressed public key + public func compressedPublicKey(compressedData: Data) -> CompressedPublicKey { + CompressedPublicKey(compressedData: compressedData) + } + + /// signMessage signs a message using a given private key, returning the signature. + /// + /// - Parameters: + /// - privateKey: The private key to use for signing the message + /// - message: The message to sign, in binary data form + /// - Returns: The signature of the message + public func signMessage(privateKey: PrivateKey, message: Data) -> Signature { + return SignMessageOperation( + logger: ApolloImpl.logger, + privateKey: privateKey, + message: message + ).compute() + } + + /// signMessage signs a message using a given private key, returning the signature. This function may throw an error if the message is invalid. + /// + /// - Parameters: + /// - privateKey: The private key to use for signing the message + /// - message: The message to sign, in string form + /// - Returns: The signature of the message + /// - Throws: An error if the message is invalid + public func signMessage(privateKey: PrivateKey, message: String) throws -> Signature { + guard let data = message.data(using: .utf8) else { throw ApolloError.couldNotParseMessageString } + return signMessage(privateKey: privateKey, message: data) + } + + /// verifySignature verifies the authenticity of a signature using the corresponding public key, challenge, and signature. This function returns a boolean value indicating whether the signature is valid or not. + /// + /// - Parameters: + /// - publicKey: The public key associated with the signature + /// - challenge: The challenge used to generate the signature + /// - signature: The signature to verify + /// - Returns: A boolean value indicating whether the signature is valid or not + public func verifySignature(publicKey: PublicKey, challenge: Data, signature: Signature) -> Bool { + return VerifySignatureOperation( + logger: ApolloImpl.logger, + publicKey: publicKey, + challenge: challenge, + signature: signature + ).compute() + } + + /// getPrivateJWKJson converts a private key pair into a JSON Web Key (JWK) format with a given ID. This function may throw an error if the key pair is invalid. + /// + /// - Parameters: + /// - id: The ID to use for the JWK + /// - keyPair: The private key pair to convert to JWK format + /// - Returns: The private key pair in JWK format, as a string + /// - Throws: An error if the key pair is invalid + public func getPrivateJWKJson(id: String, keyPair: KeyPair) throws -> String { + guard + let jsonString = try OctetKeyPair(id: id, from: keyPair).privateJson + else { throw ApolloError.invalidJWKError } + return jsonString + } + + /// getPublicJWKJson converts a public key pair into a JSON Web Key (JWK) format with a given ID. This function may throw an error if the key pair is invalid. + /// + /// - Parameters: + /// - id: The ID to use for the JWK + /// - keyPair: The public key pair to convert to JWK format + /// - Returns: The public key pair in JWK format, as a string + /// - Throws: An error if the key pair is invalid + public func getPublicJWKJson(id: String, keyPair: KeyPair) throws -> String { + guard + let jsonString = try OctetKeyPair(id: id, from: keyPair).privateJson + else { throw ApolloError.invalidJWKError } + 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(jwtVerifier: verifier) + return jwk + default: + let verifier = JWTVerifier.none + let decoder = JWTDecoder(jwtVerifier: verifier) + return jwk + } + } +} + +struct MyClaims: Claims { + let iss: String + let sub: String + let exp: Date +} diff --git a/Apollo/Sources/ApolloImpl.swift b/AtalaPrismSDK/Apollo/Sources/ApolloImpl.swift similarity index 100% rename from Apollo/Sources/ApolloImpl.swift rename to AtalaPrismSDK/Apollo/Sources/ApolloImpl.swift diff --git a/Apollo/Sources/Extensions/CompressedPublicKey+Helpers.swift b/AtalaPrismSDK/Apollo/Sources/Extensions/CompressedPublicKey+Helpers.swift similarity index 100% rename from Apollo/Sources/Extensions/CompressedPublicKey+Helpers.swift rename to AtalaPrismSDK/Apollo/Sources/Extensions/CompressedPublicKey+Helpers.swift diff --git a/Apollo/Sources/Extensions/PrivateKey+Helpers.swift b/AtalaPrismSDK/Apollo/Sources/Extensions/PrivateKey+Helpers.swift similarity index 100% rename from Apollo/Sources/Extensions/PrivateKey+Helpers.swift rename to AtalaPrismSDK/Apollo/Sources/Extensions/PrivateKey+Helpers.swift diff --git a/Apollo/Sources/Extensions/PublicKey+Compressed.swift b/AtalaPrismSDK/Apollo/Sources/Extensions/PublicKey+Compressed.swift similarity index 100% rename from Apollo/Sources/Extensions/PublicKey+Compressed.swift rename to AtalaPrismSDK/Apollo/Sources/Extensions/PublicKey+Compressed.swift diff --git a/Apollo/Sources/Helper/KotlinHelper.swift b/AtalaPrismSDK/Apollo/Sources/Helper/KotlinHelper.swift similarity index 100% rename from Apollo/Sources/Helper/KotlinHelper.swift rename to AtalaPrismSDK/Apollo/Sources/Helper/KotlinHelper.swift diff --git a/Apollo/Sources/Model/OctetKeyPair.swift b/AtalaPrismSDK/Apollo/Sources/Model/OctetKeyPair.swift similarity index 100% rename from Apollo/Sources/Model/OctetKeyPair.swift rename to AtalaPrismSDK/Apollo/Sources/Model/OctetKeyPair.swift diff --git a/Apollo/Sources/Operations/CreateEd25519KeyPairOperation.swift b/AtalaPrismSDK/Apollo/Sources/Operations/CreateEd25519KeyPairOperation.swift similarity index 100% rename from Apollo/Sources/Operations/CreateEd25519KeyPairOperation.swift rename to AtalaPrismSDK/Apollo/Sources/Operations/CreateEd25519KeyPairOperation.swift diff --git a/Apollo/Sources/Operations/CreateSec256k1KeyPairOperation.swift b/AtalaPrismSDK/Apollo/Sources/Operations/CreateSec256k1KeyPairOperation.swift similarity index 100% rename from Apollo/Sources/Operations/CreateSec256k1KeyPairOperation.swift rename to AtalaPrismSDK/Apollo/Sources/Operations/CreateSec256k1KeyPairOperation.swift diff --git a/Apollo/Sources/Operations/CreateSeedOperation.swift b/AtalaPrismSDK/Apollo/Sources/Operations/CreateSeedOperation.swift similarity index 54% rename from Apollo/Sources/Operations/CreateSeedOperation.swift rename to AtalaPrismSDK/Apollo/Sources/Operations/CreateSeedOperation.swift index 29d0c106..fb4515d0 100644 --- a/Apollo/Sources/Operations/CreateSeedOperation.swift +++ b/AtalaPrismSDK/Apollo/Sources/Operations/CreateSeedOperation.swift @@ -13,18 +13,18 @@ struct CreateSeedOperation { self.logger = logger self.words = words self.passphrase = passphrase - guard - words.allSatisfy({ - if !keyDerivation.isValidMnemonicWord(word: $0) { - logger.error( - message: "Invalid mnemonic word", - metadata: [.publicMetadata(key: "word", value: $0)] - ) - return false - } - return true - }) - else { throw ApolloError.invalidMnemonicWord } + let invalidWords = words.filter { !keyDerivation.isValidMnemonicWord(word: $0) } + guard invalidWords.isEmpty else { + logger.error( + message: "Invalid mnemonic word", + metadata: invalidWords + .enumerated() + .map { + .publicMetadata(key: "word\($0)", value: $1) + } + ) + throw ApolloError.invalidMnemonicWord(invalidWords: invalidWords) + } } func compute() -> Seed { diff --git a/Apollo/Sources/Operations/CreateX25519KeyPairOperation.swift b/AtalaPrismSDK/Apollo/Sources/Operations/CreateX25519KeyPairOperation.swift similarity index 100% rename from Apollo/Sources/Operations/CreateX25519KeyPairOperation.swift rename to AtalaPrismSDK/Apollo/Sources/Operations/CreateX25519KeyPairOperation.swift diff --git a/Apollo/Sources/Operations/RandomMnemonicsOperation.swift b/AtalaPrismSDK/Apollo/Sources/Operations/RandomMnemonicsOperation.swift similarity index 100% rename from Apollo/Sources/Operations/RandomMnemonicsOperation.swift rename to AtalaPrismSDK/Apollo/Sources/Operations/RandomMnemonicsOperation.swift diff --git a/Apollo/Sources/Operations/SignMessageOperation.swift b/AtalaPrismSDK/Apollo/Sources/Operations/SignMessageOperation.swift similarity index 100% rename from Apollo/Sources/Operations/SignMessageOperation.swift rename to AtalaPrismSDK/Apollo/Sources/Operations/SignMessageOperation.swift diff --git a/Apollo/Sources/Operations/VerifySignatureOperation.swift b/AtalaPrismSDK/Apollo/Sources/Operations/VerifySignatureOperation.swift similarity index 100% rename from Apollo/Sources/Operations/VerifySignatureOperation.swift rename to AtalaPrismSDK/Apollo/Sources/Operations/VerifySignatureOperation.swift diff --git a/Apollo/Tests/ApolloTest.swift b/AtalaPrismSDK/Apollo/Tests/ApolloTest.swift similarity index 100% rename from Apollo/Tests/ApolloTest.swift rename to AtalaPrismSDK/Apollo/Tests/ApolloTest.swift diff --git a/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/AtalaPrismSDK.md b/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/AtalaPrismSDK.md new file mode 100644 index 00000000..b0c0a9ae --- /dev/null +++ b/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/AtalaPrismSDK.md @@ -0,0 +1,50 @@ +# ``AtalaPrismSDK`` + +Atala PRISM Swift SDK is a library and documentation that helps developers build Apple connected SSI (self-sovereign identity) applications with Atala PRISM. This documentation will explain how to use the SDK in your project, how to prepare your development environment if you wish to contribute, and some basic considerations around the project. + +### Atala PRISM + +![Atala Prism Logo](logo) + +Atala PRISM is a self-sovereign identity (SSI) platform and service suite for verifiable data and digital identity. Built on Cardano, it offers core infrastructure for issuing DIDs and verifiable credentials, alongside tools and frameworks to help expand your ecosystem. + +## Features / APIs + +Atala PRISM Swift SDK provides the following building blocks to create, manage and resolve decentralized identifiers, issue, manage and verify verifiable credentials, establish and manage trusted, peer-to-peer connections and interactions between DIDs, and store, manage, and recover verifiable data linked to DIDs. + +- __Castor__: Building block that provides a suit of DID operations in a user-controlled manner. +- __Pollux__: Building block that provides a suite of credential operations in a privacy-preserving manner. +- __Mercury__: Building block that provides a set of secure, standards-based communications protocols in a transport-agnostic and interoperable manner. +- __Pluto__: Building block that provides an interface for storage operations in a portable, storage-agnostic manner. +- __Experience__: Set of commonly used operations or features that use one or multiple building blocks. + +## Getting Started + +### Setup + +To get started with the Atala PRISM Swift SDK, you can set up the SDK and start a new project, or you can integrate the SDK in an existing project. Before you start, make sure you have the following installed on your development machine: + +- Xcode 13.4 or later +- MacOS 12 or later +- iOS 13 or later + +> ⚠️ **Currently you need to always open the XCode in ROSETTA mode** + +### Integrating the SDK in an existing project + +To integrate the SDK into an existing project, you can use the Swift Package Manager, which is distributed with Xcode. + +1. Open your project in Xcode and select **File > Swift Packages > Add Package Dependency**. +2. Enter the URL for the SDK for Swift Package Manager GitHub repo (`https://github.com/input-output-hk/atala-prism-swift-sdk`) into the search bar and click **Next**. +3. You'll see the repository rules for which version of the SDK you want Swift Package Manager to install. Choose the first rule, **Version**, and select **Up to Next Minor** as it will use the latest compatible version of the dependency that can be detected from the `main` branch, then click **Next**. + +### Swift Package Manager + +The Swift Package Manager is a tool for managing the distribution of Swift code. It's integrated with the Swift build system to automate the process of downloading, compiling, and linking dependencies. + +## Documentation + +- [Getting Started](https://staging-docs.atalaprism.io/docs/getting-started) +- [What is identity?](https://staging-docs.atalaprism.io/docs/concepts/what-is-identity) +- [Digital wallets](https://staging-docs.atalaprism.io/docs/concepts/digital-wallets) +- [Atala PRISM Overview](https://staging-docs.atalaprism.io/docs/atala-prism/overview) diff --git a/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/ErrorHandling/ApolloErrors.md b/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/ErrorHandling/ApolloErrors.md new file mode 100644 index 00000000..bcd95bb4 --- /dev/null +++ b/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/ErrorHandling/ApolloErrors.md @@ -0,0 +1,57 @@ +# Apollo Errors + +This is an enum definition named `ApolloError` that conforms to `KnownPrismError` protocol. The enum has three cases, and each case represents an error scenario with a message that describes the reason for the error. + +## Error 1: Invalid Mnemonic Word + +Code: 11 +Message: "The following mnemonic words are invalid: {invalidWords}" + +This error occurs when the given mnemonic words are invalid. The reason for this error could be due to the following possible reasons: + +- The mnemonic phrase is incorrect. +- The given mnemonic word is not a valid English word. +- The order of the mnemonic words is incorrect. + +The recovery solutions for this error are: + +- Check if the mnemonic phrase is correct. +- Check if the given words are valid English words. +- Verify if the order of the words is correct. + + +## Error 2: Could Not Parse Message String + +Code: 12 +Message: "Could not get UTF8 Data from message string" + +This error occurs when the UTF8 data from the message string could not be retrieved. The reason for this error could be due to the following possible reasons: + +- The message string is empty. +- The message string has invalid characters. +- There is an issue with the encoding of the message string. + +The recovery solutions for this error are: + +- Check if the message string is not empty. +- Check if the message string contains only valid characters. +- Verify if the encoding of the message string is correct. + + +## Error 3: Invalid JWK Error + +Code: 13 +Message: "JWK is not in a valid format" + +This error occurs when the JWK (JSON Web Key) is not in a valid format. The reason for this error could be due to the following possible reasons: + +- The JWK is incomplete. +- The JWK contains invalid fields. +- The JWK is not in the correct format. + +The recovery solutions for this error are: + +- Check if the JWK is complete. +- Verify if the fields in the JWK are valid. +- Verify if the JWK is in the correct format. +- Code and Message for Each Error diff --git a/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/ErrorHandling/CastorErrors.md b/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/ErrorHandling/CastorErrors.md new file mode 100644 index 00000000..7d71872b --- /dev/null +++ b/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/ErrorHandling/CastorErrors.md @@ -0,0 +1,133 @@ +# Castor Errors + +This is an enum definition named `CastorError` that conforms to `KnownPrismError` protocol. The enum has several cases, and each case represents an error scenario with a message that describes the reason for the error. + +## Error 1: Key Curve Not Supported + +Code: 21 +Message: "Key curve {curve} is not supported for this functionality" + +This error occurs when a key curve is not supported for a specific functionality. The reason for this error could be due to the following possible reasons: + +- The key curve is not supported for the specific functionality. +- The key curve is not valid. + +The recovery solutions for this error are: + +- Check if the key curve is supported for the specific functionality. +- Verify if the key curve is valid. + +## Error 2: Invalid Long Form DID + +Code: 22 +Message: "Long form prism DID is invalid or changed" + +This error occurs when the Long form prism DID is invalid or changed. The reason for this error could be due to the following possible reasons: + +- The Long form prism DID is invalid. +- The Long form prism DID has been changed. + +The recovery solutions for this error are: + +- Check if the Long form prism DID is valid. +- Verify if the Long form prism DID has been changed. + +### Error 3: Method ID Does Not Satisfy Regex + +Code: 23 +Message: "The Prism DID provided is not passing the regex validation: {regex}" + +This error occurs when the Prism DID provided is not passing the regex validation. The reason for this error could be due to the following possible reasons: + +- The Prism DID is not passing the regex validation. + +## Error 4: Invalid Public Key Coding + +Code: 24 +Message: "Invalid encoding/decoding of key ({curve}) while trying to compute {didMethod}" + +This error occurs when there is invalid encoding/decoding of key while trying to compute a DID method. The reason for this error could be due to the following possible reasons: + +- There is invalid encoding/decoding of the key. +- There is an issue with the DID method. + +The recovery solutions for this error are: + +- Verify if there is valid encoding/decoding of the key. +- Check if the DID method is correct. + +## Error 5: Invalid DID String + +Code: 25 +Message: "Trying to parse invalid DID String: {str}" + +This error occurs when trying to parse an invalid DID string. The reason for this error could be due to the following possible reasons: + +- The DID string is not in the correct format. +- The DID string is not valid. + +The recovery solutions for this error are: + +- Verify if the DID string is in the correct format. +- Check if the DID string is valid. + +## Error 6: Initial State of DID Changed + +Code: 26 +Message: "While trying to resolve Prism DID state changed making it invalid" + +This error occurs when trying to resolve a Prism DID, the initial state changed, making it invalid. The reason for this error could be due to the following possible reasons: + +- The initial state of the Prism DID has changed. +- There is an issue with resolving the Prism DID. + +The recovery solutions for this error are: + +- Check if the initial state of the Prism DID has changed. + +## Error 7: Not Possible to Resolve DID + +Code: 27 +Message: "Not possible to resolve DID ({did}) due to {reason}" + +This error occurs when it is not possible to resolve a Prism DID due to a specific reason. The reason for this error could be due to the following possible reasons: + +- The Prism DID is not resolvable. +- There is an issue with the resolver. + +The recovery solutions for this error are: + +- Check if the Prism DID is resolvable. +- Verify if there is an issue with the resolver. + +## Error 8: Invalid JWK Error + +Code: 28 +Message: "JWK is not in a valid format" + +This error occurs when the JWK (JSON Web Key) is not in a valid format. The reason for this error could be due to the following possible reasons: + +- The JWK is incomplete. +- The JWK contains invalid fields. +- The JWK is not in the correct format. + +The recovery solutions for this error are: + +- Check if the JWK is complete. +- Verify if the fields in the JWK are valid. +- Verify if the JWK is in the correct format. + +## Error 9: No Resolvers Available for DID Method + +Code: 29 +Message: "No resolvers in castor are able to resolve the method {method}, please provide a resolver" + +This error occurs when no resolvers in Castor are able to resolve the method. The reason for this error could be due to the following possible reasons: + +- There are no resolvers available for the DID method. +- There is an issue and the resolver cannot resolve the DID. + +The recovery solutions for this error are: + +- Check if there are resolvers available for the DID method. +- Verify if there is an issue with the resolver. diff --git a/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/ErrorHandling/ErrorHandling.md b/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/ErrorHandling/ErrorHandling.md new file mode 100644 index 00000000..f7b227c3 --- /dev/null +++ b/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/ErrorHandling/ErrorHandling.md @@ -0,0 +1,107 @@ +# Error Handling + +When working with SDKs, it is common to encounter errors that are specific to that SDK. These errors may be related to network connectivity, server-side errors, or invalid user inputs, among others. To handle these errors, SDKs often define custom error types that you can catch and handle in your application. + +## Overview + +Custom errors in Swift are typically defined using an enum. In most cases, custom errors will fall into one of two categories: + +Known errors that can be identified and handled explicitly using a specific error code and message. +Unknown errors that cannot be identified explicitly but may provide additional information about the error. +To handle these errors, you need to understand the types of errors that can occur and how to handle them. + +## Handling Known Errors + +Known errors are errors that are specific to the SDK and are defined using an enum. These errors typically have a specific error code and message associated with them, which you can use to identify and handle the error. + +To handle known errors, you need to first define a catch block that catches the error thrown by the SDK. Once you have caught the error, you can then switch on the error code to determine the specific error that occurred and take appropriate action. + +Here is an example of how you can handle known errors in an SDK: + +```swift +do { + let result = try agent.doSomething() + // Do something with the result +} catch let error as KnownSDKError { + switch error.code { + case 100: + // Handle error 100 + break + case 101: + // Handle error 101 + break + default: + // Handle any other error + break + } +} catch { + // Handle any other error +} +``` + +In the example above, we catch errors thrown by the SDK and switch on the error code to determine the specific error that occurred. Depending on the error code, we take appropriate action, such as showing an error message to the user or retrying the operation. + +## Handling Unknown Errors + +Unknown errors are errors that cannot be identified explicitly but may provide additional information about the error. These errors typically provide a message that describes the error and may contain one or more underlying errors that caused the error. + +To handle unknown errors, you need to first define a catch block that catches the error thrown by the SDK. Once you have caught the error, you can then check if the error conforms to the UnknownSDKError protocol, which defines the properties code, message, and underlyingErrors. You can use these properties to provide additional information about the error and take appropriate action. + +Here is an example of how you can handle unknown errors in an SDK: + +```swift +do { + let result = try agent.doSomething() + // Do something with the result +} catch let error as UnknownSDKError { + if let code = error.code { + // Handle error with code + } + if let message = error.message { + // Handle error with message + } + if let underlyingErrors = error.underlyingErrors { + // Handle any underlying errors + } +} catch { + // Handle any other error +} +``` + +## Common Errors + +This is an enum definition named `CommonError` that conforms to the `KnownPrismError` protocol. The enum has two cases, and each case represents an error scenario with a message that describes the reason for the error. + +### Error 1: Invalid URL + +This error occurs when an invalid URL is encountered while trying to send a message. The reason for this error could be due to the following possible reasons: + +- The URL is not in the correct format. +- The URL is not valid. + +The recovery solutions for this error are: + +- Verify if the URL is in the correct format. +- Check if the URL is valid. + +### Error 2: HTTP Error + +This error occurs when an HTTP error is encountered while trying to send a message. The reason for this error could be due to the following possible reasons: + +- The HTTP response code is not successful. +- There is an issue with the message. + +The recovery solutions for this error are: + +- Verify the HTTP response code. +- Check if there is an issue with the message. + +## Topics + +### Errors + +- +- +- +- +- diff --git a/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/ErrorHandling/MercuryErrors.md b/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/ErrorHandling/MercuryErrors.md new file mode 100644 index 00000000..6c0fdbb3 --- /dev/null +++ b/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/ErrorHandling/MercuryErrors.md @@ -0,0 +1,89 @@ +# Mercury Errors + +This is an enum definition named `MercuryError` that conforms to `KnownPrismError` protocol. The enum has several cases, and each case represents an error scenario with a message that describes the reason for the error. + +### Error 1: No Recipient DID Set + +This error occurs when there is no recipient set in the message. The reason for this error could be due to the following possible reasons: + +- The recipient is not set. +- The recipient value is not valid. + +The recovery solutions for this error are: + +- Verify if the recipient is set. +- Check if the recipient value is valid. + +### Error 2: No Valid Service Found + +This error occurs when there are no valid services found for a specific DID. The reason for this error could be due to the following possible reasons: + +- There are no valid services found for the DID. +- The DID is not valid. + +The recovery solutions for this error are: + +- Verify if there are valid services available for the DID. +- Check if the DID is valid. + +### Error 3: No Sender DID Set + +This error occurs when there is no sender set in the message. The reason for this error could be due to the following possible reasons: + +- The sender is not set. +- The sender value is not valid. + +The recovery solutions for this error are: + +- Verify if the sender is set. +- Check if the sender value is valid. + +### Error 4: Unknown Attachment Data Type + +This error occurs when an unknown AttachmentData type is found while decoding a message. The reason for this error could be due to the following possible reasons: + +- The AttachmentData type is unknown. +- The AttachmentData format is invalid. + +The recovery solutions for this error are: + +- Verify if the AttachmentData type is known. +- Check if the AttachmentData format is valid. + +### Error 5: Message Attachment Without ID + +This error occurs when decoding a message, and a message attachment is found without an "id" value, which is invalid. The reason for this error could be due to the following possible reasons: + +- The message attachment does not have an "id" value. +- The message attachment format is invalid. + +The recovery solutions for this error are: + +- Verify if the message attachment has an "id" value. +- Check if the message attachment format is valid. + +### Error 6: Message Invalid Body Data + +This error occurs when decoding a message, and the message body is found to be invalid. The reason for this error could be due to the following possible reasons: + +- The message body is not valid. +- The message body format is invalid. + +The recovery solutions for this error are: + +- Verify if the message body is valid. +- Check if the message body format is valid. + +### Error 7: DIDComm Error + +This error occurs when there is an error in the DIDComm protocol. The reason for this error could be due to the following possible reasons: + +- There is an issue with the DIDComm protocol. +- The message is not valid. +- DIDComm could not find secrets (did private keys) to pack the message. + +The recovery solutions for this error are: + +- Verify if there is an issue with the DIDComm protocol. +- Check if the message is valid. +- Check if the secret resolver is finding and providing the secrets. diff --git a/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/ErrorHandling/PlutoErrors.md b/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/ErrorHandling/PlutoErrors.md new file mode 100644 index 00000000..2d5f8323 --- /dev/null +++ b/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/ErrorHandling/PlutoErrors.md @@ -0,0 +1,59 @@ +# Pluto Errors + +This is an enum definition named `PlutoError` that conforms to the `KnownPrismError` protocol. The enum has several cases, and each case represents an error scenario with a message that describes the reason for the error. + +### Error 1: Missing Data Persistence + +This error occurs when the data persistence for a specific type is missing. The reason for this error could be due to the following possible reasons: + +- A required data is not persisted. + +The recovery solutions for this error are: + +- Verify that all requirements are correctly persisted before executing this task. + +### Error 2: Missing Required Fields + +This error occurs when a specific type is missing required fields. The reason for this error could be due to the following possible reasons: + +- The required fields are not set. +- The required fields are not valid. + +The recovery solutions for this error are: + +- Verify if the required fields are set. +- Check if the required fields are valid. + +### Error 3: Duplication + +This error occurs when trying to save a record that already exists. The reason for this error could be due to the following possible reasons: + +- The record is already saved. +- The record has already been created. + +The recovery solutions for this error are: + +- Verify if the record is already saved. +- Check if the record has already been created. + +### Error 4: Unknown Credential Type + +This error occurs when the credential type is unknown. The reason for this error could be due to the following possible reasons: + +- The credential type is not recognized, it should be W3C or JWT. + +The recovery solutions for this error are: + +- Check if the credential type is valid. + +### Error 5: Invalid Credential JSON + +This error occurs when the credential JSON is invalid. The reason for this error could be due to the following possible reasons: + +- The credential JSON is not formatted correctly. +- The credential JSON is not valid. + +The recovery solutions for this error are: + +- Verify if the credential JSON is formatted correctly. +- Check if the credential JSON is valid. diff --git a/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/ErrorHandling/PrismAgentErrors.md b/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/ErrorHandling/PrismAgentErrors.md new file mode 100644 index 00000000..51ab09a4 --- /dev/null +++ b/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/ErrorHandling/PrismAgentErrors.md @@ -0,0 +1,75 @@ +# PrismAgent Errors + +This is an enum definition named `PrismAgentError` that conforms to the `KnownPrismError` protocol. The enum has several cases, and each case represents an error scenario with a message that describes the reason for the error. + +### Error 1: Cannot Find DID Key Pair Index + +This error occurs when trying to sign a DID, but the key pair index cannot be found. The reason for this error could be due to the following possible reasons: + +- The key pair is not registered. +- There is a bug in the code. + +The recovery solutions for this error are: + +- Verify if the key pair is registered. +- Check if there is a bug in the code. + +### Error 2: Invitation Is Invalid + +This error occurs when the invitation cannot be parsed, and the message/JSON is invalid. The reason for this error could be due to the following possible reasons: + +- The invitation message/JSON is not formatted correctly. +- The invitation message/JSON is not valid. + +The recovery solutions for this error are: + +- Verify if the invitation message/JSON is formatted correctly. +- Check if the invitation message/JSON is valid. + +### Error 3: Unknown Invitation Type + +This error occurs when the type of invitation is not supported. The reason for this error could be due to the following possible reasons: + +- The type of invitation is not recognized. +- The type of invitation is not valid. + +The recovery solutions for this error are: + +- Verify if the type of invitation is recognized. +- Check if the type of invitation is valid. + +### Error 4: Invalid Message Type + +This error occurs when the message type is invalid. The reason for this error could be due to the following possible reasons: + +- The message type does not represent the protocol. +- The message type does not have "from" and "to" fields. + +The recovery solutions for this error are: + +- Verify if the message type represents the protocol. +- Check if the message type has "from" and "to" fields. + +### Error 5: No Mediator Available + +This error occurs when there is no mediator available. The reason for this error could be due to the following possible reasons: + +- The mediator is not set up. +- The mediator is not available. + +The recovery solutions for this error are: + +- Verify if the mediator is set up. +- Check if the mediator is available. + +### Error 6: Mediation Request Failed + +This error occurs when the mediation request fails. The reason for this error could be due to the following possible reasons: + +- There are underlying errors. +- The mediation handler is not set up. + +The recovery solutions for this error are: + +- Verify if there are underlying errors. +- Check if the mediation handler is set up. diff --git a/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/Logging/Logging.md b/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/Logging/Logging.md new file mode 100644 index 00000000..23b9dd47 --- /dev/null +++ b/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/Logging/Logging.md @@ -0,0 +1,60 @@ +# Logging + +## Setup + +To set up logging, you can use the setupLogging method in the PrismAgent class, passing in a dictionary of LogComponent and LogLevel pairs. LogComponent is an enumeration that represents different components in the SDK, such as prism, didcomm, and apollo. LogLevel is an enumeration that represents different levels of logging, such as debug, info, and error. + +Here's an example of setting up logging: + +```swift +let logLevels: [LogComponent: LogLevel] = [ + .prismAgent: .debug, + .mercury: .debug, + .apollo: .info +] +PrismAgent.setupLogging(logLevels: logLevels) +``` + +## Logging messages + +The SDK will log events at different log levels using the debug, info, warning, error, etc methods: + +```swift +logger.debug(message: "This is a debug message.") +logger.info(message: "This is an info message.") +logger.warning(message: "This is a warning message.") +logger.error(message: "This is an error message.") +``` + +The output of this code will look something like this: + +``` +2022-03-01T14:54:06+0000 debug [ Module ] : This is a debug message. +2022-03-01T14:54:06+0000 info [ Module ] : This is an info message. +2022-03-01T14:54:06+0000 warning [ Module ] : This is a warning message. +2022-03-01T14:54:06+0000 error [ Module ] : This is an error message. +``` + +The first part of the output shows the timestamp of the log message, followed by the logging level, the logging component (in this case, myCategory), and the log message itself. + +In some case also pass metadata to the log to provide additional context for the log message. There are three types of metadata: publicMetadata, privateMetadata, and maskedMetadata. publicMetadata is metadata that is safe to expose publicly, privateMetadata is metadata that should not be exposed publicly, and maskedMetadata is metadata that should be masked in the log output. Here's an example: + +```swift +logger.debug(message: "Test public metadata", metadata: [.publicMetadata(key: "TestKey", value: "TestValue")]) +logger.info(message: "Test private metadata", metadata: [.privateMetadata(key: "TestKey", value: "TestValue")]) +logger.debug(message: "Test equal masked metadata", metadata: [.maskedMetadata(key: "TestKey", value: "TestEqualValue")]) +logger.debug(message: "Test equal masked metadata", metadata: [.maskedMetadata(key: "TestKey", value: "TestEqualValue")]) +logger.debug(message: "Test different masked metadata", metadata: [.maskedMetadata(key: "TestKey", value: "TestDifferentValue")]) +``` + +This will output the following log messages: + +``` +2022-04-07T18:20:17+0100 debug [ io.prism.swift.sdk.apollo ] : TestKey=TestValue Test public metadata +2022-04-07T18:20:17+0100 info [ io.prism.swift.sdk.apollo ] : TestKey=------ Test private metadata +2022-04-07T18:20:17+0100 debug [ io.prism.swift.sdk.apollo ] : TestKey={Random generated identifier 1} Test equal masked metadata +2022-04-07T18:20:17+0100 debug [ io.prism.swift.sdk.apollo ] : TestKey={Random generated identifier 1} Test equal masked metadata +2022-04-07T18:20:17+0100 debug [ io.prism.swift.sdk.apollo ] : TestKey={Random generated identifier 2} Test different masked metadata +``` + + diff --git a/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/Mediation.md b/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/Mediation.md new file mode 100644 index 00000000..07d5ebbb --- /dev/null +++ b/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/Mediation.md @@ -0,0 +1,37 @@ +# Mediation and Forward Messaging + +The SDK provides a set of functionalities that enable communication between different entities through DIDs and DIDComm protocols. One of the core features of the SDK is the ability to send and receive messages, which is achieved by using the DIDComm protocol. + +## DIDComm Mediation + +However, the use cases for the SDK often cannot rely on the ability to have open endpoints where they can listen to incoming messages. For instance, mobile apps running on iOS or Android platforms typically cannot have an open port to listen for incoming messages. + +To address this limitation, the SDK provides support for DIDComm mediation. DIDComm mediation is a mechanism that enables the communication between two parties that cannot communicate directly by routing messages through one or more mediators. This mechanism allows the SDK to work even in situations where a direct communication path is not possible. + +The mediator is identified through a DID (Decentralized Identifier) that is shared between the two parties. The DID is used to send the message to the mediator, who then relays it to the recipient. The mediator can perform additional functions such as message validation, translation, or modification. + +The use of a mediator in the SDK allows for the following benefits: + +- __Secure communication:__ With DIDComm mediation, the SDK provides a secure way to communicate even when direct communication is not possible. +- __Flexibility:__ The use of a mediator allows the SDK to be used in a wide range of scenarios where direct communication is not possible or practical. +- __Scalability:__ The use of a mediator allows the SDK to scale to large deployments with many entities communicating with each other. + +To achieve this, the mediator needs to have established a connection with both agents beforehand. Once the connection is established, the mediator can forward the message from the sending agent to the receiving agent, transparently relaying the necessary information between them. + +## Forward Messaging + +Forward messaging is a DIDComm message that is sent through a mediator to an intended recipient. The mediator acts as an intermediary, receiving the message from the sender, validating it, and then forwarding it to the intended recipient. + +Forward messaging is useful in situations where the sender and recipient cannot communicate directly. For example, if the recipient is behind a firewall or if the recipient's IP address is not known. + +In the Prism SDK, forward messaging is implemented using DIDComm mediation. The mediator receives the message, validates it, and then forwards it to the recipient. The recipient can then respond to the message, and the mediator will forward the response back to the original sender. + +Forward messaging is a powerful feature that allows messages to be sent securely between two parties even if they cannot communicate directly. This makes it ideal for use in applications that require secure communication between parties with strict security requirements. + +In summary, DIDComm mediation and forward messaging are essential features in the Prism SDK that enable secure communication between parties that cannot communicate directly. The mediator acts as an intermediary, receiving messages from the sender and forwarding them to the recipient. This makes it ideal for use in applications with strict security requirements that cannot rely on the ability to have open endpoints where they can listen to incoming messages. + +## How to enable Forward Messaging in the SDK? + +Forward messaging to a mediator is enabled by default when the mediator is running and available. To take advantage of this feature, you can create a Peer DID using the PrismAgent with the updateMediator flag set to true. This will insert the didcommmessage service with the routingDID of the mediator into the DID. + +When attempting to send a message, the Mercury library will automatically detect any forward DIDs in the service and pack a ForwardMessage with the original packed message included in its contents. This allows the message to be routed through the mediator to its intended recipient. diff --git a/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/Resources/logo.png b/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/Resources/logo.png new file mode 100644 index 00000000..16bfa50e Binary files /dev/null and b/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/Resources/logo.png differ diff --git a/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/SDKConsiderations.md b/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/SDKConsiderations.md new file mode 100644 index 00000000..55f8ed52 --- /dev/null +++ b/AtalaPrismSDK/AtalaPrismSDK/Sources/AtalaPrismSDK.docc/SDKConsiderations.md @@ -0,0 +1,27 @@ +# SDK Technical Considerations + +The architecture of the SDK is a result of a careful evaluation of different software development methodologies and patterns. We chose a modular, clean architecture that is based on protocol-oriented programming and domain-oriented programming principles, as well as dependency injection, for several reasons. + +## Overview + +### Modular Clean Architecture + +Modular clean architecture is a software development methodology that emphasizes the separation of concerns and the creation of independent modules that can be easily tested and maintained. This approach promotes the use of small, reusable components that can be combined in different ways to create larger systems. The SDK architecture uses this approach to ensure that each module can be developed and tested independently, reducing the risk of bugs and improving the overall quality of the code. + +### Protocol-Oriented Programming + +Protocol-oriented programming is a programming paradigm that focuses on the behavior of objects, rather than their structure. This approach promotes the use of protocols to define the behavior of objects, allowing for more flexible and extensible code. The SDK architecture uses this approach to ensure that the different modules can work together seamlessly, regardless of the underlying implementation details. + +### Domain-Oriented Programming + +Domain-oriented programming is a programming paradigm that focuses on the domain-specific requirements of a system, rather than the technical details of the implementation. This approach promotes the use of domain-specific models and concepts, which can be used to simplify the development process and improve the maintainability of the code. The SDK architecture uses this approach to ensure that the different modules are designed around the specific needs of decentralized identity management, making it easier for developers to build decentralized applications that are secure and scalable. + +### Dependency Injection + +Dependency injection is a programming pattern that promotes loose coupling between different components of a system. This approach promotes the use of interfaces and dependency injection containers to ensure that each component can be developed and tested independently, without relying on the implementation details of other components. The SDK architecture uses this approach to ensure that each module can be developed and tested independently, making it easier for developers to add new functionality to the system without affecting the existing code. + +## Topics + +### Group + +- ``Symbol`` diff --git a/AtalaPrismSDK/AtalaPrismSDK/Sources/Docs.swift b/AtalaPrismSDK/AtalaPrismSDK/Sources/Docs.swift new file mode 100644 index 00000000..30f9cefb --- /dev/null +++ b/AtalaPrismSDK/AtalaPrismSDK/Sources/Docs.swift @@ -0,0 +1 @@ +// Just a file that needs to exist so the package doesnt fail diff --git a/Authenticate/Sources/AuthenticateChallenged.swift b/AtalaPrismSDK/Authenticate/Sources/AuthenticateChallenged.swift similarity index 95% rename from Authenticate/Sources/AuthenticateChallenged.swift rename to AtalaPrismSDK/Authenticate/Sources/AuthenticateChallenged.swift index 4d3d33f5..b001c4b0 100644 --- a/Authenticate/Sources/AuthenticateChallenged.swift +++ b/AtalaPrismSDK/Authenticate/Sources/AuthenticateChallenged.swift @@ -26,7 +26,7 @@ public struct AuthenticateChallenged { services: [.init( id: "deeplink", type: ["deeplink"], - serviceEndpoint: .init(uri: scheme.scheme + "://" + scheme.host) + serviceEndpoint: [.init(uri: scheme.scheme + "://" + scheme.host)] )] ) } @@ -62,7 +62,7 @@ public struct AuthenticateChallenged { guard let service = didDocument.services .first(where: { $0.type.contains(where: { $0 == "deeplink" }) })? - .serviceEndpoint.uri + .serviceEndpoint.first?.uri else { throw AuthenticateError.cannotFindDeepLinkServiceError } guard diff --git a/Authenticate/Sources/AuthenticateChallenger.swift b/AtalaPrismSDK/Authenticate/Sources/AuthenticateChallenger.swift similarity index 96% rename from Authenticate/Sources/AuthenticateChallenger.swift rename to AtalaPrismSDK/Authenticate/Sources/AuthenticateChallenger.swift index 166a48b7..9918fe04 100644 --- a/Authenticate/Sources/AuthenticateChallenger.swift +++ b/AtalaPrismSDK/Authenticate/Sources/AuthenticateChallenger.swift @@ -26,7 +26,7 @@ public struct AuthenticateChallenger { services: [.init( id: "deeplink", type: ["deeplink"], - serviceEndpoint: .init(uri: scheme.scheme + "://" + scheme.host) + serviceEndpoint: [.init(uri: scheme.scheme + "://" + scheme.host)] )] ) } @@ -55,7 +55,7 @@ public struct AuthenticateChallenger { guard let service = didDocument.services .first(where: { $0.type.contains(where: { $0 == "deeplink" }) })? - .serviceEndpoint.uri + .serviceEndpoint.first?.uri else { throw AuthenticateError.cannotFindDeepLinkServiceError } guard diff --git a/Authenticate/Sources/AuthenticateDeepLink.swift b/AtalaPrismSDK/Authenticate/Sources/AuthenticateDeepLink.swift similarity index 100% rename from Authenticate/Sources/AuthenticateDeepLink.swift rename to AtalaPrismSDK/Authenticate/Sources/AuthenticateDeepLink.swift diff --git a/Authenticate/Sources/Errors.swift b/AtalaPrismSDK/Authenticate/Sources/AuthenticateErrors.swift similarity index 100% rename from Authenticate/Sources/Errors.swift rename to AtalaPrismSDK/Authenticate/Sources/AuthenticateErrors.swift diff --git a/Authenticate/Sources/ChallengeObject.swift b/AtalaPrismSDK/Authenticate/Sources/ChallengeObject.swift similarity index 100% rename from Authenticate/Sources/ChallengeObject.swift rename to AtalaPrismSDK/Authenticate/Sources/ChallengeObject.swift diff --git a/Authenticate/Sources/DeepLinkPusher.swift b/AtalaPrismSDK/Authenticate/Sources/DeepLinkPusher.swift similarity index 100% rename from Authenticate/Sources/DeepLinkPusher.swift rename to AtalaPrismSDK/Authenticate/Sources/DeepLinkPusher.swift diff --git a/Authenticate/Sources/SubmitedChallengeObject.swift b/AtalaPrismSDK/Authenticate/Sources/SubmitedChallengeObject.swift similarity index 100% rename from Authenticate/Sources/SubmitedChallengeObject.swift rename to AtalaPrismSDK/Authenticate/Sources/SubmitedChallengeObject.swift diff --git a/Authenticate/Tests/AuthenticateTests.swift b/AtalaPrismSDK/Authenticate/Tests/AuthenticateTests.swift similarity index 100% rename from Authenticate/Tests/AuthenticateTests.swift rename to AtalaPrismSDK/Authenticate/Tests/AuthenticateTests.swift diff --git a/Builders/Sources/ApolloBuilder.swift b/AtalaPrismSDK/Builders/Sources/ApolloBuilder.swift similarity index 100% rename from Builders/Sources/ApolloBuilder.swift rename to AtalaPrismSDK/Builders/Sources/ApolloBuilder.swift diff --git a/Builders/Sources/CastorBuilder.swift b/AtalaPrismSDK/Builders/Sources/CastorBuilder.swift similarity index 100% rename from Builders/Sources/CastorBuilder.swift rename to AtalaPrismSDK/Builders/Sources/CastorBuilder.swift diff --git a/Builders/Sources/MercuryBuilder.swift b/AtalaPrismSDK/Builders/Sources/MercuryBuilder.swift similarity index 100% rename from Builders/Sources/MercuryBuilder.swift rename to AtalaPrismSDK/Builders/Sources/MercuryBuilder.swift diff --git a/Builders/Sources/PlutoBuilder.swift b/AtalaPrismSDK/Builders/Sources/PlutoBuilder.swift similarity index 100% rename from Builders/Sources/PlutoBuilder.swift rename to AtalaPrismSDK/Builders/Sources/PlutoBuilder.swift diff --git a/Builders/Sources/PolluxBuilder.swift b/AtalaPrismSDK/Builders/Sources/PolluxBuilder.swift similarity index 100% rename from Builders/Sources/PolluxBuilder.swift rename to AtalaPrismSDK/Builders/Sources/PolluxBuilder.swift diff --git a/AtalaPrismSDK/Castor/Sources/Castor.docc/Castor.md b/AtalaPrismSDK/Castor/Sources/Castor.docc/Castor.md new file mode 100644 index 00000000..6f7827ea --- /dev/null +++ b/AtalaPrismSDK/Castor/Sources/Castor.docc/Castor.md @@ -0,0 +1,19 @@ +# ``Castor`` + +Castor is a powerful and flexible library for working with DIDs. Whether you are building a decentralized application or a more traditional system that requires secure and private identity management, Castor provides the tools and features you need to create, manage, and resolve DIDs with ease. + +## A Decentralized Identifier (DID) Library + +Castor is a powerful and versatile library that provides a suite of decentralised identifier (DID) operations. It enables developers to create, manage, and resolve standards-based DID in a user-controlled manner. Castor is designed to be flexible and easy to integrate into a variety of decentralized applications and systems. + +Decentralized Identifiers (DIDs) are a new type of identifier that allows individuals and organizations to create and manage their own digital identity. DIDs provide a secure, decentralized, and privacy-preserving way to authenticate and verify identity, without relying on centralized authorities or intermediaries. Castor allows developers to leverage the power of DIDs by providing a simple and efficient way to create, manage, and resolve them. + +Castor supports the creation and resolution of two types of DIDs out of the box: prism and peer. + +With Castor, developers can create and manage DIDs, generate and manage their associated public and private keys, and resolve DIDs to retrieve associated data. Castor also provides a range of advanced features, such as support for multiple key types and encryption methods, and a flexible API for customizing and extending its functionality. + +## Topics + +### Group + +- ``Symbol`` diff --git a/AtalaPrismSDK/Castor/Sources/Castor.docc/CastorHowTo.md b/AtalaPrismSDK/Castor/Sources/Castor.docc/CastorHowTo.md new file mode 100644 index 00000000..f05c82e7 --- /dev/null +++ b/AtalaPrismSDK/Castor/Sources/Castor.docc/CastorHowTo.md @@ -0,0 +1,77 @@ +# Castor API Tutorial + +The Castor protocol defines a set of functions for working with Decentralized Identifiers (DIDs) and DID Documents. Here's a brief explanation of each function: + +- `parseDID`: This function takes a string representation of a DID and returns a `DID` object. It may throw an error if the string is not a valid DID. + +- `createPrismDID`: This function creates a DID for a Prism (a device or server that acts as a DID owner and controller) using a given master public key and list of services. It may throw an error if the master public key or services are invalid. + +```swift +// Example usage: +do { + let castor = CastorImpl(apollo: apolloImpl) + let did = try castor.parseDID(str: "did:example:123") + let publicKey = try PublicKey(base58: "...") + let services = [DIDDocument.Service]() + let prismDID = try castor.createPrismDID(masterPublicKey: publicKey, services: services) +} catch { + // Handle error +} +``` + +- `createPeerDID`: This function creates a DID for a Peer (a device or server that acts as a DID subject) using given key agreement and authentication key pairs and a list of services. It may throw an error if the key pairs or services are invalid. + +```swift +// Example usage: +do { + let castor = CastorImpl(apollo: apolloImpl) + let keyAgreementKeyPair = try KeyPair() + let authenticationKeyPair = try KeyPair() + let services = [DIDDocument.Service]() + let peerDID = try castor.createPeerDID(keyAgreementKeyPair: keyAgreementKeyPair, authenticationKeyPair: authenticationKeyPair, services: services) +} catch { + // Handle error +} +``` + +- `resolveDID`: This function asynchronously resolves a DID to its corresponding DID Document. It may throw an error if the DID is invalid or the document cannot be retrieved. + +```swift +// Example usage: +do { + let castor = CastorImpl(apollo: apolloImpl) + let did = try castor.parseDID(str: "did:example:123") + let document = try castor.resolveDID(did: did) +} catch { + // Handle error +} +``` + +- `verifySignature`: This function verifies the authenticity of a signature using the corresponding DID or DID Document, challenge, and signature data. It returns a boolean value indicating whether the signature is valid or not. It may throw an error if the DID or signature data are invalid. + +```swift +// Example usage: +do { + let castor = CastorImpl(apollo: apolloImpl) + let did = try castor.parseDID(str: "did:example:123") + let challenge = Data(...) + let signature = Data(...) + let isValid = try castor.verifySignature(did: did, challenge: challenge, signature: signature) +} catch { + // Handle error +} +``` + +- `getEcnumbasis`: This function generates a unique ECNUM basis string for a given DID and key pair. It may throw an error if the DID or key pair are invalid. + +```swift +// Example usage: +do { + let castor = CastorImpl(apollo: apolloImpl) + let did = try castor.parseDID(str: "did:example:123") + let keyPair = try KeyPair() + let ecnumbasis = try castor.getEcnumbasis(did: did, keyPair: keyPair) +} catch { + // Handle error +} +``` diff --git a/AtalaPrismSDK/Castor/Sources/CastorImpl+Public.swift b/AtalaPrismSDK/Castor/Sources/CastorImpl+Public.swift new file mode 100644 index 00000000..b826e3c1 --- /dev/null +++ b/AtalaPrismSDK/Castor/Sources/CastorImpl+Public.swift @@ -0,0 +1,124 @@ +import Domain +import Foundation + +extension CastorImpl: Castor { + /// parseDID parses a string representation of a Decentralized Identifier (DID) into a DID object. This function may throw an error if the string is not a valid DID. + /// + /// - Parameter str: The string representation of the DID + /// - Returns: The DID object + /// - Throws: An error if the string is not a valid DID + public func parseDID(str: String) throws -> DID { + try DIDParser(didString: str).parse() + } + + /// createPrismDID creates a DID for a prism (a device or server that acts as a DID owner and controller) using a given master public key and list of services. This function may throw an error if the master public key or services are invalid. + /// + /// - Parameters: + /// - masterPublicKey: The master public key of the prism + /// - services: The list of services offered by the prism + /// - Returns: The DID of the prism + /// - Throws: An error if the master public key or services are invalid + public func createPrismDID( + masterPublicKey: PublicKey, + services: [DIDDocument.Service] + ) throws -> DID { + try CreatePrismDIDOperation( + apollo: apollo, + masterPublicKey: masterPublicKey, + services: services + ).compute() + } + + /// createPeerDID creates a DID for a peer (a device or server that acts as a DID subject) using given key agreement and authentication key pairs and a list of services. This function may throw an error if the key pairs or services are invalid. + /// + /// - Parameters: + /// - keyAgreementKeyPair: The key pair used for key agreement (establishing secure communication between peers) + /// - authenticationKeyPair: The key pair used for authentication (verifying the identity of a peer) + /// - services: The list of services offered by the peer + /// - Returns: The DID of the peer + /// - Throws: An error if the key pairs or services are invalid + public func createPeerDID( + keyAgreementKeyPair: KeyPair, + authenticationKeyPair: KeyPair, + services: [DIDDocument.Service] + ) throws -> DID { + try CreatePeerDIDOperation( + autenticationKeyPair: authenticationKeyPair, + agreementKeyPair: keyAgreementKeyPair, + services: services + ).compute() + } + + /// verifySignature asynchronously verifies the authenticity of a signature using the corresponding DID, challenge, and signature data. This function returns a boolean value indicating whether the signature is valid or not. This function may throw an error if the DID or signature data are invalid. + /// + /// - Parameters: + /// - did: The DID associated with the signature + /// - challenge: The challenge used to generate the signature + /// - signature: The signature data to verify + /// - Returns: A boolean value indicating whether the signature is valid or not + /// - Throws: An error if the DID or signature data are invalid + public func verifySignature(did: DID, challenge: Data, signature: Data) async throws -> Bool { + let document = try await resolveDID(did: did) + return verifySignature(document: document, challenge: challenge, signature: signature) + } + + /// verifySignature verifies the authenticity of a signature using the corresponding DID Document, challenge, and signature data. This function returns a boolean value indicating whether the signature is valid or not. This function may throw an error if the DID Document or signature data are invalid. + /// + /// - Parameters: + /// - document: The DID Document associated with the signature + /// - challenge: The challenge used to generate the signature + /// - signature: The signature data to verify + /// - Returns: A boolean value indicating whether the signature is valid or not + /// - Throws: An error if the DID Document or signature data are invalid + public func verifySignature( + document: DIDDocument, + challenge: Data, + signature: Data + ) -> Bool { + return VerifyDIDSignatureOperation( + apollo: apollo, + document: document, + challenge: challenge, + signature: signature + ).compute() + } + + /// resolveDID asynchronously resolves a DID to its corresponding DID Document. This function may throw an error if the DID is invalid or the document cannot be retrieved. + /// + /// - Parameter did: The DID to resolve + /// - Returns: The DID Document associated with the DID + /// - Throws: An error if the DID is invalid or the document cannot be retrieved + public func resolveDID(did: DID) async throws -> DIDDocument { + logger.info(message: "Trying to resolve DID", metadata: [ + .maskedMetadataByLevel(key: "DID", value: did.string, level: .debug) + ]) + + guard + let resolver = resolvers.first(where: { $0.method == did.method }) + else { + logger.error(message: "No resolvers for DID method \(did.method)", metadata: [ + .maskedMetadataByLevel(key: "DID", value: did.string, level: .debug) + ]) + throw CastorError.noResolversAvailableForDIDMethod(method: did.method) + } + return try await resolver.resolve(did: did) + } + + /// getEcnumbasis generates a unique ECNUM basis string for a given DID and key pair. This function may throw an error if the DID or key pair are invalid. + /// + /// - Parameters: + /// - did: The DID associated with the key pair + /// - keyPair: The key pair to use for generating the ECNUM basis + /// - Returns: The ECNUM basis string + /// - Throws: An error if the DID or key pair are invalid + public func getEcnumbasis(did: DID, keyPair: KeyPair) throws -> String { + logger.debug(message: "Getting ecnumbasis", metadata: [ + .maskedMetadataByLevel(key: "DID", value: did.string, level: .debug) + ]) + return try CreatePeerDIDOperation( + autenticationKeyPair: keyPair, + agreementKeyPair: keyPair, + services: [] + ).computeEcnumbasis(did: did, keyPair: keyPair) + } +} diff --git a/Castor/Sources/CastorImpl.swift b/AtalaPrismSDK/Castor/Sources/CastorImpl.swift similarity index 100% rename from Castor/Sources/CastorImpl.swift rename to AtalaPrismSDK/Castor/Sources/CastorImpl.swift diff --git a/Castor/Sources/DID/PeerDID/PeerDID.swift b/AtalaPrismSDK/Castor/Sources/DID/PeerDID/PeerDID.swift similarity index 96% rename from Castor/Sources/DID/PeerDID/PeerDID.swift rename to AtalaPrismSDK/Castor/Sources/DID/PeerDID/PeerDID.swift index 87612fd0..1115f063 100644 --- a/Castor/Sources/DID/PeerDID/PeerDID.swift +++ b/AtalaPrismSDK/Castor/Sources/DID/PeerDID/PeerDID.swift @@ -57,7 +57,7 @@ struct PeerDID { did.schema == "did", did.method == "peer", did.methodId.range(of: regex, options: .regularExpression) != nil - else { throw CastorError.invalidPeerDIDError } + else { throw CastorError.methodIdIsDoesNotSatisfyRegex(regex: regex) } self.did = did } diff --git a/Castor/Sources/DID/PeerDID/Types.swift b/AtalaPrismSDK/Castor/Sources/DID/PeerDID/Types.swift similarity index 100% rename from Castor/Sources/DID/PeerDID/Types.swift rename to AtalaPrismSDK/Castor/Sources/DID/PeerDID/Types.swift diff --git a/Castor/Sources/DID/PrismDID/LongFormPrismDID.swift b/AtalaPrismSDK/Castor/Sources/DID/PrismDID/LongFormPrismDID.swift similarity index 100% rename from Castor/Sources/DID/PrismDID/LongFormPrismDID.swift rename to AtalaPrismSDK/Castor/Sources/DID/PrismDID/LongFormPrismDID.swift diff --git a/Castor/Sources/DID/PrismDID/PrismDIDMethodId.swift b/AtalaPrismSDK/Castor/Sources/DID/PrismDID/PrismDIDMethodId.swift similarity index 79% rename from Castor/Sources/DID/PrismDID/PrismDIDMethodId.swift rename to AtalaPrismSDK/Castor/Sources/DID/PrismDID/PrismDIDMethodId.swift index 53deac03..709a5294 100644 --- a/Castor/Sources/DID/PrismDID/PrismDIDMethodId.swift +++ b/AtalaPrismSDK/Castor/Sources/DID/PrismDID/PrismDIDMethodId.swift @@ -13,7 +13,7 @@ struct PrismDIDMethodId: CustomStringConvertible { let range = $0.range(of: sectionRegex, options: .regularExpression) return range != nil }) - else { throw CastorError.methodIdIsDoesNotSatisfyRegex } + else { throw CastorError.methodIdIsDoesNotSatisfyRegex(regex: "^([A-Za-z0-9_-]*:)*[A-Za-z0-9_-]+$") } value = sections.joined(separator: ":") } @@ -21,7 +21,7 @@ struct PrismDIDMethodId: CustomStringConvertible { let methodSpecifiIdRegex = "^([A-Za-z0-9_-]*:)*[A-Za-z0-9_-]+$" guard string.range(of: methodSpecifiIdRegex, options: .regularExpression) != nil - else { throw CastorError.methodIdIsDoesNotSatisfyRegex } + else { throw CastorError.methodIdIsDoesNotSatisfyRegex(regex: methodSpecifiIdRegex) } value = string } } diff --git a/Castor/Sources/DID/PrismDID/PrismDIDPublicKey.swift b/AtalaPrismSDK/Castor/Sources/DID/PrismDID/PrismDIDPublicKey.swift similarity index 75% rename from Castor/Sources/DID/PrismDID/PrismDIDPublicKey.swift rename to AtalaPrismSDK/Castor/Sources/DID/PrismDID/PrismDIDPublicKey.swift index cc6f0a50..f0537d82 100644 --- a/Castor/Sources/DID/PrismDID/PrismDIDPublicKey.swift +++ b/AtalaPrismSDK/Castor/Sources/DID/PrismDID/PrismDIDPublicKey.swift @@ -5,7 +5,9 @@ struct PrismDIDPublicKey { enum Usage: String { case masterKey case issuingKey - case communicationKey + case keyAgreementKey + case capabilityDelegationKey + case capabilityInvocationKey case authenticationKey case revocationKey case unknownKey @@ -20,12 +22,16 @@ struct PrismDIDPublicKey { return .masterKey case .issuingKey: return .issuingKey - case .communicationKey: - return .communicationKey + case .capabilityInvocationKey: + return .capabilityInvocationKey + case .capabilityDelegationKey: + return .capabilityDelegationKey case .authenticationKey: return .authenticationKey case .revocationKey: return .revocationKey + case .keyAgreementKey: + return .keyAgreementKey case .unknownKey: return .unknownKey } @@ -37,12 +43,16 @@ struct PrismDIDPublicKey { return "master\(index)" case .issuingKey: return "issuing\(index)" - case .communicationKey: - return "communication\(index)" + case .capabilityDelegationKey: + return "capabilityDelegationKey\(index)" + case .capabilityInvocationKey: + return "capabilityInvocationKey\(index)" case .authenticationKey: return "authentication\(index)" case .revocationKey: return "revocation\(index)" + case .keyAgreementKey: + return "keyAgreement\(index)" case .unknownKey: return "unknown\(index)" } @@ -69,7 +79,7 @@ struct PrismDIDPublicKey { case let .compressedEcKeyData(value): keyData = apollo.compressedPublicKey(compressedData: value.data).uncompressed default: - throw CastorError.invalidPublicKeyEncoding + throw CastorError.invalidPublicKeyCoding(didMethod: "prism", curve: "secp256k1") } } @@ -92,12 +102,16 @@ private extension Io_Iohk_Atala_Prism_Protos_KeyUsage { return .unknownKey case .issuingKey: return .issuingKey - case .communicationKey: - return .communicationKey + case .capabilityInvocationKey: + return .capabilityInvocationKey + case .capabilityDelegationKey: + return .capabilityDelegationKey case .authenticationKey: return .authenticationKey case .revocationKey: return .revocationKey + case .keyAgreementKey: + return .keyAgreementKey case .UNRECOGNIZED: return .unknownKey } diff --git a/Castor/Sources/DIDParser/DIDGrammar/DIDAbnf.g4 b/AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDAbnf.g4 similarity index 100% rename from Castor/Sources/DIDParser/DIDGrammar/DIDAbnf.g4 rename to AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDAbnf.g4 diff --git a/Castor/Sources/DIDParser/DIDGrammar/DIDAbnf.interp b/AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDAbnf.interp similarity index 100% rename from Castor/Sources/DIDParser/DIDGrammar/DIDAbnf.interp rename to AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDAbnf.interp diff --git a/Castor/Sources/DIDParser/DIDGrammar/DIDAbnf.tokens b/AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDAbnf.tokens similarity index 100% rename from Castor/Sources/DIDParser/DIDGrammar/DIDAbnf.tokens rename to AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDAbnf.tokens diff --git a/Castor/Sources/DIDParser/DIDGrammar/DIDAbnfBaseListener.swift b/AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDAbnfBaseListener.swift similarity index 100% rename from Castor/Sources/DIDParser/DIDGrammar/DIDAbnfBaseListener.swift rename to AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDAbnfBaseListener.swift diff --git a/Castor/Sources/DIDParser/DIDGrammar/DIDAbnfLexer.interp b/AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDAbnfLexer.interp similarity index 100% rename from Castor/Sources/DIDParser/DIDGrammar/DIDAbnfLexer.interp rename to AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDAbnfLexer.interp diff --git a/Castor/Sources/DIDParser/DIDGrammar/DIDAbnfLexer.swift b/AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDAbnfLexer.swift similarity index 100% rename from Castor/Sources/DIDParser/DIDGrammar/DIDAbnfLexer.swift rename to AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDAbnfLexer.swift diff --git a/Castor/Sources/DIDParser/DIDGrammar/DIDAbnfLexer.tokens b/AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDAbnfLexer.tokens similarity index 100% rename from Castor/Sources/DIDParser/DIDGrammar/DIDAbnfLexer.tokens rename to AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDAbnfLexer.tokens diff --git a/Castor/Sources/DIDParser/DIDGrammar/DIDAbnfListener.swift b/AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDAbnfListener.swift similarity index 100% rename from Castor/Sources/DIDParser/DIDGrammar/DIDAbnfListener.swift rename to AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDAbnfListener.swift diff --git a/Castor/Sources/DIDParser/DIDGrammar/DIDAbnfParser.swift b/AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDAbnfParser.swift similarity index 100% rename from Castor/Sources/DIDParser/DIDGrammar/DIDAbnfParser.swift rename to AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDAbnfParser.swift diff --git a/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnf.g4 b/AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnf.g4 similarity index 100% rename from Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnf.g4 rename to AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnf.g4 diff --git a/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnf.interp b/AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnf.interp similarity index 100% rename from Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnf.interp rename to AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnf.interp diff --git a/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnf.tokens b/AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnf.tokens similarity index 100% rename from Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnf.tokens rename to AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnf.tokens diff --git a/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnfBaseListener.swift b/AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnfBaseListener.swift similarity index 100% rename from Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnfBaseListener.swift rename to AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnfBaseListener.swift diff --git a/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnfLexer.interp b/AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnfLexer.interp similarity index 100% rename from Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnfLexer.interp rename to AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnfLexer.interp diff --git a/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnfLexer.swift b/AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnfLexer.swift similarity index 100% rename from Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnfLexer.swift rename to AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnfLexer.swift diff --git a/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnfLexer.tokens b/AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnfLexer.tokens similarity index 100% rename from Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnfLexer.tokens rename to AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnfLexer.tokens diff --git a/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnfListener.swift b/AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnfListener.swift similarity index 100% rename from Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnfListener.swift rename to AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnfListener.swift diff --git a/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnfParser.swift b/AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnfParser.swift similarity index 100% rename from Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnfParser.swift rename to AtalaPrismSDK/Castor/Sources/DIDParser/DIDGrammar/DIDUrlAbnfParser.swift diff --git a/Castor/Sources/DIDParser/DIDParser.swift b/AtalaPrismSDK/Castor/Sources/DIDParser/DIDParser.swift similarity index 93% rename from Castor/Sources/DIDParser/DIDParser.swift rename to AtalaPrismSDK/Castor/Sources/DIDParser/DIDParser.swift index 7d60dd0b..3b7094b5 100644 --- a/Castor/Sources/DIDParser/DIDParser.swift +++ b/AtalaPrismSDK/Castor/Sources/DIDParser/DIDParser.swift @@ -3,8 +3,6 @@ import Domain import Foundation struct DIDParser { - struct InvalidDIDStringError: Error {} - let didString: String func parse() throws -> DID { @@ -23,7 +21,7 @@ struct DIDParser { let schema = listener.scheme, let methodName = listener.methodName, let methodId = listener.methodId - else { throw InvalidDIDStringError() } + else { throw CastorError.invalidDIDString(didString) } let did = DID( schema: schema, diff --git a/Castor/Sources/DIDParser/DIDUrlParser.swift b/AtalaPrismSDK/Castor/Sources/DIDParser/DIDUrlParser.swift similarity index 96% rename from Castor/Sources/DIDParser/DIDUrlParser.swift rename to AtalaPrismSDK/Castor/Sources/DIDParser/DIDUrlParser.swift index 2eb06775..8b808915 100644 --- a/Castor/Sources/DIDParser/DIDUrlParser.swift +++ b/AtalaPrismSDK/Castor/Sources/DIDParser/DIDUrlParser.swift @@ -3,8 +3,6 @@ import Domain import Foundation struct DIDUrlParser { - struct InvalidDIDStringError: Error {} - let didUrlString: String func parse() throws -> DIDUrl { @@ -23,7 +21,7 @@ struct DIDUrlParser { let schema = listener.scheme, let methodName = listener.methodName, let methodId = listener.methodId - else { throw InvalidDIDStringError() } + else { throw CastorError.invalidDIDString(didUrlString) } let did = DID( schema: schema, diff --git a/Castor/Sources/Helpers/JWK+Helper.swift b/AtalaPrismSDK/Castor/Sources/Helpers/JWK+Helper.swift similarity index 89% rename from Castor/Sources/Helpers/JWK+Helper.swift rename to AtalaPrismSDK/Castor/Sources/Helpers/JWK+Helper.swift index ae350337..5451427c 100644 --- a/Castor/Sources/Helpers/JWK+Helper.swift +++ b/AtalaPrismSDK/Castor/Sources/Helpers/JWK+Helper.swift @@ -9,7 +9,7 @@ struct JWKHelper { let crv = jsonDic["crv"], let xKey = jsonDic["x"], crv == "X25519" - else { throw CastorError.invalidJWKKeysError } + else { throw CastorError.invalidJWKError } return Data(base64URLEncoded: xKey) } @@ -20,7 +20,7 @@ struct JWKHelper { let crv = jsonDic["crv"], let xKey = jsonDic["x"], crv == "Ed25519" - else { throw CastorError.invalidJWKKeysError } + else { throw CastorError.invalidJWKError } return Data(base64URLEncoded: xKey) } @@ -34,7 +34,7 @@ struct JWKHelper { case let authentication as VerificationMethodTypeAuthentication where authentication == .jsonWebKey2020: crv = "Ed25519" default: - throw CastorError.invalidJWKKeysError + throw CastorError.invalidJWKError } return try convertToJsonString(dic: [ "kty" : "OKP", diff --git a/Castor/Sources/Helpers/Multicodec.swift b/AtalaPrismSDK/Castor/Sources/Helpers/Multicodec.swift similarity index 85% rename from Castor/Sources/Helpers/Multicodec.swift rename to AtalaPrismSDK/Castor/Sources/Helpers/Multicodec.swift index c7dbfff8..f969fc90 100644 --- a/Castor/Sources/Helpers/Multicodec.swift +++ b/AtalaPrismSDK/Castor/Sources/Helpers/Multicodec.swift @@ -39,7 +39,10 @@ struct Multicodec { let (code, buffer) = try uVarInt(buffer: [UInt8](value)) guard let codec = Codec(rawValue: Int(code)) else { - throw CastorError.invalidKeyError + throw UnknownError.somethingWentWrongError( + customMessage: "Error while processing multicodec", + underlyingErrors: nil + ) } return (codec, Data(buffer)) } diff --git a/Castor/Sources/Helpers/Sha256.swift b/AtalaPrismSDK/Castor/Sources/Helpers/Sha256.swift similarity index 100% rename from Castor/Sources/Helpers/Sha256.swift rename to AtalaPrismSDK/Castor/Sources/Helpers/Sha256.swift diff --git a/Castor/Sources/Helpers/VarInt.swift b/AtalaPrismSDK/Castor/Sources/Helpers/VarInt.swift similarity index 88% rename from Castor/Sources/Helpers/VarInt.swift rename to AtalaPrismSDK/Castor/Sources/Helpers/VarInt.swift index a397e817..78b55281 100644 --- a/Castor/Sources/Helpers/VarInt.swift +++ b/AtalaPrismSDK/Castor/Sources/Helpers/VarInt.swift @@ -36,7 +36,7 @@ enum VarIntError : Error { /** putVarInt encodes a UInt64 into a buffer and returns it. */ -public func putUVarInt(_ value: UInt64) -> [UInt8] { +func putUVarInt(_ value: UInt64) -> [UInt8] { var buffer = [UInt8]() var val: UInt64 = value @@ -57,7 +57,7 @@ public func putUVarInt(_ value: UInt64) -> [UInt8] { n < 0: value larger than 64 bits (overflow) and -n is the number of bytes read */ -public func uVarInt(_ buffer: [UInt8]) -> (UInt64, Int) { +func uVarInt(_ buffer: [UInt8]) -> (UInt64, Int) { var output: UInt64 = 0 var counter = 0 var shifter:UInt64 = 0 @@ -79,7 +79,7 @@ public func uVarInt(_ buffer: [UInt8]) -> (UInt64, Int) { /** putVarInt encodes an Int64 into a buffer and returns it. */ -public func putVarInt(_ value: Int64) -> [UInt8] { +func putVarInt(_ value: Int64) -> [UInt8] { let unsignedValue = UInt64(value) << 1 return putUVarInt(unsignedValue) @@ -93,7 +93,7 @@ public func putVarInt(_ value: Int64) -> [UInt8] { n < 0: value larger than 64 bits (overflow) and -n is the number of bytes read */ -public func varInt(_ buffer: [UInt8]) -> (Int64, Int) { +func varInt(_ buffer: [UInt8]) -> (Int64, Int) { let (unsignedValue, bytesRead) = uVarInt(buffer) var value = Int64(unsignedValue >> 1) @@ -104,7 +104,7 @@ public func varInt(_ buffer: [UInt8]) -> (Int64, Int) { /** readUVarInt reads an encoded unsigned integer from the reader and returns it as an UInt64 */ -public func readUVarInt(_ reader: InputStream) throws -> UInt64 { +func readUVarInt(_ reader: InputStream) throws -> UInt64 { var value: UInt64 = 0 var shifter: UInt64 = 0 var index = 0 @@ -132,7 +132,7 @@ public func readUVarInt(_ reader: InputStream) throws -> UInt64 { /** readVarInt reads an encoded signed integer from the reader and returns it as an Int64 */ -public func readVarInt(_ reader: InputStream) throws -> Int64 { +func readVarInt(_ reader: InputStream) throws -> Int64 { let unsignedValue = try readUVarInt(reader) var value = Int64(unsignedValue >> 1) @@ -148,10 +148,17 @@ public func readVarInt(_ reader: InputStream) throws -> Int64 { /// - Parameter buffer: The buffer prefixed with the size of the payload as an uvarint /// - Returns: the size as an int64 and the buffer with the uvarint indicating size removed. /// - Throws: -public func uVarInt(buffer: [UInt8]) throws -> (UInt64, [UInt8]) { +func uVarInt(buffer: [UInt8]) throws -> (UInt64, [UInt8]) { let (size, bytesRead) = uVarInt(buffer) - if bytesRead == 0 { throw CastorError.notPossibleToResolveDID } - if bytesRead < 0 { throw CastorError.notPossibleToResolveDID } + guard + bytesRead != 0, + bytesRead >= 0 + else { + throw UnknownError.somethingWentWrongError( + customMessage: "VarInt error, invalid byte size", + underlyingErrors: nil + ) + } // Return the size as read from the uvarint and the buffer without the uvarint return (size, Array(buffer[bytesRead.. String { - let peerDidServices: [PeerDID.Service] = services.compactMap { - guard let type = $0.type.first else { return nil } + let peerDidServices: [PeerDID.Service] = services.map { service in + guard + let type = service.type.first, + let endpoint = service.serviceEndpoint.first + else { return nil } return PeerDID.Service( type: type, - serviceEndpoint: $0.serviceEndpoint.uri, - routingKeys: $0.serviceEndpoint.routingKeys, - accept: $0.serviceEndpoint.accept + serviceEndpoint: endpoint.uri, + routingKeys: endpoint.routingKeys, + accept: endpoint.accept ) - } + }.compactMap { $0 } let encoder = JSONEncoder() encoder.outputFormatting = .withoutEscapingSlashes if @@ -164,6 +167,11 @@ struct CreatePeerDIDOperation { } private func validateRawKeyLength(key: Data) throws { - guard key.count == 32 else { throw CastorError.invalidKeyError } + guard key.count == 32 else { + throw UnknownError.somethingWentWrongError( + customMessage: "Invalid secp256k1 key size of 32 bytes", + underlyingErrors: nil + ) + } } } diff --git a/Castor/Sources/Operations/CreatePrismDIDOperation.swift b/AtalaPrismSDK/Castor/Sources/Operations/CreatePrismDIDOperation.swift similarity index 91% rename from Castor/Sources/Operations/CreatePrismDIDOperation.swift rename to AtalaPrismSDK/Castor/Sources/Operations/CreatePrismDIDOperation.swift index 3f6b6822..d05fc32d 100644 --- a/Castor/Sources/Operations/CreatePrismDIDOperation.swift +++ b/AtalaPrismSDK/Castor/Sources/Operations/CreatePrismDIDOperation.swift @@ -29,10 +29,10 @@ struct CreatePrismDIDOperation { var didData = Io_Iohk_Atala_Prism_Protos_CreateDIDOperation.DIDCreationData() didData.publicKeys = publicKeys.map { $0.toProto() } didData.services = services.map { - var service = Io_Iohk_Atala_Prism_Protos_CreateDIDOperation.DIDService() + var service = Io_Iohk_Atala_Prism_Protos_Service() service.id = $0.id - service.types = $0.type - service.serviceEndpoint = $0.serviceEndpoint.uri + service.type = $0.type.first ?? "" + service.serviceEndpoint = $0.serviceEndpoint.map { $0.uri } return service } diff --git a/Castor/Sources/Operations/VerifySignatureOperation.swift b/AtalaPrismSDK/Castor/Sources/Operations/VerifyDIDSignatureOperation.swift similarity index 93% rename from Castor/Sources/Operations/VerifySignatureOperation.swift rename to AtalaPrismSDK/Castor/Sources/Operations/VerifyDIDSignatureOperation.swift index a0277d31..aa35a8e8 100644 --- a/Castor/Sources/Operations/VerifySignatureOperation.swift +++ b/AtalaPrismSDK/Castor/Sources/Operations/VerifyDIDSignatureOperation.swift @@ -2,7 +2,7 @@ import Core import Domain import Foundation -struct VerifySignatureOperation { +struct VerifyDIDSignatureOperation { let apollo: Apollo let document: DIDDocument let challenge: Data diff --git a/Castor/Sources/Resolvers/LongFormPrismDIDResolver.swift b/AtalaPrismSDK/Castor/Sources/Resolvers/LongFormPrismDIDResolver.swift similarity index 96% rename from Castor/Sources/Resolvers/LongFormPrismDIDResolver.swift rename to AtalaPrismSDK/Castor/Sources/Resolvers/LongFormPrismDIDResolver.swift index b375733d..e8817828 100644 --- a/Castor/Sources/Resolvers/LongFormPrismDIDResolver.swift +++ b/AtalaPrismSDK/Castor/Sources/Resolvers/LongFormPrismDIDResolver.swift @@ -66,8 +66,8 @@ struct LongFormPrismDIDResolver: DIDResolverDomain { let services = operation.createDid.didData.services.map { DIDDocument.Service( id: $0.id, - type: $0.types, - serviceEndpoint: .init(uri: $0.serviceEndpoint) + type: [$0.type], + serviceEndpoint: $0.serviceEndpoint.map { .init(uri: $0) } ) } return (publicKeys.reduce( diff --git a/Castor/Sources/Resolvers/PeerDIDResolver.swift b/AtalaPrismSDK/Castor/Sources/Resolvers/PeerDIDResolver.swift similarity index 83% rename from Castor/Sources/Resolvers/PeerDIDResolver.swift rename to AtalaPrismSDK/Castor/Sources/Resolvers/PeerDIDResolver.swift index cd42b5a4..a3268e42 100644 --- a/Castor/Sources/Resolvers/PeerDIDResolver.swift +++ b/AtalaPrismSDK/Castor/Sources/Resolvers/PeerDIDResolver.swift @@ -10,7 +10,10 @@ struct PeerDIDResolver: DIDResolverDomain { guard did.method == "peer", did.methodId.prefix(1) == "2" - else { throw CastorError.notPossibleToResolveDID } + else { throw CastorError.notPossibleToResolveDID( + did: did.string, + reason: "Method or method id are invalid" + )} return try buildDIDDocumentAlgo2(did: did, format: .jwk) } @@ -27,12 +30,14 @@ struct PeerDIDResolver: DIDResolverDomain { switch $0.prefix(1) { case CreatePeerDIDOperation.Numalgo2Prefix.authentication.rawValue: let decoded = try decodeMultibaseEncnumbasisAuth( + did: did, multibase: String($0.dropFirst()), format: .jwk ) authenticationMethods.append(try getVerificationMethod(did: did, decodedEncumbasis: decoded)) case CreatePeerDIDOperation.Numalgo2Prefix.keyAgreement.rawValue: let decoded = try decodeMultibaseEncnumbasisAgreement( + did: did, multibase: String($0.dropFirst()), format: .jwk ) @@ -67,6 +72,7 @@ struct PeerDIDResolver: DIDResolverDomain { } func decodeMultibaseEncnumbasisAuth( + did: DID, multibase: String, format: VerificationMaterialFormatPeerDID ) throws -> (String, VerificationMaterialAuthentication) { @@ -74,11 +80,17 @@ struct PeerDIDResolver: DIDResolverDomain { multibase: multibase, format: format, defaultCodec: .ed25519 ) - guard let material = verMaterial.authentication else { throw CastorError.notPossibleToResolveDID } + guard let material = verMaterial.authentication else { + throw CastorError.notPossibleToResolveDID( + did: did.string, + reason: "Could not decode authentication multibase" + ) + } return (decoded, material) } private func decodeMultibaseEncnumbasisAgreement( + did: DID, multibase: String, format: VerificationMaterialFormatPeerDID ) throws -> (String, VerificationMaterialAgreement) { @@ -86,7 +98,11 @@ struct PeerDIDResolver: DIDResolverDomain { multibase: multibase, format: format, defaultCodec: .x25519 ) - guard let material = verMaterial.agreement else { throw CastorError.notPossibleToResolveDID } + guard let material = verMaterial.agreement else { + throw CastorError.notPossibleToResolveDID( + did: did.string, + reason: "Could not decode key agreement multibase" + )} return (decoded, material) } @@ -106,7 +122,7 @@ struct PeerDIDResolver: DIDResolverDomain { guard let jwkJsonString = try JWKHelper().toJWK( publicKey: decodedEncnum, material: VerificationMethodTypeAgreement.jsonWebKey2020 - ) else { throw CastorError.invalidJWKKeysError } + ) else { throw CastorError.invalidJWKError } return (encnum, VerificationMaterialAgreement( format: format, @@ -117,7 +133,7 @@ struct PeerDIDResolver: DIDResolverDomain { guard let jwkJsonString = try JWKHelper().toJWK( publicKey: decodedEncnum, material: VerificationMethodTypeAuthentication.jsonWebKey2020 - ) else { throw CastorError.invalidJWKKeysError } + ) else { throw CastorError.invalidJWKError } return (encnum, VerificationMaterialAuthentication( format: format, @@ -148,17 +164,22 @@ struct PeerDIDResolver: DIDResolverDomain { } private func decodeService(did: DID, encodedString: String) throws -> [DIDDocument.Service] { - guard let jsonData = Data(fromBase64URL: encodedString) else { throw CastorError.notPossibleToResolveDID } + guard let jsonData = Data(fromBase64URL: encodedString) else { + throw CastorError.notPossibleToResolveDID( + did: did.string, + reason: "Could not parse Service JSON" + ) + } let services = try jsonDecoderForServicePeerDIDService(jsonData: jsonData) return services.enumerated().map { DIDDocument.Service( id: did.string + $0.element.type.lowercased() + "-\($0.offset)", type: [$0.element.type], - serviceEndpoint: .init( + serviceEndpoint: [.init( uri: $0.element.serviceEndpoint, accept: $0.element.accept, routingKeys: $0.element.routingKeys - ) + )] ) } } @@ -173,6 +194,11 @@ struct PeerDIDResolver: DIDResolverDomain { } private func validateRawKeyLength(key: Data) throws { - guard key.count == 32 else { throw CastorError.invalidKeyError } + guard key.count == 32 else { + throw UnknownError.somethingWentWrongError( + customMessage: "Invalid secp256k1 key size of 32 bytes", + underlyingErrors: nil + ) + } } } diff --git a/AtalaPrismSDK/Castor/Sources/protobuf/common_models.pb.swift b/AtalaPrismSDK/Castor/Sources/protobuf/common_models.pb.swift new file mode 100644 index 00000000..85650ff6 --- /dev/null +++ b/AtalaPrismSDK/Castor/Sources/protobuf/common_models.pb.swift @@ -0,0 +1,586 @@ +// DO NOT EDIT. +// swift-format-ignore-file +// +// Generated by the Swift generator plugin for the protocol buffer compiler. +// Source: common_models.proto +// +// For information on using the generated types, please see the documentation: +// https://github.com/apple/swift-protobuf/ + +import Foundation +import SwiftProtobuf + +// If the compiler emits an error on this type, it is because this file +// was generated by a version of the `protoc` Swift plug-in that is +// incompatible with the version of SwiftProtobuf to which you are linking. +// Please ensure that you are building against the same version of the API +// that was used to generate this file. +fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { + struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} + typealias Version = _2 +} + +///* +/// This enum provides a way for some RPC requests to specify the direction so that the response values are sorted +/// the way you want them to. +/// Note that it specifies the direction only and doesn't say anything about a comparator +/// (e.g. natural order, some RPC-specific order etc). +enum Io_Iohk_Atala_Prism_Protos_SortByDirection: SwiftProtobuf.Enum { + typealias RawValue = Int + + /// Nothing provided, each API can define whether to fail or take a default value (commonly ASCENDING). + case unknown // = 0 + + /// Sort the results in ascending order. + case ascending // = 1 + + /// Sort the results in descending order. + case descending // = 2 + case UNRECOGNIZED(Int) + + init() { + self = .unknown + } + + init?(rawValue: Int) { + switch rawValue { + case 0: self = .unknown + case 1: self = .ascending + case 2: self = .descending + default: self = .UNRECOGNIZED(rawValue) + } + } + + var rawValue: Int { + switch self { + case .unknown: return 0 + case .ascending: return 1 + case .descending: return 2 + case .UNRECOGNIZED(let i): return i + } + } + +} + +#if swift(>=4.2) + +extension Io_Iohk_Atala_Prism_Protos_SortByDirection: CaseIterable { + // The compiler won't synthesize support with the UNRECOGNIZED case. + static var allCases: [Io_Iohk_Atala_Prism_Protos_SortByDirection] = [ + .unknown, + .ascending, + .descending, + ] +} + +#endif // swift(>=4.2) + +///* +/// The supported ledger types. Specifies which chain is used for storing transactions. +enum Io_Iohk_Atala_Prism_Protos_Ledger: SwiftProtobuf.Enum { + typealias RawValue = Int + + /// Invalid default value. + case unknownLedger // = 0 + + /// Store transactions in memory instead of blockchain, used only for development. + case inMemory // = 1 + + /// Cardano testnet, used for testing. + case cardanoTestnet // = 4 + + /// Cardano mainnet, used in production. + case cardanoMainnet // = 5 + case UNRECOGNIZED(Int) + + init() { + self = .unknownLedger + } + + init?(rawValue: Int) { + switch rawValue { + case 0: self = .unknownLedger + case 1: self = .inMemory + case 4: self = .cardanoTestnet + case 5: self = .cardanoMainnet + default: self = .UNRECOGNIZED(rawValue) + } + } + + var rawValue: Int { + switch self { + case .unknownLedger: return 0 + case .inMemory: return 1 + case .cardanoTestnet: return 4 + case .cardanoMainnet: return 5 + case .UNRECOGNIZED(let i): return i + } + } + +} + +#if swift(>=4.2) + +extension Io_Iohk_Atala_Prism_Protos_Ledger: CaseIterable { + // The compiler won't synthesize support with the UNRECOGNIZED case. + static var allCases: [Io_Iohk_Atala_Prism_Protos_Ledger] = [ + .unknownLedger, + .inMemory, + .cardanoTestnet, + .cardanoMainnet, + ] +} + +#endif // swift(>=4.2) + +///* +/// The status of an Atala operation. +enum Io_Iohk_Atala_Prism_Protos_OperationStatus: SwiftProtobuf.Enum { + typealias RawValue = Int + + /// The operation hasn't been received by the node service yet. + case unknownOperation // = 0 + + /// The transaction containing this operation hasn't been published to the chain yet. + case pendingSubmission // = 1 + + /// The transaction containing this operation has been published to the chain, but hasn't been processed by PRISM yet. + case awaitConfirmation // = 2 + + /// The operation has been successfully applied to the PRISM. + case confirmedAndApplied // = 3 + + /// The operation has been processed by PRISM, but rejected because of some error. + case confirmedAndRejected // = 4 + case UNRECOGNIZED(Int) + + init() { + self = .unknownOperation + } + + init?(rawValue: Int) { + switch rawValue { + case 0: self = .unknownOperation + case 1: self = .pendingSubmission + case 2: self = .awaitConfirmation + case 3: self = .confirmedAndApplied + case 4: self = .confirmedAndRejected + default: self = .UNRECOGNIZED(rawValue) + } + } + + var rawValue: Int { + switch self { + case .unknownOperation: return 0 + case .pendingSubmission: return 1 + case .awaitConfirmation: return 2 + case .confirmedAndApplied: return 3 + case .confirmedAndRejected: return 4 + case .UNRECOGNIZED(let i): return i + } + } + +} + +#if swift(>=4.2) + +extension Io_Iohk_Atala_Prism_Protos_OperationStatus: CaseIterable { + // The compiler won't synthesize support with the UNRECOGNIZED case. + static var allCases: [Io_Iohk_Atala_Prism_Protos_OperationStatus] = [ + .unknownOperation, + .pendingSubmission, + .awaitConfirmation, + .confirmedAndApplied, + .confirmedAndRejected, + ] +} + +#endif // swift(>=4.2) + +///* +/// A request that can be used to check service health. +/// All PRISM services expose an RPC that accepts this message as request. +struct Io_Iohk_Atala_Prism_Protos_HealthCheckRequest { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} +} + +///* +/// A response that represents service health. +/// Status code 0 with empty response represents a healthy and reachable service, +/// while all other status codes represent issues with the service. +struct Io_Iohk_Atala_Prism_Protos_HealthCheckResponse { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} +} + +///* +/// Represents a date by its parts (day, month, year). +struct Io_Iohk_Atala_Prism_Protos_Date { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// A positive value. + var year: Int32 = 0 + + /// A value in the [1, 12] range. + var month: Int32 = 0 + + /// A value in the [1, 31] range (depending on the month, the maximum value might be 28). + var day: Int32 = 0 + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} +} + +///* +/// Represents a time interval between two given timestamps. +/// The message represents a closed interval (i.e. both ends are inclusive and mandatory). +struct Io_Iohk_Atala_Prism_Protos_TimeInterval { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + ///* + /// The starting timestamp. + /// start_timestamp must be before or equal to end_timestamp. + var startTimestamp: SwiftProtobuf.Google_Protobuf_Timestamp { + get {return _startTimestamp ?? SwiftProtobuf.Google_Protobuf_Timestamp()} + set {_startTimestamp = newValue} + } + /// Returns true if `startTimestamp` has been explicitly set. + var hasStartTimestamp: Bool {return self._startTimestamp != nil} + /// Clears the value of `startTimestamp`. Subsequent reads from it will return its default value. + mutating func clearStartTimestamp() {self._startTimestamp = nil} + + ///* + /// The ending timestamp. + /// end_timestamp must be after or equal to start_timestamp. + var endTimestamp: SwiftProtobuf.Google_Protobuf_Timestamp { + get {return _endTimestamp ?? SwiftProtobuf.Google_Protobuf_Timestamp()} + set {_endTimestamp = newValue} + } + /// Returns true if `endTimestamp` has been explicitly set. + var hasEndTimestamp: Bool {return self._endTimestamp != nil} + /// Clears the value of `endTimestamp`. Subsequent reads from it will return its default value. + mutating func clearEndTimestamp() {self._endTimestamp = nil} + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} + + fileprivate var _startTimestamp: SwiftProtobuf.Google_Protobuf_Timestamp? = nil + fileprivate var _endTimestamp: SwiftProtobuf.Google_Protobuf_Timestamp? = nil +} + +///* +/// Information about a ledger block. +/// See Ledger documentation for details on which ledgers are possible. +struct Io_Iohk_Atala_Prism_Protos_BlockInfo { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Number of the block in the ledger. + var number: Int32 = 0 + + /// Index of the transaction within the block. + var index: Int32 = 0 + + /// Timestamp when the block was created. + var timestamp: SwiftProtobuf.Google_Protobuf_Timestamp { + get {return _timestamp ?? SwiftProtobuf.Google_Protobuf_Timestamp()} + set {_timestamp = newValue} + } + /// Returns true if `timestamp` has been explicitly set. + var hasTimestamp: Bool {return self._timestamp != nil} + /// Clears the value of `timestamp`. Subsequent reads from it will return its default value. + mutating func clearTimestamp() {self._timestamp = nil} + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} + + fileprivate var _timestamp: SwiftProtobuf.Google_Protobuf_Timestamp? = nil +} + +///* +/// Information about a ledger transaction and the block that the transaction is included in. +struct Io_Iohk_Atala_Prism_Protos_TransactionInfo { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Transaction ID. + var transactionID: String = String() + + /// Ledger the transaction was published to. + var ledger: Io_Iohk_Atala_Prism_Protos_Ledger = .unknownLedger + + /// Block the transaction was included in. + var block: Io_Iohk_Atala_Prism_Protos_BlockInfo { + get {return _block ?? Io_Iohk_Atala_Prism_Protos_BlockInfo()} + set {_block = newValue} + } + /// Returns true if `block` has been explicitly set. + var hasBlock: Bool {return self._block != nil} + /// Clears the value of `block`. Subsequent reads from it will return its default value. + mutating func clearBlock() {self._block = nil} + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} + + fileprivate var _block: Io_Iohk_Atala_Prism_Protos_BlockInfo? = nil +} + +// MARK: - Code below here is support for the SwiftProtobuf runtime. + +fileprivate let _protobuf_package = "io.iohk.atala.prism.protos" + +extension Io_Iohk_Atala_Prism_Protos_SortByDirection: SwiftProtobuf._ProtoNameProviding { + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 0: .same(proto: "SORT_BY_DIRECTION_UNKNOWN"), + 1: .same(proto: "SORT_BY_DIRECTION_ASCENDING"), + 2: .same(proto: "SORT_BY_DIRECTION_DESCENDING"), + ] +} + +extension Io_Iohk_Atala_Prism_Protos_Ledger: SwiftProtobuf._ProtoNameProviding { + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 0: .same(proto: "UNKNOWN_LEDGER"), + 1: .same(proto: "IN_MEMORY"), + 4: .same(proto: "CARDANO_TESTNET"), + 5: .same(proto: "CARDANO_MAINNET"), + ] +} + +extension Io_Iohk_Atala_Prism_Protos_OperationStatus: SwiftProtobuf._ProtoNameProviding { + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 0: .same(proto: "UNKNOWN_OPERATION"), + 1: .same(proto: "PENDING_SUBMISSION"), + 2: .same(proto: "AWAIT_CONFIRMATION"), + 3: .same(proto: "CONFIRMED_AND_APPLIED"), + 4: .same(proto: "CONFIRMED_AND_REJECTED"), + ] +} + +extension Io_Iohk_Atala_Prism_Protos_HealthCheckRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".HealthCheckRequest" + static let _protobuf_nameMap = SwiftProtobuf._NameMap() + + mutating func decodeMessage(decoder: inout D) throws { + while let _ = try decoder.nextFieldNumber() { + } + } + + func traverse(visitor: inout V) throws { + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_HealthCheckRequest, rhs: Io_Iohk_Atala_Prism_Protos_HealthCheckRequest) -> Bool { + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_HealthCheckResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".HealthCheckResponse" + static let _protobuf_nameMap = SwiftProtobuf._NameMap() + + mutating func decodeMessage(decoder: inout D) throws { + while let _ = try decoder.nextFieldNumber() { + } + } + + func traverse(visitor: inout V) throws { + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_HealthCheckResponse, rhs: Io_Iohk_Atala_Prism_Protos_HealthCheckResponse) -> Bool { + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_Date: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".Date" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .same(proto: "year"), + 2: .same(proto: "month"), + 3: .same(proto: "day"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularInt32Field(value: &self.year) }() + case 2: try { try decoder.decodeSingularInt32Field(value: &self.month) }() + case 3: try { try decoder.decodeSingularInt32Field(value: &self.day) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if self.year != 0 { + try visitor.visitSingularInt32Field(value: self.year, fieldNumber: 1) + } + if self.month != 0 { + try visitor.visitSingularInt32Field(value: self.month, fieldNumber: 2) + } + if self.day != 0 { + try visitor.visitSingularInt32Field(value: self.day, fieldNumber: 3) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_Date, rhs: Io_Iohk_Atala_Prism_Protos_Date) -> Bool { + if lhs.year != rhs.year {return false} + if lhs.month != rhs.month {return false} + if lhs.day != rhs.day {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_TimeInterval: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".TimeInterval" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .standard(proto: "start_timestamp"), + 2: .standard(proto: "end_timestamp"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularMessageField(value: &self._startTimestamp) }() + case 2: try { try decoder.decodeSingularMessageField(value: &self._endTimestamp) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if let v = self._startTimestamp { + try visitor.visitSingularMessageField(value: v, fieldNumber: 1) + } + if let v = self._endTimestamp { + try visitor.visitSingularMessageField(value: v, fieldNumber: 2) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_TimeInterval, rhs: Io_Iohk_Atala_Prism_Protos_TimeInterval) -> Bool { + if lhs._startTimestamp != rhs._startTimestamp {return false} + if lhs._endTimestamp != rhs._endTimestamp {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_BlockInfo: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".BlockInfo" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .same(proto: "number"), + 3: .same(proto: "index"), + 4: .same(proto: "timestamp"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularInt32Field(value: &self.number) }() + case 3: try { try decoder.decodeSingularInt32Field(value: &self.index) }() + case 4: try { try decoder.decodeSingularMessageField(value: &self._timestamp) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if self.number != 0 { + try visitor.visitSingularInt32Field(value: self.number, fieldNumber: 1) + } + if self.index != 0 { + try visitor.visitSingularInt32Field(value: self.index, fieldNumber: 3) + } + if let v = self._timestamp { + try visitor.visitSingularMessageField(value: v, fieldNumber: 4) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_BlockInfo, rhs: Io_Iohk_Atala_Prism_Protos_BlockInfo) -> Bool { + if lhs.number != rhs.number {return false} + if lhs.index != rhs.index {return false} + if lhs._timestamp != rhs._timestamp {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_TransactionInfo: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".TransactionInfo" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .standard(proto: "transaction_id"), + 2: .same(proto: "ledger"), + 3: .same(proto: "block"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &self.transactionID) }() + case 2: try { try decoder.decodeSingularEnumField(value: &self.ledger) }() + case 3: try { try decoder.decodeSingularMessageField(value: &self._block) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if !self.transactionID.isEmpty { + try visitor.visitSingularStringField(value: self.transactionID, fieldNumber: 1) + } + if self.ledger != .unknownLedger { + try visitor.visitSingularEnumField(value: self.ledger, fieldNumber: 2) + } + if let v = self._block { + try visitor.visitSingularMessageField(value: v, fieldNumber: 3) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_TransactionInfo, rhs: Io_Iohk_Atala_Prism_Protos_TransactionInfo) -> Bool { + if lhs.transactionID != rhs.transactionID {return false} + if lhs.ledger != rhs.ledger {return false} + if lhs._block != rhs._block {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} diff --git a/AtalaPrismSDK/Castor/Sources/protobuf/node_models.pb.swift b/AtalaPrismSDK/Castor/Sources/protobuf/node_models.pb.swift new file mode 100644 index 00000000..f8c3dfa5 --- /dev/null +++ b/AtalaPrismSDK/Castor/Sources/protobuf/node_models.pb.swift @@ -0,0 +1,2748 @@ +// DO NOT EDIT. +// swift-format-ignore-file +// +// Generated by the Swift generator plugin for the protocol buffer compiler. +// Source: node_models.proto +// +// For information on using the generated types, please see the documentation: +// https://github.com/apple/swift-protobuf/ + +import Foundation +import SwiftProtobuf + +// If the compiler emits an error on this type, it is because this file +// was generated by a version of the `protoc` Swift plug-in that is +// incompatible with the version of SwiftProtobuf to which you are linking. +// Please ensure that you are building against the same version of the API +// that was used to generate this file. +fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { + struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} + typealias Version = _2 +} + +/// Every key has a single purpose: +enum Io_Iohk_Atala_Prism_Protos_KeyUsage: SwiftProtobuf.Enum { + typealias RawValue = Int + + /// UNKNOWN_KEY is an invalid value - Protobuf uses 0 if no value is provided and we want the user to explicitly choose the usage. + case unknownKey // = 0 + + /// This is the most privileged key-type, when any other key is lost, you could use this to recover the others. + case masterKey // = 1 + + /// This key-type is used for issuing credentials only, it should be kept in a safe place + /// to avoid malicious credentials being issued. + case issuingKey // = 2 + + /// This key-type is used to establish a shared symmetric key for secure end-to end communication + /// use this key-type to encrypt the content. + case keyAgreementKey // = 3 + + /// This key-type is used to authenticate requests or logging into services. + case authenticationKey // = 4 + + /// This key-type is used for revoking credentials only, it should be kept in a safe place + /// to avoid malicious credentials being issued. + case revocationKey // = 5 + + /// This key-type is used to specify a verification method that might be used by the DID subject to invoke a cryptographic capability, + /// such as the authorization to update the DID Document. + case capabilityInvocationKey // = 6 + + /// This is used to specify a mechanism that might be used by the DID subject to delegate a cryptographic capability to another party, + /// such as delegating the authority to access a specific HTTP API to a subordinate. + case capabilityDelegationKey // = 7 + case UNRECOGNIZED(Int) + + init() { + self = .unknownKey + } + + init?(rawValue: Int) { + switch rawValue { + case 0: self = .unknownKey + case 1: self = .masterKey + case 2: self = .issuingKey + case 3: self = .keyAgreementKey + case 4: self = .authenticationKey + case 5: self = .revocationKey + case 6: self = .capabilityInvocationKey + case 7: self = .capabilityDelegationKey + default: self = .UNRECOGNIZED(rawValue) + } + } + + var rawValue: Int { + switch self { + case .unknownKey: return 0 + case .masterKey: return 1 + case .issuingKey: return 2 + case .keyAgreementKey: return 3 + case .authenticationKey: return 4 + case .revocationKey: return 5 + case .capabilityInvocationKey: return 6 + case .capabilityDelegationKey: return 7 + case .UNRECOGNIZED(let i): return i + } + } + +} + +#if swift(>=4.2) + +extension Io_Iohk_Atala_Prism_Protos_KeyUsage: CaseIterable { + // The compiler won't synthesize support with the UNRECOGNIZED case. + static var allCases: [Io_Iohk_Atala_Prism_Protos_KeyUsage] = [ + .unknownKey, + .masterKey, + .issuingKey, + .keyAgreementKey, + .authenticationKey, + .revocationKey, + .capabilityInvocationKey, + .capabilityDelegationKey, + ] +} + +#endif // swift(>=4.2) + +/// Includes timestamping details about a blockchain's block. +struct Io_Iohk_Atala_Prism_Protos_TimestampInfo { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// The transaction index inside the underlying block. + var blockSequenceNumber: UInt32 = 0 + + /// The operation index inside the AtalaBlock. + var operationSequenceNumber: UInt32 = 0 + + /// The timestamp provided from the underlying blockchain. + var blockTimestamp: SwiftProtobuf.Google_Protobuf_Timestamp { + get {return _blockTimestamp ?? SwiftProtobuf.Google_Protobuf_Timestamp()} + set {_blockTimestamp = newValue} + } + /// Returns true if `blockTimestamp` has been explicitly set. + var hasBlockTimestamp: Bool {return self._blockTimestamp != nil} + /// Clears the value of `blockTimestamp`. Subsequent reads from it will return its default value. + mutating func clearBlockTimestamp() {self._blockTimestamp = nil} + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} + + fileprivate var _blockTimestamp: SwiftProtobuf.Google_Protobuf_Timestamp? = nil +} + +///* +/// Holds the necessary data to recover an Elliptic Curve (EC)'s public key. +/// @exclude TODO: Consider renaming this to ECPublicKeyData. +struct Io_Iohk_Atala_Prism_Protos_ECKeyData { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// The curve name, like secp256k1. + var curve: String = String() + + /// The x coordinate, represented as bytes. + var x: Data = Data() + + /// The y coordinate, represented as bytes. + var y: Data = Data() + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} +} + +///* +/// Holds the compressed representation of data needed to recover Elliptic Curve (EC)'s public key. +/// @exclude TODO: Consider renaming this to CompressedECPublicKeyData. +struct Io_Iohk_Atala_Prism_Protos_CompressedECKeyData { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// The curve name, like secp256k1. + var curve: String = String() + + /// compressed Elliptic Curve (EC) public key data. + var data: Data = Data() + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} +} + +///* +/// Represents a public key with metadata, necessary for a DID document. +/// @exclude TODO: Consider renaming this to something more specific, like DIDPublicKey. +struct Io_Iohk_Atala_Prism_Protos_PublicKey { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// The key identifier within the DID Document. + var id: String { + get {return _storage._id} + set {_uniqueStorage()._id = newValue} + } + + /// The key's purpose. + var usage: Io_Iohk_Atala_Prism_Protos_KeyUsage { + get {return _storage._usage} + set {_uniqueStorage()._usage = newValue} + } + + /// The ledger details related to the event that added the key to the DID Document. + var addedOn: Io_Iohk_Atala_Prism_Protos_LedgerData { + get {return _storage._addedOn ?? Io_Iohk_Atala_Prism_Protos_LedgerData()} + set {_uniqueStorage()._addedOn = newValue} + } + /// Returns true if `addedOn` has been explicitly set. + var hasAddedOn: Bool {return _storage._addedOn != nil} + /// Clears the value of `addedOn`. Subsequent reads from it will return its default value. + mutating func clearAddedOn() {_uniqueStorage()._addedOn = nil} + + /// The ledger details related to the event that revoked the key to the DID Document. + var revokedOn: Io_Iohk_Atala_Prism_Protos_LedgerData { + get {return _storage._revokedOn ?? Io_Iohk_Atala_Prism_Protos_LedgerData()} + set {_uniqueStorage()._revokedOn = newValue} + } + /// Returns true if `revokedOn` has been explicitly set. + var hasRevokedOn: Bool {return _storage._revokedOn != nil} + /// Clears the value of `revokedOn`. Subsequent reads from it will return its default value. + mutating func clearRevokedOn() {_uniqueStorage()._revokedOn = nil} + + /// The key's representation. + var keyData: OneOf_KeyData? { + get {return _storage._keyData} + set {_uniqueStorage()._keyData = newValue} + } + + /// The Elliptic Curve (EC) key. + var ecKeyData: Io_Iohk_Atala_Prism_Protos_ECKeyData { + get { + if case .ecKeyData(let v)? = _storage._keyData {return v} + return Io_Iohk_Atala_Prism_Protos_ECKeyData() + } + set {_uniqueStorage()._keyData = .ecKeyData(newValue)} + } + + /// Compressed Elliptic Curve (EC) key. + var compressedEcKeyData: Io_Iohk_Atala_Prism_Protos_CompressedECKeyData { + get { + if case .compressedEcKeyData(let v)? = _storage._keyData {return v} + return Io_Iohk_Atala_Prism_Protos_CompressedECKeyData() + } + set {_uniqueStorage()._keyData = .compressedEcKeyData(newValue)} + } + + var unknownFields = SwiftProtobuf.UnknownStorage() + + /// The key's representation. + enum OneOf_KeyData: Equatable { + /// The Elliptic Curve (EC) key. + case ecKeyData(Io_Iohk_Atala_Prism_Protos_ECKeyData) + /// Compressed Elliptic Curve (EC) key. + case compressedEcKeyData(Io_Iohk_Atala_Prism_Protos_CompressedECKeyData) + + #if !swift(>=4.1) + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_PublicKey.OneOf_KeyData, rhs: Io_Iohk_Atala_Prism_Protos_PublicKey.OneOf_KeyData) -> Bool { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch (lhs, rhs) { + case (.ecKeyData, .ecKeyData): return { + guard case .ecKeyData(let l) = lhs, case .ecKeyData(let r) = rhs else { preconditionFailure() } + return l == r + }() + case (.compressedEcKeyData, .compressedEcKeyData): return { + guard case .compressedEcKeyData(let l) = lhs, case .compressedEcKeyData(let r) = rhs else { preconditionFailure() } + return l == r + }() + default: return false + } + } + #endif + } + + init() {} + + fileprivate var _storage = _StorageClass.defaultInstance +} + +/// The DID Document's data. +struct Io_Iohk_Atala_Prism_Protos_DIDData { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// The DID suffix, where DID is in form did:prism:[DID suffix] + var id: String = String() + + /// The keys that belong to this DID Document. + var publicKeys: [Io_Iohk_Atala_Prism_Protos_PublicKey] = [] + + /// The list of services that belong to this DID Document. + var services: [Io_Iohk_Atala_Prism_Protos_Service] = [] + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} +} + +/// The operation to create a public DID. +struct Io_Iohk_Atala_Prism_Protos_CreateDIDOperation { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// DIDCreationData with public keys and services + var didData: Io_Iohk_Atala_Prism_Protos_CreateDIDOperation.DIDCreationData { + get {return _didData ?? Io_Iohk_Atala_Prism_Protos_CreateDIDOperation.DIDCreationData()} + set {_didData = newValue} + } + /// Returns true if `didData` has been explicitly set. + var hasDidData: Bool {return self._didData != nil} + /// Clears the value of `didData`. Subsequent reads from it will return its default value. + mutating func clearDidData() {self._didData = nil} + + var unknownFields = SwiftProtobuf.UnknownStorage() + + /// The data necessary to create a DID. + struct DIDCreationData { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// The keys that belong to this DID Document. + var publicKeys: [Io_Iohk_Atala_Prism_Protos_PublicKey] = [] + + /// The list of services that belong to this DID Document. + var services: [Io_Iohk_Atala_Prism_Protos_Service] = [] + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} + } + + init() {} + + fileprivate var _didData: Io_Iohk_Atala_Prism_Protos_CreateDIDOperation.DIDCreationData? = nil +} + +/// The necessary data to add a key to a DID. +struct Io_Iohk_Atala_Prism_Protos_AddKeyAction { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// The key to include. + var key: Io_Iohk_Atala_Prism_Protos_PublicKey { + get {return _key ?? Io_Iohk_Atala_Prism_Protos_PublicKey()} + set {_key = newValue} + } + /// Returns true if `key` has been explicitly set. + var hasKey: Bool {return self._key != nil} + /// Clears the value of `key`. Subsequent reads from it will return its default value. + mutating func clearKey() {self._key = nil} + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} + + fileprivate var _key: Io_Iohk_Atala_Prism_Protos_PublicKey? = nil +} + +/// The necessary data to remove a key from a DID. +struct Io_Iohk_Atala_Prism_Protos_RemoveKeyAction { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// the key id to remove + var keyID: String = String() + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} +} + +struct Io_Iohk_Atala_Prism_Protos_AddServiceAction { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + var service: Io_Iohk_Atala_Prism_Protos_Service { + get {return _service ?? Io_Iohk_Atala_Prism_Protos_Service()} + set {_service = newValue} + } + /// Returns true if `service` has been explicitly set. + var hasService: Bool {return self._service != nil} + /// Clears the value of `service`. Subsequent reads from it will return its default value. + mutating func clearService() {self._service = nil} + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} + + fileprivate var _service: Io_Iohk_Atala_Prism_Protos_Service? = nil +} + +struct Io_Iohk_Atala_Prism_Protos_RemoveServiceAction { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + var serviceID: String = String() + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} +} + +struct Io_Iohk_Atala_Prism_Protos_UpdateServiceAction { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// scoped to the did, unique per did + var serviceID: String = String() + + /// new type if provided + var type: String = String() + + /// Will replace all existing service endpoints of the service with provided ones + var serviceEndpoints: [String] = [] + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} +} + +/// The potential details that can be updated in a DID. +struct Io_Iohk_Atala_Prism_Protos_UpdateDIDAction { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// The action to perform. + var action: Io_Iohk_Atala_Prism_Protos_UpdateDIDAction.OneOf_Action? = nil + + /// Used to add a new key to the DID. + var addKey: Io_Iohk_Atala_Prism_Protos_AddKeyAction { + get { + if case .addKey(let v)? = action {return v} + return Io_Iohk_Atala_Prism_Protos_AddKeyAction() + } + set {action = .addKey(newValue)} + } + + /// Used to remove a key from the DID. + var removeKey: Io_Iohk_Atala_Prism_Protos_RemoveKeyAction { + get { + if case .removeKey(let v)? = action {return v} + return Io_Iohk_Atala_Prism_Protos_RemoveKeyAction() + } + set {action = .removeKey(newValue)} + } + + /// Used to add a new service to a DID, + var addService: Io_Iohk_Atala_Prism_Protos_AddServiceAction { + get { + if case .addService(let v)? = action {return v} + return Io_Iohk_Atala_Prism_Protos_AddServiceAction() + } + set {action = .addService(newValue)} + } + + /// Used to remove an existing service from a DID, + var removeService: Io_Iohk_Atala_Prism_Protos_RemoveServiceAction { + get { + if case .removeService(let v)? = action {return v} + return Io_Iohk_Atala_Prism_Protos_RemoveServiceAction() + } + set {action = .removeService(newValue)} + } + + /// Used to Update a list of service endpoints of a given service on a given DID. + var updateService: Io_Iohk_Atala_Prism_Protos_UpdateServiceAction { + get { + if case .updateService(let v)? = action {return v} + return Io_Iohk_Atala_Prism_Protos_UpdateServiceAction() + } + set {action = .updateService(newValue)} + } + + var unknownFields = SwiftProtobuf.UnknownStorage() + + /// The action to perform. + enum OneOf_Action: Equatable { + /// Used to add a new key to the DID. + case addKey(Io_Iohk_Atala_Prism_Protos_AddKeyAction) + /// Used to remove a key from the DID. + case removeKey(Io_Iohk_Atala_Prism_Protos_RemoveKeyAction) + /// Used to add a new service to a DID, + case addService(Io_Iohk_Atala_Prism_Protos_AddServiceAction) + /// Used to remove an existing service from a DID, + case removeService(Io_Iohk_Atala_Prism_Protos_RemoveServiceAction) + /// Used to Update a list of service endpoints of a given service on a given DID. + case updateService(Io_Iohk_Atala_Prism_Protos_UpdateServiceAction) + + #if !swift(>=4.1) + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_UpdateDIDAction.OneOf_Action, rhs: Io_Iohk_Atala_Prism_Protos_UpdateDIDAction.OneOf_Action) -> Bool { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch (lhs, rhs) { + case (.addKey, .addKey): return { + guard case .addKey(let l) = lhs, case .addKey(let r) = rhs else { preconditionFailure() } + return l == r + }() + case (.removeKey, .removeKey): return { + guard case .removeKey(let l) = lhs, case .removeKey(let r) = rhs else { preconditionFailure() } + return l == r + }() + case (.addService, .addService): return { + guard case .addService(let l) = lhs, case .addService(let r) = rhs else { preconditionFailure() } + return l == r + }() + case (.removeService, .removeService): return { + guard case .removeService(let l) = lhs, case .removeService(let r) = rhs else { preconditionFailure() } + return l == r + }() + case (.updateService, .updateService): return { + guard case .updateService(let l) = lhs, case .updateService(let r) = rhs else { preconditionFailure() } + return l == r + }() + default: return false + } + } + #endif + } + + init() {} +} + +/// Specifies the necessary data to update a public DID. +struct Io_Iohk_Atala_Prism_Protos_UpdateDIDOperation { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// The hash of the operation that issued the DID. + var previousOperationHash: Data = Data() + + /// @exclude TODO: To be redefined after we start using this operation. + var id: String = String() + + /// The actual updates to perform on the DID. + var actions: [Io_Iohk_Atala_Prism_Protos_UpdateDIDAction] = [] + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} +} + +/// Represents a credential's batch. +/// +/// Check the protocol docs to understand it. +struct Io_Iohk_Atala_Prism_Protos_CredentialBatchData { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// The DID suffix that issues the credential's batch. + var issuerDid: String = String() + + /// The Merkle root for the credential's batch. + var merkleRoot: Data = Data() + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} +} + +/// Specifies the data to issue a credential batch. +struct Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOperation { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// The actual credential batch data. + var credentialBatchData: Io_Iohk_Atala_Prism_Protos_CredentialBatchData { + get {return _credentialBatchData ?? Io_Iohk_Atala_Prism_Protos_CredentialBatchData()} + set {_credentialBatchData = newValue} + } + /// Returns true if `credentialBatchData` has been explicitly set. + var hasCredentialBatchData: Bool {return self._credentialBatchData != nil} + /// Clears the value of `credentialBatchData`. Subsequent reads from it will return its default value. + mutating func clearCredentialBatchData() {self._credentialBatchData = nil} + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} + + fileprivate var _credentialBatchData: Io_Iohk_Atala_Prism_Protos_CredentialBatchData? = nil +} + +/// Specifies the credentials to revoke (the whole batch, or just a subset of it). +struct Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOperation { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// The hash of the operation that issued the batch. + var previousOperationHash: Data = Data() + + /// The corresponding batch ID, as returned in IssueCredentialBatchResponse. + var credentialBatchID: String = String() + + /// The hashes of the credentials to revoke. If empty, the full batch is revoked. + var credentialsToRevoke: [Data] = [] + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} +} + +/// Specifies the protocol version update +struct Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOperation { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// The DID suffix that proposes the protocol update. + var proposerDid: String = String() + + /// Information of the new version + var version: Io_Iohk_Atala_Prism_Protos_ProtocolVersionInfo { + get {return _version ?? Io_Iohk_Atala_Prism_Protos_ProtocolVersionInfo()} + set {_version = newValue} + } + /// Returns true if `version` has been explicitly set. + var hasVersion: Bool {return self._version != nil} + /// Clears the value of `version`. Subsequent reads from it will return its default value. + mutating func clearVersion() {self._version = nil} + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} + + fileprivate var _version: Io_Iohk_Atala_Prism_Protos_ProtocolVersionInfo? = nil +} + +struct Io_Iohk_Atala_Prism_Protos_ProtocolVersion { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// Represent the major version + var majorVersion: Int32 = 0 + + /// Represent the minor version + var minorVersion: Int32 = 0 + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} +} + +struct Io_Iohk_Atala_Prism_Protos_ProtocolVersionInfo { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// (optional) name of the version + var versionName: String = String() + + /// Cardano block number that tells since which block the update is enforced + var effectiveSince: Int32 = 0 + + /// New major and minor version to be announced, + /// If major value changes, the node MUST stop issuing and reading operations, and upgrade before `effective_since` because the new protocol version. + /// If minor value changes, the node can opt to not update. All events _published_ by this node would be also + /// understood by other nodes with the same major version. However, there may be new events that this node won't _read_ + var protocolVersion: Io_Iohk_Atala_Prism_Protos_ProtocolVersion { + get {return _protocolVersion ?? Io_Iohk_Atala_Prism_Protos_ProtocolVersion()} + set {_protocolVersion = newValue} + } + /// Returns true if `protocolVersion` has been explicitly set. + var hasProtocolVersion: Bool {return self._protocolVersion != nil} + /// Clears the value of `protocolVersion`. Subsequent reads from it will return its default value. + mutating func clearProtocolVersion() {self._protocolVersion = nil} + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} + + fileprivate var _protocolVersion: Io_Iohk_Atala_Prism_Protos_ProtocolVersion? = nil +} + +struct Io_Iohk_Atala_Prism_Protos_DeactivateDIDOperation { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// The hash of the operation that issued the DID. + var previousOperationHash: Data = Data() + + /// DID Suffix of the DID to be deactivated + var id: String = String() + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} +} + +/// The possible operations affecting the blockchain. +struct Io_Iohk_Atala_Prism_Protos_AtalaOperation { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// The actual operation. + var operation: Io_Iohk_Atala_Prism_Protos_AtalaOperation.OneOf_Operation? = nil + + /// Used to create a public DID. + var createDid: Io_Iohk_Atala_Prism_Protos_CreateDIDOperation { + get { + if case .createDid(let v)? = operation {return v} + return Io_Iohk_Atala_Prism_Protos_CreateDIDOperation() + } + set {operation = .createDid(newValue)} + } + + /// Used to update an existing public DID. + var updateDid: Io_Iohk_Atala_Prism_Protos_UpdateDIDOperation { + get { + if case .updateDid(let v)? = operation {return v} + return Io_Iohk_Atala_Prism_Protos_UpdateDIDOperation() + } + set {operation = .updateDid(newValue)} + } + + /// Used to issue a batch of credentials. + var issueCredentialBatch: Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOperation { + get { + if case .issueCredentialBatch(let v)? = operation {return v} + return Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOperation() + } + set {operation = .issueCredentialBatch(newValue)} + } + + /// Used to revoke a credential batch. + var revokeCredentials: Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOperation { + get { + if case .revokeCredentials(let v)? = operation {return v} + return Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOperation() + } + set {operation = .revokeCredentials(newValue)} + } + + /// Used to announce new protocol update + var protocolVersionUpdate: Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOperation { + get { + if case .protocolVersionUpdate(let v)? = operation {return v} + return Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOperation() + } + set {operation = .protocolVersionUpdate(newValue)} + } + + /// Used to deactivate DID + var deactivateDid: Io_Iohk_Atala_Prism_Protos_DeactivateDIDOperation { + get { + if case .deactivateDid(let v)? = operation {return v} + return Io_Iohk_Atala_Prism_Protos_DeactivateDIDOperation() + } + set {operation = .deactivateDid(newValue)} + } + + var unknownFields = SwiftProtobuf.UnknownStorage() + + /// The actual operation. + enum OneOf_Operation: Equatable { + /// Used to create a public DID. + case createDid(Io_Iohk_Atala_Prism_Protos_CreateDIDOperation) + /// Used to update an existing public DID. + case updateDid(Io_Iohk_Atala_Prism_Protos_UpdateDIDOperation) + /// Used to issue a batch of credentials. + case issueCredentialBatch(Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOperation) + /// Used to revoke a credential batch. + case revokeCredentials(Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOperation) + /// Used to announce new protocol update + case protocolVersionUpdate(Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOperation) + /// Used to deactivate DID + case deactivateDid(Io_Iohk_Atala_Prism_Protos_DeactivateDIDOperation) + + #if !swift(>=4.1) + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_AtalaOperation.OneOf_Operation, rhs: Io_Iohk_Atala_Prism_Protos_AtalaOperation.OneOf_Operation) -> Bool { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch (lhs, rhs) { + case (.createDid, .createDid): return { + guard case .createDid(let l) = lhs, case .createDid(let r) = rhs else { preconditionFailure() } + return l == r + }() + case (.updateDid, .updateDid): return { + guard case .updateDid(let l) = lhs, case .updateDid(let r) = rhs else { preconditionFailure() } + return l == r + }() + case (.issueCredentialBatch, .issueCredentialBatch): return { + guard case .issueCredentialBatch(let l) = lhs, case .issueCredentialBatch(let r) = rhs else { preconditionFailure() } + return l == r + }() + case (.revokeCredentials, .revokeCredentials): return { + guard case .revokeCredentials(let l) = lhs, case .revokeCredentials(let r) = rhs else { preconditionFailure() } + return l == r + }() + case (.protocolVersionUpdate, .protocolVersionUpdate): return { + guard case .protocolVersionUpdate(let l) = lhs, case .protocolVersionUpdate(let r) = rhs else { preconditionFailure() } + return l == r + }() + case (.deactivateDid, .deactivateDid): return { + guard case .deactivateDid(let l) = lhs, case .deactivateDid(let r) = rhs else { preconditionFailure() } + return l == r + }() + default: return false + } + } + #endif + } + + init() {} +} + +/// A signed operation, necessary to post anything on the blockchain. +struct Io_Iohk_Atala_Prism_Protos_SignedAtalaOperation { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// The key ID used to sign the operation, it must belong to the DID that signs the operation. + var signedWith: String = String() + + /// The actual signature. + var signature: Data = Data() + + /// The operation that was signed. + var operation: Io_Iohk_Atala_Prism_Protos_AtalaOperation { + get {return _operation ?? Io_Iohk_Atala_Prism_Protos_AtalaOperation()} + set {_operation = newValue} + } + /// Returns true if `operation` has been explicitly set. + var hasOperation: Bool {return self._operation != nil} + /// Clears the value of `operation`. Subsequent reads from it will return its default value. + mutating func clearOperation() {self._operation = nil} + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} + + fileprivate var _operation: Io_Iohk_Atala_Prism_Protos_AtalaOperation? = nil +} + +/// Ledger data associated to a protocol event. +/// Note that the difference with TransactionInfo is that this message contains a full +/// timestamp, and there is no expectation for it to be optional. +struct Io_Iohk_Atala_Prism_Protos_LedgerData { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + /// ID of the transaction. + var transactionID: String = String() + + /// Ledger the transaction was published to. + var ledger: Io_Iohk_Atala_Prism_Protos_Ledger = .unknownLedger + + /// The timestamp of the protocol event. + var timestampInfo: Io_Iohk_Atala_Prism_Protos_TimestampInfo { + get {return _timestampInfo ?? Io_Iohk_Atala_Prism_Protos_TimestampInfo()} + set {_timestampInfo = newValue} + } + /// Returns true if `timestampInfo` has been explicitly set. + var hasTimestampInfo: Bool {return self._timestampInfo != nil} + /// Clears the value of `timestampInfo`. Subsequent reads from it will return its default value. + mutating func clearTimestampInfo() {self._timestampInfo = nil} + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} + + fileprivate var _timestampInfo: Io_Iohk_Atala_Prism_Protos_TimestampInfo? = nil +} + +/// Used to encode the responses of the operations issued in an AtalaBlock. +struct Io_Iohk_Atala_Prism_Protos_OperationOutput { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + var result: Io_Iohk_Atala_Prism_Protos_OperationOutput.OneOf_Result? = nil + + /// Represents the response provided by IssueCredentialBatchOperation. + var batchOutput: Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOutput { + get { + if case .batchOutput(let v)? = result {return v} + return Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOutput() + } + set {result = .batchOutput(newValue)} + } + + /// Represents the response provided by CreateDIDOperation. + var createDidOutput: Io_Iohk_Atala_Prism_Protos_CreateDIDOutput { + get { + if case .createDidOutput(let v)? = result {return v} + return Io_Iohk_Atala_Prism_Protos_CreateDIDOutput() + } + set {result = .createDidOutput(newValue)} + } + + /// Represents the response provided by UpdateDIDOperation. + var updateDidOutput: Io_Iohk_Atala_Prism_Protos_UpdateDIDOutput { + get { + if case .updateDidOutput(let v)? = result {return v} + return Io_Iohk_Atala_Prism_Protos_UpdateDIDOutput() + } + set {result = .updateDidOutput(newValue)} + } + + /// Represents the response provided by RevokeCredentialOperation. + var revokeCredentialsOutput: Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOutput { + get { + if case .revokeCredentialsOutput(let v)? = result {return v} + return Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOutput() + } + set {result = .revokeCredentialsOutput(newValue)} + } + + /// Represents the response provided by ProtocolVersionUpdateOperation. + var protocolVersionUpdateOutput: Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOutput { + get { + if case .protocolVersionUpdateOutput(let v)? = result {return v} + return Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOutput() + } + set {result = .protocolVersionUpdateOutput(newValue)} + } + + var deactivateDidOutput: Io_Iohk_Atala_Prism_Protos_DeactivateDIDOutput { + get { + if case .deactivateDidOutput(let v)? = result {return v} + return Io_Iohk_Atala_Prism_Protos_DeactivateDIDOutput() + } + set {result = .deactivateDidOutput(newValue)} + } + + var operationMaybe: Io_Iohk_Atala_Prism_Protos_OperationOutput.OneOf_OperationMaybe? = nil + + /// Operation identifier. + var operationID: Data { + get { + if case .operationID(let v)? = operationMaybe {return v} + return Data() + } + set {operationMaybe = .operationID(newValue)} + } + + /// Error description if PRISM Node service haven't scheduled the operation. + var error: String { + get { + if case .error(let v)? = operationMaybe {return v} + return String() + } + set {operationMaybe = .error(newValue)} + } + + var unknownFields = SwiftProtobuf.UnknownStorage() + + enum OneOf_Result: Equatable { + /// Represents the response provided by IssueCredentialBatchOperation. + case batchOutput(Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOutput) + /// Represents the response provided by CreateDIDOperation. + case createDidOutput(Io_Iohk_Atala_Prism_Protos_CreateDIDOutput) + /// Represents the response provided by UpdateDIDOperation. + case updateDidOutput(Io_Iohk_Atala_Prism_Protos_UpdateDIDOutput) + /// Represents the response provided by RevokeCredentialOperation. + case revokeCredentialsOutput(Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOutput) + /// Represents the response provided by ProtocolVersionUpdateOperation. + case protocolVersionUpdateOutput(Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOutput) + case deactivateDidOutput(Io_Iohk_Atala_Prism_Protos_DeactivateDIDOutput) + + #if !swift(>=4.1) + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_OperationOutput.OneOf_Result, rhs: Io_Iohk_Atala_Prism_Protos_OperationOutput.OneOf_Result) -> Bool { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch (lhs, rhs) { + case (.batchOutput, .batchOutput): return { + guard case .batchOutput(let l) = lhs, case .batchOutput(let r) = rhs else { preconditionFailure() } + return l == r + }() + case (.createDidOutput, .createDidOutput): return { + guard case .createDidOutput(let l) = lhs, case .createDidOutput(let r) = rhs else { preconditionFailure() } + return l == r + }() + case (.updateDidOutput, .updateDidOutput): return { + guard case .updateDidOutput(let l) = lhs, case .updateDidOutput(let r) = rhs else { preconditionFailure() } + return l == r + }() + case (.revokeCredentialsOutput, .revokeCredentialsOutput): return { + guard case .revokeCredentialsOutput(let l) = lhs, case .revokeCredentialsOutput(let r) = rhs else { preconditionFailure() } + return l == r + }() + case (.protocolVersionUpdateOutput, .protocolVersionUpdateOutput): return { + guard case .protocolVersionUpdateOutput(let l) = lhs, case .protocolVersionUpdateOutput(let r) = rhs else { preconditionFailure() } + return l == r + }() + case (.deactivateDidOutput, .deactivateDidOutput): return { + guard case .deactivateDidOutput(let l) = lhs, case .deactivateDidOutput(let r) = rhs else { preconditionFailure() } + return l == r + }() + default: return false + } + } + #endif + } + + enum OneOf_OperationMaybe: Equatable { + /// Operation identifier. + case operationID(Data) + /// Error description if PRISM Node service haven't scheduled the operation. + case error(String) + + #if !swift(>=4.1) + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_OperationOutput.OneOf_OperationMaybe, rhs: Io_Iohk_Atala_Prism_Protos_OperationOutput.OneOf_OperationMaybe) -> Bool { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch (lhs, rhs) { + case (.operationID, .operationID): return { + guard case .operationID(let l) = lhs, case .operationID(let r) = rhs else { preconditionFailure() } + return l == r + }() + case (.error, .error): return { + guard case .error(let l) = lhs, case .error(let r) = rhs else { preconditionFailure() } + return l == r + }() + default: return false + } + } + #endif + } + + init() {} +} + +struct Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOutput { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + var batchID: String = String() + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} +} + +struct Io_Iohk_Atala_Prism_Protos_CreateDIDOutput { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + var didSuffix: String = String() + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} +} + +struct Io_Iohk_Atala_Prism_Protos_UpdateDIDOutput { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} +} + +struct Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOutput { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} +} + +struct Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOutput { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} +} + +struct Io_Iohk_Atala_Prism_Protos_DeactivateDIDOutput { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} +} + +struct Io_Iohk_Atala_Prism_Protos_Service { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + var id: String = String() + + var type: String = String() + + var serviceEndpoint: [String] = [] + + /// (when present) The ledger details related to the event that added the service. + var addedOn: Io_Iohk_Atala_Prism_Protos_LedgerData { + get {return _addedOn ?? Io_Iohk_Atala_Prism_Protos_LedgerData()} + set {_addedOn = newValue} + } + /// Returns true if `addedOn` has been explicitly set. + var hasAddedOn: Bool {return self._addedOn != nil} + /// Clears the value of `addedOn`. Subsequent reads from it will return its default value. + mutating func clearAddedOn() {self._addedOn = nil} + + /// (when present) The ledger details related to the event that revoked the service. + var deletedOn: Io_Iohk_Atala_Prism_Protos_LedgerData { + get {return _deletedOn ?? Io_Iohk_Atala_Prism_Protos_LedgerData()} + set {_deletedOn = newValue} + } + /// Returns true if `deletedOn` has been explicitly set. + var hasDeletedOn: Bool {return self._deletedOn != nil} + /// Clears the value of `deletedOn`. Subsequent reads from it will return its default value. + mutating func clearDeletedOn() {self._deletedOn = nil} + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} + + fileprivate var _addedOn: Io_Iohk_Atala_Prism_Protos_LedgerData? = nil + fileprivate var _deletedOn: Io_Iohk_Atala_Prism_Protos_LedgerData? = nil +} + +// MARK: - Code below here is support for the SwiftProtobuf runtime. + +fileprivate let _protobuf_package = "io.iohk.atala.prism.protos" + +extension Io_Iohk_Atala_Prism_Protos_KeyUsage: SwiftProtobuf._ProtoNameProviding { + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 0: .same(proto: "UNKNOWN_KEY"), + 1: .same(proto: "MASTER_KEY"), + 2: .same(proto: "ISSUING_KEY"), + 3: .same(proto: "KEY_AGREEMENT_KEY"), + 4: .same(proto: "AUTHENTICATION_KEY"), + 5: .same(proto: "REVOCATION_KEY"), + 6: .same(proto: "CAPABILITY_INVOCATION_KEY"), + 7: .same(proto: "CAPABILITY_DELEGATION_KEY"), + ] +} + +extension Io_Iohk_Atala_Prism_Protos_TimestampInfo: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".TimestampInfo" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 2: .standard(proto: "block_sequence_number"), + 3: .standard(proto: "operation_sequence_number"), + 4: .standard(proto: "block_timestamp"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 2: try { try decoder.decodeSingularUInt32Field(value: &self.blockSequenceNumber) }() + case 3: try { try decoder.decodeSingularUInt32Field(value: &self.operationSequenceNumber) }() + case 4: try { try decoder.decodeSingularMessageField(value: &self._blockTimestamp) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if self.blockSequenceNumber != 0 { + try visitor.visitSingularUInt32Field(value: self.blockSequenceNumber, fieldNumber: 2) + } + if self.operationSequenceNumber != 0 { + try visitor.visitSingularUInt32Field(value: self.operationSequenceNumber, fieldNumber: 3) + } + if let v = self._blockTimestamp { + try visitor.visitSingularMessageField(value: v, fieldNumber: 4) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_TimestampInfo, rhs: Io_Iohk_Atala_Prism_Protos_TimestampInfo) -> Bool { + if lhs.blockSequenceNumber != rhs.blockSequenceNumber {return false} + if lhs.operationSequenceNumber != rhs.operationSequenceNumber {return false} + if lhs._blockTimestamp != rhs._blockTimestamp {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_ECKeyData: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".ECKeyData" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .same(proto: "curve"), + 2: .same(proto: "x"), + 3: .same(proto: "y"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &self.curve) }() + case 2: try { try decoder.decodeSingularBytesField(value: &self.x) }() + case 3: try { try decoder.decodeSingularBytesField(value: &self.y) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if !self.curve.isEmpty { + try visitor.visitSingularStringField(value: self.curve, fieldNumber: 1) + } + if !self.x.isEmpty { + try visitor.visitSingularBytesField(value: self.x, fieldNumber: 2) + } + if !self.y.isEmpty { + try visitor.visitSingularBytesField(value: self.y, fieldNumber: 3) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_ECKeyData, rhs: Io_Iohk_Atala_Prism_Protos_ECKeyData) -> Bool { + if lhs.curve != rhs.curve {return false} + if lhs.x != rhs.x {return false} + if lhs.y != rhs.y {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_CompressedECKeyData: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".CompressedECKeyData" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .same(proto: "curve"), + 2: .same(proto: "data"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &self.curve) }() + case 2: try { try decoder.decodeSingularBytesField(value: &self.data) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if !self.curve.isEmpty { + try visitor.visitSingularStringField(value: self.curve, fieldNumber: 1) + } + if !self.data.isEmpty { + try visitor.visitSingularBytesField(value: self.data, fieldNumber: 2) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_CompressedECKeyData, rhs: Io_Iohk_Atala_Prism_Protos_CompressedECKeyData) -> Bool { + if lhs.curve != rhs.curve {return false} + if lhs.data != rhs.data {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_PublicKey: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".PublicKey" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .same(proto: "id"), + 2: .same(proto: "usage"), + 5: .standard(proto: "added_on"), + 6: .standard(proto: "revoked_on"), + 8: .standard(proto: "ec_key_data"), + 9: .standard(proto: "compressed_ec_key_data"), + ] + + fileprivate class _StorageClass { + var _id: String = String() + var _usage: Io_Iohk_Atala_Prism_Protos_KeyUsage = .unknownKey + var _addedOn: Io_Iohk_Atala_Prism_Protos_LedgerData? = nil + var _revokedOn: Io_Iohk_Atala_Prism_Protos_LedgerData? = nil + var _keyData: Io_Iohk_Atala_Prism_Protos_PublicKey.OneOf_KeyData? + + static let defaultInstance = _StorageClass() + + private init() {} + + init(copying source: _StorageClass) { + _id = source._id + _usage = source._usage + _addedOn = source._addedOn + _revokedOn = source._revokedOn + _keyData = source._keyData + } + } + + fileprivate mutating func _uniqueStorage() -> _StorageClass { + if !isKnownUniquelyReferenced(&_storage) { + _storage = _StorageClass(copying: _storage) + } + return _storage + } + + mutating func decodeMessage(decoder: inout D) throws { + _ = _uniqueStorage() + try withExtendedLifetime(_storage) { (_storage: _StorageClass) in + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &_storage._id) }() + case 2: try { try decoder.decodeSingularEnumField(value: &_storage._usage) }() + case 5: try { try decoder.decodeSingularMessageField(value: &_storage._addedOn) }() + case 6: try { try decoder.decodeSingularMessageField(value: &_storage._revokedOn) }() + case 8: try { + var v: Io_Iohk_Atala_Prism_Protos_ECKeyData? + var hadOneofValue = false + if let current = _storage._keyData { + hadOneofValue = true + if case .ecKeyData(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + _storage._keyData = .ecKeyData(v) + } + }() + case 9: try { + var v: Io_Iohk_Atala_Prism_Protos_CompressedECKeyData? + var hadOneofValue = false + if let current = _storage._keyData { + hadOneofValue = true + if case .compressedEcKeyData(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + _storage._keyData = .compressedEcKeyData(v) + } + }() + default: break + } + } + } + } + + func traverse(visitor: inout V) throws { + try withExtendedLifetime(_storage) { (_storage: _StorageClass) in + if !_storage._id.isEmpty { + try visitor.visitSingularStringField(value: _storage._id, fieldNumber: 1) + } + if _storage._usage != .unknownKey { + try visitor.visitSingularEnumField(value: _storage._usage, fieldNumber: 2) + } + if let v = _storage._addedOn { + try visitor.visitSingularMessageField(value: v, fieldNumber: 5) + } + if let v = _storage._revokedOn { + try visitor.visitSingularMessageField(value: v, fieldNumber: 6) + } + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch _storage._keyData { + case .ecKeyData?: try { + guard case .ecKeyData(let v)? = _storage._keyData else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 8) + }() + case .compressedEcKeyData?: try { + guard case .compressedEcKeyData(let v)? = _storage._keyData else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 9) + }() + case nil: break + } + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_PublicKey, rhs: Io_Iohk_Atala_Prism_Protos_PublicKey) -> Bool { + if lhs._storage !== rhs._storage { + let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in + let _storage = _args.0 + let rhs_storage = _args.1 + if _storage._id != rhs_storage._id {return false} + if _storage._usage != rhs_storage._usage {return false} + if _storage._addedOn != rhs_storage._addedOn {return false} + if _storage._revokedOn != rhs_storage._revokedOn {return false} + if _storage._keyData != rhs_storage._keyData {return false} + return true + } + if !storagesAreEqual {return false} + } + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_DIDData: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".DIDData" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .same(proto: "id"), + 2: .standard(proto: "public_keys"), + 3: .same(proto: "services"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &self.id) }() + case 2: try { try decoder.decodeRepeatedMessageField(value: &self.publicKeys) }() + case 3: try { try decoder.decodeRepeatedMessageField(value: &self.services) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if !self.id.isEmpty { + try visitor.visitSingularStringField(value: self.id, fieldNumber: 1) + } + if !self.publicKeys.isEmpty { + try visitor.visitRepeatedMessageField(value: self.publicKeys, fieldNumber: 2) + } + if !self.services.isEmpty { + try visitor.visitRepeatedMessageField(value: self.services, fieldNumber: 3) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_DIDData, rhs: Io_Iohk_Atala_Prism_Protos_DIDData) -> Bool { + if lhs.id != rhs.id {return false} + if lhs.publicKeys != rhs.publicKeys {return false} + if lhs.services != rhs.services {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_CreateDIDOperation: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".CreateDIDOperation" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .standard(proto: "did_data"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularMessageField(value: &self._didData) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if let v = self._didData { + try visitor.visitSingularMessageField(value: v, fieldNumber: 1) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_CreateDIDOperation, rhs: Io_Iohk_Atala_Prism_Protos_CreateDIDOperation) -> Bool { + if lhs._didData != rhs._didData {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_CreateDIDOperation.DIDCreationData: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = Io_Iohk_Atala_Prism_Protos_CreateDIDOperation.protoMessageName + ".DIDCreationData" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 2: .standard(proto: "public_keys"), + 3: .same(proto: "services"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 2: try { try decoder.decodeRepeatedMessageField(value: &self.publicKeys) }() + case 3: try { try decoder.decodeRepeatedMessageField(value: &self.services) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if !self.publicKeys.isEmpty { + try visitor.visitRepeatedMessageField(value: self.publicKeys, fieldNumber: 2) + } + if !self.services.isEmpty { + try visitor.visitRepeatedMessageField(value: self.services, fieldNumber: 3) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_CreateDIDOperation.DIDCreationData, rhs: Io_Iohk_Atala_Prism_Protos_CreateDIDOperation.DIDCreationData) -> Bool { + if lhs.publicKeys != rhs.publicKeys {return false} + if lhs.services != rhs.services {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_AddKeyAction: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".AddKeyAction" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .same(proto: "key"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularMessageField(value: &self._key) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if let v = self._key { + try visitor.visitSingularMessageField(value: v, fieldNumber: 1) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_AddKeyAction, rhs: Io_Iohk_Atala_Prism_Protos_AddKeyAction) -> Bool { + if lhs._key != rhs._key {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_RemoveKeyAction: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".RemoveKeyAction" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .same(proto: "keyId"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &self.keyID) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if !self.keyID.isEmpty { + try visitor.visitSingularStringField(value: self.keyID, fieldNumber: 1) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_RemoveKeyAction, rhs: Io_Iohk_Atala_Prism_Protos_RemoveKeyAction) -> Bool { + if lhs.keyID != rhs.keyID {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_AddServiceAction: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".AddServiceAction" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .same(proto: "service"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularMessageField(value: &self._service) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if let v = self._service { + try visitor.visitSingularMessageField(value: v, fieldNumber: 1) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_AddServiceAction, rhs: Io_Iohk_Atala_Prism_Protos_AddServiceAction) -> Bool { + if lhs._service != rhs._service {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_RemoveServiceAction: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".RemoveServiceAction" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .same(proto: "serviceId"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &self.serviceID) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if !self.serviceID.isEmpty { + try visitor.visitSingularStringField(value: self.serviceID, fieldNumber: 1) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_RemoveServiceAction, rhs: Io_Iohk_Atala_Prism_Protos_RemoveServiceAction) -> Bool { + if lhs.serviceID != rhs.serviceID {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_UpdateServiceAction: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".UpdateServiceAction" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .same(proto: "serviceId"), + 2: .same(proto: "type"), + 3: .standard(proto: "service_endpoints"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &self.serviceID) }() + case 2: try { try decoder.decodeSingularStringField(value: &self.type) }() + case 3: try { try decoder.decodeRepeatedStringField(value: &self.serviceEndpoints) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if !self.serviceID.isEmpty { + try visitor.visitSingularStringField(value: self.serviceID, fieldNumber: 1) + } + if !self.type.isEmpty { + try visitor.visitSingularStringField(value: self.type, fieldNumber: 2) + } + if !self.serviceEndpoints.isEmpty { + try visitor.visitRepeatedStringField(value: self.serviceEndpoints, fieldNumber: 3) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_UpdateServiceAction, rhs: Io_Iohk_Atala_Prism_Protos_UpdateServiceAction) -> Bool { + if lhs.serviceID != rhs.serviceID {return false} + if lhs.type != rhs.type {return false} + if lhs.serviceEndpoints != rhs.serviceEndpoints {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_UpdateDIDAction: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".UpdateDIDAction" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .standard(proto: "add_key"), + 2: .standard(proto: "remove_key"), + 3: .standard(proto: "add_service"), + 4: .standard(proto: "remove_service"), + 5: .standard(proto: "update_service"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { + var v: Io_Iohk_Atala_Prism_Protos_AddKeyAction? + var hadOneofValue = false + if let current = self.action { + hadOneofValue = true + if case .addKey(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.action = .addKey(v) + } + }() + case 2: try { + var v: Io_Iohk_Atala_Prism_Protos_RemoveKeyAction? + var hadOneofValue = false + if let current = self.action { + hadOneofValue = true + if case .removeKey(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.action = .removeKey(v) + } + }() + case 3: try { + var v: Io_Iohk_Atala_Prism_Protos_AddServiceAction? + var hadOneofValue = false + if let current = self.action { + hadOneofValue = true + if case .addService(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.action = .addService(v) + } + }() + case 4: try { + var v: Io_Iohk_Atala_Prism_Protos_RemoveServiceAction? + var hadOneofValue = false + if let current = self.action { + hadOneofValue = true + if case .removeService(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.action = .removeService(v) + } + }() + case 5: try { + var v: Io_Iohk_Atala_Prism_Protos_UpdateServiceAction? + var hadOneofValue = false + if let current = self.action { + hadOneofValue = true + if case .updateService(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.action = .updateService(v) + } + }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch self.action { + case .addKey?: try { + guard case .addKey(let v)? = self.action else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 1) + }() + case .removeKey?: try { + guard case .removeKey(let v)? = self.action else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 2) + }() + case .addService?: try { + guard case .addService(let v)? = self.action else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 3) + }() + case .removeService?: try { + guard case .removeService(let v)? = self.action else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 4) + }() + case .updateService?: try { + guard case .updateService(let v)? = self.action else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 5) + }() + case nil: break + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_UpdateDIDAction, rhs: Io_Iohk_Atala_Prism_Protos_UpdateDIDAction) -> Bool { + if lhs.action != rhs.action {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_UpdateDIDOperation: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".UpdateDIDOperation" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .standard(proto: "previous_operation_hash"), + 2: .same(proto: "id"), + 3: .same(proto: "actions"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularBytesField(value: &self.previousOperationHash) }() + case 2: try { try decoder.decodeSingularStringField(value: &self.id) }() + case 3: try { try decoder.decodeRepeatedMessageField(value: &self.actions) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if !self.previousOperationHash.isEmpty { + try visitor.visitSingularBytesField(value: self.previousOperationHash, fieldNumber: 1) + } + if !self.id.isEmpty { + try visitor.visitSingularStringField(value: self.id, fieldNumber: 2) + } + if !self.actions.isEmpty { + try visitor.visitRepeatedMessageField(value: self.actions, fieldNumber: 3) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_UpdateDIDOperation, rhs: Io_Iohk_Atala_Prism_Protos_UpdateDIDOperation) -> Bool { + if lhs.previousOperationHash != rhs.previousOperationHash {return false} + if lhs.id != rhs.id {return false} + if lhs.actions != rhs.actions {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_CredentialBatchData: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".CredentialBatchData" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .standard(proto: "issuer_did"), + 2: .standard(proto: "merkle_root"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &self.issuerDid) }() + case 2: try { try decoder.decodeSingularBytesField(value: &self.merkleRoot) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if !self.issuerDid.isEmpty { + try visitor.visitSingularStringField(value: self.issuerDid, fieldNumber: 1) + } + if !self.merkleRoot.isEmpty { + try visitor.visitSingularBytesField(value: self.merkleRoot, fieldNumber: 2) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_CredentialBatchData, rhs: Io_Iohk_Atala_Prism_Protos_CredentialBatchData) -> Bool { + if lhs.issuerDid != rhs.issuerDid {return false} + if lhs.merkleRoot != rhs.merkleRoot {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOperation: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".IssueCredentialBatchOperation" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .standard(proto: "credential_batch_data"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularMessageField(value: &self._credentialBatchData) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if let v = self._credentialBatchData { + try visitor.visitSingularMessageField(value: v, fieldNumber: 1) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOperation, rhs: Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOperation) -> Bool { + if lhs._credentialBatchData != rhs._credentialBatchData {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOperation: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".RevokeCredentialsOperation" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .standard(proto: "previous_operation_hash"), + 2: .standard(proto: "credential_batch_id"), + 3: .standard(proto: "credentials_to_revoke"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularBytesField(value: &self.previousOperationHash) }() + case 2: try { try decoder.decodeSingularStringField(value: &self.credentialBatchID) }() + case 3: try { try decoder.decodeRepeatedBytesField(value: &self.credentialsToRevoke) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if !self.previousOperationHash.isEmpty { + try visitor.visitSingularBytesField(value: self.previousOperationHash, fieldNumber: 1) + } + if !self.credentialBatchID.isEmpty { + try visitor.visitSingularStringField(value: self.credentialBatchID, fieldNumber: 2) + } + if !self.credentialsToRevoke.isEmpty { + try visitor.visitRepeatedBytesField(value: self.credentialsToRevoke, fieldNumber: 3) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOperation, rhs: Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOperation) -> Bool { + if lhs.previousOperationHash != rhs.previousOperationHash {return false} + if lhs.credentialBatchID != rhs.credentialBatchID {return false} + if lhs.credentialsToRevoke != rhs.credentialsToRevoke {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOperation: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".ProtocolVersionUpdateOperation" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .standard(proto: "proposer_did"), + 2: .same(proto: "version"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &self.proposerDid) }() + case 2: try { try decoder.decodeSingularMessageField(value: &self._version) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if !self.proposerDid.isEmpty { + try visitor.visitSingularStringField(value: self.proposerDid, fieldNumber: 1) + } + if let v = self._version { + try visitor.visitSingularMessageField(value: v, fieldNumber: 2) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOperation, rhs: Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOperation) -> Bool { + if lhs.proposerDid != rhs.proposerDid {return false} + if lhs._version != rhs._version {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_ProtocolVersion: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".ProtocolVersion" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .standard(proto: "major_version"), + 2: .standard(proto: "minor_version"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularInt32Field(value: &self.majorVersion) }() + case 2: try { try decoder.decodeSingularInt32Field(value: &self.minorVersion) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if self.majorVersion != 0 { + try visitor.visitSingularInt32Field(value: self.majorVersion, fieldNumber: 1) + } + if self.minorVersion != 0 { + try visitor.visitSingularInt32Field(value: self.minorVersion, fieldNumber: 2) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_ProtocolVersion, rhs: Io_Iohk_Atala_Prism_Protos_ProtocolVersion) -> Bool { + if lhs.majorVersion != rhs.majorVersion {return false} + if lhs.minorVersion != rhs.minorVersion {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_ProtocolVersionInfo: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".ProtocolVersionInfo" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .standard(proto: "version_name"), + 4: .standard(proto: "effective_since"), + 5: .standard(proto: "protocol_version"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &self.versionName) }() + case 4: try { try decoder.decodeSingularInt32Field(value: &self.effectiveSince) }() + case 5: try { try decoder.decodeSingularMessageField(value: &self._protocolVersion) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if !self.versionName.isEmpty { + try visitor.visitSingularStringField(value: self.versionName, fieldNumber: 1) + } + if self.effectiveSince != 0 { + try visitor.visitSingularInt32Field(value: self.effectiveSince, fieldNumber: 4) + } + if let v = self._protocolVersion { + try visitor.visitSingularMessageField(value: v, fieldNumber: 5) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_ProtocolVersionInfo, rhs: Io_Iohk_Atala_Prism_Protos_ProtocolVersionInfo) -> Bool { + if lhs.versionName != rhs.versionName {return false} + if lhs.effectiveSince != rhs.effectiveSince {return false} + if lhs._protocolVersion != rhs._protocolVersion {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_DeactivateDIDOperation: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".DeactivateDIDOperation" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .standard(proto: "previous_operation_hash"), + 2: .same(proto: "id"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularBytesField(value: &self.previousOperationHash) }() + case 2: try { try decoder.decodeSingularStringField(value: &self.id) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if !self.previousOperationHash.isEmpty { + try visitor.visitSingularBytesField(value: self.previousOperationHash, fieldNumber: 1) + } + if !self.id.isEmpty { + try visitor.visitSingularStringField(value: self.id, fieldNumber: 2) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_DeactivateDIDOperation, rhs: Io_Iohk_Atala_Prism_Protos_DeactivateDIDOperation) -> Bool { + if lhs.previousOperationHash != rhs.previousOperationHash {return false} + if lhs.id != rhs.id {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_AtalaOperation: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".AtalaOperation" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .standard(proto: "create_did"), + 2: .standard(proto: "update_did"), + 3: .standard(proto: "issue_credential_batch"), + 4: .standard(proto: "revoke_credentials"), + 5: .standard(proto: "protocol_version_update"), + 6: .standard(proto: "deactivate_did"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { + var v: Io_Iohk_Atala_Prism_Protos_CreateDIDOperation? + var hadOneofValue = false + if let current = self.operation { + hadOneofValue = true + if case .createDid(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.operation = .createDid(v) + } + }() + case 2: try { + var v: Io_Iohk_Atala_Prism_Protos_UpdateDIDOperation? + var hadOneofValue = false + if let current = self.operation { + hadOneofValue = true + if case .updateDid(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.operation = .updateDid(v) + } + }() + case 3: try { + var v: Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOperation? + var hadOneofValue = false + if let current = self.operation { + hadOneofValue = true + if case .issueCredentialBatch(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.operation = .issueCredentialBatch(v) + } + }() + case 4: try { + var v: Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOperation? + var hadOneofValue = false + if let current = self.operation { + hadOneofValue = true + if case .revokeCredentials(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.operation = .revokeCredentials(v) + } + }() + case 5: try { + var v: Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOperation? + var hadOneofValue = false + if let current = self.operation { + hadOneofValue = true + if case .protocolVersionUpdate(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.operation = .protocolVersionUpdate(v) + } + }() + case 6: try { + var v: Io_Iohk_Atala_Prism_Protos_DeactivateDIDOperation? + var hadOneofValue = false + if let current = self.operation { + hadOneofValue = true + if case .deactivateDid(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.operation = .deactivateDid(v) + } + }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch self.operation { + case .createDid?: try { + guard case .createDid(let v)? = self.operation else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 1) + }() + case .updateDid?: try { + guard case .updateDid(let v)? = self.operation else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 2) + }() + case .issueCredentialBatch?: try { + guard case .issueCredentialBatch(let v)? = self.operation else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 3) + }() + case .revokeCredentials?: try { + guard case .revokeCredentials(let v)? = self.operation else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 4) + }() + case .protocolVersionUpdate?: try { + guard case .protocolVersionUpdate(let v)? = self.operation else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 5) + }() + case .deactivateDid?: try { + guard case .deactivateDid(let v)? = self.operation else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 6) + }() + case nil: break + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_AtalaOperation, rhs: Io_Iohk_Atala_Prism_Protos_AtalaOperation) -> Bool { + if lhs.operation != rhs.operation {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_SignedAtalaOperation: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".SignedAtalaOperation" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .standard(proto: "signed_with"), + 2: .same(proto: "signature"), + 3: .same(proto: "operation"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &self.signedWith) }() + case 2: try { try decoder.decodeSingularBytesField(value: &self.signature) }() + case 3: try { try decoder.decodeSingularMessageField(value: &self._operation) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if !self.signedWith.isEmpty { + try visitor.visitSingularStringField(value: self.signedWith, fieldNumber: 1) + } + if !self.signature.isEmpty { + try visitor.visitSingularBytesField(value: self.signature, fieldNumber: 2) + } + if let v = self._operation { + try visitor.visitSingularMessageField(value: v, fieldNumber: 3) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_SignedAtalaOperation, rhs: Io_Iohk_Atala_Prism_Protos_SignedAtalaOperation) -> Bool { + if lhs.signedWith != rhs.signedWith {return false} + if lhs.signature != rhs.signature {return false} + if lhs._operation != rhs._operation {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_LedgerData: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".LedgerData" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .standard(proto: "transaction_id"), + 2: .same(proto: "ledger"), + 3: .standard(proto: "timestamp_info"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &self.transactionID) }() + case 2: try { try decoder.decodeSingularEnumField(value: &self.ledger) }() + case 3: try { try decoder.decodeSingularMessageField(value: &self._timestampInfo) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if !self.transactionID.isEmpty { + try visitor.visitSingularStringField(value: self.transactionID, fieldNumber: 1) + } + if self.ledger != .unknownLedger { + try visitor.visitSingularEnumField(value: self.ledger, fieldNumber: 2) + } + if let v = self._timestampInfo { + try visitor.visitSingularMessageField(value: v, fieldNumber: 3) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_LedgerData, rhs: Io_Iohk_Atala_Prism_Protos_LedgerData) -> Bool { + if lhs.transactionID != rhs.transactionID {return false} + if lhs.ledger != rhs.ledger {return false} + if lhs._timestampInfo != rhs._timestampInfo {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_OperationOutput: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".OperationOutput" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .standard(proto: "batch_output"), + 2: .standard(proto: "create_did_output"), + 3: .standard(proto: "update_did_output"), + 4: .standard(proto: "revoke_credentials_output"), + 7: .standard(proto: "protocol_version_update_output"), + 8: .standard(proto: "deactivate_did_output"), + 5: .standard(proto: "operation_id"), + 6: .same(proto: "error"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { + var v: Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOutput? + var hadOneofValue = false + if let current = self.result { + hadOneofValue = true + if case .batchOutput(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.result = .batchOutput(v) + } + }() + case 2: try { + var v: Io_Iohk_Atala_Prism_Protos_CreateDIDOutput? + var hadOneofValue = false + if let current = self.result { + hadOneofValue = true + if case .createDidOutput(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.result = .createDidOutput(v) + } + }() + case 3: try { + var v: Io_Iohk_Atala_Prism_Protos_UpdateDIDOutput? + var hadOneofValue = false + if let current = self.result { + hadOneofValue = true + if case .updateDidOutput(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.result = .updateDidOutput(v) + } + }() + case 4: try { + var v: Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOutput? + var hadOneofValue = false + if let current = self.result { + hadOneofValue = true + if case .revokeCredentialsOutput(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.result = .revokeCredentialsOutput(v) + } + }() + case 5: try { + var v: Data? + try decoder.decodeSingularBytesField(value: &v) + if let v = v { + if self.operationMaybe != nil {try decoder.handleConflictingOneOf()} + self.operationMaybe = .operationID(v) + } + }() + case 6: try { + var v: String? + try decoder.decodeSingularStringField(value: &v) + if let v = v { + if self.operationMaybe != nil {try decoder.handleConflictingOneOf()} + self.operationMaybe = .error(v) + } + }() + case 7: try { + var v: Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOutput? + var hadOneofValue = false + if let current = self.result { + hadOneofValue = true + if case .protocolVersionUpdateOutput(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.result = .protocolVersionUpdateOutput(v) + } + }() + case 8: try { + var v: Io_Iohk_Atala_Prism_Protos_DeactivateDIDOutput? + var hadOneofValue = false + if let current = self.result { + hadOneofValue = true + if case .deactivateDidOutput(let m) = current {v = m} + } + try decoder.decodeSingularMessageField(value: &v) + if let v = v { + if hadOneofValue {try decoder.handleConflictingOneOf()} + self.result = .deactivateDidOutput(v) + } + }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch self.result { + case .batchOutput?: try { + guard case .batchOutput(let v)? = self.result else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 1) + }() + case .createDidOutput?: try { + guard case .createDidOutput(let v)? = self.result else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 2) + }() + case .updateDidOutput?: try { + guard case .updateDidOutput(let v)? = self.result else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 3) + }() + case .revokeCredentialsOutput?: try { + guard case .revokeCredentialsOutput(let v)? = self.result else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 4) + }() + default: break + } + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch self.operationMaybe { + case .operationID?: try { + guard case .operationID(let v)? = self.operationMaybe else { preconditionFailure() } + try visitor.visitSingularBytesField(value: v, fieldNumber: 5) + }() + case .error?: try { + guard case .error(let v)? = self.operationMaybe else { preconditionFailure() } + try visitor.visitSingularStringField(value: v, fieldNumber: 6) + }() + case nil: break + } + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch self.result { + case .protocolVersionUpdateOutput?: try { + guard case .protocolVersionUpdateOutput(let v)? = self.result else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 7) + }() + case .deactivateDidOutput?: try { + guard case .deactivateDidOutput(let v)? = self.result else { preconditionFailure() } + try visitor.visitSingularMessageField(value: v, fieldNumber: 8) + }() + default: break + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_OperationOutput, rhs: Io_Iohk_Atala_Prism_Protos_OperationOutput) -> Bool { + if lhs.result != rhs.result {return false} + if lhs.operationMaybe != rhs.operationMaybe {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOutput: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".IssueCredentialBatchOutput" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .standard(proto: "batch_id"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &self.batchID) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if !self.batchID.isEmpty { + try visitor.visitSingularStringField(value: self.batchID, fieldNumber: 1) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOutput, rhs: Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOutput) -> Bool { + if lhs.batchID != rhs.batchID {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_CreateDIDOutput: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".CreateDIDOutput" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .standard(proto: "did_suffix"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &self.didSuffix) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if !self.didSuffix.isEmpty { + try visitor.visitSingularStringField(value: self.didSuffix, fieldNumber: 1) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_CreateDIDOutput, rhs: Io_Iohk_Atala_Prism_Protos_CreateDIDOutput) -> Bool { + if lhs.didSuffix != rhs.didSuffix {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_UpdateDIDOutput: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".UpdateDIDOutput" + static let _protobuf_nameMap = SwiftProtobuf._NameMap() + + mutating func decodeMessage(decoder: inout D) throws { + while let _ = try decoder.nextFieldNumber() { + } + } + + func traverse(visitor: inout V) throws { + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_UpdateDIDOutput, rhs: Io_Iohk_Atala_Prism_Protos_UpdateDIDOutput) -> Bool { + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOutput: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".RevokeCredentialsOutput" + static let _protobuf_nameMap = SwiftProtobuf._NameMap() + + mutating func decodeMessage(decoder: inout D) throws { + while let _ = try decoder.nextFieldNumber() { + } + } + + func traverse(visitor: inout V) throws { + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOutput, rhs: Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOutput) -> Bool { + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOutput: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".ProtocolVersionUpdateOutput" + static let _protobuf_nameMap = SwiftProtobuf._NameMap() + + mutating func decodeMessage(decoder: inout D) throws { + while let _ = try decoder.nextFieldNumber() { + } + } + + func traverse(visitor: inout V) throws { + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOutput, rhs: Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOutput) -> Bool { + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_DeactivateDIDOutput: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".DeactivateDIDOutput" + static let _protobuf_nameMap = SwiftProtobuf._NameMap() + + mutating func decodeMessage(decoder: inout D) throws { + while let _ = try decoder.nextFieldNumber() { + } + } + + func traverse(visitor: inout V) throws { + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_DeactivateDIDOutput, rhs: Io_Iohk_Atala_Prism_Protos_DeactivateDIDOutput) -> Bool { + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +extension Io_Iohk_Atala_Prism_Protos_Service: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".Service" + static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .same(proto: "id"), + 2: .same(proto: "type"), + 3: .standard(proto: "service_endpoint"), + 4: .standard(proto: "added_on"), + 5: .standard(proto: "deleted_on"), + ] + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &self.id) }() + case 2: try { try decoder.decodeSingularStringField(value: &self.type) }() + case 3: try { try decoder.decodeRepeatedStringField(value: &self.serviceEndpoint) }() + case 4: try { try decoder.decodeSingularMessageField(value: &self._addedOn) }() + case 5: try { try decoder.decodeSingularMessageField(value: &self._deletedOn) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if !self.id.isEmpty { + try visitor.visitSingularStringField(value: self.id, fieldNumber: 1) + } + if !self.type.isEmpty { + try visitor.visitSingularStringField(value: self.type, fieldNumber: 2) + } + if !self.serviceEndpoint.isEmpty { + try visitor.visitRepeatedStringField(value: self.serviceEndpoint, fieldNumber: 3) + } + if let v = self._addedOn { + try visitor.visitSingularMessageField(value: v, fieldNumber: 4) + } + if let v = self._deletedOn { + try visitor.visitSingularMessageField(value: v, fieldNumber: 5) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Io_Iohk_Atala_Prism_Protos_Service, rhs: Io_Iohk_Atala_Prism_Protos_Service) -> Bool { + if lhs.id != rhs.id {return false} + if lhs.type != rhs.type {return false} + if lhs.serviceEndpoint != rhs.serviceEndpoint {return false} + if lhs._addedOn != rhs._addedOn {return false} + if lhs._deletedOn != rhs._deletedOn {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} diff --git a/Castor/Tests/DIDParserTests.swift b/AtalaPrismSDK/Castor/Tests/DIDParserTests.swift similarity index 100% rename from Castor/Tests/DIDParserTests.swift rename to AtalaPrismSDK/Castor/Tests/DIDParserTests.swift diff --git a/Castor/Tests/DIDUrlParserTests.swift b/AtalaPrismSDK/Castor/Tests/DIDUrlParserTests.swift similarity index 100% rename from Castor/Tests/DIDUrlParserTests.swift rename to AtalaPrismSDK/Castor/Tests/DIDUrlParserTests.swift diff --git a/Castor/Tests/EncumbasisEncodeDecodeTests.swift b/AtalaPrismSDK/Castor/Tests/EncumbasisEncodeDecodeTests.swift similarity index 93% rename from Castor/Tests/EncumbasisEncodeDecodeTests.swift rename to AtalaPrismSDK/Castor/Tests/EncumbasisEncodeDecodeTests.swift index 806d3cf8..4e920c3d 100644 --- a/Castor/Tests/EncumbasisEncodeDecodeTests.swift +++ b/AtalaPrismSDK/Castor/Tests/EncumbasisEncodeDecodeTests.swift @@ -1,4 +1,5 @@ import Core +import Domain @testable import Castor import XCTest @@ -18,6 +19,7 @@ final class EncumbasisEncodeDecodeTests: XCTestCase { ) let ecnumbasisResult = try PeerDIDResolver().decodeMultibaseEncnumbasisAuth( + did: DID(method: "test", methodId: "test1"), multibase: ecnumBasis, format: .jwk ) diff --git a/Castor/Tests/MultiCodecTests.swift b/AtalaPrismSDK/Castor/Tests/MultiCodecTests.swift similarity index 100% rename from Castor/Tests/MultiCodecTests.swift rename to AtalaPrismSDK/Castor/Tests/MultiCodecTests.swift diff --git a/Castor/Tests/PeerDIDCreationTests.swift b/AtalaPrismSDK/Castor/Tests/PeerDIDCreationTests.swift similarity index 98% rename from Castor/Tests/PeerDIDCreationTests.swift rename to AtalaPrismSDK/Castor/Tests/PeerDIDCreationTests.swift index 45339b70..bcd91eb8 100644 --- a/Castor/Tests/PeerDIDCreationTests.swift +++ b/AtalaPrismSDK/Castor/Tests/PeerDIDCreationTests.swift @@ -33,10 +33,10 @@ final class PeerDIDCreationTests: XCTestCase { let service = DIDDocument.Service( id: "didcomm", type: ["DIDCommMessaging"], - serviceEndpoint: .init( + serviceEndpoint: [.init( uri: "https://example.com/endpoint", routingKeys: ["did:example:somemediator#somekey"] - ) + )] ) let did = try castor.createPeerDID( keyAgreementKeyPair: keyAgreementKeyPair, diff --git a/Castor/Tests/PrismDIDMethodIdTests.swift b/AtalaPrismSDK/Castor/Tests/PrismDIDMethodIdTests.swift similarity index 100% rename from Castor/Tests/PrismDIDMethodIdTests.swift rename to AtalaPrismSDK/Castor/Tests/PrismDIDMethodIdTests.swift diff --git a/Castor/Tests/PrismDIDPublicKeyTests.swift b/AtalaPrismSDK/Castor/Tests/PrismDIDPublicKeyTests.swift similarity index 100% rename from Castor/Tests/PrismDIDPublicKeyTests.swift rename to AtalaPrismSDK/Castor/Tests/PrismDIDPublicKeyTests.swift diff --git a/Domain/Sources/BBs/Apollo.swift b/AtalaPrismSDK/Domain/Sources/BBs/Apollo.swift similarity index 100% rename from Domain/Sources/BBs/Apollo.swift rename to AtalaPrismSDK/Domain/Sources/BBs/Apollo.swift diff --git a/Domain/Sources/BBs/Castor.swift b/AtalaPrismSDK/Domain/Sources/BBs/Castor.swift similarity index 100% rename from Domain/Sources/BBs/Castor.swift rename to AtalaPrismSDK/Domain/Sources/BBs/Castor.swift diff --git a/Domain/Sources/BBs/Mercury.swift b/AtalaPrismSDK/Domain/Sources/BBs/Mercury.swift similarity index 100% rename from Domain/Sources/BBs/Mercury.swift rename to AtalaPrismSDK/Domain/Sources/BBs/Mercury.swift diff --git a/Domain/Sources/BBs/Pluto.swift b/AtalaPrismSDK/Domain/Sources/BBs/Pluto.swift similarity index 76% rename from Domain/Sources/BBs/Pluto.swift rename to AtalaPrismSDK/Domain/Sources/BBs/Pluto.swift index c683c3c1..ac2df8b5 100644 --- a/Domain/Sources/BBs/Pluto.swift +++ b/AtalaPrismSDK/Domain/Sources/BBs/Pluto.swift @@ -7,8 +7,8 @@ public protocol Pluto { keyPairIndex: Int, alias: String? ) -> AnyPublisher - func storePeerDID(did: DID, privateKeys: [PrivateKey]) -> AnyPublisher - func storeDIDPair(holder: DID, other: DID, name: String) -> AnyPublisher + func storePeerDID(did: DID, privateKeys: [PrivateKey], alias: String?) -> AnyPublisher + func storeDIDPair(pair: DIDPair) -> AnyPublisher func storeMessage(message: Message, direction: Message.Direction) -> AnyPublisher func storeMessages(messages: [(Message, Message.Direction)]) -> AnyPublisher func storeMediator(peer: DID, routingDID: DID, mediatorDID: DID) -> AnyPublisher @@ -20,14 +20,15 @@ public protocol Pluto { func getPrismDIDKeyPairIndex(did: DID) -> AnyPublisher func getPrismLastKeyPairIndex() -> AnyPublisher - func getAllPeerDIDs() -> AnyPublisher<[(did: DID, privateKeys: [PrivateKey])], Error> - func getPeerDIDInfo(did: DID) -> AnyPublisher<(did: DID, privateKeys: [PrivateKey])?, Error> + func getAllPeerDIDs() -> AnyPublisher<[(did: DID, privateKeys: [PrivateKey], alias: String?)], Error> + func getPeerDIDInfo(did: DID) -> AnyPublisher<(did: DID, privateKeys: [PrivateKey], alias: String?)?, Error> + func getPeerDIDInfo(alias: String) -> AnyPublisher<[(did: DID, privateKeys: [PrivateKey], alias: String?)], Error> func getPeerDIDPrivateKeys(did: DID) -> AnyPublisher<[PrivateKey]?, Error> - func getAllDidPairs() -> AnyPublisher<[(holder: DID, other: DID, name: String?)], Error> - func getPair(otherDID: DID) -> AnyPublisher<(holder: DID, other: DID, name: String?)?, Error> - func getPair(name: String) -> AnyPublisher<(holder: DID, other: DID, name: String?)?, Error> - func getPair(holderDID: DID) -> AnyPublisher<(holder: DID, other: DID, name: String?)?, Error> + func getAllDidPairs() -> AnyPublisher<[DIDPair], Error> + func getPair(otherDID: DID) -> AnyPublisher + func getPair(name: String) -> AnyPublisher + func getPair(holderDID: DID) -> AnyPublisher func getAllMessages() -> AnyPublisher<[Message], Error> func getAllMessages(did: DID) -> AnyPublisher<[Message], Error> diff --git a/Domain/Sources/BBs/Pollux.swift b/AtalaPrismSDK/Domain/Sources/BBs/Pollux.swift similarity index 100% rename from Domain/Sources/BBs/Pollux.swift rename to AtalaPrismSDK/Domain/Sources/BBs/Pollux.swift diff --git a/Domain/Sources/Helper/Map+AsyncAwait.swift b/AtalaPrismSDK/Domain/Sources/Helper/Map+AsyncAwait.swift similarity index 100% rename from Domain/Sources/Helper/Map+AsyncAwait.swift rename to AtalaPrismSDK/Domain/Sources/Helper/Map+AsyncAwait.swift diff --git a/Domain/Sources/Logging.swift b/AtalaPrismSDK/Domain/Sources/Logging.swift similarity index 100% rename from Domain/Sources/Logging.swift rename to AtalaPrismSDK/Domain/Sources/Logging.swift diff --git a/Domain/Sources/Models/DID.swift b/AtalaPrismSDK/Domain/Sources/Models/DID.swift similarity index 99% rename from Domain/Sources/Models/DID.swift rename to AtalaPrismSDK/Domain/Sources/Models/DID.swift index 72c91da4..c2710d3d 100644 --- a/Domain/Sources/Models/DID.swift +++ b/AtalaPrismSDK/Domain/Sources/Models/DID.swift @@ -42,7 +42,7 @@ public struct DID: Equatable { /// - Parameter string: DID String public init(string: String) throws { var aux = string.components(separatedBy: ":") - guard aux.count >= 3 else { throw CastorError.invalidDIDString } + guard aux.count >= 3 else { throw CastorError.invalidDIDString(string) } self.schema = aux.removeFirst() self.method = aux.removeFirst() self.methodId = aux.joined(separator: ":") diff --git a/Domain/Sources/Models/DIDDocument.swift b/AtalaPrismSDK/Domain/Sources/Models/DIDDocument.swift similarity index 99% rename from Domain/Sources/Models/DIDDocument.swift rename to AtalaPrismSDK/Domain/Sources/Models/DIDDocument.swift index 26b5bcc9..8599da65 100644 --- a/Domain/Sources/Models/DIDDocument.swift +++ b/AtalaPrismSDK/Domain/Sources/Models/DIDDocument.swift @@ -82,12 +82,12 @@ public struct DIDDocument { public let type: [String] /// The service endpoint of the service. - public let serviceEndpoint: ServiceEndpoint + public let serviceEndpoint: [ServiceEndpoint] public init( id: String, type: [String], - serviceEndpoint: ServiceEndpoint + serviceEndpoint: [ServiceEndpoint] ) { self.id = id self.type = type diff --git a/Domain/Sources/Models/DIDPair.swift b/AtalaPrismSDK/Domain/Sources/Models/DIDPair.swift similarity index 100% rename from Domain/Sources/Models/DIDPair.swift rename to AtalaPrismSDK/Domain/Sources/Models/DIDPair.swift diff --git a/Domain/Sources/Models/DIDResolverDomain.swift b/AtalaPrismSDK/Domain/Sources/Models/DIDResolverDomain.swift similarity index 100% rename from Domain/Sources/Models/DIDResolverDomain.swift rename to AtalaPrismSDK/Domain/Sources/Models/DIDResolverDomain.swift diff --git a/Domain/Sources/Models/DIDUrl.swift b/AtalaPrismSDK/Domain/Sources/Models/DIDUrl.swift similarity index 100% rename from Domain/Sources/Models/DIDUrl.swift rename to AtalaPrismSDK/Domain/Sources/Models/DIDUrl.swift diff --git a/AtalaPrismSDK/Domain/Sources/Models/Errors.swift b/AtalaPrismSDK/Domain/Sources/Models/Errors.swift new file mode 100644 index 00000000..fc5dd858 --- /dev/null +++ b/AtalaPrismSDK/Domain/Sources/Models/Errors.swift @@ -0,0 +1,575 @@ +import Foundation + +/** + A protocol representing an unknown error in a Prism API response. + + - Note: When an error occurs during an API request/response cycle, the server may return an error object in the response. This object may include an error code, an error message, and possibly an array of underlying errors. If the error received does not conform to the `KnownPrismError` protocol, it will be classified as an `UnknownPrismError`. + + - SeeAlso: `KnownPrismError` + */ +public protocol UnknownPrismError: Error { + /// The error code returned by the server. + var code: Int? { get } + + /// The error message returned by the server. + var message: String? { get } + + /// An array of underlying errors that may have contributed to this error. + var underlyingErrors: [Error]? { get } +} + +/** + A protocol representing a known error in a Prism API response. + + - Note: When an error occurs during an API request/response cycle, the server may return an error object in the response. This object may include an error code and an error message. If the error received conforms to the `KnownPrismError` protocol, it will be classified as a known error. + + - SeeAlso: `UnknownPrismError` + */ +public protocol KnownPrismError: LocalizedError { + /// The error code returned by the server. + var code: Int { get } + + /// The error message returned by the server. + var message: String { get } +} + +/** + An enum representing an unknown error in a Prism API response. + + - Note: When an error occurs during an API request/response cycle, the server may return an error object in the response. This object may include an error code, an error message, and possibly an array of underlying errors. If the error received does not conform to the `KnownPrismError` protocol, it will be classified as an `UnknownPrismError`. + + - SeeAlso: `UnknownPrismError`, `KnownPrismError` + */ +public enum UnknownError: UnknownPrismError { + + /** + An error case representing a generic "something went wrong" error. + + - Parameters: + - customMessage: A custom error message, if provided. + - underlyingErrors: An array of underlying errors that may have contributed to this error, if provided. + */ + case somethingWentWrongError(customMessage: String? = nil, underlyingErrors: [Error]? = nil) + + /// The error code returned by the server. In this case, the code is always -1. + public var code: Int? { return -1 } + + /** + The error message returned by the server. + + - Note: For this enum, the error message will either be a custom message provided at initialization or the default message "Something Went Wrong". + + - SeeAlso: `somethingWentWrongError(customMessage:underlyingErrors:)` + */ + public var message: String? { + switch self { + case let .somethingWentWrongError(customMessage, _): + return customMessage ?? "Something Went Wrong" + } + } + + /** + An array of underlying errors that may have contributed to this error. + + - Note: For this enum, the array of underlying errors is determined at initialization and returned as-is. + + - SeeAlso: `somethingWentWrongError(customMessage:underlyingErrors:)` + */ + public var underlyingErrors: [Error]? { + switch self { + case let .somethingWentWrongError(_, errors): + return errors + } + } +} + +extension UnknownError: Equatable { + public static func == (lhs: UnknownError, rhs: UnknownError) -> Bool { + switch (lhs, rhs) { + case (.somethingWentWrongError, .somethingWentWrongError): + return lhs.message == rhs.message && lhs.code == rhs.code + } + } +} + +/** + An enum representing a known error in a Prism API response. + + - Note: When an error occurs during an API request/response cycle, the server may return an error object in the response. This object may include an error code and an error message. If the error received conforms to the `KnownPrismError` protocol, it will be classified as a known error. + + - SeeAlso: `UnknownPrismError`, `KnownPrismError` + */ +public enum CommonError: KnownPrismError { + + /** + An error case representing an invalid URL when attempting to send a message. + + - Parameters: + - url: The invalid URL that caused the error. + */ + case invalidURLError(url: String) + + /** + An error case representing an HTTP error returned by the server. + + - Parameters: + - code: The HTTP error code returned by the server. + - message: The HTTP error message returned by the server. + */ + case httpError(code: Int, message: String) + + /// The error code returned by the server. + public var code: Int { + switch self { + case .invalidURLError: + return -2 + case let .httpError(code, _): + return code + } + } + + /** + The error message returned by the server. + + - Note: For this enum, the error message is determined based on the specific error case that was encountered. + + - SeeAlso: `invalidURLError(url:)`, `httpError(code:message:)` + */ + public var message: String { + switch self { + case .invalidURLError(let url): + return "Invalid url while trying to send message: \(url)" + case let .httpError(_, message): + return message + } + } +} + +extension CommonError: Equatable { + public static func == (lhs: CommonError, rhs: CommonError) -> Bool { + lhs.message == rhs.message + } +} + +/** + An enum representing a known error in a Prism API response. + + - Note: When an error occurs during an API request/response cycle, the server may return an error object in the response. This object may include an error code and an error message. If the error received conforms to the `KnownPrismError` protocol, it will be classified as a known error. + + - SeeAlso: `KnownPrismError` + */ +public enum ApolloError: KnownPrismError { + + /** + An error case representing invalid mnemonic words. + + - Parameters: + - invalidWords: An array of invalid mnemonic words that caused the error. + */ + case invalidMnemonicWord(invalidWords: [String]) + + /** + An error case representing a failure to parse a message string. + + - Note: This error occurs when attempting to convert a message string to UTF8 data. + + - SeeAlso: `Data(_:).utf8` + */ + case couldNotParseMessageString + + /// An error case representing an invalid JWK format. + case invalidJWKError + + /// The error code returned by the server. + public var code: Int { + switch self { + case .invalidMnemonicWord: + return 11 + case .couldNotParseMessageString: + return 12 + case .invalidJWKError: + return 13 + } + } + + /** + The error message returned by the server. + + - Note: For this enum, the error message is determined based on the specific error case that was encountered. + + - SeeAlso: `invalidMnemonicWord(invalidWords:)`, `couldNotParseMessageString`, `invalidJWKError` + */ + public var message: String { + switch self { + case .invalidMnemonicWord(let words): + return "The following mnemonic words are invalid: \(words.joined(separator: ","))" + case .couldNotParseMessageString: + return "Could not get UTF8 Data from message string" + case .invalidJWKError: + return "JWK is not in a valid format" + } + } +} + +extension ApolloError: Equatable { + public static func == (lhs: ApolloError, rhs: ApolloError) -> Bool { + lhs.message == rhs.message + } +} + +/** + An enum representing a known error in a Prism API response. + + - Note: When an error occurs during an API request/response cycle, the server may return an error object in the response. This object may include an error code and an error message. If the error received conforms to the `KnownPrismError` protocol, it will be classified as a known error. + + - SeeAlso: `UnknownPrismError`, `KnownPrismError` + */ +public enum CastorError: KnownPrismError { + + /** + An error case representing an unsupported key curve. + + - Parameters: + - curve: The unsupported key curve that caused the error. + */ + case keyCurveNotSupported(curve: String) + + /// An error case representing an invalid long form DID. + case invalidLongFormDID + + /** + An error case representing a DID method ID that does not satisfy a regex pattern. + + - Parameters: + - regex: The regex pattern that the DID method ID does not satisfy. + */ + case methodIdIsDoesNotSatisfyRegex(regex: String) + + /** + An error case representing invalid encoding/decoding of a public key while computing a DID. + + - Parameters: + - didMethod: The DID method being computed. + - curve: The key curve that was invalidly encoded/decoded. + */ + case invalidPublicKeyCoding(didMethod: String, curve: String) + + /** + An error case representing an invalid DID string. + + - Parameters: + - str: The invalid DID string that caused the error. + */ + case invalidDIDString(String) + + /// An error case representing a change in the initial state of a DID. + case initialStateOfDIDChanged + + /** + An error case representing the inability to resolve a DID. + + - Parameters: + - did: The DID that could not be resolved. + - reason: The reason why the DID could not be resolved. + */ + case notPossibleToResolveDID(did: String, reason: String) + + /// An error case representing an invalid JWK format. + case invalidJWKError + + /** + An error case representing a lack of available resolvers for a given DID method. + + - Parameters: + - method: The DID method that has no available resolvers. + */ + case noResolversAvailableForDIDMethod(method: String) + + /// The error code returned by the server. + public var code: Int { + switch self { + case .keyCurveNotSupported: + return 21 + case .invalidLongFormDID: + return 22 + case .methodIdIsDoesNotSatisfyRegex: + return 23 + case .invalidPublicKeyCoding: + return 24 + case .invalidDIDString: + return 25 + case .initialStateOfDIDChanged: + return 26 + case .notPossibleToResolveDID: + return 27 + case .invalidJWKError: + return 28 + case .noResolversAvailableForDIDMethod: + return 29 + } + } + + /** + The error message returned by the server. + + - Note: For this enum, the error message is determined based on the specific error case that was encountered. + + - SeeAlso: `keyCurveNotSupported(curve:)`, `invalidLongFormDID`, `methodIdIsDoesNotSatisfyRegex(regex:)`, `invalidPublicKeyCoding(didMethod:curve:)`, `invalidDIDString(String)`, `initialStateOfDIDChanged`, `notPossibleToResolveDID(did:reason:)`, `invalidJWK` + */ + public var message: String { + switch self { + case .keyCurveNotSupported(let curve): + return "Key curve \(curve) is not supported for this funcionality" + case .invalidLongFormDID: + return "Long form prism DID is invalid or changed" + case .methodIdIsDoesNotSatisfyRegex(let regex): + return "The Prism DID provided is not passing the regex validation: \(regex)" + case let .invalidPublicKeyCoding(didMethod, curve): + return "Invalid encoding/decoding of key (\(curve)) while trying to compute \(didMethod)" + case .invalidDIDString(let str): + return "Trying to parse invalid DID String: \(str)" + case .initialStateOfDIDChanged: + return "While trying to resolve Prism DID state changed making it invalid" + case let .notPossibleToResolveDID(did, reason): + return "Not possible to resolve DID (\(did)) due to \(reason)" + case .invalidJWKError: + return "JWK is not in a valid format" + case .noResolversAvailableForDIDMethod(let method): + return "No resolvers in castor are able to resolve the method \(method), please provide a resolver" + } + } +} + +extension CastorError: Equatable { + public static func == (lhs: CastorError, rhs: CastorError) -> Bool { + lhs.message == rhs.message + } +} + +/** + An enum representing a known error in a Prism API response. + + - Note: When an error occurs during an API request/response cycle, the server may return an error object in the response. This object may include an error code and an error message. If the error received conforms to the `KnownPrismError` protocol, it will be classified as a known error. + + - SeeAlso: `UnknownPrismError`, `KnownPrismError` + */ +public enum MercuryError: KnownPrismError { + + /// An error case representing the lack of a recipient DID in a message. + case noRecipientDIDSetError + + /** + An error case representing the lack of valid services for a DID. + + - Parameters: + - did: The DID that has no valid services. + */ + case noValidServiceFoundError(did: String) + + /// An error case representing the lack of a sender DID in a message. + case noSenderDIDSetError + + /// An error case representing an unknown attachment data type. + case unknownAttachmentDataTypeError + + /// An error case representing a message attachment without an ID. + case messageAttachmentWithoutIDError + + /// 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. + */ + case didcommError(msg: String) + + /// The error code returned by the server. + public var code: Int { + switch self { + case .noRecipientDIDSetError: + return 31 + case .noValidServiceFoundError: + return 32 + case .noSenderDIDSetError: + return 33 + case .unknownAttachmentDataTypeError: + return 34 + case .messageAttachmentWithoutIDError: + return 35 + case .messageInvalidBodyDataError: + return 36 + case .didcommError: + return 37 + } + } + + /** + The error message returned by the server. + + - Note: For this enum, the error message is determined based on the specific error case that was encountered. + + - SeeAlso: `noRecipientDIDSetError`, `noValidServiceFoundError(did:)`, `noSenderDIDSetError`, `unknownAttachmentDataTypeError`, `messageAttachmentWithoutIDError`, `messageInvalidBodyDataError`, `didcommError(msg:)` + */ + public var message: String { + switch self { + case .noRecipientDIDSetError: + return "Message has no recipient set, to send a message please set the \"to\"" + case .noSenderDIDSetError: + return "Message has no sender set, to send a message please set the \"from\"" + case let .noValidServiceFoundError(did): + return "The did (\(did)) has no valid services" + case .unknownAttachmentDataTypeError: + return "Unknown AttachamentData type was found while decoding message" + case .messageAttachmentWithoutIDError: + return "While decoding a message, a message attachment was found without \"id\" this is invalid" + case .messageInvalidBodyDataError: + return "While decoding a message, a body was found to be invalid while decoding" + case .didcommError(let msg): + return "DIDComm error as ocurred with message: \(msg)" + } + } +} + +extension MercuryError: Equatable { + public static func == (lhs: MercuryError, rhs: MercuryError) -> Bool { + lhs.message == rhs.message + } +} + +/** + An enum representing a known error in a Pluto API response. + + - Note: When an error occurs during an API request/response cycle, the server may return an error object in the response. This object may include an error code and an error message. If the error received conforms to the `KnownPrismError` protocol, it will be classified as a known error. + + - SeeAlso: `UnknownPrismError`, `KnownPrismError` + */ +public enum PlutoError: KnownPrismError { + + /** + An error case representing missing data persistence. + + - Parameters: + - type: The type of data that is missing. + - affecting: The action that is being taken when the error occurs. + */ + case missingDataPersistence(type: String, affecting: String) + + /** + An error case representing missing required fields. + + - Parameters: + - type: The type of data that is missing required fields. + - fields: An array of the required fields. + */ + case missingRequiredFields(type: String, fields: [String]) + + /** + An error case representing a duplicate object. + + - Parameters: + - type: The type of object that is a duplicate. + */ + case duplication(type: String) + + /// An error case representing an unknown credential type. + case unknownCredentialTypeError + + /// An error case representing invalid JSON in a credential. + case invalidCredentialJsonError + + /// The error code returned by the server. + public var code: Int { + switch self { + case .missingDataPersistence: + return 41 + case .missingRequiredFields: + return 42 + case .duplication: + return 43 + case .unknownCredentialTypeError: + return 44 + case .invalidCredentialJsonError: + return 45 + } + } + + /** + The error message returned by the server. + + - Note: For this enum, the error message is determined based on the specific error case that was encountered. + + - SeeAlso: `missingDataPersistence(type:affecting:)`, `missingRequiredFields(type:fields:)`, `duplication(type:)`, `unknownCredentialTypeError`, `invalidCredentialJsonError` + */ + public var message: String { + switch self { + case let .missingDataPersistence(type, affecting): + return "\(type) is not persisted while trying to add or make changes to \(affecting)" + case let .missingRequiredFields(type, fields): + return "\(type) requires the following fields: \(fields.joined(separator: ", "))" + case .duplication(let type): + return "Trying to save \(type) with an ID that already exists" + case .invalidCredentialJsonError: + return "Could not decode the credential JSON" + case .unknownCredentialTypeError: + return "The credential type needs to be JWT or W3C" + } + } +} + +extension PlutoError: Equatable { + public static func == (lhs: PlutoError, rhs: PlutoError) -> Bool { + lhs.message == rhs.message + } +} + +/** + An enum representing a known error in a Pollux API response. + + - Note: When an error occurs during an API request/response cycle, the server may return an error object in the response. This object may include an error code and an error message. If the error received conforms to the `KnownPrismError` protocol, it will be classified as a known error. + + - SeeAlso: `UnknownPrismError`, `KnownPrismError` + */ +public enum PolluxError: KnownPrismError { + + /// An error case representing an invalid credential. + case invalidCredentialError + + /// An error case representing an invalid JWT string. + case invalidJWTString + + /// The error code returned by the server. + public var code: Int { + switch self { + case .invalidCredentialError: + return 51 + case .invalidJWTString: + return 52 + } + } + + /** + The error message returned by the server. + + - Note: For this enum, the error message is determined based on the specific error case that was encountered. + + - SeeAlso: `invalidCredentialError`, `invalidJWTString` + */ + public var message: String { + switch self { + case .invalidCredentialError: + return "Invalid credential, could not decode" + case .invalidJWTString: + return "Invalid JWT while decoding credential" + } + } +} + +extension PolluxError: Equatable { + public static func == (lhs: PolluxError, rhs: PolluxError) -> Bool { + lhs.message == rhs.message + } +} + diff --git a/Domain/Sources/Models/JWTVerifiableCredential+Codable.swift b/AtalaPrismSDK/Domain/Sources/Models/JWTVerifiableCredential+Codable.swift similarity index 100% rename from Domain/Sources/Models/JWTVerifiableCredential+Codable.swift rename to AtalaPrismSDK/Domain/Sources/Models/JWTVerifiableCredential+Codable.swift diff --git a/Domain/Sources/Models/JWTVerifiableCredential.swift b/AtalaPrismSDK/Domain/Sources/Models/JWTVerifiableCredential.swift similarity index 100% rename from Domain/Sources/Models/JWTVerifiableCredential.swift rename to AtalaPrismSDK/Domain/Sources/Models/JWTVerifiableCredential.swift diff --git a/Domain/Sources/Models/KeyPair.swift b/AtalaPrismSDK/Domain/Sources/Models/KeyPair.swift similarity index 100% rename from Domain/Sources/Models/KeyPair.swift rename to AtalaPrismSDK/Domain/Sources/Models/KeyPair.swift diff --git a/Domain/Sources/Models/Message.swift b/AtalaPrismSDK/Domain/Sources/Models/Message.swift similarity index 100% rename from Domain/Sources/Models/Message.swift rename to AtalaPrismSDK/Domain/Sources/Models/Message.swift diff --git a/Domain/Sources/Models/MessageAttachment.swift b/AtalaPrismSDK/Domain/Sources/Models/MessageAttachment.swift similarity index 100% rename from Domain/Sources/Models/MessageAttachment.swift rename to AtalaPrismSDK/Domain/Sources/Models/MessageAttachment.swift diff --git a/Domain/Sources/Models/PrivateKey.swift b/AtalaPrismSDK/Domain/Sources/Models/PrivateKey.swift similarity index 100% rename from Domain/Sources/Models/PrivateKey.swift rename to AtalaPrismSDK/Domain/Sources/Models/PrivateKey.swift diff --git a/Domain/Sources/Models/PublicKey.swift b/AtalaPrismSDK/Domain/Sources/Models/PublicKey.swift similarity index 100% rename from Domain/Sources/Models/PublicKey.swift rename to AtalaPrismSDK/Domain/Sources/Models/PublicKey.swift diff --git a/Domain/Sources/Models/Secret.swift b/AtalaPrismSDK/Domain/Sources/Models/Secret.swift similarity index 100% rename from Domain/Sources/Models/Secret.swift rename to AtalaPrismSDK/Domain/Sources/Models/Secret.swift diff --git a/Domain/Sources/Models/SecretResolver.swift b/AtalaPrismSDK/Domain/Sources/Models/SecretResolver.swift similarity index 100% rename from Domain/Sources/Models/SecretResolver.swift rename to AtalaPrismSDK/Domain/Sources/Models/SecretResolver.swift diff --git a/Domain/Sources/Models/Seed.swift b/AtalaPrismSDK/Domain/Sources/Models/Seed.swift similarity index 100% rename from Domain/Sources/Models/Seed.swift rename to AtalaPrismSDK/Domain/Sources/Models/Seed.swift diff --git a/Domain/Sources/Models/Session.swift b/AtalaPrismSDK/Domain/Sources/Models/Session.swift similarity index 100% rename from Domain/Sources/Models/Session.swift rename to AtalaPrismSDK/Domain/Sources/Models/Session.swift diff --git a/Domain/Sources/Models/Signature.swift b/AtalaPrismSDK/Domain/Sources/Models/Signature.swift similarity index 100% rename from Domain/Sources/Models/Signature.swift rename to AtalaPrismSDK/Domain/Sources/Models/Signature.swift diff --git a/Domain/Sources/Models/VerifiableCredential.swift b/AtalaPrismSDK/Domain/Sources/Models/VerifiableCredential.swift similarity index 100% rename from Domain/Sources/Models/VerifiableCredential.swift rename to AtalaPrismSDK/Domain/Sources/Models/VerifiableCredential.swift diff --git a/Domain/Sources/Models/W3CVerifiableCredential+Codable.swift b/AtalaPrismSDK/Domain/Sources/Models/W3CVerifiableCredential+Codable.swift similarity index 100% rename from Domain/Sources/Models/W3CVerifiableCredential+Codable.swift rename to AtalaPrismSDK/Domain/Sources/Models/W3CVerifiableCredential+Codable.swift diff --git a/Domain/Sources/Models/W3CVerifiableCredential.swift b/AtalaPrismSDK/Domain/Sources/Models/W3CVerifiableCredential.swift similarity index 100% rename from Domain/Sources/Models/W3CVerifiableCredential.swift rename to AtalaPrismSDK/Domain/Sources/Models/W3CVerifiableCredential.swift diff --git a/Domain/Tests/DomainTest.swift b/AtalaPrismSDK/Domain/Tests/DomainTest.swift similarity index 100% rename from Domain/Tests/DomainTest.swift rename to AtalaPrismSDK/Domain/Tests/DomainTest.swift diff --git a/Mercury/Sources/DIDCommWrappers/DIDCommDIDResolverWrapper.swift b/AtalaPrismSDK/Mercury/Sources/DIDCommWrappers/DIDCommDIDResolverWrapper.swift similarity index 82% rename from Mercury/Sources/DIDCommWrappers/DIDCommDIDResolverWrapper.swift rename to AtalaPrismSDK/Mercury/Sources/DIDCommWrappers/DIDCommDIDResolverWrapper.swift index 139156fa..2bbd4b96 100644 --- a/Mercury/Sources/DIDCommWrappers/DIDCommDIDResolverWrapper.swift +++ b/AtalaPrismSDK/Mercury/Sources/DIDCommWrappers/DIDCommDIDResolverWrapper.swift @@ -88,23 +88,27 @@ extension DidDoc { ) } - let services = from.services.map { - if $0.type.contains("DIDCommMessaging") { - return Service( - id: $0.id, - kind: .didCommMessaging( - value: .init( - serviceEndpoint: $0.serviceEndpoint.uri, - accept: $0.serviceEndpoint.accept, - routingKeys: $0.serviceEndpoint.routingKeys + let services = from.services.compactMap { service in + if service.type.contains("DIDCommMessaging") { + return service.serviceEndpoint.first.map { + Service( + id: service.id, + kind: .didCommMessaging( + value: .init( + serviceEndpoint: $0.uri, + accept: $0.accept, + routingKeys: $0.routingKeys + ) ) ) - ) + } } else { - return Service( - id: $0.id, - kind: .other(value: $0.serviceEndpoint.uri) - ) + return service.serviceEndpoint.first.map { + Service( + id: service.id, + kind: .other(value: $0.uri) + ) + } } } self.init( diff --git a/Mercury/Sources/DIDCommWrappers/DIDCommSecretsResolverWrapper.swift b/AtalaPrismSDK/Mercury/Sources/DIDCommWrappers/DIDCommSecretsResolverWrapper.swift similarity index 98% rename from Mercury/Sources/DIDCommWrappers/DIDCommSecretsResolverWrapper.swift rename to AtalaPrismSDK/Mercury/Sources/DIDCommWrappers/DIDCommSecretsResolverWrapper.swift index 316c9b53..b75bab9e 100644 --- a/Mercury/Sources/DIDCommWrappers/DIDCommSecretsResolverWrapper.swift +++ b/AtalaPrismSDK/Mercury/Sources/DIDCommWrappers/DIDCommSecretsResolverWrapper.swift @@ -27,7 +27,7 @@ class DIDCommSecretsResolverWrapper { pluto .getAllPeerDIDs() .tryMap { [weak self] in - try $0.map { did, privateKeys in + try $0.map { did, privateKeys, _ in try self?.parsePrivateKeys(did: did, privateKeys: privateKeys) } } diff --git a/Mercury/Sources/DIDCommWrappers/PackEncryptedOperation.swift b/AtalaPrismSDK/Mercury/Sources/DIDCommWrappers/PackEncryptedOperation.swift similarity index 80% rename from Mercury/Sources/DIDCommWrappers/PackEncryptedOperation.swift rename to AtalaPrismSDK/Mercury/Sources/DIDCommWrappers/PackEncryptedOperation.swift index 9f3c3893..31410dfe 100644 --- a/Mercury/Sources/DIDCommWrappers/PackEncryptedOperation.swift +++ b/AtalaPrismSDK/Mercury/Sources/DIDCommWrappers/PackEncryptedOperation.swift @@ -16,10 +16,9 @@ final class PackEncryptedOperation: OnPackEncryptedResult { } func packEncrypted(msg: Domain.Message) async throws -> String { - guard - let fromDID = msg.from, - let toDID = msg.to - else { throw MercuryError.fromFieldNotSetError } + guard let fromDID = msg.from else { throw MercuryError.noSenderDIDSetError } + guard let toDID = msg.to else { throw MercuryError.noRecipientDIDSetError } + let result: String = try await withCheckedThrowingContinuation { [weak self] continuation in guard let self else { return } self.cancellable = self.published @@ -62,10 +61,14 @@ final class PackEncryptedOperation: OnPackEncryptedResult { case.success: break case .error: - continuation.resume(throwing: MercuryError.unknowPackingMessageError) + continuation.resume(throwing: MercuryError.didcommError( + msg: "Unknown error on initializing pack encrypted function" + )) } - } catch { - continuation.resume(throwing: MercuryError.unknowPackingMessageError) + } catch let error { + continuation.resume(throwing: MercuryError.didcommError( + msg: "Error on parsing Domain message to DIDComm library model: \(error.localizedDescription)" + )) } } return result @@ -78,7 +81,7 @@ final class PackEncryptedOperation: OnPackEncryptedResult { func error(err: DIDCommxSwift.ErrorKind, msg: String) { logger.error( - message: "Could not pack message", + message: "Packing message failed with error", metadata: [ .publicMetadata( key: "Error", @@ -88,6 +91,8 @@ final class PackEncryptedOperation: OnPackEncryptedResult { ) ] ) - published.send(completion: .failure(MercuryError.didcommError(msg: msg))) + published.send(completion: .failure(MercuryError.didcommError( + msg: "Error on trying to pack encrypted a message: \(msg)" + ))) } } diff --git a/Mercury/Sources/DIDCommWrappers/UnpackOperation.swift b/AtalaPrismSDK/Mercury/Sources/DIDCommWrappers/UnpackOperation.swift similarity index 85% rename from Mercury/Sources/DIDCommWrappers/UnpackOperation.swift rename to AtalaPrismSDK/Mercury/Sources/DIDCommWrappers/UnpackOperation.swift index ea399195..85f9afc0 100644 --- a/Mercury/Sources/DIDCommWrappers/UnpackOperation.swift +++ b/AtalaPrismSDK/Mercury/Sources/DIDCommWrappers/UnpackOperation.swift @@ -50,7 +50,9 @@ final class UnpackOperation: OnUnpackResult { }) } case .error: - throw MercuryError.unknowPackingMessageError + throw MercuryError.didcommError( + msg: "Unknown error on initializing unpack message function" + ) } } @@ -65,11 +67,15 @@ final class UnpackOperation: OnUnpackResult { .publicMetadata(key: "Error", value: error.localizedDescription) ] ) - published.send(completion: .failure(error)) + published.send(completion: .failure(MercuryError.didcommError( + msg: "Error on parsing DIDComm library model message to Domain message : \(error.localizedDescription)" + ))) } } func error(err: DIDCommxSwift.ErrorKind, msg: String) { - published.send(completion: .failure(MercuryError.didcommError(msg: msg))) + published.send(completion: .failure(MercuryError.didcommError( + msg: "Error on trying to unpack a message: \(msg)" + ))) } } diff --git a/Mercury/Sources/Helpers/DIDCommMessage+DomainParse.swift b/AtalaPrismSDK/Mercury/Sources/Helpers/DIDCommMessage+DomainParse.swift similarity index 97% rename from Mercury/Sources/Helpers/DIDCommMessage+DomainParse.swift rename to AtalaPrismSDK/Mercury/Sources/Helpers/DIDCommMessage+DomainParse.swift index 36b06987..c97120a8 100644 --- a/Mercury/Sources/Helpers/DIDCommMessage+DomainParse.swift +++ b/AtalaPrismSDK/Mercury/Sources/Helpers/DIDCommMessage+DomainParse.swift @@ -90,7 +90,7 @@ extension DIDCommxSwift.AttachmentData { } else if let jwsData = domain as? AttachmentJwsData { self = .base64(value: .init(base64: jwsData.base64, jws: jwsData.jws.signature)) } else { - throw MercuryError.unknownAttachmentDataError + throw MercuryError.unknownAttachmentDataTypeError } } @@ -102,7 +102,7 @@ extension DIDCommxSwift.AttachmentData { return AttachmentLinkData(links: value.links, hash: value.hash) case let .json(value): guard let jsonData = value.json.data(using: .utf8) else { - throw MercuryError.unknownAttachmentDataError + throw MercuryError.unknownAttachmentDataTypeError } return AttachmentJsonData(data: jsonData) } diff --git a/Mercury/Sources/Helpers/MediaType.swift b/AtalaPrismSDK/Mercury/Sources/Helpers/MediaType.swift similarity index 100% rename from Mercury/Sources/Helpers/MediaType.swift rename to AtalaPrismSDK/Mercury/Sources/Helpers/MediaType.swift diff --git a/Mercury/Sources/Helpers/Session.swift b/AtalaPrismSDK/Mercury/Sources/Helpers/SessionManager.swift similarity index 86% rename from Mercury/Sources/Helpers/Session.swift rename to AtalaPrismSDK/Mercury/Sources/Helpers/SessionManager.swift index 4c627297..05be1802 100644 --- a/Mercury/Sources/Helpers/Session.swift +++ b/AtalaPrismSDK/Mercury/Sources/Helpers/SessionManager.swift @@ -34,10 +34,9 @@ struct SessionManager { let (data, response) = try await session.data(for: request) if let urlResponse = response as? HTTPURLResponse { guard 200...299 ~= urlResponse.statusCode else { - throw MercuryError.urlSessionError( - statusCode: urlResponse.statusCode, - error: nil, - msg: String(data: data, encoding: .utf8) + throw CommonError.httpError( + code: urlResponse.statusCode, + message: String(data: data, encoding: .utf8) ?? "" ) } } @@ -62,7 +61,9 @@ struct SessionManager { if !parameters.isEmpty { composition?.queryItems = parameters.map { URLQueryItem(name: $0, value: $1) } } - guard let url = composition?.url else { throw MercuryError.invalidURLError } + guard let url = composition?.url else { + throw CommonError.invalidURLError(url: urlParsed.absoluteString) + } var request = URLRequest(url: url, timeoutInterval: timeout) request.allHTTPHeaderFields = headers request.httpBody = body diff --git a/AtalaPrismSDK/Mercury/Sources/Mercury.docc/Mercury.md b/AtalaPrismSDK/Mercury/Sources/Mercury.docc/Mercury.md new file mode 100644 index 00000000..35e0b1d9 --- /dev/null +++ b/AtalaPrismSDK/Mercury/Sources/Mercury.docc/Mercury.md @@ -0,0 +1,19 @@ +# ``Mercury`` + +Mercury is a powerful and flexible library for working with decentralized identifiers and secure communications protocols. Whether you are a developer looking to build a secure and private messaging app, or you are building a more complex decentralized system that requires trusted peer-to-peer connections, Mercury provides the tools and features you need to establish, manage, and secure your communications with ease. + +## A Secure Communications Protocol SDK for DIDs + +Mercury is a comprehensive library that provides a set of secure, standards-based communications protocols for establishing and managing trusted, peer-to-peer connections and interactions between decentralized identifiers (DIDs). Mercury is designed to be transport-agnostic and interoperable, meaning that it can be used across a wide range of communication channels and platforms. + +DIDCommV2 is a secure, privacy-preserving messaging protocol that allows for the exchange of information between DIDs in a secure and efficient manner. Mercury supports a range of DIDCommV2 operations, including pack encrypted and unpack, which enables users to securely transmit and receive messages across the network. + +With Mercury, developers can easily establish and manage trusted, peer-to-peer connections between DIDs, allowing for secure and private communication across a range of platforms and use cases. Whether you are building a messaging app, a decentralized social network, or any other application that requires secure and private communications, Mercury provides the tools and features you need to get the job done. + +Mercury also provides a range of advanced features, including support for message threading, priority levels, and message expiration, as well as support for a range of transport protocols, including HTTP. + +## Topics + +### Group + +- ``Symbol`` diff --git a/AtalaPrismSDK/Mercury/Sources/Mercury.docc/MercuryHowTo.md b/AtalaPrismSDK/Mercury/Sources/Mercury.docc/MercuryHowTo.md new file mode 100644 index 00000000..6d06c673 --- /dev/null +++ b/AtalaPrismSDK/Mercury/Sources/Mercury.docc/MercuryHowTo.md @@ -0,0 +1,55 @@ +# Mercury SDK API Tutorial + +The Mercury protocol defines a set of functions for packing and sending messages. Here's a brief explanation of each function: + +- `packMessage`: This function asynchronously packs a given message object into a string representation. It may throw an error if the message object is invalid. + +``` swift + // Example usage: + let mercury = MercuryImpl(apollo: apolloImpl, castor: castorImpl, pluto: plutoImpl) + let message = Message(...) + do { + let packedMessage = try mercury.packMessage(msg: message) // returns the String packed message + } catch { + // Handle error + } +``` + +- `unpackMessage`: This function asynchronously unpacks a given string representation of a message into a message object. It may throw an error if the string is not a valid message representation. + +```swift + // Example usage: + let mercury = MercuryImpl(apollo: apolloImpl, castor: castorImpl, pluto: plutoImpl) + let packedMessage = "..." + do { + let message = try mercury.unpackMessage(msg: packedMessage) // returns the ``Message`` + } catch { + // Handle error + } +``` + +- `sendMessage`: This function asynchronously sends a given message and returns the response data. It may throw an error if the message is invalid or the send operation fails. + +```swift + // Example usage: + let mercury = MercuryImpl(apollo: apolloImpl, castor: castorImpl, pluto: plutoImpl) + let message = Message(...) + do { + let responseData = try mercury.sendMessage(msg: message) + } catch { + // Handle error + } +``` + +- `sendMessageParseMessage`: This function asynchronously sends a given message and returns the response message object. It may throw an error if the message is invalid, the send operation fails, or the response message is invalid. + +```swift + // Example usage: + let mercury = MercuryImpl(apollo: apolloImpl, castor: castorImpl, pluto: plutoImpl) + let message = Domain.Message(...) + do { + let responseMessage = try mercury.sendMessageParseMessage(msg: message) + } catch { + // Handle error + } +``` diff --git a/AtalaPrismSDK/Mercury/Sources/MercuryImpl+Public.swift b/AtalaPrismSDK/Mercury/Sources/MercuryImpl+Public.swift new file mode 100644 index 00000000..edc997ed --- /dev/null +++ b/AtalaPrismSDK/Mercury/Sources/MercuryImpl+Public.swift @@ -0,0 +1,60 @@ +import Core +import DIDCommxSwift +import Domain +import Foundation + +extension MercuryImpl: Mercury { + /// packMessage asynchronously packs a given message object into a string representation. This function may throw an error if the message object is invalid. + /// + /// - Parameter msg: The message object to pack + /// - 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, logger: logger).packEncrypted(msg: msg) + } + + /// 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. + /// + /// - Parameter msg: The string representation of the message to unpack + /// - 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) + } + + /// sendMessage asynchronously sends a given message and returns the response data. This function may throw an error if the message is invalid or the send operation fails. + /// + /// - Parameter msg: The message to send + /// - Returns: The response data + /// - Throws: An error if the message is invalid or the send operation fails + public func sendMessage(msg: Domain.Message) async throws -> Data? { + guard let toDID = msg.to else { throw MercuryError.noRecipientDIDSetError } + let document = try await castor.resolveDID(did: toDID) + guard + let urlString = document.services.first?.serviceEndpoint.first?.uri, + let url = URL(string: urlString) + else { + logger.error(message: "Could not find a valid service on the DID to send message") + throw MercuryError.noValidServiceFoundError(did: toDID.string) + } + let packedMessage = try await packMessage(msg: msg) + return try await session.post( + url: url, + body: packedMessage.data(using: .utf8), + headers: ["content-type": MediaType.contentTypeEncrypted.rawValue] + ) + } + + /// sendMessageParseMessage asynchronously sends a given message and returns the response message object. This function may throw an error if the message is invalid, the send operation fails, or the response message is invalid. + /// + /// - Parameter msg: The message to send + /// - Returns: The response message object + /// - Throws: An error if the message is invalid, the send operation fails, or the response message is invalid + public func sendMessageParseMessage(msg: Domain.Message) async throws -> Domain.Message? { + guard + let msgData = try await sendMessage(msg: msg), + let msgStr = String(data: msgData, encoding: .utf8) + else { return nil } + return try? await self.unpackMessage(msg: msgStr) + } +} diff --git a/Mercury/Sources/MercuryImpl.swift b/AtalaPrismSDK/Mercury/Sources/MercuryImpl.swift similarity index 100% rename from Mercury/Sources/MercuryImpl.swift rename to AtalaPrismSDK/Mercury/Sources/MercuryImpl.swift diff --git a/Mercury/Tests/ExperiencesTest.swift b/AtalaPrismSDK/Mercury/Tests/ExperiencesTest.swift similarity index 100% rename from Mercury/Tests/ExperiencesTest.swift rename to AtalaPrismSDK/Mercury/Tests/ExperiencesTest.swift diff --git a/AtalaPrismSDK/Pluto/Sources/Domain/Providers/DIDPairProvider.swift b/AtalaPrismSDK/Pluto/Sources/Domain/Providers/DIDPairProvider.swift new file mode 100644 index 00000000..42a7c5de --- /dev/null +++ b/AtalaPrismSDK/Pluto/Sources/Domain/Providers/DIDPairProvider.swift @@ -0,0 +1,10 @@ +import Combine +import Domain +import Foundation + +protocol DIDPairProvider { + func getAll() -> AnyPublisher<[DIDPair], Error> + func getPair(otherDID: DID) -> AnyPublisher + func getPair(name: String) -> AnyPublisher + func getPair(holderDID: DID) -> AnyPublisher +} diff --git a/Pluto/Sources/Domain/Providers/DIDPrivateKeyProvider.swift b/AtalaPrismSDK/Pluto/Sources/Domain/Providers/DIDPrivateKeyProvider.swift similarity index 59% rename from Pluto/Sources/Domain/Providers/DIDPrivateKeyProvider.swift rename to AtalaPrismSDK/Pluto/Sources/Domain/Providers/DIDPrivateKeyProvider.swift index acb7bae4..570a608c 100644 --- a/Pluto/Sources/Domain/Providers/DIDPrivateKeyProvider.swift +++ b/AtalaPrismSDK/Pluto/Sources/Domain/Providers/DIDPrivateKeyProvider.swift @@ -3,7 +3,8 @@ import Domain import Foundation protocol DIDPrivateKeyProvider { - func getAll() -> AnyPublisher<[(did: DID, privateKeys: [PrivateKey])], Error> - func getDIDInfo(did: DID) -> AnyPublisher<(did: DID, privateKeys: [PrivateKey])?, Error> + func getAll() -> AnyPublisher<[(did: DID, privateKeys: [PrivateKey], alias: String?)], Error> + func getDIDInfo(did: DID) -> AnyPublisher<(did: DID, privateKeys: [PrivateKey], alias: String?)?, Error> + func getDIDInfo(alias: String) -> AnyPublisher<[(did: DID, privateKeys: [PrivateKey], alias: String?)], Error> func getPrivateKeys(did: DID) -> AnyPublisher<[PrivateKey]?, Error> } diff --git a/Pluto/Sources/Domain/Providers/DIDProvider.swift b/AtalaPrismSDK/Pluto/Sources/Domain/Providers/DIDProvider.swift similarity index 100% rename from Pluto/Sources/Domain/Providers/DIDProvider.swift rename to AtalaPrismSDK/Pluto/Sources/Domain/Providers/DIDProvider.swift diff --git a/Pluto/Sources/Domain/Providers/MediatorProvider.swift b/AtalaPrismSDK/Pluto/Sources/Domain/Providers/MediatorProvider.swift similarity index 100% rename from Pluto/Sources/Domain/Providers/MediatorProvider.swift rename to AtalaPrismSDK/Pluto/Sources/Domain/Providers/MediatorProvider.swift diff --git a/Pluto/Sources/Domain/Providers/MessageProvider.swift b/AtalaPrismSDK/Pluto/Sources/Domain/Providers/MessageProvider.swift similarity index 100% rename from Pluto/Sources/Domain/Providers/MessageProvider.swift rename to AtalaPrismSDK/Pluto/Sources/Domain/Providers/MessageProvider.swift diff --git a/Pluto/Sources/Domain/Providers/VerifiableCredentialProvider.swift b/AtalaPrismSDK/Pluto/Sources/Domain/Providers/VerifiableCredentialProvider.swift similarity index 100% rename from Pluto/Sources/Domain/Providers/VerifiableCredentialProvider.swift rename to AtalaPrismSDK/Pluto/Sources/Domain/Providers/VerifiableCredentialProvider.swift diff --git a/Pluto/Sources/Domain/Stores/DIDPairStore.swift b/AtalaPrismSDK/Pluto/Sources/Domain/Stores/DIDPairStore.swift similarity index 69% rename from Pluto/Sources/Domain/Stores/DIDPairStore.swift rename to AtalaPrismSDK/Pluto/Sources/Domain/Stores/DIDPairStore.swift index 2354a4f5..30952444 100644 --- a/Pluto/Sources/Domain/Stores/DIDPairStore.swift +++ b/AtalaPrismSDK/Pluto/Sources/Domain/Stores/DIDPairStore.swift @@ -3,7 +3,7 @@ import Domain import Foundation protocol DIDPairStore { - func addDIDPair(holder: DID, other: DID, name: String) -> AnyPublisher + func addDIDPair(pair: DIDPair) -> AnyPublisher func removeDIDPair(holder: DID, other: DID) -> AnyPublisher func removeAll() -> AnyPublisher } diff --git a/Pluto/Sources/Domain/Stores/DIDPrivateKeyStore.swift b/AtalaPrismSDK/Pluto/Sources/Domain/Stores/DIDPrivateKeyStore.swift similarity index 65% rename from Pluto/Sources/Domain/Stores/DIDPrivateKeyStore.swift rename to AtalaPrismSDK/Pluto/Sources/Domain/Stores/DIDPrivateKeyStore.swift index 9b06695e..9c797873 100644 --- a/Pluto/Sources/Domain/Stores/DIDPrivateKeyStore.swift +++ b/AtalaPrismSDK/Pluto/Sources/Domain/Stores/DIDPrivateKeyStore.swift @@ -3,7 +3,7 @@ import Domain import Foundation protocol DIDPrivateKeyStore { - func addDID(did: DID, privateKeys: [PrivateKey]) -> AnyPublisher + func addDID(did: DID, privateKeys: [PrivateKey], alias: String?) -> AnyPublisher func removeDID(did: DID) -> AnyPublisher func removeAll() -> AnyPublisher } diff --git a/Pluto/Sources/Domain/Stores/DIDStore.swift b/AtalaPrismSDK/Pluto/Sources/Domain/Stores/DIDStore.swift similarity index 100% rename from Pluto/Sources/Domain/Stores/DIDStore.swift rename to AtalaPrismSDK/Pluto/Sources/Domain/Stores/DIDStore.swift diff --git a/Pluto/Sources/Domain/Stores/MediatorStore.swift b/AtalaPrismSDK/Pluto/Sources/Domain/Stores/MediatorStore.swift similarity index 100% rename from Pluto/Sources/Domain/Stores/MediatorStore.swift rename to AtalaPrismSDK/Pluto/Sources/Domain/Stores/MediatorStore.swift diff --git a/Pluto/Sources/Domain/Stores/MessageStore.swift b/AtalaPrismSDK/Pluto/Sources/Domain/Stores/MessageStore.swift similarity index 100% rename from Pluto/Sources/Domain/Stores/MessageStore.swift rename to AtalaPrismSDK/Pluto/Sources/Domain/Stores/MessageStore.swift diff --git a/Pluto/Sources/Domain/Stores/VerifiableCredentialStore.swift b/AtalaPrismSDK/Pluto/Sources/Domain/Stores/VerifiableCredentialStore.swift similarity index 100% rename from Pluto/Sources/Domain/Stores/VerifiableCredentialStore.swift rename to AtalaPrismSDK/Pluto/Sources/Domain/Stores/VerifiableCredentialStore.swift diff --git a/Pluto/Sources/Helpers/AttachmentDescriptor+Codable.swift b/AtalaPrismSDK/Pluto/Sources/Helpers/AttachmentDescriptor+Codable.swift similarity index 100% rename from Pluto/Sources/Helpers/AttachmentDescriptor+Codable.swift rename to AtalaPrismSDK/Pluto/Sources/Helpers/AttachmentDescriptor+Codable.swift diff --git a/Pluto/Sources/Helpers/CoreData/CoreDataDAO+Combine.swift b/AtalaPrismSDK/Pluto/Sources/Helpers/CoreData/CoreDataDAO+Combine.swift similarity index 100% rename from Pluto/Sources/Helpers/CoreData/CoreDataDAO+Combine.swift rename to AtalaPrismSDK/Pluto/Sources/Helpers/CoreData/CoreDataDAO+Combine.swift diff --git a/Pluto/Sources/Helpers/CoreData/CoreDataDAO.swift b/AtalaPrismSDK/Pluto/Sources/Helpers/CoreData/CoreDataDAO.swift similarity index 100% rename from Pluto/Sources/Helpers/CoreData/CoreDataDAO.swift rename to AtalaPrismSDK/Pluto/Sources/Helpers/CoreData/CoreDataDAO.swift diff --git a/Pluto/Sources/Helpers/CoreData/CoreDataManager.swift b/AtalaPrismSDK/Pluto/Sources/Helpers/CoreData/CoreDataManager.swift similarity index 100% rename from Pluto/Sources/Helpers/CoreData/CoreDataManager.swift rename to AtalaPrismSDK/Pluto/Sources/Helpers/CoreData/CoreDataManager.swift diff --git a/Pluto/Sources/Helpers/CoreData/NSFetchedResultsControllerPublisher.swift b/AtalaPrismSDK/Pluto/Sources/Helpers/CoreData/NSFetchedResultsControllerPublisher.swift similarity index 100% rename from Pluto/Sources/Helpers/CoreData/NSFetchedResultsControllerPublisher.swift rename to AtalaPrismSDK/Pluto/Sources/Helpers/CoreData/NSFetchedResultsControllerPublisher.swift diff --git a/Pluto/Sources/Helpers/CoreData/NSManagedObjectContext+Combine.swift b/AtalaPrismSDK/Pluto/Sources/Helpers/CoreData/NSManagedObjectContext+Combine.swift similarity index 100% rename from Pluto/Sources/Helpers/CoreData/NSManagedObjectContext+Combine.swift rename to AtalaPrismSDK/Pluto/Sources/Helpers/CoreData/NSManagedObjectContext+Combine.swift diff --git a/Pluto/Sources/Helpers/CoreData/NSManagedObjectContext+Save.swift b/AtalaPrismSDK/Pluto/Sources/Helpers/CoreData/NSManagedObjectContext+Save.swift similarity index 100% rename from Pluto/Sources/Helpers/CoreData/NSManagedObjectContext+Save.swift rename to AtalaPrismSDK/Pluto/Sources/Helpers/CoreData/NSManagedObjectContext+Save.swift diff --git a/Pluto/Sources/Helpers/DID+Codable.swift b/AtalaPrismSDK/Pluto/Sources/Helpers/DID+Codable.swift similarity index 100% rename from Pluto/Sources/Helpers/DID+Codable.swift rename to AtalaPrismSDK/Pluto/Sources/Helpers/DID+Codable.swift diff --git a/Pluto/Sources/Helpers/Message+Codable.swift b/AtalaPrismSDK/Pluto/Sources/Helpers/Message+Codable.swift similarity index 100% rename from Pluto/Sources/Helpers/Message+Codable.swift rename to AtalaPrismSDK/Pluto/Sources/Helpers/Message+Codable.swift diff --git a/Pluto/Sources/PersistentStorage/DAO/CDDIDDAO.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDDIDDAO.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/DAO/CDDIDDAO.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDDIDDAO.swift diff --git a/Pluto/Sources/PersistentStorage/DAO/CDDIDPairDao+DIDPairProvider.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDDIDPairDao+DIDPairProvider.swift similarity index 58% rename from Pluto/Sources/PersistentStorage/DAO/CDDIDPairDao+DIDPairProvider.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDDIDPairDao+DIDPairProvider.swift index e20d9155..2d8cbc8c 100644 --- a/Pluto/Sources/PersistentStorage/DAO/CDDIDPairDao+DIDPairProvider.swift +++ b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDDIDPairDao+DIDPairProvider.swift @@ -3,51 +3,69 @@ import CoreData import Domain extension CDDIDPairDAO: DIDPairProvider { - func getAll() -> AnyPublisher<[(holder: DID, other: DID, name: String?)], Error> { + func getAll() -> AnyPublisher<[DIDPair], Error> { fetchController(context: readContext) .map { $0.map { - (DID(from: $0.holderDID), DID(from: $0), $0.name) + $0.toDomain() }} .eraseToAnyPublisher() } - func getPair(otherDID: DID) -> AnyPublisher<(holder: DID, other: DID, name: String?)?, Error> { + func getPair(otherDID: DID) -> AnyPublisher { fetchController( predicate: NSPredicate(format: "did == %@", otherDID.string), context: readContext ) .map { $0.first.map { - (DID(from: $0.holderDID), DID(from: $0), $0.name) + $0.toDomain() }} .eraseToAnyPublisher() } - func getPair(name: String) -> AnyPublisher<(holder: DID, other: DID, name: String?)?, Error> { + func getPair(name: String) -> AnyPublisher { fetchController( predicate: NSPredicate(format: "name == %@", name), context: readContext ) .map { $0.first.map { - (DID(from: $0.holderDID), DID(from: $0), $0.name) + $0.toDomain() }} .eraseToAnyPublisher() } - func getPair(holderDID: DID) -> AnyPublisher<(holder: DID, other: DID, name: String?)?, Error> { + func getPair(holderDID: DID) -> AnyPublisher { fetchController( predicate: NSPredicate(format: "holderDID.did == %@", holderDID.string), context: readContext ) .map { $0.first.map { - (DID(from: $0.holderDID), DID(from: $0), $0.name) + $0.toDomain() }} .eraseToAnyPublisher() } - func getPair(holderDID: DID, otherDID: DID) -> AnyPublisher<(holder: DID, other: DID, name: String?)?, Error> { + func getPair(holderDID: DID, otherDID: DID) -> AnyPublisher { fetchController( predicate: NSPredicate(format: "(holderDID.did == %@) AND (did == %@)", holderDID.string, otherDID.string), context: readContext ) .map { $0.first.map { - (DID(from: $0.holderDID), DID(from: $0), $0.name) + $0.toDomain() }} .eraseToAnyPublisher() } } + +extension CDDIDPair { + func toDomain() -> DIDPair { + return DIDPair( + holder: DID( + schema: self.holderDID.schema, + method: self.holderDID.method, + methodId: self.holderDID.methodId + ), + other: DID( + schema: self.schema, + method: self.method, + methodId: self.methodId + ), + name: self.name + ) + } +} diff --git a/Pluto/Sources/PersistentStorage/DAO/CDDIDPairDao+DIDPairStore.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDDIDPairDao+DIDPairStore.swift similarity index 51% rename from Pluto/Sources/PersistentStorage/DAO/CDDIDPairDao+DIDPairStore.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDDIDPairDao+DIDPairStore.swift index 9df154ab..72c0c1d0 100644 --- a/Pluto/Sources/PersistentStorage/DAO/CDDIDPairDao+DIDPairStore.swift +++ b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDDIDPairDao+DIDPairStore.swift @@ -3,18 +3,33 @@ import CoreData import Domain extension CDDIDPairDAO: DIDPairStore { - func addDIDPair(holder: DID, other: DID, name: String) -> AnyPublisher { + func addDIDPair(pair: DIDPair) -> AnyPublisher { privateKeyDIDDAO - .fetchByIDsPublisher(holder.string, context: writeContext) + .fetchByIDsPublisher( + pair.holder.string, + context: writeContext + ) .first() .tryMap { cdobj in - guard let did = cdobj else { throw PlutoError.invalidHolderDIDNotPersistedError } - guard did.pair == nil else { throw PlutoError.holderDIDAlreadyPairingError } + guard let did = cdobj else { + throw PlutoError.missingDataPersistence( + type: "Holder DID", + affecting: "DID Pair" + ) + } + guard did.pair == nil else { + throw PlutoError.duplication(type: "Holder DID/DID Pair") + } return did } .flatMap { didObjc in - updateOrCreate(other.string, context: writeContext) { cdobj, context in - cdobj.parseFrom(holder: didObjc, other: other, name: name, context: context) + updateOrCreate(pair.other.string, context: writeContext) { cdobj, context in + cdobj.parseFrom( + holder: didObjc, + other: pair.other, + name: pair.name ?? "", + context: context + ) } } .map { _ in } diff --git a/Pluto/Sources/PersistentStorage/DAO/CDDIDPairDao.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDDIDPairDao.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/DAO/CDDIDPairDao.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDDIDPairDao.swift diff --git a/Pluto/Sources/PersistentStorage/DAO/CDDIDPrivateKeyDAO+DIDPrivateKeyProvider.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDDIDPrivateKeyDAO+DIDPrivateKeyProvider.swift similarity index 70% rename from Pluto/Sources/PersistentStorage/DAO/CDDIDPrivateKeyDAO+DIDPrivateKeyProvider.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDDIDPrivateKeyDAO+DIDPrivateKeyProvider.swift index 26a6edf5..d6222911 100644 --- a/Pluto/Sources/PersistentStorage/DAO/CDDIDPrivateKeyDAO+DIDPrivateKeyProvider.swift +++ b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDDIDPrivateKeyDAO+DIDPrivateKeyProvider.swift @@ -3,26 +3,44 @@ import CoreData import Domain extension CDDIDPrivateKeyDAO: DIDPrivateKeyProvider { - func getAll() -> AnyPublisher<[(did: DID, privateKeys: [PrivateKey])], Error> { + func getAll() -> AnyPublisher<[(did: DID, privateKeys: [PrivateKey], alias: String?)], Error> { fetchController(context: readContext) .tryMap { try $0.map { ( DID(from: $0), - try $0.parsePrivateKeys() + try $0.parsePrivateKeys(), + $0.alias ) }} .eraseToAnyPublisher() } - func getDIDInfo(did: DID) -> AnyPublisher<(did: DID, privateKeys: [PrivateKey])?, Error> { + func getDIDInfo(did: DID) -> AnyPublisher<(did: DID, privateKeys: [PrivateKey], alias: String?)?, Error> { fetchByIDsPublisher(did.string, context: readContext) .tryMap { try $0.map { ( DID(from: $0), - try $0.parsePrivateKeys() + try $0.parsePrivateKeys(), + $0.alias ) }} .eraseToAnyPublisher() } + + func getDIDInfo(alias: String) -> AnyPublisher<[(did: DID, privateKeys: [PrivateKey], alias: String?)], Error> { + fetchController( + predicate: NSPredicate(format: "alias == %@", alias), + context: readContext + ) + .tryMap { + try $0.map { ( + DID(from: $0), + try $0.parsePrivateKeys(), + $0.alias + ) + }} + .eraseToAnyPublisher() + } + func getPrivateKeys(did: DID) -> AnyPublisher<[PrivateKey]?, Error> { fetchByIDsPublisher(did.string, context: readContext) .tryMap { did in diff --git a/Pluto/Sources/PersistentStorage/DAO/CDDIDPrivateKeyDAO+DIDPrivateKeyStore.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDDIDPrivateKeyDAO+DIDPrivateKeyStore.swift similarity index 80% rename from Pluto/Sources/PersistentStorage/DAO/CDDIDPrivateKeyDAO+DIDPrivateKeyStore.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDDIDPrivateKeyDAO+DIDPrivateKeyStore.swift index 421d7ac5..3c2a90ef 100644 --- a/Pluto/Sources/PersistentStorage/DAO/CDDIDPrivateKeyDAO+DIDPrivateKeyStore.swift +++ b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDDIDPrivateKeyDAO+DIDPrivateKeyStore.swift @@ -3,9 +3,9 @@ import CoreData import Domain extension CDDIDPrivateKeyDAO: DIDPrivateKeyStore { - func addDID(did: DID, privateKeys: [PrivateKey]) -> AnyPublisher { + func addDID(did: DID, privateKeys: [PrivateKey], alias: String?) -> AnyPublisher { updateOrCreate(did.string, context: writeContext) { cdobj, _ in - cdobj.parseFrom(did: did, privateKeys: privateKeys) + cdobj.parseFrom(did: did, privateKeys: privateKeys, alias: alias) } .map { _ in () } .eraseToAnyPublisher() @@ -20,7 +20,7 @@ extension CDDIDPrivateKeyDAO: DIDPrivateKeyStore { } private extension CDDIDPrivateKey { - func parseFrom(did: DID, privateKeys: [PrivateKey]) { + func parseFrom(did: DID, privateKeys: [PrivateKey], alias: String?) { self.did = did.string self.schema = did.schema self.method = did.method @@ -66,7 +66,10 @@ extension KeyCurve { case "Ed25519": self = .ed25519 default: - throw CommonError.somethingWentWrongError + throw UnknownError.somethingWentWrongError( + customMessage: "Curve (\(storageName)) is not valid", + underlyingErrors: nil + ) } } } diff --git a/Pluto/Sources/PersistentStorage/DAO/CDDIDPrivateKeyDAO.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDDIDPrivateKeyDAO.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/DAO/CDDIDPrivateKeyDAO.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDDIDPrivateKeyDAO.swift diff --git a/Pluto/Sources/PersistentStorage/DAO/CDMediatorDIDDAO+MediatorProvider.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDMediatorDIDDAO+MediatorProvider.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/DAO/CDMediatorDIDDAO+MediatorProvider.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDMediatorDIDDAO+MediatorProvider.swift diff --git a/Pluto/Sources/PersistentStorage/DAO/CDMediatorDIDDAO+MediatorStore.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDMediatorDIDDAO+MediatorStore.swift similarity index 89% rename from Pluto/Sources/PersistentStorage/DAO/CDMediatorDIDDAO+MediatorStore.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDMediatorDIDDAO+MediatorStore.swift index db670bb7..6dbf0f97 100644 --- a/Pluto/Sources/PersistentStorage/DAO/CDMediatorDIDDAO+MediatorStore.swift +++ b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDMediatorDIDDAO+MediatorStore.swift @@ -8,7 +8,12 @@ extension CDMediatorDIDDAO: MediatorStore { .fetchByIDsPublisher(peer.string, context: writeContext) .first() .tryMap { cdobj in - guard let did = cdobj else { throw PlutoError.invalidHolderDIDNotPersistedError } + guard let did = cdobj else { + throw PlutoError.missingDataPersistence( + type: "Holder DID", + affecting: "Mediator" + ) + } return did } .flatMap { peerDID in diff --git a/Pluto/Sources/PersistentStorage/DAO/CDMediatorDIDDAO.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDMediatorDIDDAO.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/DAO/CDMediatorDIDDAO.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDMediatorDIDDAO.swift diff --git a/Pluto/Sources/PersistentStorage/DAO/CDMessageDAO+MessageProvider.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDMessageDAO+MessageProvider.swift similarity index 96% rename from Pluto/Sources/PersistentStorage/DAO/CDMessageDAO+MessageProvider.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDMessageDAO+MessageProvider.swift index bc44fdd8..3801de96 100644 --- a/Pluto/Sources/PersistentStorage/DAO/CDMessageDAO+MessageProvider.swift +++ b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDMessageDAO+MessageProvider.swift @@ -5,7 +5,10 @@ import Domain extension CDMessageDAO: MessageProvider { func getAll() -> AnyPublisher<[Message], Error> { fetchController(context: readContext) - .tryMap { try $0.map { try $0.toDomain() } } + .tryMap { + try $0.map { + try $0.toDomain() + }} .eraseToAnyPublisher() } diff --git a/Pluto/Sources/PersistentStorage/DAO/CDMessageDAO+MessageStore.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDMessageDAO+MessageStore.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/DAO/CDMessageDAO+MessageStore.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDMessageDAO+MessageStore.swift diff --git a/Pluto/Sources/PersistentStorage/DAO/CDMessageDAO.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDMessageDAO.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/DAO/CDMessageDAO.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDMessageDAO.swift diff --git a/Pluto/Sources/PersistentStorage/DAO/CDRegisteredDIDDAO+DIDProvider.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDRegisteredDIDDAO+DIDProvider.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/DAO/CDRegisteredDIDDAO+DIDProvider.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDRegisteredDIDDAO+DIDProvider.swift diff --git a/Pluto/Sources/PersistentStorage/DAO/CDRegisteredDIDDAO+DIDStore.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDRegisteredDIDDAO+DIDStore.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/DAO/CDRegisteredDIDDAO+DIDStore.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDRegisteredDIDDAO+DIDStore.swift diff --git a/Pluto/Sources/PersistentStorage/DAO/CDRegisteredDIDDAO.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDRegisteredDIDDAO.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/DAO/CDRegisteredDIDDAO.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDRegisteredDIDDAO.swift diff --git a/Pluto/Sources/PersistentStorage/DAO/CDVerifiableCredentialDAO+VerifiableCredentialProvider.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDVerifiableCredentialDAO+VerifiableCredentialProvider.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/DAO/CDVerifiableCredentialDAO+VerifiableCredentialProvider.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDVerifiableCredentialDAO+VerifiableCredentialProvider.swift diff --git a/Pluto/Sources/PersistentStorage/DAO/CDVerifiableCredentialDAO+VerifiableCredentialStore.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDVerifiableCredentialDAO+VerifiableCredentialStore.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/DAO/CDVerifiableCredentialDAO+VerifiableCredentialStore.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDVerifiableCredentialDAO+VerifiableCredentialStore.swift diff --git a/Pluto/Sources/PersistentStorage/DAO/CDVerifiableCredentialDAO.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDVerifiableCredentialDAO.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/DAO/CDVerifiableCredentialDAO.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/DAO/CDVerifiableCredentialDAO.swift diff --git a/Pluto/Sources/PersistentStorage/Models/CDDID+CoreDataClass.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDDID+CoreDataClass.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/Models/CDDID+CoreDataClass.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDDID+CoreDataClass.swift diff --git a/Pluto/Sources/PersistentStorage/Models/CDDID+CoreDataProperties.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDDID+CoreDataProperties.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/Models/CDDID+CoreDataProperties.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDDID+CoreDataProperties.swift diff --git a/Pluto/Sources/PersistentStorage/Models/CDDIDPair+CoreDataClass.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDDIDPair+CoreDataClass.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/Models/CDDIDPair+CoreDataClass.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDDIDPair+CoreDataClass.swift diff --git a/Pluto/Sources/PersistentStorage/Models/CDDIDPair+CoreDataProperties.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDDIDPair+CoreDataProperties.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/Models/CDDIDPair+CoreDataProperties.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDDIDPair+CoreDataProperties.swift diff --git a/Pluto/Sources/PersistentStorage/Models/CDDIDPrivateKey+CoreDataClass.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDDIDPrivateKey+CoreDataClass.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/Models/CDDIDPrivateKey+CoreDataClass.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDDIDPrivateKey+CoreDataClass.swift diff --git a/Pluto/Sources/PersistentStorage/Models/CDDIDPrivateKey+CoreDataProperties.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDDIDPrivateKey+CoreDataProperties.swift similarity index 94% rename from Pluto/Sources/PersistentStorage/Models/CDDIDPrivateKey+CoreDataProperties.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDDIDPrivateKey+CoreDataProperties.swift index a83cafbf..926809f9 100644 --- a/Pluto/Sources/PersistentStorage/Models/CDDIDPrivateKey+CoreDataProperties.swift +++ b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDDIDPrivateKey+CoreDataProperties.swift @@ -11,5 +11,6 @@ extension CDDIDPrivateKey { @NSManaged var privateKeyKeyAgreement: Data? @NSManaged var curveKeyAgreement: String? @NSManaged var curveAuthenticate: String? + @NSManaged var alias: String? @NSManaged var pair: CDDIDPair? } diff --git a/Pluto/Sources/PersistentStorage/Models/CDIssueCredentialProtocol+CoreDataClass.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDIssueCredentialProtocol+CoreDataClass.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/Models/CDIssueCredentialProtocol+CoreDataClass.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDIssueCredentialProtocol+CoreDataClass.swift diff --git a/Pluto/Sources/PersistentStorage/Models/CDIssueCredentialProtocol+CoreDataProperties.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDIssueCredentialProtocol+CoreDataProperties.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/Models/CDIssueCredentialProtocol+CoreDataProperties.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDIssueCredentialProtocol+CoreDataProperties.swift diff --git a/Pluto/Sources/PersistentStorage/Models/CDMediatorDID+CoreDataClass.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDMediatorDID+CoreDataClass.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/Models/CDMediatorDID+CoreDataClass.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDMediatorDID+CoreDataClass.swift diff --git a/Pluto/Sources/PersistentStorage/Models/CDMediatorDID+CoreDataProperties.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDMediatorDID+CoreDataProperties.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/Models/CDMediatorDID+CoreDataProperties.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDMediatorDID+CoreDataProperties.swift diff --git a/Pluto/Sources/PersistentStorage/Models/CDMessage+CoreDataClass.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDMessage+CoreDataClass.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/Models/CDMessage+CoreDataClass.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDMessage+CoreDataClass.swift diff --git a/Pluto/Sources/PersistentStorage/Models/CDMessage+CoreDataProperties.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDMessage+CoreDataProperties.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/Models/CDMessage+CoreDataProperties.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDMessage+CoreDataProperties.swift diff --git a/Pluto/Sources/PersistentStorage/Models/CDProofProtocol+CoreDataClass.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDProofProtocol+CoreDataClass.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/Models/CDProofProtocol+CoreDataClass.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDProofProtocol+CoreDataClass.swift diff --git a/Pluto/Sources/PersistentStorage/Models/CDProofProtocol+CoreDataProperties.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDProofProtocol+CoreDataProperties.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/Models/CDProofProtocol+CoreDataProperties.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDProofProtocol+CoreDataProperties.swift diff --git a/Pluto/Sources/PersistentStorage/Models/CDRegisteredDID+CoreDataClass.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDRegisteredDID+CoreDataClass.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/Models/CDRegisteredDID+CoreDataClass.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDRegisteredDID+CoreDataClass.swift diff --git a/Pluto/Sources/PersistentStorage/Models/CDRegisteredDID+CoreDataProperties.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDRegisteredDID+CoreDataProperties.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/Models/CDRegisteredDID+CoreDataProperties.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDRegisteredDID+CoreDataProperties.swift diff --git a/Pluto/Sources/PersistentStorage/Models/CDVerifiableCredential+CoreDataClass.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDVerifiableCredential+CoreDataClass.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/Models/CDVerifiableCredential+CoreDataClass.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDVerifiableCredential+CoreDataClass.swift diff --git a/Pluto/Sources/PersistentStorage/Models/CDVerifiableCredential+CoreDataProperties.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDVerifiableCredential+CoreDataProperties.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/Models/CDVerifiableCredential+CoreDataProperties.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDVerifiableCredential+CoreDataProperties.swift diff --git a/Pluto/Sources/PersistentStorage/Models/CDVerifiableCredentialContext+CoreDataClass.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDVerifiableCredentialContext+CoreDataClass.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/Models/CDVerifiableCredentialContext+CoreDataClass.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDVerifiableCredentialContext+CoreDataClass.swift diff --git a/Pluto/Sources/PersistentStorage/Models/CDVerifiableCredentialContext+CoreDataProperties.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDVerifiableCredentialContext+CoreDataProperties.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/Models/CDVerifiableCredentialContext+CoreDataProperties.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDVerifiableCredentialContext+CoreDataProperties.swift diff --git a/Pluto/Sources/PersistentStorage/Models/CDVerifiableCredentialType+CoreDataClass.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDVerifiableCredentialType+CoreDataClass.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/Models/CDVerifiableCredentialType+CoreDataClass.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDVerifiableCredentialType+CoreDataClass.swift diff --git a/Pluto/Sources/PersistentStorage/Models/CDVerifiableCredentialType+CoreDataProperties.swift b/AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDVerifiableCredentialType+CoreDataProperties.swift similarity index 100% rename from Pluto/Sources/PersistentStorage/Models/CDVerifiableCredentialType+CoreDataProperties.swift rename to AtalaPrismSDK/Pluto/Sources/PersistentStorage/Models/CDVerifiableCredentialType+CoreDataProperties.swift diff --git a/AtalaPrismSDK/Pluto/Sources/Pluto.docc/Pluto.md b/AtalaPrismSDK/Pluto/Sources/Pluto.docc/Pluto.md new file mode 100644 index 00000000..96c07428 --- /dev/null +++ b/AtalaPrismSDK/Pluto/Sources/Pluto.docc/Pluto.md @@ -0,0 +1,21 @@ +# ``Pluto`` + +Pluto is a powerful and flexible data storage interface library for working with decentralized identifiers. Whether you are building a decentralized application that requires secure and private data storage, or you are working with a more traditional system that requires reliable and redundant storage for your DID-related data, Pluto provides the tools and features you need to get the job done with ease. + +## A Secure DID Data Storage Interface Library + +Pluto is a versatile and secure data storage interface library that provides developers with an easy way to store, manage, and recover verifiable data linked to decentralized identifiers (DIDs). Pluto is designed to be storage-agnostic, meaning that it can be used with a wide range of storage systems, from traditional databases to decentralized storage networks. + +Pluto supports a range of storage operations, including DID storage (including DIDPair), private key secure storage, DIDComm message storage, and mediator storage. This allows developers to easily store and manage a wide range of DID-related data, from basic identity information to more complex message and mediation records. + +The default implementation of Pluto includes a secure and robust storage backend that uses Core Data and Keychain to secure sensitive items. This means that developers can easily leverage the powerful security features of these frameworks without having to write complex code to manage the storage of sensitive data. + +With Pluto, developers can easily store and manage verifiable data linked to DIDs in a secure and private manner. Pluto provides a range of advanced security features, including support for private key storage and encryption, as well as support for multiple storage backends for added redundancy and resilience. + +Pluto also supports a range of DID-related data types, including DIDPairs, which are used to store the public and private keys associated with a DID, and DIDComm messages, which are used to store the encrypted messages sent and received between DIDs. + +## Topics + +### Group + +- ``Symbol`` diff --git a/Pluto/Sources/PlutoImpl+Public.swift b/AtalaPrismSDK/Pluto/Sources/PlutoImpl+Public.swift similarity index 82% rename from Pluto/Sources/PlutoImpl+Public.swift rename to AtalaPrismSDK/Pluto/Sources/PlutoImpl+Public.swift index 66fa63b9..bee0a9b2 100644 --- a/Pluto/Sources/PlutoImpl+Public.swift +++ b/AtalaPrismSDK/Pluto/Sources/PlutoImpl+Public.swift @@ -7,11 +7,11 @@ extension PlutoImpl: Pluto { registeredDIDDao.addDID(did: did, keyPairIndex: keyPairIndex, alias: alias) } - public func storePeerDID(did: DID, privateKeys: [PrivateKey]) -> AnyPublisher { - privateKeyDIDDao.addDID(did: did, privateKeys: privateKeys) + public func storePeerDID(did: DID, privateKeys: [PrivateKey], alias: String?) -> AnyPublisher { + privateKeyDIDDao.addDID(did: did, privateKeys: privateKeys, alias: alias) } - public func storeDIDPair(holder: DID, other: DID, name: String) -> AnyPublisher { - pairDIDDao.addDIDPair(holder: holder, other: other, name: name) + public func storeDIDPair(pair: DIDPair) -> AnyPublisher { + pairDIDDao.addDIDPair(pair: pair) } public func storeMessage(message: Message, direction: Message.Direction) -> AnyPublisher { @@ -54,31 +54,39 @@ extension PlutoImpl: Pluto { registeredDIDDao.getLastKeyPairIndex() } - public func getAllPeerDIDs() -> AnyPublisher<[(did: DID, privateKeys: [PrivateKey])], Error> { + public func getAllPeerDIDs() -> AnyPublisher<[(did: DID, privateKeys: [PrivateKey], alias: String?)], Error> { privateKeyDIDDao.getAll() } - public func getPeerDIDInfo(did: DID) -> AnyPublisher<(did: DID, privateKeys: [PrivateKey])?, Error> { + public func getPeerDIDInfo( + did: DID + ) -> AnyPublisher<(did: DID, privateKeys: [PrivateKey], alias: String?)?, Error> { privateKeyDIDDao.getDIDInfo(did: did) } + public func getPeerDIDInfo( + alias: String + ) -> AnyPublisher<[(did: DID, privateKeys: [PrivateKey], alias: String?)], Error> { + privateKeyDIDDao.getDIDInfo(alias: alias) + } + public func getPeerDIDPrivateKeys(did: DID) -> AnyPublisher<[PrivateKey]?, Error> { privateKeyDIDDao.getPrivateKeys(did: did) } - public func getAllDidPairs() -> AnyPublisher<[(holder: DID, other: DID, name: String?)], Error> { + public func getAllDidPairs() -> AnyPublisher<[DIDPair], Error> { pairDIDDao.getAll() } - public func getPair(otherDID: DID) -> AnyPublisher<(holder: DID, other: DID, name: String?)?, Error> { + public func getPair(otherDID: DID) -> AnyPublisher { pairDIDDao.getPair(otherDID: otherDID) } - public func getPair(name: String) -> AnyPublisher<(holder: DID, other: DID, name: String?)?, Error> { + public func getPair(name: String) -> AnyPublisher { pairDIDDao.getPair(name: name) } - public func getPair(holderDID: DID) -> AnyPublisher<(holder: DID, other: DID, name: String?)?, Error> { + public func getPair(holderDID: DID) -> AnyPublisher { pairDIDDao.getPair(holderDID: holderDID) } diff --git a/Pluto/Sources/PlutoImpl.swift b/AtalaPrismSDK/Pluto/Sources/PlutoImpl.swift similarity index 100% rename from Pluto/Sources/PlutoImpl.swift rename to AtalaPrismSDK/Pluto/Sources/PlutoImpl.swift diff --git a/Pluto/Sources/Resources/PrismPluto.xcdatamodeld/.xccurrentversion b/AtalaPrismSDK/Pluto/Sources/Resources/PrismPluto.xcdatamodeld/.xccurrentversion similarity index 100% rename from Pluto/Sources/Resources/PrismPluto.xcdatamodeld/.xccurrentversion rename to AtalaPrismSDK/Pluto/Sources/Resources/PrismPluto.xcdatamodeld/.xccurrentversion diff --git a/Pluto/Sources/Resources/PrismPluto.xcdatamodeld/Model.xcdatamodel/contents b/AtalaPrismSDK/Pluto/Sources/Resources/PrismPluto.xcdatamodeld/Model.xcdatamodel/contents similarity index 100% rename from Pluto/Sources/Resources/PrismPluto.xcdatamodeld/Model.xcdatamodel/contents rename to AtalaPrismSDK/Pluto/Sources/Resources/PrismPluto.xcdatamodeld/Model.xcdatamodel/contents diff --git a/Pluto/Sources/Resources/PrismPluto.xcdatamodeld/PrismPluto.xcdatamodel/contents b/AtalaPrismSDK/Pluto/Sources/Resources/PrismPluto.xcdatamodeld/PrismPluto.xcdatamodel/contents similarity index 98% rename from Pluto/Sources/Resources/PrismPluto.xcdatamodeld/PrismPluto.xcdatamodel/contents rename to AtalaPrismSDK/Pluto/Sources/Resources/PrismPluto.xcdatamodeld/PrismPluto.xcdatamodel/contents index 1b4fe1b9..7b1e1576 100644 --- a/Pluto/Sources/Resources/PrismPluto.xcdatamodeld/PrismPluto.xcdatamodel/contents +++ b/AtalaPrismSDK/Pluto/Sources/Resources/PrismPluto.xcdatamodeld/PrismPluto.xcdatamodel/contents @@ -1,5 +1,5 @@ - + @@ -12,6 +12,7 @@ + diff --git a/Pluto/Tests/CDDIDPairDAOTests.swift b/AtalaPrismSDK/Pluto/Tests/CDDIDPairDAOTests.swift similarity index 84% rename from Pluto/Tests/CDDIDPairDAOTests.swift rename to AtalaPrismSDK/Pluto/Tests/CDDIDPairDAOTests.swift index 71ae65d2..4fb8d94d 100644 --- a/Pluto/Tests/CDDIDPairDAOTests.swift +++ b/AtalaPrismSDK/Pluto/Tests/CDDIDPairDAOTests.swift @@ -31,12 +31,14 @@ final class CDDIDPairDAOTests: XCTestCase { let testName = "test" let expectation = expectation(description: "Awaiting publisher") let cancellable = privateKeyDao - .addDID(did: testHolderDID, privateKeys: [testPrivateKey]) + .addDID(did: testHolderDID, privateKeys: [testPrivateKey], alias: nil) .flatMap { dao.addDIDPair( - holder: testHolderDID, - other: testOtherDID, - name: testName + pair: .init( + holder: testHolderDID, + other: testOtherDID, + name: testName + ) ) } .flatMap { @@ -63,16 +65,21 @@ final class CDDIDPairDAOTests: XCTestCase { let testName = "test" let expectation = expectation(description: "Awaiting publisher") let cancellable = dao.addDIDPair( - holder: testHolderDID, - other: testOtherDID, - name: testName + pair: .init( + holder: testHolderDID, + other: testOtherDID, + name: testName + ) ) .flatMap { dao.getPair(holderDID: testHolderDID).first() }.sink { switch $0 { case .failure(let error): - XCTAssertEqual(error as? PlutoError, .invalidHolderDIDNotPersistedError) + XCTAssertEqual(error as? PlutoError, .missingDataPersistence( + type: "Holder DID", + affecting: "DID Pair") + ) default: XCTFail("Error not thrown") } @@ -97,24 +104,25 @@ final class CDDIDPairDAOTests: XCTestCase { let testName = "test" let expectation = expectation(description: "Awaiting publisher") let cancellable = privateKeyDao - .addDID(did: testHolderDID1, privateKeys: [testPrivateKey]) + .addDID(did: testHolderDID1, privateKeys: [testPrivateKey], alias: nil) .flatMap { self.privateKeyDao - .addDID(did: testHolderDID2, privateKeys: [testPrivateKey]) + .addDID(did: testHolderDID2, privateKeys: [testPrivateKey], alias: nil) } .flatMap { - dao.addDIDPair( - holder: testHolderDID1, - other: testOtherDID1, - name: testName + dao.addDIDPair(pair: .init( + holder: testHolderDID1, + other: testOtherDID1, + name: testName + ) ) } .flatMap { - dao.addDIDPair( + dao.addDIDPair(pair: .init( holder: testHolderDID2, other: testOtherDID2, name: testName - ) + )) } .flatMap { dao.getAll().first() @@ -147,27 +155,27 @@ final class CDDIDPairDAOTests: XCTestCase { let testName = "test" let expectation = expectation(description: "Awaiting publisher") let cancellable = privateKeyDao - .addDID(did: testHolderDID, privateKeys: [testPrivateKey]) + .addDID(did: testHolderDID, privateKeys: [testPrivateKey], alias: nil) .flatMap { - dao.addDIDPair( + dao.addDIDPair(pair: .init( holder: testHolderDID, other: testOtherDID1, name: testName - ) + )) } .flatMap { - dao.addDIDPair( + dao.addDIDPair(pair: .init( holder: testHolderDID, other: testOtherDID2, name: testName - ) + )) } .flatMap { dao.getAll().first() }.sink { switch $0 { case .failure(let error): - XCTAssertEqual(error as? PlutoError, .holderDIDAlreadyPairingError) + XCTAssertEqual(error as? PlutoError, .duplication(type: "Holder DID/DID Pair")) default: XCTFail("Error not thrown") } @@ -192,24 +200,24 @@ final class CDDIDPairDAOTests: XCTestCase { let testName = "test" let expectation = expectation(description: "Awaiting publisher") let cancellable = privateKeyDao - .addDID(did: testHolderDID1, privateKeys: [testPrivateKey]) + .addDID(did: testHolderDID1, privateKeys: [testPrivateKey], alias: nil) .flatMap { self.privateKeyDao - .addDID(did: testHolderDID2, privateKeys: [testPrivateKey]) + .addDID(did: testHolderDID2, privateKeys: [testPrivateKey], alias: nil) } .flatMap { - dao.addDIDPair( + dao.addDIDPair(pair: .init( holder: testHolderDID1, other: testOtherDID1, name: testName - ) + )) } .flatMap { - dao.addDIDPair( + dao.addDIDPair(pair: .init( holder: testHolderDID2, other: testOtherDID2, name: testName - ) + )) } .flatMap { dao.getPair(holderDID: testHolderDID2).first() diff --git a/Pluto/Tests/CDDIDPrivateKeyDAOTests.swift b/AtalaPrismSDK/Pluto/Tests/CDDIDPrivateKeyDAOTests.swift similarity index 89% rename from Pluto/Tests/CDDIDPrivateKeyDAOTests.swift rename to AtalaPrismSDK/Pluto/Tests/CDDIDPrivateKeyDAOTests.swift index c86eef5b..3a43e702 100644 --- a/Pluto/Tests/CDDIDPrivateKeyDAOTests.swift +++ b/AtalaPrismSDK/Pluto/Tests/CDDIDPrivateKeyDAOTests.swift @@ -24,7 +24,8 @@ final class CDDIDPrivateKeyDAOTestsTests: XCTestCase { let expectation = expectation(description: "Awaiting publisher") let cancellable = dao.addDID( did: testDID, - privateKeys: [testPrivateKey] + privateKeys: [testPrivateKey], + alias: nil ).flatMap { dao.getDIDInfo(did: testDID) }.sink { _ in } receiveValue: { @@ -47,11 +48,13 @@ final class CDDIDPrivateKeyDAOTestsTests: XCTestCase { let expectation = expectation(description: "Awaiting publisher") let cancellable = dao.addDID( did: testDID, - privateKeys: [testPrivateKey] + privateKeys: [testPrivateKey], + alias: nil ).flatMap { dao.addDID( did: testDID, - privateKeys: [testPrivateKey] + privateKeys: [testPrivateKey], + alias: nil ) } .flatMap { @@ -79,11 +82,13 @@ final class CDDIDPrivateKeyDAOTestsTests: XCTestCase { let expectation = expectation(description: "Awaiting publisher") let cancellable = dao.addDID( did: testDID1, - privateKeys: [testPrivateKey1] + privateKeys: [testPrivateKey1], + alias: nil ).flatMap { dao.addDID( did: testDID2, - privateKeys: [testPrivateKey2] + privateKeys: [testPrivateKey2], + alias: nil ) } .flatMap { @@ -111,11 +116,13 @@ final class CDDIDPrivateKeyDAOTestsTests: XCTestCase { let expectation = expectation(description: "Awaiting publisher") let cancellable = dao.addDID( did: testDID1, - privateKeys: [testPrivateKey1] + privateKeys: [testPrivateKey1], + alias: nil ).flatMap { dao.addDID( did: testDID2, - privateKeys: [testPrivateKey2] + privateKeys: [testPrivateKey2], + alias: nil ) } .flatMap { diff --git a/Pluto/Tests/CDMessagesDAOTests.swift b/AtalaPrismSDK/Pluto/Tests/CDMessagesDAOTests.swift similarity index 94% rename from Pluto/Tests/CDMessagesDAOTests.swift rename to AtalaPrismSDK/Pluto/Tests/CDMessagesDAOTests.swift index ea345e8c..5e82fd3b 100644 --- a/Pluto/Tests/CDMessagesDAOTests.swift +++ b/AtalaPrismSDK/Pluto/Tests/CDMessagesDAOTests.swift @@ -42,13 +42,13 @@ final class CDMessagesDAOTests: XCTestCase { ) let expectation = expectation(description: "Awaiting publisher") let cancellable = privateDAO - .addDID(did: testHolderDID, privateKeys: [testPrivateKey]) + .addDID(did: testHolderDID, privateKeys: [testPrivateKey], alias: nil) .flatMap { - self.pairDAO.addDIDPair( + self.pairDAO.addDIDPair(pair: .init( holder: testHolderDID, other: testOtherDID, name: testName - ) + )) } .flatMap { dao.addMessage(msg: testMessage, direction: .received) @@ -89,13 +89,13 @@ final class CDMessagesDAOTests: XCTestCase { ) let expectation = expectation(description: "Awaiting publisher") let cancellable = privateDAO - .addDID(did: testHolderDID, privateKeys: [testPrivateKey]) + .addDID(did: testHolderDID, privateKeys: [testPrivateKey], alias: nil) .flatMap { - self.pairDAO.addDIDPair( + self.pairDAO.addDIDPair(pair: .init( holder: testHolderDID, other: testOtherDID, name: testName - ) + )) } .flatMap { dao.addMessage(msg: testMessage, direction: .received) @@ -147,24 +147,24 @@ final class CDMessagesDAOTests: XCTestCase { ) let expectation = expectation(description: "Awaiting publisher") let cancellable = privateDAO - .addDID(did: testHolderDID, privateKeys: [testPrivateKey]) + .addDID(did: testHolderDID, privateKeys: [testPrivateKey], alias: nil) .flatMap { self.privateDAO - .addDID(did: testHolderDID2, privateKeys: [testPrivateKey2]) + .addDID(did: testHolderDID2, privateKeys: [testPrivateKey2], alias: nil) } .flatMap { - self.pairDAO.addDIDPair( + self.pairDAO.addDIDPair(pair: .init( holder: testHolderDID, other: testOtherDID, name: testName - ) + )) } .flatMap { - self.pairDAO.addDIDPair( + self.pairDAO.addDIDPair(pair: .init( holder: testHolderDID2, other: testOtherDID2, name: testName - ) + )) } .flatMap { dao.addMessage(msg: testMessage1, direction: .received) diff --git a/Pluto/Tests/CDRegisteredDIDDaoTests.swift b/AtalaPrismSDK/Pluto/Tests/CDRegisteredDIDDaoTests.swift similarity index 100% rename from Pluto/Tests/CDRegisteredDIDDaoTests.swift rename to AtalaPrismSDK/Pluto/Tests/CDRegisteredDIDDaoTests.swift diff --git a/Pluto/Tests/Helper/DID+Testing.swift b/AtalaPrismSDK/Pluto/Tests/Helper/DID+Testing.swift similarity index 100% rename from Pluto/Tests/Helper/DID+Testing.swift rename to AtalaPrismSDK/Pluto/Tests/Helper/DID+Testing.swift diff --git a/Pollux/Sources/JWTCredential.swift b/AtalaPrismSDK/Pollux/Sources/JWTCredential.swift similarity index 100% rename from Pollux/Sources/JWTCredential.swift rename to AtalaPrismSDK/Pollux/Sources/JWTCredential.swift diff --git a/Pollux/Sources/PolluxImpl+Public.swift b/AtalaPrismSDK/Pollux/Sources/PolluxImpl+Public.swift similarity index 100% rename from Pollux/Sources/PolluxImpl+Public.swift rename to AtalaPrismSDK/Pollux/Sources/PolluxImpl+Public.swift diff --git a/Pollux/Sources/PolluxImpl.swift b/AtalaPrismSDK/Pollux/Sources/PolluxImpl.swift similarity index 100% rename from Pollux/Sources/PolluxImpl.swift rename to AtalaPrismSDK/Pollux/Sources/PolluxImpl.swift diff --git a/Pollux/Tests/PolluxTest.swift b/AtalaPrismSDK/Pollux/Tests/PolluxTest.swift similarity index 100% rename from Pollux/Tests/PolluxTest.swift rename to AtalaPrismSDK/Pollux/Tests/PolluxTest.swift diff --git a/PrismAgent/Sources/ConnectionsManager/ConnectionsManager.swift b/AtalaPrismSDK/PrismAgent/Sources/ConnectionsManager/ConnectionsManager.swift similarity index 96% rename from PrismAgent/Sources/ConnectionsManager/ConnectionsManager.swift rename to AtalaPrismSDK/PrismAgent/Sources/ConnectionsManager/ConnectionsManager.swift index 11dac634..f6ff0f45 100644 --- a/PrismAgent/Sources/ConnectionsManager/ConnectionsManager.swift +++ b/AtalaPrismSDK/PrismAgent/Sources/ConnectionsManager/ConnectionsManager.swift @@ -45,7 +45,7 @@ class ConnectionsManagerImpl: ConnectionsManager { try await withCheckedThrowingContinuation { continuation in pluto - .storeDIDPair(holder: paired.holder, other: paired.other, name: paired.name ?? "") + .storeDIDPair(pair: paired) .sink(receiveCompletion: { switch $0 { case .finished: @@ -96,7 +96,7 @@ extension ConnectionsManagerImpl: DIDCommConnection { } func awaitMessages() throws -> AnyPublisher<[Message], Error> { - guard mediationHandler.mediator == nil else { throw PrismAgentError.noMediatorAvailableError } + guard mediationHandler.mediator != nil else { throw PrismAgentError.noMediatorAvailableError } let mediationHandler = mediationHandler let pluto = pluto return Future { diff --git a/PrismAgent/Sources/ConnectionsManager/DIDCommProtocol.swift b/AtalaPrismSDK/PrismAgent/Sources/ConnectionsManager/DIDCommProtocol.swift similarity index 100% rename from PrismAgent/Sources/ConnectionsManager/DIDCommProtocol.swift rename to AtalaPrismSDK/PrismAgent/Sources/ConnectionsManager/DIDCommProtocol.swift diff --git a/PrismAgent/Sources/Helpers/AttachmentDescriptor+Builder.swift b/AtalaPrismSDK/PrismAgent/Sources/Helpers/AttachmentDescriptor+Builder.swift similarity index 100% rename from PrismAgent/Sources/Helpers/AttachmentDescriptor+Builder.swift rename to AtalaPrismSDK/PrismAgent/Sources/Helpers/AttachmentDescriptor+Builder.swift diff --git a/PrismAgent/Sources/Mediator/BasicMediatorHandler.swift b/AtalaPrismSDK/PrismAgent/Sources/Mediator/BasicMediatorHandler.swift similarity index 74% rename from PrismAgent/Sources/Mediator/BasicMediatorHandler.swift rename to AtalaPrismSDK/PrismAgent/Sources/Mediator/BasicMediatorHandler.swift index 16f65b19..31e43496 100644 --- a/PrismAgent/Sources/Mediator/BasicMediatorHandler.swift +++ b/AtalaPrismSDK/PrismAgent/Sources/Mediator/BasicMediatorHandler.swift @@ -54,34 +54,41 @@ public class BasicMediatorHandler: MediatorHandler { public func bootRegisteredMediator() async throws -> Mediator? { guard let mediator else { - self.mediator = try await mediatorStore.getAllMediators().first - return self.mediator + let mediator = try await mediatorStore.getAllMediators().first + self.mediator = mediator + return mediator } return mediator } public func achieveMediation(host: DID) async throws -> Mediator { guard let mediator = try await bootRegisteredMediator() else { - guard let message: Message = try await mercury - .sendMessageParseMessage(msg: MediationRequest( - from: host, - to: mediatorDID - ).makeMessage()) - else { throw PrismAgentError.mediationRequestFailedError } - - let grantMessage = try MediationGrant(fromMessage: message) - let routingDID = try DID(string: grantMessage.body.routingDid) - - let mediator = Mediator( - hostDID: host, - routingDID: routingDID, - mediatorDID: mediatorDID - ) + do { + guard let message: Message = try await mercury + .sendMessageParseMessage(msg: MediationRequest( + from: host, + to: mediatorDID + ).makeMessage()) + else { throw UnknownError.somethingWentWrongError( + customMessage: "Trying to achieve mediation returned empty data", + underlyingErrors: nil + ) } + let grantMessage = try MediationGrant(fromMessage: message) + let routingDID = try DID(string: grantMessage.body.routingDid) + + let mediator = Mediator( + hostDID: host, + routingDID: routingDID, + mediatorDID: mediatorDID + ) - try await mediatorStore.storeMediator(mediator: mediator) + try await mediatorStore.storeMediator(mediator: mediator) - self.mediator = mediator - return mediator + self.mediator = mediator + return mediator + } catch let error { + throw PrismAgentError.mediationRequestFailedError(underlyingErrors: [error]) + } } return mediator diff --git a/PrismAgent/Sources/Mediator/MediatorStore.swift b/AtalaPrismSDK/PrismAgent/Sources/Mediator/Mediator.swift similarity index 61% rename from PrismAgent/Sources/Mediator/MediatorStore.swift rename to AtalaPrismSDK/PrismAgent/Sources/Mediator/Mediator.swift index b4731851..3aa5cd0b 100644 --- a/PrismAgent/Sources/Mediator/MediatorStore.swift +++ b/AtalaPrismSDK/PrismAgent/Sources/Mediator/Mediator.swift @@ -4,3 +4,9 @@ public protocol MediatorStore { func storeMediator(mediator: Mediator) async throws func getAllMediators() async throws -> [Mediator] } + +public struct Mediator { + let hostDID: DID + let routingDID: DID + let mediatorDID: DID +} diff --git a/PrismAgent/Sources/Mediator/MediatorHandler.swift b/AtalaPrismSDK/PrismAgent/Sources/Mediator/MediatorHandler.swift similarity index 100% rename from PrismAgent/Sources/Mediator/MediatorHandler.swift rename to AtalaPrismSDK/PrismAgent/Sources/Mediator/MediatorHandler.swift diff --git a/PrismAgent/Sources/PrismAgent+Credentials.swift b/AtalaPrismSDK/PrismAgent/Sources/PrismAgent+Credentials.swift similarity index 100% rename from PrismAgent/Sources/PrismAgent+Credentials.swift rename to AtalaPrismSDK/PrismAgent/Sources/PrismAgent+Credentials.swift diff --git a/PrismAgent/Sources/PrismAgent+DIDHigherFucntions.swift b/AtalaPrismSDK/PrismAgent/Sources/PrismAgent+DIDHigherFucntions.swift similarity index 82% rename from PrismAgent/Sources/PrismAgent+DIDHigherFucntions.swift rename to AtalaPrismSDK/PrismAgent/Sources/PrismAgent+DIDHigherFucntions.swift index 3e936d28..3dc4c599 100644 --- a/PrismAgent/Sources/PrismAgent+DIDHigherFucntions.swift +++ b/AtalaPrismSDK/PrismAgent/Sources/PrismAgent+DIDHigherFucntions.swift @@ -1,3 +1,4 @@ +import Combine import Domain import Foundation @@ -110,20 +111,33 @@ Could not find key in storage please use Castor instead and provide the private /// /// - Parameters: /// - services: The services associated to the new DID. - /// - updateMediator: Indicates if the new DID should be added to the mediator's list. + /// - updateMediator: Indicates if the new DID should be added to the mediator's list. It will as well add the mediator service. /// - Returns: A new DID /// - Throws: PrismAgentError, if updateMediator is true and there is no mediator available or if storing the new DID failed func createNewPeerDID( services: [DIDDocument.Service] = [], + alias: String? = "", updateMediator: Bool ) async throws -> DID { let keyAgreementKeyPair = apollo.createKeyPair(seed: seed, curve: .x25519) let authenticationKeyPair = apollo.createKeyPair(seed: seed, curve: .ed25519) + let withServices: [DIDDocument.Service] + if updateMediator, let routingDID = mediatorRoutingDID?.string { + withServices = services + [.init( + id: "#didcomm-1", + type: ["DIDCommMessaging"], + serviceEndpoint: [.init( + uri: routingDID + )])] + } else { + withServices = services + } + let newDID = try castor.createPeerDID( keyAgreementKeyPair: keyAgreementKeyPair, authenticationKeyPair: authenticationKeyPair, - services: services + services: withServices ) logger.debug(message: "Created new Peer DID", metadata: [ @@ -136,6 +150,7 @@ Could not find key in storage please use Castor instead and provide the private keyAgreementKeyPair.privateKey, authenticationKeyPair.privateKey ], + alias: alias, updateMediator: updateMediator ) @@ -152,12 +167,12 @@ Could not find key in storage please use Castor instead and provide the private func registerPeerDID( did: DID, privateKeys: [PrivateKey], + alias: String?, updateMediator: Bool ) async throws { if updateMediator { try await updateMediatorWithDID(did: did) } - logger.debug(message: "Register of DID in storage", metadata: [ .maskedMetadataByLevel(key: "DID", value: did.string, level: .debug) ]) @@ -165,7 +180,8 @@ Could not find key in storage please use Castor instead and provide the private try await pluto .storePeerDID( did: did, - privateKeys: privateKeys + privateKeys: privateKeys, + alias: alias ) .first() .await() @@ -185,4 +201,38 @@ Could not find key in storage please use Castor instead and provide the private try await mediationHandler.updateKeyListWithDIDs(dids: [did]) } + + func getDIDInfo(did: DID) async throws -> (did: DID, alias: String?)? { + let pluto = self.pluto + switch did.method { + case "prism": + return try await pluto + .getPrismDIDInfo(did: did) + .map { + $0.map { ($0.did, $0.alias) } + } + .first() + .await() + case "peer": + return try await pluto + .getPeerDIDInfo(did: did) + .map { + $0.map { ($0.did, $0.alias) } + } + .first() + .await() + default: + return nil + } + } + + func registerDIDPair(pair: DIDPair) async throws { + try await pluto.storeDIDPair(pair: pair) + .first() + .await() + } + + func getAllDIDPairs() -> AnyPublisher<[DIDPair], Error> { + pluto.getAllDidPairs() + } } diff --git a/PrismAgent/Sources/PrismAgent+Invitations.swift b/AtalaPrismSDK/PrismAgent/Sources/PrismAgent+Invitations.swift similarity index 84% rename from PrismAgent/Sources/PrismAgent+Invitations.swift rename to AtalaPrismSDK/PrismAgent/Sources/PrismAgent+Invitations.swift index 665b5618..1dea2f22 100644 --- a/PrismAgent/Sources/PrismAgent+Invitations.swift +++ b/AtalaPrismSDK/PrismAgent/Sources/PrismAgent+Invitations.swift @@ -44,16 +44,16 @@ public extension PrismAgent { let prismOnboarding = try PrismOnboardingInvitation(jsonString: str) guard let url = URL(string: prismOnboarding.body.onboardEndpoint) - else { throw PrismAgentError.invalidURLError } + else { throw CommonError.invalidURLError(url: prismOnboarding.body.onboardEndpoint) } let ownDID = try await createNewPeerDID( services: [.init( id: "#didcomm-1", type: ["DIDCommMessaging"], - serviceEndpoint: .init( + serviceEndpoint: [.init( uri: "https://localhost:8080/didcomm" - )) - ], + )] + )], updateMediator: false ) @@ -69,7 +69,7 @@ public extension PrismAgent { /// - Returns: The parsed Out-of-Band invitation /// - Throws: `PrismAgentError` if the string is not a valid URL func parseOOBInvitation(url: String) throws -> OutOfBandInvitation { - guard let url = URL(string: url) else { throw PrismAgentError.invalidURLError } + guard let url = URL(string: url) else { throw CommonError.invalidURLError(url: url) } return try parseOOBInvitation(url: url) } @@ -91,10 +91,10 @@ public extension PrismAgent { services: [.init( id: "#didcomm-1", type: ["DIDCommMessaging"], - serviceEndpoint: .init( + serviceEndpoint: [.init( uri: mediatorRoutingDID.string - )) - ], + )] + )], updateMediator: true ) @@ -120,10 +120,17 @@ public extension PrismAgent { request.httpMethod = "POST" request.httpBody = try JSONEncoder().encode(SendDID(did: invitation.ownDID.string)) request.setValue("application/json", forHTTPHeaderField: "content-type") - let response = try await URLSession.shared.data(for: request) - guard - let urlResponse = response.1 as? HTTPURLResponse, - urlResponse.statusCode == 200 - else { throw PrismAgentError.failedToOnboardError } + do { + let response = try await URLSession.shared.data(for: request) + guard let urlResponse = response.1 as? HTTPURLResponse else { + throw UnknownError.somethingWentWrongError() + } + guard urlResponse.statusCode == 200 else { + throw CommonError.httpError( + code: urlResponse.statusCode, + message: String(data: response.0, encoding: .utf8) ?? "" + ) + } + } } } diff --git a/PrismAgent/Sources/PrismAgent+MessageEvents.swift b/AtalaPrismSDK/PrismAgent/Sources/PrismAgent+MessageEvents.swift similarity index 100% rename from PrismAgent/Sources/PrismAgent+MessageEvents.swift rename to AtalaPrismSDK/PrismAgent/Sources/PrismAgent+MessageEvents.swift diff --git a/AtalaPrismSDK/PrismAgent/Sources/PrismAgent.docc/PrismAgent.md b/AtalaPrismSDK/PrismAgent/Sources/PrismAgent.docc/PrismAgent.md new file mode 100644 index 00000000..f02160f4 --- /dev/null +++ b/AtalaPrismSDK/PrismAgent/Sources/PrismAgent.docc/PrismAgent.md @@ -0,0 +1,19 @@ +# ``PrismAgent`` + +Prism Agent is a powerful and flexible library for working with decentralized identifiers on the Prism platform. Whether you are building a decentralized application that requires secure and private identity management, or you are working with a more traditional system that requires reliable and resilient communication between DIDs, Prism Agent provides the tools and features you need to get the job done with ease. + +## Overview + +Prism Agent is a comprehensive library that brings together all the building blocks of the Prism platform - Apollo, Castor, Pluto, Mercury, and Pollux - to provide a seamless experience for developers working with decentralized identifiers (DIDs) on the Prism platform. + +Prism Agent is designed to provide high-level functionality for DID management and DID communication. This includes features such as DID management, DIDComm mediation management, and support for a range of DIDComm protocols, including mediation, proof presentation, issue credential, and out-of-band messages. + +With Prism Agent, developers can easily manage and communicate with DIDs in a seamless and efficient manner. Prism Agent provides a range of advanced features, including support for secure and private messaging using the Mercury protocol, and secure and portable data storage using the Pluto library. + +Prism Agent also provides support for receiving messages through the mediator, allowing developers to easily manage and respond to incoming messages in a secure and efficient manner. + +## Topics + +### Group + +- ``Symbol`` diff --git a/AtalaPrismSDK/PrismAgent/Sources/PrismAgent.docc/PrismAgentHowTo.md b/AtalaPrismSDK/PrismAgent/Sources/PrismAgent.docc/PrismAgentHowTo.md new file mode 100644 index 00000000..8377782d --- /dev/null +++ b/AtalaPrismSDK/PrismAgent/Sources/PrismAgent.docc/PrismAgentHowTo.md @@ -0,0 +1,95 @@ +# PrismAgent API Tutorial + +To use the `PrismAgent`, you must first create an instance of it by passing in the necessary dependency objects and seed data. You can also use the `convenience init` to create an instance with default objects. Once you have an instance of `PrismAgent`, you can call the `start` method to start the agent and the mediator services. + +```swift +let mediatorDID = DID("did:example:123") +let prismAgent = PrismAgent(seedData: nil, mediatorDID: mediatorDID) + +do { + try await prismAgent.start() +} catch { + print("Error starting PrismAgent: \(error)") +} +``` + +After the PrismAgent has started, you can use the various methods and properties of the PrismAgent to interact with other agents in the network. For example, you can create a new peer DID by calling the createNewPeerDID method of the Apollo object: + +```swift +let services = [Service( + id: "#didcomm-1", + type: ["DIDCommMessaging"], + serviceEndpoint: [ServiceEndpoint(uri: prismAgent.mediatorRoutingDID?.string ?? "")] +)] +let peerDID = try await prismAgent.apollo.createNewPeerDID( + seed: prismAgent.seed, + services: services, + updateMediator: true +) +``` + +To stop the PrismAgent, you can call the stop method: + +```swift +do { + try await prismAgent.stop() +} catch { + print("Error stopping PrismAgent: \(error)") +} +``` + +## High-level DID functionalities + +The PrismAgent has some high-level did functionalities that make it easy to interact with the ledger and perform various cryptographic operations. + +### DID Management + +The PrismAgent provides several methods to manage DIDs: + +- `createNewPrismDID`: This method creates a new Prism DID and registers it in the agent's storage. It returns the new DID. + +```swift +let did = try? await agent.createNewPrismDID( + // Add this if you want to provide a IndexPath + // keyPathIndex: <#T##Int?#> + // Add this if you want to provide an alias for this DID + // alias: <#T##String?#> + // Add any services available in the DID + services: [ .init( + id: "DemoID", + type: ["DemoType"], + serviceEndpoint: [.init(uri: "DemoServiceEndpoint")] + ) +]) +``` +- `registerPrismDID`: This method registers a pre-existing Prism DID in the agent's storage. It takes a `DID` object and a `keyPathIndex` used to identify the DID, and an optional `alias` that can be used to identify the DID. It assumes the seed given in the initialization was used to create the DID. + +```swift + agent.registerPrismDID(did: did, keyPathIndex: 2) +``` + +- `createNewPeerDID`: This method creates a new Peer DID and registers it in the agent's storage. It returns the new DID. It also takes an optional `services` array that can be used to associate services with the new DID and a `updateMediator` flag that, if `true`, will add the new DID to the mediator's key list. + +```swift + agent.createNewPeerDID(services: [ + .init(id: "demoId", + type: ["DemoType"], + serviceEndpoint: [.init( + uri: "https://demo.io", + accept: ["accept"], // Optional + routingKeys: ["demo"]// Optional + )]) + ], updateMediator: true) +``` + +- `registerPeerDID`: This method registers a pre-existing Peer DID in the agent's storage. It takes a `DID` object, an array of `privateKeys` used to sign messages, and a `updateMediator` flag that, if `true`, will add the new DID to the mediator's key list. + +```swift + let did = DID(...) // did:peer:demo + let privateKey1 = PrivateKey(...) // Pair with the public key inside of the DID + agent.registerPeerDID(did: did, privateKeys: [privateKey1], updateMediator: true) +``` + +### Signing Messages + +The `signWith(did:message:)` method is used to sign messages with a DID. It takes a `DID` object and a `Data` object representing the message to sign. It returns the `Signature` object representing the signature of the message. If the DID is a Prism DID, the agent will use the corresponding key pair to sign the message. If the DID is a Peer DID, the agent will use the first private key in the `privateKeys` array associated with the DID. diff --git a/PrismAgent/Sources/PrismAgent.swift b/AtalaPrismSDK/PrismAgent/Sources/PrismAgent.swift similarity index 96% rename from PrismAgent/Sources/PrismAgent.swift rename to AtalaPrismSDK/PrismAgent/Sources/PrismAgent.swift index bf3aee93..6ac06043 100644 --- a/PrismAgent/Sources/PrismAgent.swift +++ b/AtalaPrismSDK/PrismAgent/Sources/PrismAgent.swift @@ -136,8 +136,8 @@ public class PrismAgent { services: [.init( id: "#didcomm-1", type: ["DIDCommMessaging"], - serviceEndpoint:.init(uri: mediationHandler.mediatorDID.string)) - ], + serviceEndpoint: [.init(uri: mediationHandler.mediatorDID.string)] + )], updateMediator: false ) try await connectionManager.registerMediator(hostDID: hostDID) @@ -173,7 +173,10 @@ public class PrismAgent { credential: VerifiableCredential ) async throws { guard let jwtBase64 = credential.id.data(using: .utf8)?.base64UrlEncodedString() else { - throw PrismAgentError.invalidRequestPresentationMessageError + throw UnknownError.somethingWentWrongError( + customMessage: "Could not decode JWT Credential", + underlyingErrors: nil + ) } let presentation = Presentation( body: .init(goalCode: request.body.goalCode, comment: request.body.comment), diff --git a/AtalaPrismSDK/PrismAgent/Sources/PrismAgentErrors.swift b/AtalaPrismSDK/PrismAgent/Sources/PrismAgentErrors.swift new file mode 100644 index 00000000..6cca33dc --- /dev/null +++ b/AtalaPrismSDK/PrismAgent/Sources/PrismAgentErrors.swift @@ -0,0 +1,87 @@ +import Domain + +/** + An enum representing a known error in a Prism agent API response. + + - Note: When an error occurs during an API request/response cycle, the server may return an error object in the response. This object may include an error code and an error message. If the error received conforms to the `KnownPrismError` protocol, it will be classified as a known error. + + - SeeAlso: `UnknownPrismError`, `KnownPrismError` + */ +public enum PrismAgentError: KnownPrismError { + + /// An error case representing that a DID key pair index could not be found. + case cannotFindDIDKeyPairIndex + + /// An error case representing that an invitation is invalid. + case invitationIsInvalidError + + /// An error case representing an unknown invitation type. + case unknownInvitationTypeError + + /// An error case representing an invalid message type. + case invalidMessageType(type: String, shouldBe: String) + + /// An error case representing that no mediator is available. + case noMediatorAvailableError + + /// An error case representing that a mediation request has failed. + case mediationRequestFailedError(underlyingErrors: [Error]?) + + /// The error code returned by the server. + public var code: Int { + switch self { + case .cannotFindDIDKeyPairIndex: + return 111 + case .invitationIsInvalidError: + return 112 + case .unknownInvitationTypeError: + return 113 + case .invalidMessageType: + return 114 + case .noMediatorAvailableError: + return 115 + case .mediationRequestFailedError: + return 116 + } + } + + /** + The error message returned by the server. + + - Note: For this enum, the error message is determined based on the specific error case that was encountered. + + - SeeAlso: `cannotFindDIDKeyPairIndex`, `invitationIsInvalidError`, `unknownInvitationTypeError`, `invalidMessageType`, `noMediatorAvailableError`, `mediationRequestFailedError` + */ + public var message: String { + switch self { + case .cannotFindDIDKeyPairIndex: + return "To sign with a DID a key pair needs to be registered, please register the key pair first/" + case .invitationIsInvalidError: + return "The system could not parse the invitation, the message/json are invalid" + case .unknownInvitationTypeError: + return "The type of the invitation is not supported." + case let .invalidMessageType(type, shouldBe): + return """ +The following message \(type), does not represent the protocol \(shouldBe). +Also the message should have \"from\" and \"to\" fields +""" + case .noMediatorAvailableError: + return """ +There is no mediator. +You need to provide a mediation handler and start the prism agent before doing some operations. +""" + case .mediationRequestFailedError(let underlyningErrors): + let errorsMessages = underlyningErrors + .map { $0.map { $0.localizedDescription } }? + .joined(separator: ", ") + let message = errorsMessages.map { "Errors: " + $0 } ?? "" + return "Something failed while trying to achieve mediation. \(message)" + } + } +} + +extension PrismAgentError: Equatable { + public static func == (lhs: PrismAgentError, rhs: PrismAgentError) -> Bool { + lhs.message == rhs.message + } +} diff --git a/AtalaPrismSDK/PrismAgent/Sources/Protocols/Connection/ConnectionAccept.swift b/AtalaPrismSDK/PrismAgent/Sources/Protocols/Connection/ConnectionAccept.swift new file mode 100644 index 00000000..bb7476b0 --- /dev/null +++ b/AtalaPrismSDK/PrismAgent/Sources/Protocols/Connection/ConnectionAccept.swift @@ -0,0 +1,83 @@ +import Core +import Domain +import Foundation + +public struct ConnectionAccept { + // Connection Body is the same as Invitation body message + public struct Body: Codable { + public let goalCode: String? + public let goal: String? + public let accept: [String]? + + public init( + goalCode: String? = nil, + goal: String? = nil, + accept: [String]? = nil + ) { + self.goalCode = goalCode + self.goal = goal + self.accept = accept + } + } + public let type: String = ProtocolTypes.didcommconnectionResponse.rawValue + public let id: String + public let from: DID + public let to: DID + public let thid: String? + public let body: Body + + public init(fromMessage: Message) throws { + guard + fromMessage.piuri == ProtocolTypes.didcommconnectionResponse.rawValue, + let from = fromMessage.from, + let to = fromMessage.to + else { throw PrismAgentError.invalidMessageType( + type: fromMessage.piuri, + shouldBe: ProtocolTypes.didcommconnectionResponse.rawValue + ) } + self.init( + from: from, + to: to, + thid: fromMessage.thid, + body: try JSONDecoder.didComm().decode(Body.self, from: fromMessage.body) + ) + } + + public init(fromRequest: ConnectionRequest) { + self.init( + from: fromRequest.to, + to: fromRequest.from, + thid: fromRequest.id, + body: .init( + goalCode: fromRequest.body.goalCode, + goal: fromRequest.body.goal, + accept: fromRequest.body.accept + ) + ) + } + + public init( + id: String = UUID().uuidString, + from: DID, + to: DID, + thid: String?, + body: Body + ) { + self.id = id + self.from = from + self.to = to + self.thid = thid + self.body = body + } + + public func makeMessage() throws -> Message { + Message( + id: id, + piuri: type, + from: from, + to: to, + body: try JSONEncoder.didComm().encode(self.body), + thid: thid + ) + } +} diff --git a/PrismAgent/Sources/Protocols/Connection/HandshakeRequest.swift b/AtalaPrismSDK/PrismAgent/Sources/Protocols/Connection/ConnectionRequest.swift similarity index 54% rename from PrismAgent/Sources/Protocols/Connection/HandshakeRequest.swift rename to AtalaPrismSDK/PrismAgent/Sources/Protocols/Connection/ConnectionRequest.swift index 19a55d01..24c8fd3a 100644 --- a/PrismAgent/Sources/Protocols/Connection/HandshakeRequest.swift +++ b/AtalaPrismSDK/PrismAgent/Sources/Protocols/Connection/ConnectionRequest.swift @@ -2,14 +2,14 @@ import Core import Domain import Foundation -struct HandshakeRequest { +public struct ConnectionRequest { // Connection Body is the same as Invitation body message - struct Body: Codable { - let goalCode: String? - let goal: String? - let accept: [String]? + public struct Body: Codable { + public let goalCode: String? + public let goal: String? + public let accept: [String]? - init( + public init( goalCode: String? = nil, goal: String? = nil, accept: [String]? = nil @@ -19,20 +19,20 @@ struct HandshakeRequest { self.accept = accept } } - let type: String = ProtocolTypes.didcommconnectionRequest.rawValue - let id: String - let from: DID - let to: DID - let thid: String? - let body: Body + public let type: String = ProtocolTypes.didcommconnectionRequest.rawValue + public let id: String + public let from: DID + public let to: DID + public let thid: String? + public let body: Body - init(inviteMessage: Message, from: DID) throws { + public init(inviteMessage: Message, from: DID) throws { guard let toDID = inviteMessage.from else { throw PrismAgentError.invitationIsInvalidError } let body = try JSONDecoder.didComm().decode(Body.self, from: inviteMessage.body) self.init(from: from, to: toDID, thid: inviteMessage.id, body: body) } - init(inviteMessage: OutOfBandInvitation, from: DID) throws { + public init(inviteMessage: OutOfBandInvitation, from: DID) throws { let toDID = try DID(string: inviteMessage.from) self.init( from: from, @@ -46,7 +46,24 @@ struct HandshakeRequest { ) } - init( + public init(fromMessage: Message) throws { + guard + fromMessage.piuri == ProtocolTypes.didcommconnectionRequest.rawValue, + let from = fromMessage.from, + let to = fromMessage.to + else { throw PrismAgentError.invalidMessageType( + type: fromMessage.piuri, + shouldBe: ProtocolTypes.didcommconnectionRequest.rawValue) + } + self.init( + from: from, + to: to, + thid: fromMessage.id, + body: try JSONDecoder.didComm().decode(Body.self, from: fromMessage.body) + ) + } + + public init( id: String = UUID().uuidString, from: DID, to: DID, @@ -60,7 +77,7 @@ struct HandshakeRequest { self.body = body } - func makeMessage() throws -> Message { + public func makeMessage() throws -> Message { Message( id: id, piuri: type, diff --git a/PrismAgent/Sources/Protocols/Connection/DIDCommConnectionRunner.swift b/AtalaPrismSDK/PrismAgent/Sources/Protocols/Connection/DIDCommConnectionRunner.swift similarity index 88% rename from PrismAgent/Sources/Protocols/Connection/DIDCommConnectionRunner.swift rename to AtalaPrismSDK/PrismAgent/Sources/Protocols/Connection/DIDCommConnectionRunner.swift index 4cc6e110..dad7eaf2 100644 --- a/PrismAgent/Sources/Protocols/Connection/DIDCommConnectionRunner.swift +++ b/AtalaPrismSDK/PrismAgent/Sources/Protocols/Connection/DIDCommConnectionRunner.swift @@ -7,7 +7,7 @@ class DIDCommConnectionRunner { private let pluto: Pluto private let ownDID: DID private let connection: DIDCommConnection - private var request: HandshakeRequest? + private var request: ConnectionRequest? init( invitationMessage: OutOfBandInvitation, @@ -22,7 +22,7 @@ class DIDCommConnectionRunner { } func run() async throws -> DIDPair { - let request = try HandshakeRequest(inviteMessage: invitationMessage, from: ownDID) + let request = try ConnectionRequest(inviteMessage: invitationMessage, from: ownDID) try await connection.sendMessage(request.makeMessage()) // let message = try await pluto.getAllMessagesReceived() // .flatMap { $0.publisher } diff --git a/PrismAgent/Sources/Protocols/Invitation/V2/DIDCommInvitationRunner.swift b/AtalaPrismSDK/PrismAgent/Sources/Protocols/Invitation/V2/DIDCommInvitationRunner.swift similarity index 100% rename from PrismAgent/Sources/Protocols/Invitation/V2/DIDCommInvitationRunner.swift rename to AtalaPrismSDK/PrismAgent/Sources/Protocols/Invitation/V2/DIDCommInvitationRunner.swift diff --git a/PrismAgent/Sources/Protocols/Invitation/V2/InvitationRunner.swift b/AtalaPrismSDK/PrismAgent/Sources/Protocols/Invitation/V2/InvitationRunner.swift similarity index 88% rename from PrismAgent/Sources/Protocols/Invitation/V2/InvitationRunner.swift rename to AtalaPrismSDK/PrismAgent/Sources/Protocols/Invitation/V2/InvitationRunner.swift index c634af1f..c66f8f80 100644 --- a/PrismAgent/Sources/Protocols/Invitation/V2/InvitationRunner.swift +++ b/AtalaPrismSDK/PrismAgent/Sources/Protocols/Invitation/V2/InvitationRunner.swift @@ -14,7 +14,7 @@ class InvitationRunner { let messageData = try OutOfBandParser().parseMessage(url: url) guard let messageString = String(data: messageData, encoding: .utf8) - else { throw PrismAgentError.invalidURLError } + else { throw UnknownError.somethingWentWrongError() } return try await mercury.unpackMessage(msg: messageString) } } diff --git a/PrismAgent/Sources/Protocols/Invitation/V2/OutOfBandInvitation.swift b/AtalaPrismSDK/PrismAgent/Sources/Protocols/Invitation/V2/OutOfBandInvitation.swift similarity index 100% rename from PrismAgent/Sources/Protocols/Invitation/V2/OutOfBandInvitation.swift rename to AtalaPrismSDK/PrismAgent/Sources/Protocols/Invitation/V2/OutOfBandInvitation.swift diff --git a/PrismAgent/Sources/Protocols/Invitation/V2/OutOfBandParser.swift b/AtalaPrismSDK/PrismAgent/Sources/Protocols/Invitation/V2/OutOfBandParser.swift similarity index 72% rename from PrismAgent/Sources/Protocols/Invitation/V2/OutOfBandParser.swift rename to AtalaPrismSDK/PrismAgent/Sources/Protocols/Invitation/V2/OutOfBandParser.swift index 627abf32..61be9a7e 100644 --- a/PrismAgent/Sources/Protocols/Invitation/V2/OutOfBandParser.swift +++ b/AtalaPrismSDK/PrismAgent/Sources/Protocols/Invitation/V2/OutOfBandParser.swift @@ -1,17 +1,18 @@ import Core +import Domain import Foundation struct OutOfBandParser { func parseMessage(url: URL) throws -> Data { guard let components = URLComponents(url: url, resolvingAgainstBaseURL: true) - else { throw PrismAgentError.invalidURLError } + else { throw CommonError.invalidURLError(url: url.absoluteString) } guard let message = components .queryItems? .first(where: { $0.name == "_oob" })? .value, let dataJson = Data(base64URLEncoded: message) - else { throw PrismAgentError.invalidURLError } + else { throw CommonError.invalidURLError(url: url.absoluteString) } return dataJson } diff --git a/PrismAgent/Sources/Protocols/IssueCredential/CredentialPreview.swift b/AtalaPrismSDK/PrismAgent/Sources/Protocols/IssueCredential/CredentialPreview.swift similarity index 100% rename from PrismAgent/Sources/Protocols/IssueCredential/CredentialPreview.swift rename to AtalaPrismSDK/PrismAgent/Sources/Protocols/IssueCredential/CredentialPreview.swift diff --git a/PrismAgent/Sources/Protocols/IssueCredential/IssueCredential.swift b/AtalaPrismSDK/PrismAgent/Sources/Protocols/IssueCredential/IssueCredential.swift similarity index 96% rename from PrismAgent/Sources/Protocols/IssueCredential/IssueCredential.swift rename to AtalaPrismSDK/PrismAgent/Sources/Protocols/IssueCredential/IssueCredential.swift index 83fdb6de..55a87485 100644 --- a/PrismAgent/Sources/Protocols/IssueCredential/IssueCredential.swift +++ b/AtalaPrismSDK/PrismAgent/Sources/Protocols/IssueCredential/IssueCredential.swift @@ -56,7 +56,10 @@ public struct IssueCredential { fromMessage.piuri == ProtocolTypes.didcommIssueCredential.rawValue, let fromDID = fromMessage.from, let toDID = fromMessage.to - else { throw PrismAgentError.invalidIssueCredentialMessageError } + else { throw PrismAgentError.invalidMessageType( + type: fromMessage.piuri, + shouldBe: ProtocolTypes.didcommIssueCredential.rawValue + ) } let body = try JSONDecoder.didComm().decode(Body.self, from: fromMessage.body) self.init( diff --git a/PrismAgent/Sources/Protocols/IssueCredential/IssueCredentialProtocol.swift b/AtalaPrismSDK/PrismAgent/Sources/Protocols/IssueCredential/IssueCredentialProtocol.swift similarity index 95% rename from PrismAgent/Sources/Protocols/IssueCredential/IssueCredentialProtocol.swift rename to AtalaPrismSDK/PrismAgent/Sources/Protocols/IssueCredential/IssueCredentialProtocol.swift index 45d368ca..5891bb57 100644 --- a/PrismAgent/Sources/Protocols/IssueCredential/IssueCredentialProtocol.swift +++ b/AtalaPrismSDK/PrismAgent/Sources/Protocols/IssueCredential/IssueCredentialProtocol.swift @@ -28,7 +28,10 @@ public class IssueCredentialProtocol { self.stage = .request self.request = requested } else { - throw PrismAgentError.invalidStepError + throw UnknownError.somethingWentWrongError( + customMessage: "Invalid Step", + underlyingErrors: nil + ) } self.connector = connector } diff --git a/PrismAgent/Sources/Protocols/IssueCredential/OfferCredential.swift b/AtalaPrismSDK/PrismAgent/Sources/Protocols/IssueCredential/OfferCredential.swift similarity index 95% rename from PrismAgent/Sources/Protocols/IssueCredential/OfferCredential.swift rename to AtalaPrismSDK/PrismAgent/Sources/Protocols/IssueCredential/OfferCredential.swift index 987347af..aa51f46c 100644 --- a/PrismAgent/Sources/Protocols/IssueCredential/OfferCredential.swift +++ b/AtalaPrismSDK/PrismAgent/Sources/Protocols/IssueCredential/OfferCredential.swift @@ -59,7 +59,10 @@ public struct OfferCredential { fromMessage.piuri == ProtocolTypes.didcommOfferCredential.rawValue, let fromDID = fromMessage.from, let toDID = fromMessage.to - else { throw PrismAgentError.invalidOfferCredentialMessageError } + else { throw PrismAgentError.invalidMessageType( + type: fromMessage.piuri, + shouldBe: ProtocolTypes.didcommOfferCredential.rawValue + ) } let body = try JSONDecoder.didComm().decode(Body.self, from: fromMessage.body) self.init( diff --git a/PrismAgent/Sources/Protocols/IssueCredential/ProposeCredential.swift b/AtalaPrismSDK/PrismAgent/Sources/Protocols/IssueCredential/ProposeCredential.swift similarity index 94% rename from PrismAgent/Sources/Protocols/IssueCredential/ProposeCredential.swift rename to AtalaPrismSDK/PrismAgent/Sources/Protocols/IssueCredential/ProposeCredential.swift index 8649af4b..3199e4e2 100644 --- a/PrismAgent/Sources/Protocols/IssueCredential/ProposeCredential.swift +++ b/AtalaPrismSDK/PrismAgent/Sources/Protocols/IssueCredential/ProposeCredential.swift @@ -53,7 +53,10 @@ public struct ProposeCredential { fromMessage.piuri == ProtocolTypes.didcommProposeCredential.rawValue, let fromDID = fromMessage.from, let toDID = fromMessage.to - else { throw PrismAgentError.invalidProposedCredentialMessageError } + else { throw PrismAgentError.invalidMessageType( + type: fromMessage.piuri, + shouldBe: ProtocolTypes.didcommProposeCredential.rawValue + ) } let body = try JSONDecoder.didComm().decode(Body.self, from: fromMessage.body) self.init( id: fromMessage.id, diff --git a/PrismAgent/Sources/Protocols/IssueCredential/RequestCredential.swift b/AtalaPrismSDK/PrismAgent/Sources/Protocols/IssueCredential/RequestCredential.swift similarity index 95% rename from PrismAgent/Sources/Protocols/IssueCredential/RequestCredential.swift rename to AtalaPrismSDK/PrismAgent/Sources/Protocols/IssueCredential/RequestCredential.swift index 40118d73..ca2ce78b 100644 --- a/PrismAgent/Sources/Protocols/IssueCredential/RequestCredential.swift +++ b/AtalaPrismSDK/PrismAgent/Sources/Protocols/IssueCredential/RequestCredential.swift @@ -50,7 +50,10 @@ public struct RequestCredential { fromMessage.piuri == ProtocolTypes.didcommRequestCredential.rawValue, let fromDID = fromMessage.from, let toDID = fromMessage.to - else { throw PrismAgentError.invalidRequestCredentialMessageError } + else { throw PrismAgentError.invalidMessageType( + type: fromMessage.piuri, + shouldBe: ProtocolTypes.didcommRequestCredential.rawValue + ) } let body = try JSONDecoder.didComm().decode(Body.self, from: fromMessage.body) self.init( diff --git a/PrismAgent/Sources/Protocols/Mediation/MediationGrant.swift b/AtalaPrismSDK/PrismAgent/Sources/Protocols/Mediation/MediationGrant.swift similarity index 78% rename from PrismAgent/Sources/Protocols/Mediation/MediationGrant.swift rename to AtalaPrismSDK/PrismAgent/Sources/Protocols/Mediation/MediationGrant.swift index 24b80f7b..4e63f5f4 100644 --- a/PrismAgent/Sources/Protocols/Mediation/MediationGrant.swift +++ b/AtalaPrismSDK/PrismAgent/Sources/Protocols/Mediation/MediationGrant.swift @@ -21,7 +21,10 @@ struct MediationGrant { init(fromMessage: Message) throws { guard fromMessage.piuri == ProtocolTypes.didcommMediationGrant.rawValue - else { throw PrismAgentError.invalidMediationGrantMessageError } + else { throw PrismAgentError.invalidMessageType( + type: fromMessage.piuri, + shouldBe: ProtocolTypes.didcommMediationGrant.rawValue + ) } self.init( id: fromMessage.id, body: try JSONDecoder.didComm().decode(Body.self, from: fromMessage.body) diff --git a/PrismAgent/Sources/Protocols/Mediation/MediationKeysUpdateList.swift b/AtalaPrismSDK/PrismAgent/Sources/Protocols/Mediation/MediationKeysUpdateList.swift similarity index 100% rename from PrismAgent/Sources/Protocols/Mediation/MediationKeysUpdateList.swift rename to AtalaPrismSDK/PrismAgent/Sources/Protocols/Mediation/MediationKeysUpdateList.swift diff --git a/PrismAgent/Sources/Protocols/Mediation/MediationRequest.swift b/AtalaPrismSDK/PrismAgent/Sources/Protocols/Mediation/MediationRequest.swift similarity index 100% rename from PrismAgent/Sources/Protocols/Mediation/MediationRequest.swift rename to AtalaPrismSDK/PrismAgent/Sources/Protocols/Mediation/MediationRequest.swift diff --git a/PrismAgent/Sources/Protocols/Pickup/PickupRequest.swift b/AtalaPrismSDK/PrismAgent/Sources/Protocols/Pickup/PickupRequest.swift similarity index 100% rename from PrismAgent/Sources/Protocols/Pickup/PickupRequest.swift rename to AtalaPrismSDK/PrismAgent/Sources/Protocols/Pickup/PickupRequest.swift diff --git a/PrismAgent/Sources/Protocols/Pickup/PickupRunner.swift b/AtalaPrismSDK/PrismAgent/Sources/Protocols/Pickup/PickupRunner.swift similarity index 86% rename from PrismAgent/Sources/Protocols/Pickup/PickupRunner.swift rename to AtalaPrismSDK/PrismAgent/Sources/Protocols/Pickup/PickupRunner.swift index 8339f4af..cd09c294 100644 --- a/PrismAgent/Sources/Protocols/Pickup/PickupRunner.swift +++ b/AtalaPrismSDK/PrismAgent/Sources/Protocols/Pickup/PickupRunner.swift @@ -17,7 +17,10 @@ class PickupRunner { case ProtocolTypes.pickupDelivery.rawValue: self.message = .delivery(message) default: - throw PrismAgentError.invalidPickupDeliveryMessageError + throw PrismAgentError.invalidMessageType( + type: message.piuri, + shouldBe: ProtocolTypes.pickupStatus.rawValue + " or " + ProtocolTypes.pickupDelivery.rawValue + ) } self.mercury = mercury } diff --git a/PrismAgent/Sources/Protocols/Pickup/PrickupReceived.swift b/AtalaPrismSDK/PrismAgent/Sources/Protocols/Pickup/PrickupReceived.swift similarity index 100% rename from PrismAgent/Sources/Protocols/Pickup/PrickupReceived.swift rename to AtalaPrismSDK/PrismAgent/Sources/Protocols/Pickup/PrickupReceived.swift diff --git a/PrismAgent/Sources/Protocols/PrismOnboarding/PrismOnboardingInvitation.swift b/AtalaPrismSDK/PrismAgent/Sources/Protocols/PrismOnboarding/PrismOnboardingInvitation.swift similarity index 89% rename from PrismAgent/Sources/Protocols/PrismOnboarding/PrismOnboardingInvitation.swift rename to AtalaPrismSDK/PrismAgent/Sources/Protocols/PrismOnboarding/PrismOnboardingInvitation.swift index e646147e..7764c4d7 100644 --- a/PrismAgent/Sources/Protocols/PrismOnboarding/PrismOnboardingInvitation.swift +++ b/AtalaPrismSDK/PrismAgent/Sources/Protocols/PrismOnboarding/PrismOnboardingInvitation.swift @@ -13,7 +13,7 @@ struct PrismOnboardingInvitation { guard let jsonData = jsonString.data(using: .utf8) else { throw PrismAgentError.invitationIsInvalidError } let object = try JSONDecoder.didComm().decode(Body.self, from: jsonData) guard object.type == ProtocolTypes.prismOnboarding.rawValue else { - throw PrismAgentError.unknownPrismOnboardingTypeError + throw PrismAgentError.unknownInvitationTypeError } self.body = object } diff --git a/PrismAgent/Sources/Protocols/ProofPresentation/Presentation.swift b/AtalaPrismSDK/PrismAgent/Sources/Protocols/ProofPresentation/Presentation.swift similarity index 93% rename from PrismAgent/Sources/Protocols/ProofPresentation/Presentation.swift rename to AtalaPrismSDK/PrismAgent/Sources/Protocols/ProofPresentation/Presentation.swift index f890bb4d..9927cf45 100644 --- a/PrismAgent/Sources/Protocols/ProofPresentation/Presentation.swift +++ b/AtalaPrismSDK/PrismAgent/Sources/Protocols/ProofPresentation/Presentation.swift @@ -50,7 +50,10 @@ public struct Presentation { fromMessage.piuri == ProtocolTypes.didcommPresentation.rawValue, let fromDID = fromMessage.from, let toDID = fromMessage.to - else { throw PrismAgentError.invalidPresentationMessageError } + else { throw PrismAgentError.invalidMessageType( + type: fromMessage.piuri, + shouldBe: ProtocolTypes.didcommPresentation.rawValue + ) } let body = try JSONDecoder.didComm().decode(Body.self, from: fromMessage.body) self.init( diff --git a/PrismAgent/Sources/Protocols/ProofPresentation/ProposePresentation.swift b/AtalaPrismSDK/PrismAgent/Sources/Protocols/ProofPresentation/ProposePresentation.swift similarity index 93% rename from PrismAgent/Sources/Protocols/ProofPresentation/ProposePresentation.swift rename to AtalaPrismSDK/PrismAgent/Sources/Protocols/ProofPresentation/ProposePresentation.swift index 26113128..07c8bdd3 100644 --- a/PrismAgent/Sources/Protocols/ProofPresentation/ProposePresentation.swift +++ b/AtalaPrismSDK/PrismAgent/Sources/Protocols/ProofPresentation/ProposePresentation.swift @@ -47,7 +47,10 @@ public struct ProposePresentation { fromMessage.piuri == ProtocolTypes.didcommProposePresentation.rawValue, let fromDID = fromMessage.from, let toDID = fromMessage.to - else { throw PrismAgentError.invalidProposePresentationMessageError } + else { throw PrismAgentError.invalidMessageType( + type: fromMessage.piuri, + shouldBe: ProtocolTypes.didcommProposePresentation.rawValue + ) } let body = try JSONDecoder.didComm().decode(Body.self, from: fromMessage.body) self.init( diff --git a/PrismAgent/Sources/Protocols/ProofPresentation/RequestPresentation.swift b/AtalaPrismSDK/PrismAgent/Sources/Protocols/ProofPresentation/RequestPresentation.swift similarity index 94% rename from PrismAgent/Sources/Protocols/ProofPresentation/RequestPresentation.swift rename to AtalaPrismSDK/PrismAgent/Sources/Protocols/ProofPresentation/RequestPresentation.swift index 8c1862cb..485eca7a 100644 --- a/PrismAgent/Sources/Protocols/ProofPresentation/RequestPresentation.swift +++ b/AtalaPrismSDK/PrismAgent/Sources/Protocols/ProofPresentation/RequestPresentation.swift @@ -50,7 +50,10 @@ public struct RequestPresentation { fromMessage.piuri == ProtocolTypes.didcommRequestPresentation.rawValue, let fromDID = fromMessage.from, let toDID = fromMessage.to - else { throw PrismAgentError.invalidRequestPresentationMessageError } + else { throw PrismAgentError.invalidMessageType( + type: fromMessage.piuri, + shouldBe: ProtocolTypes.didcommRequestPresentation.rawValue + ) } let body = try JSONDecoder.didComm().decode(Body.self, from: fromMessage.body) self.init( diff --git a/PrismAgent/Sources/Protocols/ProtocolTypes.swift b/AtalaPrismSDK/PrismAgent/Sources/Protocols/ProtocolTypes.swift similarity index 100% rename from PrismAgent/Sources/Protocols/ProtocolTypes.swift rename to AtalaPrismSDK/PrismAgent/Sources/Protocols/ProtocolTypes.swift diff --git a/PrismAgent/Tests/CheckTest.swift b/AtalaPrismSDK/PrismAgent/Tests/CheckTest.swift similarity index 100% rename from PrismAgent/Tests/CheckTest.swift rename to AtalaPrismSDK/PrismAgent/Tests/CheckTest.swift diff --git a/PrismAgent/Tests/ConnectionRunnerTests.swift b/AtalaPrismSDK/PrismAgent/Tests/ConnectionRunnerTests.swift similarity index 96% rename from PrismAgent/Tests/ConnectionRunnerTests.swift rename to AtalaPrismSDK/PrismAgent/Tests/ConnectionRunnerTests.swift index 7f78ddf6..b7d208f5 100644 --- a/PrismAgent/Tests/ConnectionRunnerTests.swift +++ b/AtalaPrismSDK/PrismAgent/Tests/ConnectionRunnerTests.swift @@ -6,7 +6,7 @@ final class ConnectionRunnerTests: XCTestCase { private let mercury = MercuryStub() func testWhenInvitationMessageThenTryConnectingWith() async throws { - let body = HandshakeRequest.Body( + let body = ConnectionRequest.Body( goalCode: "123", goal: "Test", accept: ["Test1"] diff --git a/PrismAgent/Tests/DIDCommInvitationRunnerTests.swift b/AtalaPrismSDK/PrismAgent/Tests/DIDCommInvitationRunnerTests.swift similarity index 100% rename from PrismAgent/Tests/DIDCommInvitationRunnerTests.swift rename to AtalaPrismSDK/PrismAgent/Tests/DIDCommInvitationRunnerTests.swift diff --git a/PrismAgent/Tests/HandshakeRequestTests.swift b/AtalaPrismSDK/PrismAgent/Tests/HandshakeRequestTests.swift similarity index 78% rename from PrismAgent/Tests/HandshakeRequestTests.swift rename to AtalaPrismSDK/PrismAgent/Tests/HandshakeRequestTests.swift index d0757797..0bb5f47e 100644 --- a/PrismAgent/Tests/HandshakeRequestTests.swift +++ b/AtalaPrismSDK/PrismAgent/Tests/HandshakeRequestTests.swift @@ -4,7 +4,7 @@ import XCTest final class HandshakeRequestTests: XCTestCase { func testHandshakeRequestMakeMessage() throws { - let request = HandshakeRequest( + let request = ConnectionRequest( from: DID(index: 1), to: DID(index: 2), thid: "0", @@ -17,12 +17,12 @@ final class HandshakeRequestTests: XCTestCase { XCTAssertEqual(message.from, request.from) XCTAssertEqual(message.to, request.to) XCTAssertEqual(message.thid, request.thid) - let decodedBody = try JSONDecoder.didComm().decode(HandshakeRequest.Body.self, from: message.body) + let decodedBody = try JSONDecoder.didComm().decode(ConnectionRequest.Body.self, from: message.body) XCTAssertEqual(decodedBody, request.body) } func testHandshakeRequestInitFromInvitationMessage() throws { - let body = HandshakeRequest.Body( + let body = ConnectionRequest.Body( goalCode: "123", goal: "Test", accept: ["Test1"] @@ -37,7 +37,7 @@ final class HandshakeRequestTests: XCTestCase { let selfDID = DID(index: 3) - let request = try HandshakeRequest(inviteMessage: exampleMessage, from: selfDID) + let request = try ConnectionRequest(inviteMessage: exampleMessage, from: selfDID) XCTAssertNotEqual(exampleMessage.id, request.id) XCTAssertEqual(request.type, ProtocolTypes.didcommconnectionRequest.rawValue) XCTAssertEqual(selfDID, request.from) @@ -47,8 +47,8 @@ final class HandshakeRequestTests: XCTestCase { } } -extension HandshakeRequest.Body: Equatable { - public static func == (lhs: HandshakeRequest.Body, rhs: HandshakeRequest.Body) -> Bool { +extension ConnectionRequest.Body: Equatable { + public static func == (lhs: ConnectionRequest.Body, rhs: ConnectionRequest.Body) -> Bool { lhs.goalCode == rhs.goalCode && lhs.goal == rhs.goal && lhs.accept == rhs.accept } } diff --git a/PrismAgent/Tests/Helper/Castor+Testing.swift b/AtalaPrismSDK/PrismAgent/Tests/Helper/Castor+Testing.swift similarity index 100% rename from PrismAgent/Tests/Helper/Castor+Testing.swift rename to AtalaPrismSDK/PrismAgent/Tests/Helper/Castor+Testing.swift diff --git a/PrismAgent/Tests/Helper/DID+Testing.swift b/AtalaPrismSDK/PrismAgent/Tests/Helper/DID+Testing.swift similarity index 100% rename from PrismAgent/Tests/Helper/DID+Testing.swift rename to AtalaPrismSDK/PrismAgent/Tests/Helper/DID+Testing.swift diff --git a/PrismAgent/Tests/Helper/DIDCommConnection+Testing.swift b/AtalaPrismSDK/PrismAgent/Tests/Helper/DIDCommConnection+Testing.swift similarity index 100% rename from PrismAgent/Tests/Helper/DIDCommConnection+Testing.swift rename to AtalaPrismSDK/PrismAgent/Tests/Helper/DIDCommConnection+Testing.swift diff --git a/PrismAgent/Tests/Helper/Mercury+Testing.swift b/AtalaPrismSDK/PrismAgent/Tests/Helper/Mercury+Testing.swift similarity index 100% rename from PrismAgent/Tests/Helper/Mercury+Testing.swift rename to AtalaPrismSDK/PrismAgent/Tests/Helper/Mercury+Testing.swift diff --git a/PrismAgent/Tests/Helper/Message+Testing.swift b/AtalaPrismSDK/PrismAgent/Tests/Helper/Message+Testing.swift similarity index 100% rename from PrismAgent/Tests/Helper/Message+Testing.swift rename to AtalaPrismSDK/PrismAgent/Tests/Helper/Message+Testing.swift diff --git a/PrismAgent/Tests/Helper/MessageAttachment+Testing.swift b/AtalaPrismSDK/PrismAgent/Tests/Helper/MessageAttachment+Testing.swift similarity index 100% rename from PrismAgent/Tests/Helper/MessageAttachment+Testing.swift rename to AtalaPrismSDK/PrismAgent/Tests/Helper/MessageAttachment+Testing.swift diff --git a/PrismAgent/Tests/IssueCredentialTests.swift b/AtalaPrismSDK/PrismAgent/Tests/IssueCredentialTests.swift similarity index 100% rename from PrismAgent/Tests/IssueCredentialTests.swift rename to AtalaPrismSDK/PrismAgent/Tests/IssueCredentialTests.swift diff --git a/PrismAgent/Tests/OfferCredentialTests.swift b/AtalaPrismSDK/PrismAgent/Tests/OfferCredentialTests.swift similarity index 100% rename from PrismAgent/Tests/OfferCredentialTests.swift rename to AtalaPrismSDK/PrismAgent/Tests/OfferCredentialTests.swift diff --git a/PrismAgent/Tests/PickupRunnerTests.swift b/AtalaPrismSDK/PrismAgent/Tests/PickupRunnerTests.swift similarity index 100% rename from PrismAgent/Tests/PickupRunnerTests.swift rename to AtalaPrismSDK/PrismAgent/Tests/PickupRunnerTests.swift diff --git a/PrismAgent/Tests/PresentationTests.swift b/AtalaPrismSDK/PrismAgent/Tests/PresentationTests.swift similarity index 100% rename from PrismAgent/Tests/PresentationTests.swift rename to AtalaPrismSDK/PrismAgent/Tests/PresentationTests.swift diff --git a/PrismAgent/Tests/PrismOnboardingInvitationTests.swift b/AtalaPrismSDK/PrismAgent/Tests/PrismOnboardingInvitationTests.swift similarity index 100% rename from PrismAgent/Tests/PrismOnboardingInvitationTests.swift rename to AtalaPrismSDK/PrismAgent/Tests/PrismOnboardingInvitationTests.swift diff --git a/PrismAgent/Tests/ProposeCredentialTests.swift b/AtalaPrismSDK/PrismAgent/Tests/ProposeCredentialTests.swift similarity index 100% rename from PrismAgent/Tests/ProposeCredentialTests.swift rename to AtalaPrismSDK/PrismAgent/Tests/ProposeCredentialTests.swift diff --git a/PrismAgent/Tests/ProposePresentationTests.swift b/AtalaPrismSDK/PrismAgent/Tests/ProposePresentationTests.swift similarity index 100% rename from PrismAgent/Tests/ProposePresentationTests.swift rename to AtalaPrismSDK/PrismAgent/Tests/ProposePresentationTests.swift diff --git a/PrismAgent/Tests/RequestCredentialTests.swift b/AtalaPrismSDK/PrismAgent/Tests/RequestCredentialTests.swift similarity index 100% rename from PrismAgent/Tests/RequestCredentialTests.swift rename to AtalaPrismSDK/PrismAgent/Tests/RequestCredentialTests.swift diff --git a/PrismAgent/Tests/RequestPresentationTests.swift b/AtalaPrismSDK/PrismAgent/Tests/RequestPresentationTests.swift similarity index 100% rename from PrismAgent/Tests/RequestPresentationTests.swift rename to AtalaPrismSDK/PrismAgent/Tests/RequestPresentationTests.swift diff --git a/Castor/Sources/CastorImpl+Public.swift b/Castor/Sources/CastorImpl+Public.swift deleted file mode 100644 index cb10bfbe..00000000 --- a/Castor/Sources/CastorImpl+Public.swift +++ /dev/null @@ -1,75 +0,0 @@ -import Domain -import Foundation - -extension CastorImpl: Castor { - public func parseDID(str: String) throws -> DID { - try DIDParser(didString: str).parse() - } - - public func createPrismDID( - masterPublicKey: PublicKey, - services: [DIDDocument.Service] - ) throws -> DID { - try CreatePrismDIDOperation( - apollo: apollo, - masterPublicKey: masterPublicKey, - services: services - ).compute() - } - - public func createPeerDID( - keyAgreementKeyPair: KeyPair, - authenticationKeyPair: KeyPair, - services: [DIDDocument.Service] - ) throws -> DID { - try CreatePeerDIDOperation( - autenticationKeyPair: authenticationKeyPair, - agreementKeyPair: keyAgreementKeyPair, - services: services - ).compute() - } - - public func verifySignature(did: DID, challenge: Data, signature: Data) async throws -> Bool { - let document = try await resolveDID(did: did) - return verifySignature(document: document, challenge: challenge, signature: signature) - } - - public func verifySignature( - document: DIDDocument, - challenge: Data, - signature: Data - ) -> Bool { - return VerifySignatureOperation( - apollo: apollo, - document: document, - challenge: challenge, - signature: signature - ).compute() - } - - public func resolveDID(did: DID) async throws -> DIDDocument { - logger.info(message: "Trying to resolve DID", metadata: [ - .maskedMetadataByLevel(key: "DID", value: did.string, level: .debug) - ]) - guard - let resolver = resolvers.first(where: { $0.method == did.method }) - else { - logger.error(message: "No resolvers for DID method \(did.method)", metadata: [ - .maskedMetadataByLevel(key: "DID", value: did.string, level: .debug) - ]) - throw CastorError.notPossibleToResolveDID - } - return try await resolver.resolve(did: did) - } - - public func getEcnumbasis(did: DID, keyPair: KeyPair) throws -> String { - logger.debug(message: "Getting ecnumbasis", metadata: [ - .maskedMetadataByLevel(key: "DID", value: did.string, level: .debug) - ]) - return try CreatePeerDIDOperation( - autenticationKeyPair: keyPair, - agreementKeyPair: keyPair, - services: [] - ).computeEcnumbasis(did: did, keyPair: keyPair) - } -} diff --git a/Castor/Sources/protobuf/common_models.pb.swift b/Castor/Sources/protobuf/common_models.pb.swift deleted file mode 100644 index 674089bc..00000000 --- a/Castor/Sources/protobuf/common_models.pb.swift +++ /dev/null @@ -1,585 +0,0 @@ -// DO NOT EDIT. -// swift-format-ignore-file -// -// Generated by the Swift generator plugin for the protocol buffer compiler. -// Source: common_models.proto -// -// For information on using the generated types, please see the documentation: -// https://github.com/apple/swift-protobuf/ - -import Foundation -@_implementationOnly import SwiftProtobuf - -// If the compiler emits an error on this type, it is because this file -// was generated by a version of the `protoc` Swift plug-in that is -// incompatible with the version of SwiftProtobuf to which you are linking. -// Please ensure that you are building against the same version of the API -// that was used to generate this file. -private struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { - struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} - typealias Version = _2 -} - -/// * -/// This enum provides a way for some RPC requests to specify the direction so that the response values are sorted -/// the way you want them to. -/// Note that it specifies the direction only and doesn't say anything about a comparator -/// (e.g. natural order, some RPC-specific order etc). -enum Io_Iohk_Atala_Prism_Protos_SortByDirection: SwiftProtobuf.Enum { - typealias RawValue = Int - - /// Nothing provided, each API can define whether to fail or take a default value (commonly ASCENDING). - case unknown // = 0 - - /// Sort the results in ascending order. - case ascending // = 1 - - /// Sort the results in descending order. - case descending // = 2 - case UNRECOGNIZED(Int) - - init() { - self = .unknown - } - - init?(rawValue: Int) { - switch rawValue { - case 0: self = .unknown - case 1: self = .ascending - case 2: self = .descending - default: self = .UNRECOGNIZED(rawValue) - } - } - - var rawValue: Int { - switch self { - case .unknown: return 0 - case .ascending: return 1 - case .descending: return 2 - case let .UNRECOGNIZED(i): return i - } - } -} - -#if swift(>=4.2) - - extension Io_Iohk_Atala_Prism_Protos_SortByDirection: CaseIterable { - // The compiler won't synthesize support with the UNRECOGNIZED case. - static var allCases: [Io_Iohk_Atala_Prism_Protos_SortByDirection] = [ - .unknown, - .ascending, - .descending, - ] - } - -#endif // swift(>=4.2) - -/// * -/// The supported ledger types. Specifies which chain is used for storing transactions. -enum Io_Iohk_Atala_Prism_Protos_Ledger: SwiftProtobuf.Enum { - typealias RawValue = Int - - /// Invalid default value. - case unknownLedger // = 0 - - /// Store transactions in memory instead of blockchain, used only for development. - case inMemory // = 1 - - /// Cardano testnet, used for testing. - case cardanoTestnet // = 4 - - /// Cardano mainnet, used in production. - case cardanoMainnet // = 5 - case UNRECOGNIZED(Int) - - init() { - self = .unknownLedger - } - - init?(rawValue: Int) { - switch rawValue { - case 0: self = .unknownLedger - case 1: self = .inMemory - case 4: self = .cardanoTestnet - case 5: self = .cardanoMainnet - default: self = .UNRECOGNIZED(rawValue) - } - } - - var rawValue: Int { - switch self { - case .unknownLedger: return 0 - case .inMemory: return 1 - case .cardanoTestnet: return 4 - case .cardanoMainnet: return 5 - case let .UNRECOGNIZED(i): return i - } - } -} - -#if swift(>=4.2) - - extension Io_Iohk_Atala_Prism_Protos_Ledger: CaseIterable { - // The compiler won't synthesize support with the UNRECOGNIZED case. - static var allCases: [Io_Iohk_Atala_Prism_Protos_Ledger] = [ - .unknownLedger, - .inMemory, - .cardanoTestnet, - .cardanoMainnet, - ] - } - -#endif // swift(>=4.2) - -/// * -/// The status of an Atala operation. -enum Io_Iohk_Atala_Prism_Protos_OperationStatus: SwiftProtobuf.Enum { - typealias RawValue = Int - - /// The operation hasn't been received by the node service yet. - case unknownOperation // = 0 - - /// The transaction containing this operation hasn't been published to the chain yet. - case pendingSubmission // = 1 - - /// The transaction containing this operation has been published to the chain, but hasn't been processed by PRISM yet. - case awaitConfirmation // = 2 - - /// The operation has been successfully applied to the PRISM. - case confirmedAndApplied // = 3 - - /// The operation has been processed by PRISM, but rejected because of some error. - case confirmedAndRejected // = 4 - case UNRECOGNIZED(Int) - - init() { - self = .unknownOperation - } - - init?(rawValue: Int) { - switch rawValue { - case 0: self = .unknownOperation - case 1: self = .pendingSubmission - case 2: self = .awaitConfirmation - case 3: self = .confirmedAndApplied - case 4: self = .confirmedAndRejected - default: self = .UNRECOGNIZED(rawValue) - } - } - - var rawValue: Int { - switch self { - case .unknownOperation: return 0 - case .pendingSubmission: return 1 - case .awaitConfirmation: return 2 - case .confirmedAndApplied: return 3 - case .confirmedAndRejected: return 4 - case let .UNRECOGNIZED(i): return i - } - } -} - -#if swift(>=4.2) - - extension Io_Iohk_Atala_Prism_Protos_OperationStatus: CaseIterable { - // The compiler won't synthesize support with the UNRECOGNIZED case. - static var allCases: [Io_Iohk_Atala_Prism_Protos_OperationStatus] = [ - .unknownOperation, - .pendingSubmission, - .awaitConfirmation, - .confirmedAndApplied, - .confirmedAndRejected, - ] - } - -#endif // swift(>=4.2) - -/// * -/// A request that can be used to check service health. -/// All PRISM services expose an RPC that accepts this message as request. -struct Io_Iohk_Atala_Prism_Protos_HealthCheckRequest { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} -} - -/// * -/// A response that represents service health. -/// Status code 0 with empty response represents a healthy and reachable service, -/// while all other status codes represent issues with the service. -struct Io_Iohk_Atala_Prism_Protos_HealthCheckResponse { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} -} - -/// * -/// Represents a date by its parts (day, month, year). -struct Io_Iohk_Atala_Prism_Protos_Date { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// A positive value. - var year: Int32 = 0 - - /// A value in the [1, 12] range. - var month: Int32 = 0 - - /// A value in the [1, 31] range (depending on the month, the maximum value might be 28). - var day: Int32 = 0 - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} -} - -/// * -/// Represents a time interval between two given timestamps. -/// The message represents a closed interval (i.e. both ends are inclusive and mandatory). -struct Io_Iohk_Atala_Prism_Protos_TimeInterval { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// * - /// The starting timestamp. - /// start_timestamp must be before or equal to end_timestamp. - var startTimestamp: SwiftProtobuf.Google_Protobuf_Timestamp { - get { return _startTimestamp ?? SwiftProtobuf.Google_Protobuf_Timestamp() } - set { _startTimestamp = newValue } - } - - /// Returns true if `startTimestamp` has been explicitly set. - var hasStartTimestamp: Bool { return self._startTimestamp != nil } - /// Clears the value of `startTimestamp`. Subsequent reads from it will return its default value. - mutating func clearStartTimestamp() { _startTimestamp = nil } - - /// * - /// The ending timestamp. - /// end_timestamp must be after or equal to start_timestamp. - var endTimestamp: SwiftProtobuf.Google_Protobuf_Timestamp { - get { return _endTimestamp ?? SwiftProtobuf.Google_Protobuf_Timestamp() } - set { _endTimestamp = newValue } - } - - /// Returns true if `endTimestamp` has been explicitly set. - var hasEndTimestamp: Bool { return self._endTimestamp != nil } - /// Clears the value of `endTimestamp`. Subsequent reads from it will return its default value. - mutating func clearEndTimestamp() { _endTimestamp = nil } - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} - - fileprivate var _startTimestamp: SwiftProtobuf.Google_Protobuf_Timestamp? - fileprivate var _endTimestamp: SwiftProtobuf.Google_Protobuf_Timestamp? -} - -/// * -/// Information about a ledger block. -/// See Ledger documentation for details on which ledgers are possible. -struct Io_Iohk_Atala_Prism_Protos_BlockInfo { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// Number of the block in the ledger. - var number: Int32 = 0 - - /// Index of the transaction within the block. - var index: Int32 = 0 - - /// Timestamp when the block was created. - var timestamp: SwiftProtobuf.Google_Protobuf_Timestamp { - get { return _timestamp ?? SwiftProtobuf.Google_Protobuf_Timestamp() } - set { _timestamp = newValue } - } - - /// Returns true if `timestamp` has been explicitly set. - var hasTimestamp: Bool { return self._timestamp != nil } - /// Clears the value of `timestamp`. Subsequent reads from it will return its default value. - mutating func clearTimestamp() { _timestamp = nil } - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} - - fileprivate var _timestamp: SwiftProtobuf.Google_Protobuf_Timestamp? -} - -/// * -/// Information about a ledger transaction and the block that the transaction is included in. -struct Io_Iohk_Atala_Prism_Protos_TransactionInfo { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// Transaction ID. - var transactionID: String = .init() - - /// Ledger the transaction was published to. - var ledger: Io_Iohk_Atala_Prism_Protos_Ledger = .unknownLedger - - /// Block the transaction was included in. - var block: Io_Iohk_Atala_Prism_Protos_BlockInfo { - get { return _block ?? Io_Iohk_Atala_Prism_Protos_BlockInfo() } - set { _block = newValue } - } - - /// Returns true if `block` has been explicitly set. - var hasBlock: Bool { return self._block != nil } - /// Clears the value of `block`. Subsequent reads from it will return its default value. - mutating func clearBlock() { _block = nil } - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} - - fileprivate var _block: Io_Iohk_Atala_Prism_Protos_BlockInfo? -} - -// MARK: - Code below here is support for the SwiftProtobuf runtime. - -private let _protobuf_package = "io.iohk.atala.prism.protos" - -extension Io_Iohk_Atala_Prism_Protos_SortByDirection: SwiftProtobuf._ProtoNameProviding { - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 0: .same(proto: "SORT_BY_DIRECTION_UNKNOWN"), - 1: .same(proto: "SORT_BY_DIRECTION_ASCENDING"), - 2: .same(proto: "SORT_BY_DIRECTION_DESCENDING"), - ] -} - -extension Io_Iohk_Atala_Prism_Protos_Ledger: SwiftProtobuf._ProtoNameProviding { - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 0: .same(proto: "UNKNOWN_LEDGER"), - 1: .same(proto: "IN_MEMORY"), - 4: .same(proto: "CARDANO_TESTNET"), - 5: .same(proto: "CARDANO_MAINNET"), - ] -} - -extension Io_Iohk_Atala_Prism_Protos_OperationStatus: SwiftProtobuf._ProtoNameProviding { - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 0: .same(proto: "UNKNOWN_OPERATION"), - 1: .same(proto: "PENDING_SUBMISSION"), - 2: .same(proto: "AWAIT_CONFIRMATION"), - 3: .same(proto: "CONFIRMED_AND_APPLIED"), - 4: .same(proto: "CONFIRMED_AND_REJECTED"), - ] -} - -extension Io_Iohk_Atala_Prism_Protos_HealthCheckRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".HealthCheckRequest" - static let _protobuf_nameMap = SwiftProtobuf._NameMap() - - mutating func decodeMessage(decoder: inout D) throws { - while let _ = try decoder.nextFieldNumber() {} - } - - func traverse(visitor: inout V) throws { - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_HealthCheckRequest, rhs: Io_Iohk_Atala_Prism_Protos_HealthCheckRequest) -> Bool { - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_HealthCheckResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".HealthCheckResponse" - static let _protobuf_nameMap = SwiftProtobuf._NameMap() - - mutating func decodeMessage(decoder: inout D) throws { - while let _ = try decoder.nextFieldNumber() {} - } - - func traverse(visitor: inout V) throws { - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_HealthCheckResponse, rhs: Io_Iohk_Atala_Prism_Protos_HealthCheckResponse) -> Bool { - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_Date: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".Date" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .same(proto: "year"), - 2: .same(proto: "month"), - 3: .same(proto: "day"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try try decoder.decodeSingularInt32Field(value: &year) - case 2: try try decoder.decodeSingularInt32Field(value: &month) - case 3: try try decoder.decodeSingularInt32Field(value: &day) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if year != 0 { - try visitor.visitSingularInt32Field(value: year, fieldNumber: 1) - } - if month != 0 { - try visitor.visitSingularInt32Field(value: month, fieldNumber: 2) - } - if day != 0 { - try visitor.visitSingularInt32Field(value: day, fieldNumber: 3) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_Date, rhs: Io_Iohk_Atala_Prism_Protos_Date) -> Bool { - if lhs.year != rhs.year { return false } - if lhs.month != rhs.month { return false } - if lhs.day != rhs.day { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_TimeInterval: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".TimeInterval" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .standard(proto: "start_timestamp"), - 2: .standard(proto: "end_timestamp"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try try decoder.decodeSingularMessageField(value: &_startTimestamp) - case 2: try try decoder.decodeSingularMessageField(value: &_endTimestamp) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if let v = _startTimestamp { - try visitor.visitSingularMessageField(value: v, fieldNumber: 1) - } - if let v = _endTimestamp { - try visitor.visitSingularMessageField(value: v, fieldNumber: 2) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_TimeInterval, rhs: Io_Iohk_Atala_Prism_Protos_TimeInterval) -> Bool { - if lhs._startTimestamp != rhs._startTimestamp { return false } - if lhs._endTimestamp != rhs._endTimestamp { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_BlockInfo: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".BlockInfo" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .same(proto: "number"), - 3: .same(proto: "index"), - 4: .same(proto: "timestamp"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try try decoder.decodeSingularInt32Field(value: &number) - case 3: try try decoder.decodeSingularInt32Field(value: &index) - case 4: try try decoder.decodeSingularMessageField(value: &_timestamp) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if number != 0 { - try visitor.visitSingularInt32Field(value: number, fieldNumber: 1) - } - if index != 0 { - try visitor.visitSingularInt32Field(value: index, fieldNumber: 3) - } - if let v = _timestamp { - try visitor.visitSingularMessageField(value: v, fieldNumber: 4) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_BlockInfo, rhs: Io_Iohk_Atala_Prism_Protos_BlockInfo) -> Bool { - if lhs.number != rhs.number { return false } - if lhs.index != rhs.index { return false } - if lhs._timestamp != rhs._timestamp { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_TransactionInfo: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".TransactionInfo" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .standard(proto: "transaction_id"), - 2: .same(proto: "ledger"), - 3: .same(proto: "block"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try try decoder.decodeSingularStringField(value: &transactionID) - case 2: try try decoder.decodeSingularEnumField(value: &ledger) - case 3: try try decoder.decodeSingularMessageField(value: &_block) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if !transactionID.isEmpty { - try visitor.visitSingularStringField(value: transactionID, fieldNumber: 1) - } - if ledger != .unknownLedger { - try visitor.visitSingularEnumField(value: ledger, fieldNumber: 2) - } - if let v = _block { - try visitor.visitSingularMessageField(value: v, fieldNumber: 3) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_TransactionInfo, rhs: Io_Iohk_Atala_Prism_Protos_TransactionInfo) -> Bool { - if lhs.transactionID != rhs.transactionID { return false } - if lhs.ledger != rhs.ledger { return false } - if lhs._block != rhs._block { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} diff --git a/Castor/Sources/protobuf/node_models.pb.swift b/Castor/Sources/protobuf/node_models.pb.swift deleted file mode 100644 index 59b1040c..00000000 --- a/Castor/Sources/protobuf/node_models.pb.swift +++ /dev/null @@ -1,2433 +0,0 @@ -// DO NOT EDIT. -// swift-format-ignore-file -// -// Generated by the Swift generator plugin for the protocol buffer compiler. -// Source: node_models.proto -// -// For information on using the generated types, please see the documentation: -// https://github.com/apple/swift-protobuf/ - -import Foundation -@_implementationOnly import SwiftProtobuf - -// If the compiler emits an error on this type, it is because this file -// was generated by a version of the `protoc` Swift plug-in that is -// incompatible with the version of SwiftProtobuf to which you are linking. -// Please ensure that you are building against the same version of the API -// that was used to generate this file. -private struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { - struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} - typealias Version = _2 -} - -/// Every key has a single purpose: -enum Io_Iohk_Atala_Prism_Protos_KeyUsage: SwiftProtobuf.Enum { - typealias RawValue = Int - - /// UNKNOWN_KEY is an invalid value - Protobuf uses 0 if no value is provided and we want the user to explicitly choose the usage. - case unknownKey // = 0 - - /// This is the most privileged key-type, when any other key is lost, you could use this to recover the others. - case masterKey // = 1 - - /// This key-type is used for issuing credentials only, it should be kept in a safe place - /// to avoid malicious credentials being issued. - case issuingKey // = 2 - - /// This key-type is used for end-to-end encrypted communication, whoever wants to send a message should - /// use this key-type to encrypt the content. - case communicationKey // = 3 - - /// This key-type is used to authenticate requests or logging into services. - case authenticationKey // = 4 - - /// This key-type is used for revoking credentials only, it should be kept in a safe place - /// to avoid malicious credentials being issued. - case revocationKey // = 5 - case UNRECOGNIZED(Int) - - init() { - self = .unknownKey - } - - init?(rawValue: Int) { - switch rawValue { - case 0: self = .unknownKey - case 1: self = .masterKey - case 2: self = .issuingKey - case 3: self = .communicationKey - case 4: self = .authenticationKey - case 5: self = .revocationKey - default: self = .UNRECOGNIZED(rawValue) - } - } - - var rawValue: Int { - switch self { - case .unknownKey: return 0 - case .masterKey: return 1 - case .issuingKey: return 2 - case .communicationKey: return 3 - case .authenticationKey: return 4 - case .revocationKey: return 5 - case let .UNRECOGNIZED(i): return i - } - } -} - -#if swift(>=4.2) - - extension Io_Iohk_Atala_Prism_Protos_KeyUsage: CaseIterable { - // The compiler won't synthesize support with the UNRECOGNIZED case. - static var allCases: [Io_Iohk_Atala_Prism_Protos_KeyUsage] = [ - .unknownKey, - .masterKey, - .issuingKey, - .communicationKey, - .authenticationKey, - .revocationKey, - ] - } - -#endif // swift(>=4.2) - -/// Includes timestamping details about a blockchain's block. -struct Io_Iohk_Atala_Prism_Protos_TimestampInfo { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// The transaction index inside the underlying block. - var blockSequenceNumber: UInt32 = 0 - - /// The operation index inside the AtalaBlock. - var operationSequenceNumber: UInt32 = 0 - - /// The timestamp provided from the underlying blockchain. - var blockTimestamp: SwiftProtobuf.Google_Protobuf_Timestamp { - get { return _blockTimestamp ?? SwiftProtobuf.Google_Protobuf_Timestamp() } - set { _blockTimestamp = newValue } - } - - /// Returns true if `blockTimestamp` has been explicitly set. - var hasBlockTimestamp: Bool { return self._blockTimestamp != nil } - /// Clears the value of `blockTimestamp`. Subsequent reads from it will return its default value. - mutating func clearBlockTimestamp() { _blockTimestamp = nil } - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} - - fileprivate var _blockTimestamp: SwiftProtobuf.Google_Protobuf_Timestamp? -} - -/// * -/// Holds the necessary data to recover an Elliptic Curve (EC)'s public key. -/// @exclude TODO: Consider renaming this to ECPublicKeyData. -struct Io_Iohk_Atala_Prism_Protos_ECKeyData { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// The curve name, like secp256k1. - var curve: String = .init() - - /// The x coordinate, represented as bytes. - var x: Data = .init() - - /// The y coordinate, represented as bytes. - var y: Data = .init() - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} -} - -/// * -/// Holds the compressed representation of data needed to recover Elliptic Curve (EC)'s public key. -/// @exclude TODO: Consider renaming this to CompressedECPublicKeyData. -struct Io_Iohk_Atala_Prism_Protos_CompressedECKeyData { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// The curve name, like secp256k1. - var curve: String = .init() - - /// compressed Elliptic Curve (EC) public key data. - var data: Data = .init() - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} -} - -/// * -/// Represents a public key with metadata, necessary for a DID document. -/// @exclude TODO: Consider renaming this to something more specific, like DIDPublicKey. -struct Io_Iohk_Atala_Prism_Protos_PublicKey { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// The key identifier within the DID Document. - var id: String { - get { return _storage._id } - set { _uniqueStorage()._id = newValue } - } - - /// The key's purpose. - var usage: Io_Iohk_Atala_Prism_Protos_KeyUsage { - get { return _storage._usage } - set { _uniqueStorage()._usage = newValue } - } - - /// The ledger details related to the event that added the key to the DID Document. - var addedOn: Io_Iohk_Atala_Prism_Protos_LedgerData { - get { return _storage._addedOn ?? Io_Iohk_Atala_Prism_Protos_LedgerData() } - set { _uniqueStorage()._addedOn = newValue } - } - - /// Returns true if `addedOn` has been explicitly set. - var hasAddedOn: Bool { return _storage._addedOn != nil } - /// Clears the value of `addedOn`. Subsequent reads from it will return its default value. - mutating func clearAddedOn() { _uniqueStorage()._addedOn = nil } - - /// The ledger details related to the event that revoked the key to the DID Document. - var revokedOn: Io_Iohk_Atala_Prism_Protos_LedgerData { - get { return _storage._revokedOn ?? Io_Iohk_Atala_Prism_Protos_LedgerData() } - set { _uniqueStorage()._revokedOn = newValue } - } - - /// Returns true if `revokedOn` has been explicitly set. - var hasRevokedOn: Bool { return _storage._revokedOn != nil } - /// Clears the value of `revokedOn`. Subsequent reads from it will return its default value. - mutating func clearRevokedOn() { _uniqueStorage()._revokedOn = nil } - - /// The key's representation. - var keyData: OneOf_KeyData? { - get { return _storage._keyData } - set { _uniqueStorage()._keyData = newValue } - } - - /// The Elliptic Curve (EC) key. - var ecKeyData: Io_Iohk_Atala_Prism_Protos_ECKeyData { - get { - if case let .ecKeyData(v)? = _storage._keyData { return v } - return Io_Iohk_Atala_Prism_Protos_ECKeyData() - } - set { _uniqueStorage()._keyData = .ecKeyData(newValue) } - } - - /// Compressed Elliptic Curve (EC) key. - var compressedEcKeyData: Io_Iohk_Atala_Prism_Protos_CompressedECKeyData { - get { - if case let .compressedEcKeyData(v)? = _storage._keyData { return v } - return Io_Iohk_Atala_Prism_Protos_CompressedECKeyData() - } - set { _uniqueStorage()._keyData = .compressedEcKeyData(newValue) } - } - - var unknownFields = SwiftProtobuf.UnknownStorage() - - /// The key's representation. - enum OneOf_KeyData: Equatable { - /// The Elliptic Curve (EC) key. - case ecKeyData(Io_Iohk_Atala_Prism_Protos_ECKeyData) - /// Compressed Elliptic Curve (EC) key. - case compressedEcKeyData(Io_Iohk_Atala_Prism_Protos_CompressedECKeyData) - - #if !swift(>=4.1) - static func == (lhs: Io_Iohk_Atala_Prism_Protos_PublicKey.OneOf_KeyData, rhs: Io_Iohk_Atala_Prism_Protos_PublicKey.OneOf_KeyData) -> Bool { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch (lhs, rhs) { - case (.ecKeyData, .ecKeyData): return { - guard case let .ecKeyData(l) = lhs, case let .ecKeyData(r) = rhs else { preconditionFailure() } - return l == r - }() - case (.compressedEcKeyData, .compressedEcKeyData): return { - guard case let .compressedEcKeyData(l) = lhs, case let .compressedEcKeyData(r) = rhs else { preconditionFailure() } - return l == r - }() - default: return false - } - } - #endif - } - - init() {} - - fileprivate var _storage = _StorageClass.defaultInstance -} - -/// The DID Document's data. -struct Io_Iohk_Atala_Prism_Protos_DIDData { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// The DID suffix, where DID is in form did:prism:[DID suffix] - var id: String = .init() - - /// The keys that belong to this DID Document. - var publicKeys: [Io_Iohk_Atala_Prism_Protos_PublicKey] = [] - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} -} - -/// The operation to create a public DID. -struct Io_Iohk_Atala_Prism_Protos_CreateDIDOperation { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// DIDCreationData with public keys - var didData: Io_Iohk_Atala_Prism_Protos_CreateDIDOperation.DIDCreationData { - get { return _didData ?? Io_Iohk_Atala_Prism_Protos_CreateDIDOperation.DIDCreationData() } - set { _didData = newValue } - } - - /// Returns true if `didData` has been explicitly set. - var hasDidData: Bool { return self._didData != nil } - /// Clears the value of `didData`. Subsequent reads from it will return its default value. - mutating func clearDidData() { _didData = nil } - - var unknownFields = SwiftProtobuf.UnknownStorage() - - /// The data necessary to create a DID. - struct DIDCreationData { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// The keys that belong to this DID Document. - var publicKeys: [Io_Iohk_Atala_Prism_Protos_PublicKey] = [] - - var services: [Io_Iohk_Atala_Prism_Protos_CreateDIDOperation.DIDService] = [] - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} - } - - struct DIDService { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - var id: String = .init() - - var types: [String] = [] - - var serviceEndpoint: String = .init() - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} - } - - init() {} - - fileprivate var _didData: Io_Iohk_Atala_Prism_Protos_CreateDIDOperation.DIDCreationData? -} - -/// The necessary data to add a key to a DID. -struct Io_Iohk_Atala_Prism_Protos_AddKeyAction { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// The key to include. - var key: Io_Iohk_Atala_Prism_Protos_PublicKey { - get { return _key ?? Io_Iohk_Atala_Prism_Protos_PublicKey() } - set { _key = newValue } - } - - /// Returns true if `key` has been explicitly set. - var hasKey: Bool { return self._key != nil } - /// Clears the value of `key`. Subsequent reads from it will return its default value. - mutating func clearKey() { _key = nil } - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} - - fileprivate var _key: Io_Iohk_Atala_Prism_Protos_PublicKey? -} - -/// The necessary data to remove a key from a DID. -struct Io_Iohk_Atala_Prism_Protos_RemoveKeyAction { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// the key id to remove - var keyID: String = .init() - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} -} - -/// The potential details that can be updated in a DID. -struct Io_Iohk_Atala_Prism_Protos_UpdateDIDAction { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// The action to perform. - var action: Io_Iohk_Atala_Prism_Protos_UpdateDIDAction.OneOf_Action? - - /// Used to add a new key to the DID. - var addKey: Io_Iohk_Atala_Prism_Protos_AddKeyAction { - get { - if case let .addKey(v)? = action { return v } - return Io_Iohk_Atala_Prism_Protos_AddKeyAction() - } - set { action = .addKey(newValue) } - } - - /// Used to remove a key from the DID. - var removeKey: Io_Iohk_Atala_Prism_Protos_RemoveKeyAction { - get { - if case let .removeKey(v)? = action { return v } - return Io_Iohk_Atala_Prism_Protos_RemoveKeyAction() - } - set { action = .removeKey(newValue) } - } - - var unknownFields = SwiftProtobuf.UnknownStorage() - - /// The action to perform. - enum OneOf_Action: Equatable { - /// Used to add a new key to the DID. - case addKey(Io_Iohk_Atala_Prism_Protos_AddKeyAction) - /// Used to remove a key from the DID. - case removeKey(Io_Iohk_Atala_Prism_Protos_RemoveKeyAction) - - #if !swift(>=4.1) - static func == (lhs: Io_Iohk_Atala_Prism_Protos_UpdateDIDAction.OneOf_Action, rhs: Io_Iohk_Atala_Prism_Protos_UpdateDIDAction.OneOf_Action) -> Bool { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch (lhs, rhs) { - case (.addKey, .addKey): return { - guard case let .addKey(l) = lhs, case let .addKey(r) = rhs else { preconditionFailure() } - return l == r - }() - case (.removeKey, .removeKey): return { - guard case let .removeKey(l) = lhs, case let .removeKey(r) = rhs else { preconditionFailure() } - return l == r - }() - default: return false - } - } - #endif - } - - init() {} -} - -/// Specifies the necessary data to update a public DID. -struct Io_Iohk_Atala_Prism_Protos_UpdateDIDOperation { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// The hash of the operation that issued the DID. - var previousOperationHash: Data = .init() - - /// @exclude TODO: To be redefined after we start using this operation. - var id: String = .init() - - /// The actual updates to perform on the DID. - var actions: [Io_Iohk_Atala_Prism_Protos_UpdateDIDAction] = [] - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} -} - -/// Represents a credential's batch. -/// -/// Check the protocol docs to understand it. -struct Io_Iohk_Atala_Prism_Protos_CredentialBatchData { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// The DID suffix that issues the credential's batch. - var issuerDid: String = .init() - - /// The Merkle root for the credential's batch. - var merkleRoot: Data = .init() - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} -} - -/// Specifies the data to issue a credential batch. -struct Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOperation { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// The actual credential batch data. - var credentialBatchData: Io_Iohk_Atala_Prism_Protos_CredentialBatchData { - get { return _credentialBatchData ?? Io_Iohk_Atala_Prism_Protos_CredentialBatchData() } - set { _credentialBatchData = newValue } - } - - /// Returns true if `credentialBatchData` has been explicitly set. - var hasCredentialBatchData: Bool { return self._credentialBatchData != nil } - /// Clears the value of `credentialBatchData`. Subsequent reads from it will return its default value. - mutating func clearCredentialBatchData() { _credentialBatchData = nil } - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} - - fileprivate var _credentialBatchData: Io_Iohk_Atala_Prism_Protos_CredentialBatchData? -} - -/// Specifies the credentials to revoke (the whole batch, or just a subset of it). -struct Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOperation { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// The hash of the operation that issued the batch. - var previousOperationHash: Data = .init() - - /// The corresponding batch ID, as returned in IssueCredentialBatchResponse. - var credentialBatchID: String = .init() - - /// The hashes of the credentials to revoke. If empty, the full batch is revoked. - var credentialsToRevoke: [Data] = [] - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} -} - -/// Specifies the protocol version update -struct Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOperation { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// The DID suffix that proposes the protocol update. - var proposerDid: String = .init() - - /// Information of the new version - var version: Io_Iohk_Atala_Prism_Protos_ProtocolVersionInfo { - get { return _version ?? Io_Iohk_Atala_Prism_Protos_ProtocolVersionInfo() } - set { _version = newValue } - } - - /// Returns true if `version` has been explicitly set. - var hasVersion: Bool { return self._version != nil } - /// Clears the value of `version`. Subsequent reads from it will return its default value. - mutating func clearVersion() { _version = nil } - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} - - fileprivate var _version: Io_Iohk_Atala_Prism_Protos_ProtocolVersionInfo? -} - -struct Io_Iohk_Atala_Prism_Protos_ProtocolVersion { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// Represent the major version - var majorVersion: Int32 = 0 - - /// Represent the minor version - var minorVersion: Int32 = 0 - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} -} - -struct Io_Iohk_Atala_Prism_Protos_ProtocolVersionInfo { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// (optional) name of the version - var versionName: String = .init() - - /// Cardano block number that tells since which block the update is enforced - var effectiveSince: Int32 = 0 - - /// New major and minor version to be announced, - /// If major value changes, the node MUST stop issuing and reading operations, and upgrade before `effective_since` because the new protocol version. - /// If minor value changes, the node can opt to not update. All events _published_ by this node would be also - /// understood by other nodes with the same major version. However, there may be new events that this node won't _read_ - var protocolVersion: Io_Iohk_Atala_Prism_Protos_ProtocolVersion { - get { return _protocolVersion ?? Io_Iohk_Atala_Prism_Protos_ProtocolVersion() } - set { _protocolVersion = newValue } - } - - /// Returns true if `protocolVersion` has been explicitly set. - var hasProtocolVersion: Bool { return self._protocolVersion != nil } - /// Clears the value of `protocolVersion`. Subsequent reads from it will return its default value. - mutating func clearProtocolVersion() { _protocolVersion = nil } - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} - - fileprivate var _protocolVersion: Io_Iohk_Atala_Prism_Protos_ProtocolVersion? -} - -struct Io_Iohk_Atala_Prism_Protos_DeactivateDIDOperation { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// The hash of the operation that issued the DID. - var previousOperationHash: Data = .init() - - /// DID Suffix of the DID to be deactivated - var id: String = .init() - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} -} - -/// The possible operations affecting the blockchain. -struct Io_Iohk_Atala_Prism_Protos_AtalaOperation { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// The actual operation. - var operation: Io_Iohk_Atala_Prism_Protos_AtalaOperation.OneOf_Operation? - - /// Used to create a public DID. - var createDid: Io_Iohk_Atala_Prism_Protos_CreateDIDOperation { - get { - if case let .createDid(v)? = operation { return v } - return Io_Iohk_Atala_Prism_Protos_CreateDIDOperation() - } - set { operation = .createDid(newValue) } - } - - /// Used to update an existing public DID. - var updateDid: Io_Iohk_Atala_Prism_Protos_UpdateDIDOperation { - get { - if case let .updateDid(v)? = operation { return v } - return Io_Iohk_Atala_Prism_Protos_UpdateDIDOperation() - } - set { operation = .updateDid(newValue) } - } - - /// Used to issue a batch of credentials. - var issueCredentialBatch: Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOperation { - get { - if case let .issueCredentialBatch(v)? = operation { return v } - return Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOperation() - } - set { operation = .issueCredentialBatch(newValue) } - } - - /// Used to revoke a credential batch. - var revokeCredentials: Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOperation { - get { - if case let .revokeCredentials(v)? = operation { return v } - return Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOperation() - } - set { operation = .revokeCredentials(newValue) } - } - - /// Used to announce new protocol update - var protocolVersionUpdate: Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOperation { - get { - if case let .protocolVersionUpdate(v)? = operation { return v } - return Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOperation() - } - set { operation = .protocolVersionUpdate(newValue) } - } - - /// Used to deactivate DID - var deactivateDid: Io_Iohk_Atala_Prism_Protos_DeactivateDIDOperation { - get { - if case let .deactivateDid(v)? = operation { return v } - return Io_Iohk_Atala_Prism_Protos_DeactivateDIDOperation() - } - set { operation = .deactivateDid(newValue) } - } - - var unknownFields = SwiftProtobuf.UnknownStorage() - - /// The actual operation. - enum OneOf_Operation: Equatable { - /// Used to create a public DID. - case createDid(Io_Iohk_Atala_Prism_Protos_CreateDIDOperation) - /// Used to update an existing public DID. - case updateDid(Io_Iohk_Atala_Prism_Protos_UpdateDIDOperation) - /// Used to issue a batch of credentials. - case issueCredentialBatch(Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOperation) - /// Used to revoke a credential batch. - case revokeCredentials(Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOperation) - /// Used to announce new protocol update - case protocolVersionUpdate(Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOperation) - /// Used to deactivate DID - case deactivateDid(Io_Iohk_Atala_Prism_Protos_DeactivateDIDOperation) - - #if !swift(>=4.1) - static func == (lhs: Io_Iohk_Atala_Prism_Protos_AtalaOperation.OneOf_Operation, rhs: Io_Iohk_Atala_Prism_Protos_AtalaOperation.OneOf_Operation) -> Bool { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch (lhs, rhs) { - case (.createDid, .createDid): return { - guard case let .createDid(l) = lhs, case let .createDid(r) = rhs else { preconditionFailure() } - return l == r - }() - case (.updateDid, .updateDid): return { - guard case let .updateDid(l) = lhs, case let .updateDid(r) = rhs else { preconditionFailure() } - return l == r - }() - case (.issueCredentialBatch, .issueCredentialBatch): return { - guard case let .issueCredentialBatch(l) = lhs, case let .issueCredentialBatch(r) = rhs else { preconditionFailure() } - return l == r - }() - case (.revokeCredentials, .revokeCredentials): return { - guard case let .revokeCredentials(l) = lhs, case let .revokeCredentials(r) = rhs else { preconditionFailure() } - return l == r - }() - case (.protocolVersionUpdate, .protocolVersionUpdate): return { - guard case let .protocolVersionUpdate(l) = lhs, case let .protocolVersionUpdate(r) = rhs else { preconditionFailure() } - return l == r - }() - case (.deactivateDid, .deactivateDid): return { - guard case let .deactivateDid(l) = lhs, case let .deactivateDid(r) = rhs else { preconditionFailure() } - return l == r - }() - default: return false - } - } - #endif - } - - init() {} -} - -/// A signed operation, necessary to post anything on the blockchain. -struct Io_Iohk_Atala_Prism_Protos_SignedAtalaOperation { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// The key ID used to sign the operation, it must belong to the DID that signs the operation. - var signedWith: String = .init() - - /// The actual signature. - var signature: Data = .init() - - /// The operation that was signed. - var operation: Io_Iohk_Atala_Prism_Protos_AtalaOperation { - get { return _operation ?? Io_Iohk_Atala_Prism_Protos_AtalaOperation() } - set { _operation = newValue } - } - - /// Returns true if `operation` has been explicitly set. - var hasOperation: Bool { return self._operation != nil } - /// Clears the value of `operation`. Subsequent reads from it will return its default value. - mutating func clearOperation() { _operation = nil } - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} - - fileprivate var _operation: Io_Iohk_Atala_Prism_Protos_AtalaOperation? -} - -/// Ledger data associated to a protocol event. -/// Note that the difference with TransactionInfo is that this message contains a full -/// timestamp, and there is no expectation for it to be optional. -struct Io_Iohk_Atala_Prism_Protos_LedgerData { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - /// ID of the transaction. - var transactionID: String = .init() - - /// Ledger the transaction was published to. - var ledger: Io_Iohk_Atala_Prism_Protos_Ledger = .unknownLedger - - /// The timestamp of the protocol event. - var timestampInfo: Io_Iohk_Atala_Prism_Protos_TimestampInfo { - get { return _timestampInfo ?? Io_Iohk_Atala_Prism_Protos_TimestampInfo() } - set { _timestampInfo = newValue } - } - - /// Returns true if `timestampInfo` has been explicitly set. - var hasTimestampInfo: Bool { return self._timestampInfo != nil } - /// Clears the value of `timestampInfo`. Subsequent reads from it will return its default value. - mutating func clearTimestampInfo() { _timestampInfo = nil } - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} - - fileprivate var _timestampInfo: Io_Iohk_Atala_Prism_Protos_TimestampInfo? -} - -/// Used to encode the responses of the operations issued in an AtalaBlock. -struct Io_Iohk_Atala_Prism_Protos_OperationOutput { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - var result: Io_Iohk_Atala_Prism_Protos_OperationOutput.OneOf_Result? - - /// Represents the response provided by IssueCredentialBatchOperation. - var batchOutput: Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOutput { - get { - if case let .batchOutput(v)? = result { return v } - return Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOutput() - } - set { result = .batchOutput(newValue) } - } - - /// Represents the response provided by CreateDIDOperation. - var createDidOutput: Io_Iohk_Atala_Prism_Protos_CreateDIDOutput { - get { - if case let .createDidOutput(v)? = result { return v } - return Io_Iohk_Atala_Prism_Protos_CreateDIDOutput() - } - set { result = .createDidOutput(newValue) } - } - - /// Represents the response provided by UpdateDIDOperation. - var updateDidOutput: Io_Iohk_Atala_Prism_Protos_UpdateDIDOutput { - get { - if case let .updateDidOutput(v)? = result { return v } - return Io_Iohk_Atala_Prism_Protos_UpdateDIDOutput() - } - set { result = .updateDidOutput(newValue) } - } - - /// Represents the response provided by RevokeCredentialOperation. - var revokeCredentialsOutput: Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOutput { - get { - if case let .revokeCredentialsOutput(v)? = result { return v } - return Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOutput() - } - set { result = .revokeCredentialsOutput(newValue) } - } - - /// Represents the response provided by ProtocolVersionUpdateOperation. - var protocolVersionUpdateOutput: Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOutput { - get { - if case let .protocolVersionUpdateOutput(v)? = result { return v } - return Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOutput() - } - set { result = .protocolVersionUpdateOutput(newValue) } - } - - var deactivateDidOutput: Io_Iohk_Atala_Prism_Protos_DeactivateDIDOutput { - get { - if case let .deactivateDidOutput(v)? = result { return v } - return Io_Iohk_Atala_Prism_Protos_DeactivateDIDOutput() - } - set { result = .deactivateDidOutput(newValue) } - } - - var operationMaybe: Io_Iohk_Atala_Prism_Protos_OperationOutput.OneOf_OperationMaybe? - - /// Operation identifier. - var operationID: Data { - get { - if case let .operationID(v)? = operationMaybe { return v } - return Data() - } - set { operationMaybe = .operationID(newValue) } - } - - /// Error description if PRISM Node service haven't scheduled the operation. - var error: String { - get { - if case let .error(v)? = operationMaybe { return v } - return String() - } - set { operationMaybe = .error(newValue) } - } - - var unknownFields = SwiftProtobuf.UnknownStorage() - - enum OneOf_Result: Equatable { - /// Represents the response provided by IssueCredentialBatchOperation. - case batchOutput(Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOutput) - /// Represents the response provided by CreateDIDOperation. - case createDidOutput(Io_Iohk_Atala_Prism_Protos_CreateDIDOutput) - /// Represents the response provided by UpdateDIDOperation. - case updateDidOutput(Io_Iohk_Atala_Prism_Protos_UpdateDIDOutput) - /// Represents the response provided by RevokeCredentialOperation. - case revokeCredentialsOutput(Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOutput) - /// Represents the response provided by ProtocolVersionUpdateOperation. - case protocolVersionUpdateOutput(Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOutput) - case deactivateDidOutput(Io_Iohk_Atala_Prism_Protos_DeactivateDIDOutput) - - #if !swift(>=4.1) - static func == (lhs: Io_Iohk_Atala_Prism_Protos_OperationOutput.OneOf_Result, rhs: Io_Iohk_Atala_Prism_Protos_OperationOutput.OneOf_Result) -> Bool { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch (lhs, rhs) { - case (.batchOutput, .batchOutput): return { - guard case let .batchOutput(l) = lhs, case let .batchOutput(r) = rhs else { preconditionFailure() } - return l == r - }() - case (.createDidOutput, .createDidOutput): return { - guard case let .createDidOutput(l) = lhs, case let .createDidOutput(r) = rhs else { preconditionFailure() } - return l == r - }() - case (.updateDidOutput, .updateDidOutput): return { - guard case let .updateDidOutput(l) = lhs, case let .updateDidOutput(r) = rhs else { preconditionFailure() } - return l == r - }() - case (.revokeCredentialsOutput, .revokeCredentialsOutput): return { - guard case let .revokeCredentialsOutput(l) = lhs, case let .revokeCredentialsOutput(r) = rhs else { preconditionFailure() } - return l == r - }() - case (.protocolVersionUpdateOutput, .protocolVersionUpdateOutput): return { - guard case let .protocolVersionUpdateOutput(l) = lhs, case let .protocolVersionUpdateOutput(r) = rhs else { preconditionFailure() } - return l == r - }() - case (.deactivateDidOutput, .deactivateDidOutput): return { - guard case let .deactivateDidOutput(l) = lhs, case let .deactivateDidOutput(r) = rhs else { preconditionFailure() } - return l == r - }() - default: return false - } - } - #endif - } - - enum OneOf_OperationMaybe: Equatable { - /// Operation identifier. - case operationID(Data) - /// Error description if PRISM Node service haven't scheduled the operation. - case error(String) - - #if !swift(>=4.1) - static func == (lhs: Io_Iohk_Atala_Prism_Protos_OperationOutput.OneOf_OperationMaybe, rhs: Io_Iohk_Atala_Prism_Protos_OperationOutput.OneOf_OperationMaybe) -> Bool { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch (lhs, rhs) { - case (.operationID, .operationID): return { - guard case let .operationID(l) = lhs, case let .operationID(r) = rhs else { preconditionFailure() } - return l == r - }() - case (.error, .error): return { - guard case let .error(l) = lhs, case let .error(r) = rhs else { preconditionFailure() } - return l == r - }() - default: return false - } - } - #endif - } - - init() {} -} - -struct Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOutput { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - var batchID: String = .init() - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} -} - -struct Io_Iohk_Atala_Prism_Protos_CreateDIDOutput { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - var didSuffix: String = .init() - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} -} - -struct Io_Iohk_Atala_Prism_Protos_UpdateDIDOutput { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} -} - -struct Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOutput { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} -} - -struct Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOutput { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} -} - -struct Io_Iohk_Atala_Prism_Protos_DeactivateDIDOutput { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. - - var unknownFields = SwiftProtobuf.UnknownStorage() - - init() {} -} - -// MARK: - Code below here is support for the SwiftProtobuf runtime. - -private let _protobuf_package = "io.iohk.atala.prism.protos" - -extension Io_Iohk_Atala_Prism_Protos_KeyUsage: SwiftProtobuf._ProtoNameProviding { - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 0: .same(proto: "UNKNOWN_KEY"), - 1: .same(proto: "MASTER_KEY"), - 2: .same(proto: "ISSUING_KEY"), - 3: .same(proto: "COMMUNICATION_KEY"), - 4: .same(proto: "AUTHENTICATION_KEY"), - 5: .same(proto: "REVOCATION_KEY"), - ] -} - -extension Io_Iohk_Atala_Prism_Protos_TimestampInfo: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".TimestampInfo" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 2: .standard(proto: "block_sequence_number"), - 3: .standard(proto: "operation_sequence_number"), - 4: .standard(proto: "block_timestamp"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 2: try try decoder.decodeSingularUInt32Field(value: &blockSequenceNumber) - case 3: try try decoder.decodeSingularUInt32Field(value: &operationSequenceNumber) - case 4: try try decoder.decodeSingularMessageField(value: &_blockTimestamp) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if blockSequenceNumber != 0 { - try visitor.visitSingularUInt32Field(value: blockSequenceNumber, fieldNumber: 2) - } - if operationSequenceNumber != 0 { - try visitor.visitSingularUInt32Field(value: operationSequenceNumber, fieldNumber: 3) - } - if let v = _blockTimestamp { - try visitor.visitSingularMessageField(value: v, fieldNumber: 4) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_TimestampInfo, rhs: Io_Iohk_Atala_Prism_Protos_TimestampInfo) -> Bool { - if lhs.blockSequenceNumber != rhs.blockSequenceNumber { return false } - if lhs.operationSequenceNumber != rhs.operationSequenceNumber { return false } - if lhs._blockTimestamp != rhs._blockTimestamp { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_ECKeyData: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".ECKeyData" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .same(proto: "curve"), - 2: .same(proto: "x"), - 3: .same(proto: "y"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try try decoder.decodeSingularStringField(value: &curve) - case 2: try try decoder.decodeSingularBytesField(value: &x) - case 3: try try decoder.decodeSingularBytesField(value: &y) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if !curve.isEmpty { - try visitor.visitSingularStringField(value: curve, fieldNumber: 1) - } - if !x.isEmpty { - try visitor.visitSingularBytesField(value: x, fieldNumber: 2) - } - if !y.isEmpty { - try visitor.visitSingularBytesField(value: y, fieldNumber: 3) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_ECKeyData, rhs: Io_Iohk_Atala_Prism_Protos_ECKeyData) -> Bool { - if lhs.curve != rhs.curve { return false } - if lhs.x != rhs.x { return false } - if lhs.y != rhs.y { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_CompressedECKeyData: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".CompressedECKeyData" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .same(proto: "curve"), - 2: .same(proto: "data"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try try decoder.decodeSingularStringField(value: &curve) - case 2: try try decoder.decodeSingularBytesField(value: &data) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if !curve.isEmpty { - try visitor.visitSingularStringField(value: curve, fieldNumber: 1) - } - if !data.isEmpty { - try visitor.visitSingularBytesField(value: data, fieldNumber: 2) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_CompressedECKeyData, rhs: Io_Iohk_Atala_Prism_Protos_CompressedECKeyData) -> Bool { - if lhs.curve != rhs.curve { return false } - if lhs.data != rhs.data { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_PublicKey: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".PublicKey" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .same(proto: "id"), - 2: .same(proto: "usage"), - 5: .standard(proto: "added_on"), - 6: .standard(proto: "revoked_on"), - 8: .standard(proto: "ec_key_data"), - 9: .standard(proto: "compressed_ec_key_data"), - ] - - fileprivate class _StorageClass { - var _id: String = .init() - var _usage: Io_Iohk_Atala_Prism_Protos_KeyUsage = .unknownKey - var _addedOn: Io_Iohk_Atala_Prism_Protos_LedgerData? - var _revokedOn: Io_Iohk_Atala_Prism_Protos_LedgerData? - var _keyData: Io_Iohk_Atala_Prism_Protos_PublicKey.OneOf_KeyData? - - static let defaultInstance = _StorageClass() - - private init() {} - - init(copying source: _StorageClass) { - _id = source._id - _usage = source._usage - _addedOn = source._addedOn - _revokedOn = source._revokedOn - _keyData = source._keyData - } - } - - fileprivate mutating func _uniqueStorage() -> _StorageClass { - if !isKnownUniquelyReferenced(&_storage) { - _storage = _StorageClass(copying: _storage) - } - return _storage - } - - mutating func decodeMessage(decoder: inout D) throws { - _ = _uniqueStorage() - try withExtendedLifetime(_storage) { (_storage: _StorageClass) in - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try try decoder.decodeSingularStringField(value: &_storage._id) - case 2: try try decoder.decodeSingularEnumField(value: &_storage._usage) - case 5: try try decoder.decodeSingularMessageField(value: &_storage._addedOn) - case 6: try try decoder.decodeSingularMessageField(value: &_storage._revokedOn) - case 8: try { - var v: Io_Iohk_Atala_Prism_Protos_ECKeyData? - var hadOneofValue = false - if let current = _storage._keyData { - hadOneofValue = true - if case let .ecKeyData(m) = current { v = m } - } - try decoder.decodeSingularMessageField(value: &v) - if let v = v { - if hadOneofValue { try decoder.handleConflictingOneOf() } - _storage._keyData = .ecKeyData(v) - } - }() - case 9: try { - var v: Io_Iohk_Atala_Prism_Protos_CompressedECKeyData? - var hadOneofValue = false - if let current = _storage._keyData { - hadOneofValue = true - if case let .compressedEcKeyData(m) = current { v = m } - } - try decoder.decodeSingularMessageField(value: &v) - if let v = v { - if hadOneofValue { try decoder.handleConflictingOneOf() } - _storage._keyData = .compressedEcKeyData(v) - } - }() - default: break - } - } - } - } - - func traverse(visitor: inout V) throws { - try withExtendedLifetime(_storage) { (_storage: _StorageClass) in - if !_storage._id.isEmpty { - try visitor.visitSingularStringField(value: _storage._id, fieldNumber: 1) - } - if _storage._usage != .unknownKey { - try visitor.visitSingularEnumField(value: _storage._usage, fieldNumber: 2) - } - if let v = _storage._addedOn { - try visitor.visitSingularMessageField(value: v, fieldNumber: 5) - } - if let v = _storage._revokedOn { - try visitor.visitSingularMessageField(value: v, fieldNumber: 6) - } - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch _storage._keyData { - case .ecKeyData?: try { - guard case let .ecKeyData(v)? = _storage._keyData else { preconditionFailure() } - try visitor.visitSingularMessageField(value: v, fieldNumber: 8) - }() - case .compressedEcKeyData?: try { - guard case let .compressedEcKeyData(v)? = _storage._keyData else { preconditionFailure() } - try visitor.visitSingularMessageField(value: v, fieldNumber: 9) - }() - case nil: break - } - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_PublicKey, rhs: Io_Iohk_Atala_Prism_Protos_PublicKey) -> Bool { - if lhs._storage !== rhs._storage { - let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in - let _storage = _args.0 - let rhs_storage = _args.1 - if _storage._id != rhs_storage._id { return false } - if _storage._usage != rhs_storage._usage { return false } - if _storage._addedOn != rhs_storage._addedOn { return false } - if _storage._revokedOn != rhs_storage._revokedOn { return false } - if _storage._keyData != rhs_storage._keyData { return false } - return true - } - if !storagesAreEqual { return false } - } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_DIDData: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".DIDData" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .same(proto: "id"), - 2: .standard(proto: "public_keys"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try try decoder.decodeSingularStringField(value: &id) - case 2: try try decoder.decodeRepeatedMessageField(value: &publicKeys) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if !id.isEmpty { - try visitor.visitSingularStringField(value: id, fieldNumber: 1) - } - if !publicKeys.isEmpty { - try visitor.visitRepeatedMessageField(value: publicKeys, fieldNumber: 2) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_DIDData, rhs: Io_Iohk_Atala_Prism_Protos_DIDData) -> Bool { - if lhs.id != rhs.id { return false } - if lhs.publicKeys != rhs.publicKeys { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_CreateDIDOperation: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".CreateDIDOperation" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .standard(proto: "did_data"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try try decoder.decodeSingularMessageField(value: &_didData) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if let v = _didData { - try visitor.visitSingularMessageField(value: v, fieldNumber: 1) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_CreateDIDOperation, rhs: Io_Iohk_Atala_Prism_Protos_CreateDIDOperation) -> Bool { - if lhs._didData != rhs._didData { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_CreateDIDOperation.DIDCreationData: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = Io_Iohk_Atala_Prism_Protos_CreateDIDOperation.protoMessageName + ".DIDCreationData" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 2: .standard(proto: "public_keys"), - 3: .same(proto: "services"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 2: try try decoder.decodeRepeatedMessageField(value: &publicKeys) - case 3: try try decoder.decodeRepeatedMessageField(value: &services) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if !publicKeys.isEmpty { - try visitor.visitRepeatedMessageField(value: publicKeys, fieldNumber: 2) - } - if !services.isEmpty { - try visitor.visitRepeatedMessageField(value: services, fieldNumber: 3) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_CreateDIDOperation.DIDCreationData, rhs: Io_Iohk_Atala_Prism_Protos_CreateDIDOperation.DIDCreationData) -> Bool { - if lhs.publicKeys != rhs.publicKeys { return false } - if lhs.services != rhs.services { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_CreateDIDOperation.DIDService: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = Io_Iohk_Atala_Prism_Protos_CreateDIDOperation.protoMessageName + ".DIDService" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .same(proto: "id"), - 2: .same(proto: "types"), - 3: .same(proto: "serviceEndpoint"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try try decoder.decodeSingularStringField(value: &id) - case 2: try try decoder.decodeRepeatedStringField(value: &types) - case 3: try try decoder.decodeSingularStringField(value: &serviceEndpoint) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if !id.isEmpty { - try visitor.visitSingularStringField(value: id, fieldNumber: 1) - } - if !types.isEmpty { - try visitor.visitRepeatedStringField(value: types, fieldNumber: 2) - } - if !serviceEndpoint.isEmpty { - try visitor.visitSingularStringField(value: serviceEndpoint, fieldNumber: 3) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_CreateDIDOperation.DIDService, rhs: Io_Iohk_Atala_Prism_Protos_CreateDIDOperation.DIDService) -> Bool { - if lhs.id != rhs.id { return false } - if lhs.types != rhs.types { return false } - if lhs.serviceEndpoint != rhs.serviceEndpoint { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_AddKeyAction: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".AddKeyAction" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .same(proto: "key"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try try decoder.decodeSingularMessageField(value: &_key) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if let v = _key { - try visitor.visitSingularMessageField(value: v, fieldNumber: 1) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_AddKeyAction, rhs: Io_Iohk_Atala_Prism_Protos_AddKeyAction) -> Bool { - if lhs._key != rhs._key { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_RemoveKeyAction: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".RemoveKeyAction" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .same(proto: "keyId"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try try decoder.decodeSingularStringField(value: &keyID) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if !keyID.isEmpty { - try visitor.visitSingularStringField(value: keyID, fieldNumber: 1) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_RemoveKeyAction, rhs: Io_Iohk_Atala_Prism_Protos_RemoveKeyAction) -> Bool { - if lhs.keyID != rhs.keyID { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_UpdateDIDAction: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".UpdateDIDAction" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .standard(proto: "add_key"), - 2: .standard(proto: "remove_key"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try { - var v: Io_Iohk_Atala_Prism_Protos_AddKeyAction? - var hadOneofValue = false - if let current = self.action { - hadOneofValue = true - if case let .addKey(m) = current { v = m } - } - try decoder.decodeSingularMessageField(value: &v) - if let v = v { - if hadOneofValue { try decoder.handleConflictingOneOf() } - self.action = .addKey(v) - } - }() - case 2: try { - var v: Io_Iohk_Atala_Prism_Protos_RemoveKeyAction? - var hadOneofValue = false - if let current = self.action { - hadOneofValue = true - if case let .removeKey(m) = current { v = m } - } - try decoder.decodeSingularMessageField(value: &v) - if let v = v { - if hadOneofValue { try decoder.handleConflictingOneOf() } - self.action = .removeKey(v) - } - }() - default: break - } - } - } - - func traverse(visitor: inout V) throws { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch action { - case .addKey?: try { - guard case let .addKey(v)? = self.action else { preconditionFailure() } - try visitor.visitSingularMessageField(value: v, fieldNumber: 1) - }() - case .removeKey?: try { - guard case let .removeKey(v)? = self.action else { preconditionFailure() } - try visitor.visitSingularMessageField(value: v, fieldNumber: 2) - }() - case nil: break - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_UpdateDIDAction, rhs: Io_Iohk_Atala_Prism_Protos_UpdateDIDAction) -> Bool { - if lhs.action != rhs.action { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_UpdateDIDOperation: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".UpdateDIDOperation" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .standard(proto: "previous_operation_hash"), - 2: .same(proto: "id"), - 3: .same(proto: "actions"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try try decoder.decodeSingularBytesField(value: &previousOperationHash) - case 2: try try decoder.decodeSingularStringField(value: &id) - case 3: try try decoder.decodeRepeatedMessageField(value: &actions) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if !previousOperationHash.isEmpty { - try visitor.visitSingularBytesField(value: previousOperationHash, fieldNumber: 1) - } - if !id.isEmpty { - try visitor.visitSingularStringField(value: id, fieldNumber: 2) - } - if !actions.isEmpty { - try visitor.visitRepeatedMessageField(value: actions, fieldNumber: 3) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_UpdateDIDOperation, rhs: Io_Iohk_Atala_Prism_Protos_UpdateDIDOperation) -> Bool { - if lhs.previousOperationHash != rhs.previousOperationHash { return false } - if lhs.id != rhs.id { return false } - if lhs.actions != rhs.actions { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_CredentialBatchData: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".CredentialBatchData" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .standard(proto: "issuer_did"), - 2: .standard(proto: "merkle_root"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try try decoder.decodeSingularStringField(value: &issuerDid) - case 2: try try decoder.decodeSingularBytesField(value: &merkleRoot) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if !issuerDid.isEmpty { - try visitor.visitSingularStringField(value: issuerDid, fieldNumber: 1) - } - if !merkleRoot.isEmpty { - try visitor.visitSingularBytesField(value: merkleRoot, fieldNumber: 2) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_CredentialBatchData, rhs: Io_Iohk_Atala_Prism_Protos_CredentialBatchData) -> Bool { - if lhs.issuerDid != rhs.issuerDid { return false } - if lhs.merkleRoot != rhs.merkleRoot { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOperation: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".IssueCredentialBatchOperation" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .standard(proto: "credential_batch_data"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try try decoder.decodeSingularMessageField(value: &_credentialBatchData) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if let v = _credentialBatchData { - try visitor.visitSingularMessageField(value: v, fieldNumber: 1) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOperation, rhs: Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOperation) -> Bool { - if lhs._credentialBatchData != rhs._credentialBatchData { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOperation: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".RevokeCredentialsOperation" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .standard(proto: "previous_operation_hash"), - 2: .standard(proto: "credential_batch_id"), - 3: .standard(proto: "credentials_to_revoke"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try try decoder.decodeSingularBytesField(value: &previousOperationHash) - case 2: try try decoder.decodeSingularStringField(value: &credentialBatchID) - case 3: try try decoder.decodeRepeatedBytesField(value: &credentialsToRevoke) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if !previousOperationHash.isEmpty { - try visitor.visitSingularBytesField(value: previousOperationHash, fieldNumber: 1) - } - if !credentialBatchID.isEmpty { - try visitor.visitSingularStringField(value: credentialBatchID, fieldNumber: 2) - } - if !credentialsToRevoke.isEmpty { - try visitor.visitRepeatedBytesField(value: credentialsToRevoke, fieldNumber: 3) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOperation, rhs: Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOperation) -> Bool { - if lhs.previousOperationHash != rhs.previousOperationHash { return false } - if lhs.credentialBatchID != rhs.credentialBatchID { return false } - if lhs.credentialsToRevoke != rhs.credentialsToRevoke { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOperation: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".ProtocolVersionUpdateOperation" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .standard(proto: "proposer_did"), - 2: .same(proto: "version"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try try decoder.decodeSingularStringField(value: &proposerDid) - case 2: try try decoder.decodeSingularMessageField(value: &_version) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if !proposerDid.isEmpty { - try visitor.visitSingularStringField(value: proposerDid, fieldNumber: 1) - } - if let v = _version { - try visitor.visitSingularMessageField(value: v, fieldNumber: 2) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOperation, rhs: Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOperation) -> Bool { - if lhs.proposerDid != rhs.proposerDid { return false } - if lhs._version != rhs._version { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_ProtocolVersion: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".ProtocolVersion" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .standard(proto: "major_version"), - 2: .standard(proto: "minor_version"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try try decoder.decodeSingularInt32Field(value: &majorVersion) - case 2: try try decoder.decodeSingularInt32Field(value: &minorVersion) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if majorVersion != 0 { - try visitor.visitSingularInt32Field(value: majorVersion, fieldNumber: 1) - } - if minorVersion != 0 { - try visitor.visitSingularInt32Field(value: minorVersion, fieldNumber: 2) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_ProtocolVersion, rhs: Io_Iohk_Atala_Prism_Protos_ProtocolVersion) -> Bool { - if lhs.majorVersion != rhs.majorVersion { return false } - if lhs.minorVersion != rhs.minorVersion { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_ProtocolVersionInfo: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".ProtocolVersionInfo" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .standard(proto: "version_name"), - 4: .standard(proto: "effective_since"), - 5: .standard(proto: "protocol_version"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try try decoder.decodeSingularStringField(value: &versionName) - case 4: try try decoder.decodeSingularInt32Field(value: &effectiveSince) - case 5: try try decoder.decodeSingularMessageField(value: &_protocolVersion) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if !versionName.isEmpty { - try visitor.visitSingularStringField(value: versionName, fieldNumber: 1) - } - if effectiveSince != 0 { - try visitor.visitSingularInt32Field(value: effectiveSince, fieldNumber: 4) - } - if let v = _protocolVersion { - try visitor.visitSingularMessageField(value: v, fieldNumber: 5) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_ProtocolVersionInfo, rhs: Io_Iohk_Atala_Prism_Protos_ProtocolVersionInfo) -> Bool { - if lhs.versionName != rhs.versionName { return false } - if lhs.effectiveSince != rhs.effectiveSince { return false } - if lhs._protocolVersion != rhs._protocolVersion { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_DeactivateDIDOperation: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".DeactivateDIDOperation" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .standard(proto: "previous_operation_hash"), - 2: .same(proto: "id"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try try decoder.decodeSingularBytesField(value: &previousOperationHash) - case 2: try try decoder.decodeSingularStringField(value: &id) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if !previousOperationHash.isEmpty { - try visitor.visitSingularBytesField(value: previousOperationHash, fieldNumber: 1) - } - if !id.isEmpty { - try visitor.visitSingularStringField(value: id, fieldNumber: 2) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_DeactivateDIDOperation, rhs: Io_Iohk_Atala_Prism_Protos_DeactivateDIDOperation) -> Bool { - if lhs.previousOperationHash != rhs.previousOperationHash { return false } - if lhs.id != rhs.id { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_AtalaOperation: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".AtalaOperation" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .standard(proto: "create_did"), - 2: .standard(proto: "update_did"), - 3: .standard(proto: "issue_credential_batch"), - 4: .standard(proto: "revoke_credentials"), - 5: .standard(proto: "protocol_version_update"), - 6: .standard(proto: "deactivate_did"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try { - var v: Io_Iohk_Atala_Prism_Protos_CreateDIDOperation? - var hadOneofValue = false - if let current = self.operation { - hadOneofValue = true - if case let .createDid(m) = current { v = m } - } - try decoder.decodeSingularMessageField(value: &v) - if let v = v { - if hadOneofValue { try decoder.handleConflictingOneOf() } - self.operation = .createDid(v) - } - }() - case 2: try { - var v: Io_Iohk_Atala_Prism_Protos_UpdateDIDOperation? - var hadOneofValue = false - if let current = self.operation { - hadOneofValue = true - if case let .updateDid(m) = current { v = m } - } - try decoder.decodeSingularMessageField(value: &v) - if let v = v { - if hadOneofValue { try decoder.handleConflictingOneOf() } - self.operation = .updateDid(v) - } - }() - case 3: try { - var v: Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOperation? - var hadOneofValue = false - if let current = self.operation { - hadOneofValue = true - if case let .issueCredentialBatch(m) = current { v = m } - } - try decoder.decodeSingularMessageField(value: &v) - if let v = v { - if hadOneofValue { try decoder.handleConflictingOneOf() } - self.operation = .issueCredentialBatch(v) - } - }() - case 4: try { - var v: Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOperation? - var hadOneofValue = false - if let current = self.operation { - hadOneofValue = true - if case let .revokeCredentials(m) = current { v = m } - } - try decoder.decodeSingularMessageField(value: &v) - if let v = v { - if hadOneofValue { try decoder.handleConflictingOneOf() } - self.operation = .revokeCredentials(v) - } - }() - case 5: try { - var v: Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOperation? - var hadOneofValue = false - if let current = self.operation { - hadOneofValue = true - if case let .protocolVersionUpdate(m) = current { v = m } - } - try decoder.decodeSingularMessageField(value: &v) - if let v = v { - if hadOneofValue { try decoder.handleConflictingOneOf() } - self.operation = .protocolVersionUpdate(v) - } - }() - case 6: try { - var v: Io_Iohk_Atala_Prism_Protos_DeactivateDIDOperation? - var hadOneofValue = false - if let current = self.operation { - hadOneofValue = true - if case let .deactivateDid(m) = current { v = m } - } - try decoder.decodeSingularMessageField(value: &v) - if let v = v { - if hadOneofValue { try decoder.handleConflictingOneOf() } - self.operation = .deactivateDid(v) - } - }() - default: break - } - } - } - - func traverse(visitor: inout V) throws { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch operation { - case .createDid?: try { - guard case let .createDid(v)? = self.operation else { preconditionFailure() } - try visitor.visitSingularMessageField(value: v, fieldNumber: 1) - }() - case .updateDid?: try { - guard case let .updateDid(v)? = self.operation else { preconditionFailure() } - try visitor.visitSingularMessageField(value: v, fieldNumber: 2) - }() - case .issueCredentialBatch?: try { - guard case let .issueCredentialBatch(v)? = self.operation else { preconditionFailure() } - try visitor.visitSingularMessageField(value: v, fieldNumber: 3) - }() - case .revokeCredentials?: try { - guard case let .revokeCredentials(v)? = self.operation else { preconditionFailure() } - try visitor.visitSingularMessageField(value: v, fieldNumber: 4) - }() - case .protocolVersionUpdate?: try { - guard case let .protocolVersionUpdate(v)? = self.operation else { preconditionFailure() } - try visitor.visitSingularMessageField(value: v, fieldNumber: 5) - }() - case .deactivateDid?: try { - guard case let .deactivateDid(v)? = self.operation else { preconditionFailure() } - try visitor.visitSingularMessageField(value: v, fieldNumber: 6) - }() - case nil: break - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_AtalaOperation, rhs: Io_Iohk_Atala_Prism_Protos_AtalaOperation) -> Bool { - if lhs.operation != rhs.operation { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_SignedAtalaOperation: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".SignedAtalaOperation" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .standard(proto: "signed_with"), - 2: .same(proto: "signature"), - 3: .same(proto: "operation"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try try decoder.decodeSingularStringField(value: &signedWith) - case 2: try try decoder.decodeSingularBytesField(value: &signature) - case 3: try try decoder.decodeSingularMessageField(value: &_operation) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if !signedWith.isEmpty { - try visitor.visitSingularStringField(value: signedWith, fieldNumber: 1) - } - if !signature.isEmpty { - try visitor.visitSingularBytesField(value: signature, fieldNumber: 2) - } - if let v = _operation { - try visitor.visitSingularMessageField(value: v, fieldNumber: 3) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_SignedAtalaOperation, rhs: Io_Iohk_Atala_Prism_Protos_SignedAtalaOperation) -> Bool { - if lhs.signedWith != rhs.signedWith { return false } - if lhs.signature != rhs.signature { return false } - if lhs._operation != rhs._operation { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_LedgerData: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".LedgerData" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .standard(proto: "transaction_id"), - 2: .same(proto: "ledger"), - 3: .standard(proto: "timestamp_info"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try try decoder.decodeSingularStringField(value: &transactionID) - case 2: try try decoder.decodeSingularEnumField(value: &ledger) - case 3: try try decoder.decodeSingularMessageField(value: &_timestampInfo) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if !transactionID.isEmpty { - try visitor.visitSingularStringField(value: transactionID, fieldNumber: 1) - } - if ledger != .unknownLedger { - try visitor.visitSingularEnumField(value: ledger, fieldNumber: 2) - } - if let v = _timestampInfo { - try visitor.visitSingularMessageField(value: v, fieldNumber: 3) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_LedgerData, rhs: Io_Iohk_Atala_Prism_Protos_LedgerData) -> Bool { - if lhs.transactionID != rhs.transactionID { return false } - if lhs.ledger != rhs.ledger { return false } - if lhs._timestampInfo != rhs._timestampInfo { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_OperationOutput: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".OperationOutput" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .standard(proto: "batch_output"), - 2: .standard(proto: "create_did_output"), - 3: .standard(proto: "update_did_output"), - 4: .standard(proto: "revoke_credentials_output"), - 7: .standard(proto: "protocol_version_update_output"), - 8: .standard(proto: "deactivate_did_output"), - 5: .standard(proto: "operation_id"), - 6: .same(proto: "error"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try { - var v: Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOutput? - var hadOneofValue = false - if let current = self.result { - hadOneofValue = true - if case let .batchOutput(m) = current { v = m } - } - try decoder.decodeSingularMessageField(value: &v) - if let v = v { - if hadOneofValue { try decoder.handleConflictingOneOf() } - self.result = .batchOutput(v) - } - }() - case 2: try { - var v: Io_Iohk_Atala_Prism_Protos_CreateDIDOutput? - var hadOneofValue = false - if let current = self.result { - hadOneofValue = true - if case let .createDidOutput(m) = current { v = m } - } - try decoder.decodeSingularMessageField(value: &v) - if let v = v { - if hadOneofValue { try decoder.handleConflictingOneOf() } - self.result = .createDidOutput(v) - } - }() - case 3: try { - var v: Io_Iohk_Atala_Prism_Protos_UpdateDIDOutput? - var hadOneofValue = false - if let current = self.result { - hadOneofValue = true - if case let .updateDidOutput(m) = current { v = m } - } - try decoder.decodeSingularMessageField(value: &v) - if let v = v { - if hadOneofValue { try decoder.handleConflictingOneOf() } - self.result = .updateDidOutput(v) - } - }() - case 4: try { - var v: Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOutput? - var hadOneofValue = false - if let current = self.result { - hadOneofValue = true - if case let .revokeCredentialsOutput(m) = current { v = m } - } - try decoder.decodeSingularMessageField(value: &v) - if let v = v { - if hadOneofValue { try decoder.handleConflictingOneOf() } - self.result = .revokeCredentialsOutput(v) - } - }() - case 5: try { - var v: Data? - try decoder.decodeSingularBytesField(value: &v) - if let v = v { - if self.operationMaybe != nil { try decoder.handleConflictingOneOf() } - self.operationMaybe = .operationID(v) - } - }() - case 6: try { - var v: String? - try decoder.decodeSingularStringField(value: &v) - if let v = v { - if self.operationMaybe != nil { try decoder.handleConflictingOneOf() } - self.operationMaybe = .error(v) - } - }() - case 7: try { - var v: Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOutput? - var hadOneofValue = false - if let current = self.result { - hadOneofValue = true - if case let .protocolVersionUpdateOutput(m) = current { v = m } - } - try decoder.decodeSingularMessageField(value: &v) - if let v = v { - if hadOneofValue { try decoder.handleConflictingOneOf() } - self.result = .protocolVersionUpdateOutput(v) - } - }() - case 8: try { - var v: Io_Iohk_Atala_Prism_Protos_DeactivateDIDOutput? - var hadOneofValue = false - if let current = self.result { - hadOneofValue = true - if case let .deactivateDidOutput(m) = current { v = m } - } - try decoder.decodeSingularMessageField(value: &v) - if let v = v { - if hadOneofValue { try decoder.handleConflictingOneOf() } - self.result = .deactivateDidOutput(v) - } - }() - default: break - } - } - } - - func traverse(visitor: inout V) throws { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch result { - case .batchOutput?: try { - guard case let .batchOutput(v)? = self.result else { preconditionFailure() } - try visitor.visitSingularMessageField(value: v, fieldNumber: 1) - }() - case .createDidOutput?: try { - guard case let .createDidOutput(v)? = self.result else { preconditionFailure() } - try visitor.visitSingularMessageField(value: v, fieldNumber: 2) - }() - case .updateDidOutput?: try { - guard case let .updateDidOutput(v)? = self.result else { preconditionFailure() } - try visitor.visitSingularMessageField(value: v, fieldNumber: 3) - }() - case .revokeCredentialsOutput?: try { - guard case let .revokeCredentialsOutput(v)? = self.result else { preconditionFailure() } - try visitor.visitSingularMessageField(value: v, fieldNumber: 4) - }() - default: break - } - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch operationMaybe { - case .operationID?: try { - guard case let .operationID(v)? = self.operationMaybe else { preconditionFailure() } - try visitor.visitSingularBytesField(value: v, fieldNumber: 5) - }() - case .error?: try { - guard case let .error(v)? = self.operationMaybe else { preconditionFailure() } - try visitor.visitSingularStringField(value: v, fieldNumber: 6) - }() - case nil: break - } - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch result { - case .protocolVersionUpdateOutput?: try { - guard case let .protocolVersionUpdateOutput(v)? = self.result else { preconditionFailure() } - try visitor.visitSingularMessageField(value: v, fieldNumber: 7) - }() - case .deactivateDidOutput?: try { - guard case let .deactivateDidOutput(v)? = self.result else { preconditionFailure() } - try visitor.visitSingularMessageField(value: v, fieldNumber: 8) - }() - default: break - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_OperationOutput, rhs: Io_Iohk_Atala_Prism_Protos_OperationOutput) -> Bool { - if lhs.result != rhs.result { return false } - if lhs.operationMaybe != rhs.operationMaybe { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOutput: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".IssueCredentialBatchOutput" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .standard(proto: "batch_id"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try try decoder.decodeSingularStringField(value: &batchID) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if !batchID.isEmpty { - try visitor.visitSingularStringField(value: batchID, fieldNumber: 1) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOutput, rhs: Io_Iohk_Atala_Prism_Protos_IssueCredentialBatchOutput) -> Bool { - if lhs.batchID != rhs.batchID { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_CreateDIDOutput: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".CreateDIDOutput" - static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .standard(proto: "did_suffix"), - ] - - mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try try decoder.decodeSingularStringField(value: &didSuffix) - default: break - } - } - } - - func traverse(visitor: inout V) throws { - if !didSuffix.isEmpty { - try visitor.visitSingularStringField(value: didSuffix, fieldNumber: 1) - } - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_CreateDIDOutput, rhs: Io_Iohk_Atala_Prism_Protos_CreateDIDOutput) -> Bool { - if lhs.didSuffix != rhs.didSuffix { return false } - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_UpdateDIDOutput: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".UpdateDIDOutput" - static let _protobuf_nameMap = SwiftProtobuf._NameMap() - - mutating func decodeMessage(decoder: inout D) throws { - while let _ = try decoder.nextFieldNumber() {} - } - - func traverse(visitor: inout V) throws { - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_UpdateDIDOutput, rhs: Io_Iohk_Atala_Prism_Protos_UpdateDIDOutput) -> Bool { - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOutput: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".RevokeCredentialsOutput" - static let _protobuf_nameMap = SwiftProtobuf._NameMap() - - mutating func decodeMessage(decoder: inout D) throws { - while let _ = try decoder.nextFieldNumber() {} - } - - func traverse(visitor: inout V) throws { - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOutput, rhs: Io_Iohk_Atala_Prism_Protos_RevokeCredentialsOutput) -> Bool { - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOutput: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".ProtocolVersionUpdateOutput" - static let _protobuf_nameMap = SwiftProtobuf._NameMap() - - mutating func decodeMessage(decoder: inout D) throws { - while let _ = try decoder.nextFieldNumber() {} - } - - func traverse(visitor: inout V) throws { - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOutput, rhs: Io_Iohk_Atala_Prism_Protos_ProtocolVersionUpdateOutput) -> Bool { - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} - -extension Io_Iohk_Atala_Prism_Protos_DeactivateDIDOutput: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - static let protoMessageName: String = _protobuf_package + ".DeactivateDIDOutput" - static let _protobuf_nameMap = SwiftProtobuf._NameMap() - - mutating func decodeMessage(decoder: inout D) throws { - while let _ = try decoder.nextFieldNumber() {} - } - - func traverse(visitor: inout V) throws { - try unknownFields.traverse(visitor: &visitor) - } - - static func == (lhs: Io_Iohk_Atala_Prism_Protos_DeactivateDIDOutput, rhs: Io_Iohk_Atala_Prism_Protos_DeactivateDIDOutput) -> Bool { - if lhs.unknownFields != rhs.unknownFields { return false } - return true - } -} diff --git a/Core/Sources/Logger/PrismLogger.swift b/Core/Sources/Logger/PrismLogger.swift index 6438cb49..17a0096b 100644 --- a/Core/Sources/Logger/PrismLogger.swift +++ b/Core/Sources/Logger/PrismLogger.swift @@ -147,7 +147,7 @@ public extension PrismLogger { /// - metadata: Private/Public/Masked metadata func warning(message: String, metadata: [Metadata] = []) { guard logLevel != .none else { return } - logger.warning("\(message)", metadata: metadata.loggerMetadata(logLevel: logLevel)) + logger.warning("⚠️ \(message)", metadata: metadata.loggerMetadata(logLevel: logLevel)) } /// Logs error level message and metadata @@ -156,7 +156,7 @@ public extension PrismLogger { /// - metadata: Private/Public/Masked metadata func error(message: String, metadata: [Metadata] = []) { guard logLevel != .none else { return } - logger.error("\(message)", metadata: metadata.loggerMetadata(logLevel: logLevel)) + logger.error("🛑 \(message)", metadata: metadata.loggerMetadata(logLevel: logLevel)) } /// Logs error level message and metadata @@ -165,7 +165,20 @@ public extension PrismLogger { /// - metadata: Private/Public/Masked metadata func error(error: Error, metadata: [Metadata] = []) { guard logLevel != .none else { return } - logger.error("\(error.localizedDescription)", metadata: metadata.loggerMetadata(logLevel: logLevel)) + if + let localized = error as? LocalizedError, + let message = localized.errorDescription + { + logger.error( + "🛑 \(message)", + metadata: metadata.loggerMetadata(logLevel: logLevel) + ) + } else { + logger.error( + "🛑 \(error.localizedDescription)", + metadata: metadata.loggerMetadata(logLevel: logLevel) + ) + } } } diff --git a/Domain/Sources/Models/Errors.swift b/Domain/Sources/Models/Errors.swift deleted file mode 100644 index 7dd0af2e..00000000 --- a/Domain/Sources/Models/Errors.swift +++ /dev/null @@ -1,50 +0,0 @@ -import Foundation - -public enum CommonError: Error { - case somethingWentWrongError -} - -public enum ApolloError: Error { - case invalidMnemonicWord - case couldNotParseMessageString -} - -public enum CastorError: Error { - case invalidLongFormDID - case methodIdIsDoesNotSatisfyRegex - case invalidPublicKeyEncoding - case invalidDIDString - case initialStateOfDIDChanged - case notPossibleToResolveDID - case invalidJWKKeysError - case invalidKeyError - case invalidPeerDIDError -} - -public enum MercuryError: Error { - case invalidURLError - case noDIDReceiverSetError - case noValidServiceFoundError - case fromFieldNotSetError - case unknownAttachmentDataError - case messageAttachmentWithoutIDError - case messageInvalidBodyDataError - case unknowPackingMessageError - case couldNotResolveDIDError - case didcommError(msg: String) - case urlSessionError(statusCode: Int, error: Error?, msg: String?) -} - -public enum PlutoError: Error { - case invalidHolderDIDNotPersistedError - case messageMissingFromOrToDIDError - case didPairIsNotPersistedError - case holderDIDAlreadyPairingError - case unknownCredentialTypeError - case invalidCredentialJsonError -} - -public enum PolluxError: Error { - case invalidCredentialError - case invalidJWTString -} diff --git a/Mercury/Sources/MercuryImpl+Public.swift b/Mercury/Sources/MercuryImpl+Public.swift deleted file mode 100644 index 80baad44..00000000 --- a/Mercury/Sources/MercuryImpl+Public.swift +++ /dev/null @@ -1,40 +0,0 @@ -import Core -import DIDCommxSwift -import Domain -import Foundation - -extension MercuryImpl: Mercury { - public func packMessage(msg: Domain.Message) async throws -> String { - try await PackEncryptedOperation(didcomm: didcomm, logger: logger).packEncrypted(msg: msg) - } - - public func unpackMessage(msg: String) async throws -> Domain.Message { - try await UnpackOperation(didcomm: didcomm, castor: castor, logger: logger).unpackEncrypted(messageString: msg) - } - - public func sendMessage(msg: Domain.Message) async throws -> Data? { - 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 { - logger.error(message: "Could not find a valid service on the DID to send message") - throw MercuryError.noValidServiceFoundError - } - let packedMessage = try await packMessage(msg: msg) - return try await session.post( - url: url, - body: packedMessage.data(using: .utf8), - headers: ["content-type": MediaType.contentTypeEncrypted.rawValue] - ) - } - - public func sendMessageParseMessage(msg: Domain.Message) async throws -> Domain.Message? { - guard - let msgData = try await sendMessage(msg: msg), - let msgStr = String(data: msgData, encoding: .utf8) - else { return nil } - return try? await self.unpackMessage(msg: msgStr) - } -} diff --git a/Package.swift b/Package.swift index 1cdec84a..8a30fa5a 100644 --- a/Package.swift +++ b/Package.swift @@ -5,8 +5,21 @@ import PackageDescription let package = Package( name: "AtalaPRISMSDK", - platforms: [.iOS(.v15)], + platforms: [.iOS(.v15), .macOS(.v12)], products: [ + .library( + name: "AtalaPrismSDK", + targets: [ + "AtalaPrismSDK", + "Domain", + "Castor", + "Apollo", + "Mercury", + "Pluto", + "Pollux", + "PrismAgent" + ] + ), .library( name: "Domain", targets: ["Domain"] @@ -56,17 +69,32 @@ let package = Package( .package(url: "git@github.com:input-output-hk/atala-prism-didcomm-swift.git", from: "0.3.4"), .package(url: "git@github.com:input-output-hk/atala-prism-crypto-sdk-sp.git", from: "1.4.1"), .package(url: "git@github.com:swift-libp2p/swift-multibase.git", branch: "main"), - .package(url: "git@github.com:Kitura/Swift-JWT.git", from: "4.0.0") + .package(url: "git@github.com:Kitura/Swift-JWT.git", from: "4.0.0"), + .package(url: "git@github.com:goncalo-frade-iohk/swift-docc-plugin.git", from: "1.2.0") ], targets: [ + .target( + name: "AtalaPrismSDK", + dependencies: [ + "Domain", + "Castor", + "Apollo", + "Mercury", + "Pluto", + "Pollux", + "PrismAgent" + ], + path: "AtalaPrismSDK/AtalaPrismSDK/Sources", + resources: [.process("Documentation.docc/Resources")] + ), .target( name: "Domain", - path: "Domain/Sources" + path: "AtalaPrismSDK/Domain/Sources" ), .testTarget( name: "DomainTests", dependencies: ["Domain"], - path: "Domain/Tests" + path: "AtalaPrismSDK/Domain/Tests" ), .target( name: "Apollo", @@ -76,12 +104,12 @@ let package = Package( .product(name: "PrismAPI", package: "atala-prism-crypto-sdk-sp"), .product(name: "SwiftJWT", package: "Swift-JWT") ], - path: "Apollo/Sources" + path: "AtalaPrismSDK/Apollo/Sources" ), .testTarget( name: "ApolloTests", dependencies: ["Apollo"], - path: "Apollo/Tests" + path: "AtalaPrismSDK/Apollo/Tests" ), .target( name: "Castor", @@ -92,12 +120,12 @@ let package = Package( .product(name: "SwiftProtobuf", package: "swift-protobuf"), .product(name: "Antlr4", package: "antlr4") ], - path: "Castor/Sources" + path: "AtalaPrismSDK/Castor/Sources" ), .testTarget( name: "CastorTests", dependencies: ["Castor", "Apollo"], - path: "Castor/Tests" + path: "AtalaPrismSDK/Castor/Tests" ), .target( name: "Pollux", @@ -105,12 +133,12 @@ let package = Package( "Domain", "Core" ], - path: "Pollux/Sources" + path: "AtalaPrismSDK/Pollux/Sources" ), .testTarget( name: "PolluxTests", dependencies: ["Pollux"], - path: "Pollux/Tests" + path: "AtalaPrismSDK/Pollux/Tests" ), .target( name: "Mercury", @@ -119,48 +147,48 @@ let package = Package( "Core", .product(name: "DIDCommxSwift", package: "atala-prism-didcomm-swift") ], - path: "Mercury/Sources" + path: "AtalaPrismSDK/Mercury/Sources" ), .testTarget( name: "MercuryTests", dependencies: ["Mercury"], - path: "Mercury/Tests" + path: "AtalaPrismSDK/Mercury/Tests" ), .target( name: "Pluto", dependencies: ["Domain"], - path: "Pluto/Sources", + path: "AtalaPrismSDK/Pluto/Sources", resources: [.process("Resources/PrismPluto.xcdatamodeld")] ), .testTarget( name: "PlutoTests", dependencies: ["Pluto"], - path: "Pluto/Tests" + path: "AtalaPrismSDK/Pluto/Tests" ), .target( name: "Builders", dependencies: ["Domain", "Castor", "Pollux", "Mercury", "Pluto", "Apollo"], - path: "Builders/Sources" + path: "AtalaPrismSDK/Builders/Sources" ), .target( name: "PrismAgent", dependencies: ["Domain", "Builders", "Core"], - path: "PrismAgent/Sources" + path: "AtalaPrismSDK/PrismAgent/Sources" ), .testTarget( name: "PrismAgentTests", dependencies: ["PrismAgent"], - path: "PrismAgent/Tests" + path: "AtalaPrismSDK/PrismAgent/Tests" ), .target( name: "Authenticate", dependencies: ["Domain", "Builders", "Core"], - path: "Authenticate/Sources" + path: "AtalaPrismSDK/Authenticate/Sources" ), .testTarget( name: "AuthenticateTests", dependencies: ["Authenticate"], - path: "Authenticate/Tests" + path: "AtalaPrismSDK/Authenticate/Tests" ), // Internal core components (ex: logging) not public distributed .target( diff --git a/Pluto/Sources/Domain/Providers/DIDPairProvider.swift b/Pluto/Sources/Domain/Providers/DIDPairProvider.swift deleted file mode 100644 index af5e7952..00000000 --- a/Pluto/Sources/Domain/Providers/DIDPairProvider.swift +++ /dev/null @@ -1,10 +0,0 @@ -import Combine -import Domain -import Foundation - -protocol DIDPairProvider { - func getAll() -> AnyPublisher<[(holder: DID, other: DID, name: String?)], Error> - func getPair(otherDID: DID) -> AnyPublisher<(holder: DID, other: DID, name: String?)?, Error> - func getPair(name: String) -> AnyPublisher<(holder: DID, other: DID, name: String?)?, Error> - func getPair(holderDID: DID) -> AnyPublisher<(holder: DID, other: DID, name: String?)?, Error> -} diff --git a/PrismAgent/Sources/Errors.swift b/PrismAgent/Sources/Errors.swift deleted file mode 100644 index 1dff096d..00000000 --- a/PrismAgent/Sources/Errors.swift +++ /dev/null @@ -1,24 +0,0 @@ -public enum PrismAgentError: Error { - case invalidURLError - case cannotFindDIDKeyPairIndex - case invitationHasNoFromDIDError - case noValidServiceEndpointError - case invitationIsInvalidError - case noConnectionOpenError - case noHandshakeResponseError - case unknownInvitationTypeError - case unknownPrismOnboardingTypeError - case failedToOnboardError - case invalidPickupDeliveryMessageError - case invalidOfferCredentialMessageError - case invalidProposedCredentialMessageError - case invalidIssueCredentialMessageError - case invalidRequestCredentialMessageError - case invalidPresentationMessageError - case invalidRequestPresentationMessageError - case invalidProposePresentationMessageError - case invalidMediationGrantMessageError - case noMediatorAvailableError - case mediationRequestFailedError - case invalidStepError -} diff --git a/PrismAgent/Sources/Mediator/Mediator.swift b/PrismAgent/Sources/Mediator/Mediator.swift deleted file mode 100644 index f598ab68..00000000 --- a/PrismAgent/Sources/Mediator/Mediator.swift +++ /dev/null @@ -1,7 +0,0 @@ -import Domain - -public struct Mediator { - let hostDID: DID - let routingDID: DID - let mediatorDID: DID -} diff --git a/Sample/AtalaPrismWalletDemo/AtalaPrismWalletDemo/Modules/DID/DIDFuncionalitiesViewModel.swift b/Sample/AtalaPrismWalletDemo/AtalaPrismWalletDemo/Modules/DID/DIDFuncionalitiesViewModel.swift index 5658011c..cfc3cbed 100644 --- a/Sample/AtalaPrismWalletDemo/AtalaPrismWalletDemo/Modules/DID/DIDFuncionalitiesViewModel.swift +++ b/Sample/AtalaPrismWalletDemo/AtalaPrismWalletDemo/Modules/DID/DIDFuncionalitiesViewModel.swift @@ -21,14 +21,14 @@ final class DIDFuncionalitiesViewModel: ObservableObject { // Creates new PRISM DID let did = try? await agent.createNewPrismDID( // Add this if you want to provide a IndexPath - // keyPathIndex: <#T##Int?#> + keyPathIndex: 2, // Add this if you want to provide an alias for this DID // alias: <#T##String?#> // Add any services available in the DID services: [ .init( id: "DemoID", type: ["DemoType"], - serviceEndpoint: .init(uri: "DemoServiceEndpoint") + serviceEndpoint: [.init(uri: "DemoServiceEndpoint")] ) ]) diff --git a/Sample/AtalaPrismWalletDemo/AtalaPrismWalletDemo/Modules/SigningVerification/SigningVerificationViewModel.swift b/Sample/AtalaPrismWalletDemo/AtalaPrismWalletDemo/Modules/SigningVerification/SigningVerificationViewModel.swift index 7ee9efa0..24a660b0 100644 --- a/Sample/AtalaPrismWalletDemo/AtalaPrismWalletDemo/Modules/SigningVerification/SigningVerificationViewModel.swift +++ b/Sample/AtalaPrismWalletDemo/AtalaPrismWalletDemo/Modules/SigningVerification/SigningVerificationViewModel.swift @@ -31,7 +31,7 @@ final class SigningVerificationViewModel: ObservableObject { services: [ .init( id: "DemoID", type: ["DemoType"], - serviceEndpoint: .init(uri: "DemoServiceEndpoint") + serviceEndpoint: [.init(uri: "DemoServiceEndpoint")] ) ]) await MainActor.run {