diff --git a/.github/ISSUE_TEMPLATE/1-bug-report.yaml b/.github/ISSUE_TEMPLATE/1-bug-report.yaml index 7e4a93351..87c193f5b 100644 --- a/.github/ISSUE_TEMPLATE/1-bug-report.yaml +++ b/.github/ISSUE_TEMPLATE/1-bug-report.yaml @@ -1,5 +1,5 @@ name: Bug Report -description: Report a bug in the Atala PRISM KMM SDK +description: Report a bug in the Edge Agent KMM SDK body: - type: dropdown diff --git a/.github/ISSUE_TEMPLATE/2-feature-request.yaml b/.github/ISSUE_TEMPLATE/2-feature-request.yaml index d6ca5d75e..ed6f436ce 100644 --- a/.github/ISSUE_TEMPLATE/2-feature-request.yaml +++ b/.github/ISSUE_TEMPLATE/2-feature-request.yaml @@ -1,5 +1,5 @@ name: 'Feature Request' -description: Suggest a new feature for Atala PRISM KMM SDK +description: Suggest a new feature for Edge Agent KMM SDK body: - type: textarea diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index d6c0e7e42..82d91f413 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -47,14 +47,14 @@ jobs: - name: Coveralls uses: coverallsapp/github-action@v2 with: - file: "${{ github.workspace }}/atala-prism-sdk/build/reports/android/result.xml" + file: "${{ github.workspace }}/edge-agent-sdk/build/reports/android/result.xml" github-token: ${{ secrets.GITHUB_TOKEN }} - name: Publish test results if: always() uses: EnricoMi/publish-unit-test-result-action/composite@v2 with: - files: "${{ github.workspace }}/atala-prism-sdk/build/test-results/testReleaseUnitTest/TEST-*.xml" + files: "${{ github.workspace }}/edge-agent-sdk/build/test-results/testReleaseUnitTest/TEST-*.xml" comment_title: "Unit Test Results" check_name: "Unit Test Results" @@ -64,6 +64,6 @@ jobs: with: name: coverage-results path: | - atala-prism-sdk/build/reports/jvm - atala-prism-sdk/build/reports/android + edge-agent-sdk/build/reports/jvm + edge-agent-sdk/build/reports/android if-no-files-found: error diff --git a/.github/workflows/e2e-tests.yml b/.github/workflows/e2e-tests.yml index 008d80d44..732334b8d 100644 --- a/.github/workflows/e2e-tests.yml +++ b/.github/workflows/e2e-tests.yml @@ -91,6 +91,6 @@ jobs: uses: actions/upload-artifact@v4 if: always() with: - name: atala-prism-sdk-kmm + name: edge-agent-sdk-kmm path: tests/end-to-end/target/site/serenity if-no-files-found: 'error' diff --git a/.github/workflows/release-documentation.yml b/.github/workflows/release-documentation.yml index 734f511a9..7cb84dac5 100644 --- a/.github/workflows/release-documentation.yml +++ b/.github/workflows/release-documentation.yml @@ -46,13 +46,13 @@ jobs: - name: Dokka Documentation Generation run: | - ./gradlew :atala-prism-sdk:dokkaHtml + ./gradlew :edge-agent-sdk:dokkaHtml - name: Push uses: s0/git-publish-subdir-action@develop env: REPO: self BRANCH: gh-pages # The branch name where you want to push the assets - FOLDER: "atala-prism-sdk/build/dokka/html/" # The directory where your assets are generated + FOLDER: "edge-agent-sdk/build/dokka/html/" # The directory where your assets are generated GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # GitHub will automatically add this - you don't need to bother getting a token MESSAGE: "feat(docs): ({sha}) {msg}" # The commit message diff --git a/.mega-linter.yml b/.mega-linter.yml index 3f1b295c9..4a7dfa166 100644 --- a/.mega-linter.yml +++ b/.mega-linter.yml @@ -1,5 +1,5 @@ APPLY_FIXES: none -FILTER_REGEX_INCLUDE: (.editorconfig|.github/|atala-prism-sdk/src/|sampleapp/src/|protosLib/src/) +FILTER_REGEX_INCLUDE: (.editorconfig|.github/|edge-agent-sdk/src/|sampleapp/src/|protosLib/src/) FILTER_REGEX_EXCLUDE: (tests/) VALIDATE_ALL_CODEBASE: false diff --git a/.releaserc.yml b/.releaserc.yml index dd05f7d68..639199ec0 100644 --- a/.releaserc.yml +++ b/.releaserc.yml @@ -5,7 +5,7 @@ plugins: - "@semantic-release/commit-analyzer" - "@semantic-release/release-notes-generator" - [ '@semantic-release/exec', { - prepareCmd: 'sed -i.bak "s/atala-prism-sdk:${lastRelease.version}/atala-prism-sdk:${nextRelease.version}/g" ./tests/end-to-end/build.gradle.kts && rm -f ./tests/end-to-end/build.gradle.kts.bak' } ] + prepareCmd: 'sed -i.bak "s/edge-agent-sdk:${lastRelease.version}/edge-agent-sdk:${nextRelease.version}/g" ./tests/end-to-end/build.gradle.kts && rm -f ./tests/end-to-end/build.gradle.kts.bak' } ] - ["@semantic-release/changelog", {changelogFile: "CHANGELOG.md"}] - "gradle-semantic-release-plugin" - [ diff --git a/CHANGELOG.md b/CHANGELOG.md index eeb7fb749..787737a95 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -160,7 +160,7 @@ * **agent:** add mediator request message ([617640c](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/commit/617640cece9ae1090fe76c78b6b712eabd0f050e)) * **agent:** add mediator request message ([#5](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/issues/5)) ([60cfd13](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/commit/60cfd1368dcfeb8b287cc71d12d93dcb45d1aca4)) * **agent:** add prism agent and create did functionalities ([431201b](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/commit/431201bc15492f3a66f0bfe742b2d644a1465e17)) -* **Agent:** Implement Credential Issue Protocol in PrismAgent ([#27](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/issues/27)) ([0f635f3](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/commit/0f635f34c94e3446c8beb4e38d572a9b0dd36d8c)) +* **Agent:** Implement Credential Issue Protocol in EdgeAgent ([#27](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/issues/27)) ([0f635f3](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/commit/0f635f34c94e3446c8beb4e38d572a9b0dd36d8c)) * **agent:** Implementation Onboarding invitation on Agent ([#18](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/issues/18)) ([c6188ec](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/commit/c6188ec259eb3347a231d47cece51c37d71fe12d)) * **Agent:** Logic to parse out of band invitations ([#25](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/issues/25)) ([85535c5](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/commit/85535c5d82792f50fe89ae82ef15a561222b66d8)) * **Agent:** Persist key pairs into local storage ([#22](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/issues/22)) ([7cc738f](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/commit/7cc738fe7708ca5ab3d0418dc963967c8f1e0821)) @@ -186,7 +186,7 @@ * **pollux:** add create credential request and presentation jwt string and prism agent higher functionality ([9a38c18](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/commit/9a38c182ee91eb322194d5282348fdb2123196c1)) * **pollux:** add create credential request and presentation jwt string and prism agent higher functionality ([231387d](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/commit/231387ddfcca5327e9070ff90a2538afc6c4f5ae)) * **Prism Agent:** Add connection data persistency ([#37](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/issues/37)) ([ad5132b](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/commit/ad5132bf8d832c78461db53504f088fa161a255e)) -* **PrismAgent:** Implement message signature ([#21](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/issues/21)) ([fec99aa](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/commit/fec99aadd34138452d6fa1429d3631b1d02b6175)) +* **EdgeAgent:** Implement message signature ([#21](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/issues/21)) ([fec99aa](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/commit/fec99aadd34138452d6fa1429d3631b1d02b6175)) * project init ([29f62bb](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/commit/29f62bbc8a6fd779c5c7b3db5a10427e84527c53)) * release first production version ([99ce9e0](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/commit/99ce9e0129cbed436e01f315a2479634ec45da03)) * Sample app with full flow ([#66](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/issues/66)) ([77ab0e4](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/commit/77ab0e4ef67b88a79698c525cf437377757838c3)) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 43469e70a..d5406568a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,13 +1,13 @@ -# Contributing to Atala PRISM KMM SDK +# Contributing to AIdentus KMM SDK :rocket::tada: First off, thanks for taking the time to contribute! :tada::rocket: -The following is a set of guidelines for contributing to Atala PRISM KMM SDK. These are mostly guidelines. Use your best judgment, and feel free to propose changes to this document in a pull request. +The following is a set of guidelines for contributing to Identus KMM SDK. These are mostly guidelines. Use your best judgment, and feel free to propose changes to this document in a pull request. #### Table Of Contents [What should I know before I get started?](#what-should-i-know-before-i-get-started) - * [Atala PRISM](#atala-prism) - * [Atala PRISM KMM SDK](#atala-prism-kmm) + * [Identus](#Identus) + * [Identus KMM SDK](#Identus-kmm) [How Can I Contribute?](#how-can-i-contribute) * [Your First Code Contribution](#your-first-code-contribution) @@ -21,9 +21,9 @@ The following is a set of guidelines for contributing to Atala PRISM KMM SDK. Th ## What should I know before I get started? -### Atala PRISM +### Identus -Atala PRISM is a self-sovereign identity (SSI) platform and service suite for verifiable data and digital identity. Built on Cardano, it offers the core infrastructure for issuing DIDs (Decentralized identifiers) and verifiable credentials alongside tools and frameworks to help expand your ecosystem. +Identus is a self-sovereign identity (SSI) platform and service suite for verifiable data and digital identity. Built on Cardano, it offers the core infrastructure for issuing DIDs (Decentralized identifiers) and verifiable credentials alongside tools and frameworks to help expand your ecosystem. The complete platform is separated into multiple repositories: * [atala-prism-building-blocks](https://github.com/hyperledger-labs/open-enterprise-agent) - Repo that contains the servers Building Blocks. @@ -31,13 +31,13 @@ The complete platform is separated into multiple repositories: * [atala-prism-wallet-sdk-ts](https://github.com/input-output-hk/atala-prism-wallet-sdk-ts) - Repo for the TS version of the SDK. * [atala-prism-mediator](https://github.com/input-output-hk/atala-prism-mediator) - Repo for DIDComm V2 Mediator -### Atala PRISM KMM SDK +### Identus KMM SDK -Atala PRISM KMM software development kit will help adoption within Kotlin platforms (Java/Android) by providing key functionalities. For more information about the SDK, please have a look at the [Readme](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/blob/main/README.md) +Identus KMM software development kit will help adoption within Kotlin platforms (Java/Android) by providing key functionalities. For more information about the SDK, please have a look at the [Readme](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/blob/main/README.md) ### Your First Code Contribution -Unsure where to begin contributing to Atala PRISM KMM SDK? You can start by looking through the [Readme](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/blob/main/README.md) that provides all the steps to setup your environment. +Unsure where to begin contributing to Identus KMM SDK? You can start by looking through the [Readme](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/blob/main/README.md) that provides all the steps to setup your environment. ### Pull Requests @@ -58,7 +58,7 @@ While the prerequisites above must be satisfied prior to having your pull reques ### Reporting Bugs -This section guides you through submitting a bug report for Atala PRISM KMM SDK. Following these guidelines helps maintainers and the community understand your report :pencil:, reproduce the behaviour :computer: :computer:, and find related reports :mag_right:. +This section guides you through submitting a bug report for Identus KMM SDK. Following these guidelines helps maintainers and the community understand your report :pencil:, reproduce the behaviour :computer: :computer:, and find related reports :mag_right:. Before creating bug reports, please check [this list](#before-submitting-a-bug-report), as you might not need to create one. When you are creating a bug report, please [include as many details as possible](#how-do-i-submit-a-good-bug-report). Fill out [the required template](https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/blob/main/.github/ISSUE_TEMPLATE/1-bug-report.yaml), the information it asks for helps us resolve issues faster. @@ -110,7 +110,7 @@ Enhancement suggestions are tracked as [GitHub issues](https://guides.github.com ### Git Commit Messages -Atala PRISM uses [Conventional commits](https://www.conventionalcommits.org/en/v1.0.0/#specification). Please always provide a commit following these specifications. +Edge Agent uses [Conventional commits](https://www.conventionalcommits.org/en/v1.0.0/#specification). Please always provide a commit following these specifications. #### Commit Message Format diff --git a/Logo.png b/Logo.png deleted file mode 100644 index 16bfa50e4..000000000 Binary files a/Logo.png and /dev/null differ diff --git a/README.md b/README.md index d45bd3aad..b6828dc36 100644 --- a/README.md +++ b/README.md @@ -1,45 +1,43 @@ -# Atala Prism Wallet SDK - Kotlin Multiplatform (Android/JVM) +# Identus Wallet SDK - Kotlin Multiplatform (Android/JVM) ![badge-platform-android] ![badge-platform-jvm] [![Coverage Status](https://coveralls.io/repos/github/input-output-hk/atala-prism-wallet-sdk-kmm/badge.svg?branch=main)](https://coveralls.io/github/input-output-hk/atala-prism-wallet-sdk-kmm?branch=main) -![Atala Prism Logo](Logo.png) - -# Welcome to Atala PRISM Kotlin multiplatform SDK +# Welcome to Identus Kotlin multiplatform SDK The following 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. -This SDK provides a library and documentation for developers to build Android and JVM connected SSI applications with Atala PRISM. +This SDK provides a library and documentation for developers to build Android and JVM connected SSI applications with Identus. ## Basic considerations -### Atala PRISM +### Identus -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 (Decentralized identifiers) and verifiable credentials, alongside tools and frameworks to help expand your ecosystem. +Identus 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 (Decentralized identifiers) and verifiable credentials, alongside tools and frameworks to help expand your ecosystem. The complete platform is separated in multiple repositories: -* [atala-prism-wallet-sdk-swift](https://github.com/input-output-hk/atala-prism-wallet-sdk-swift) - Repo that implements Atala PRISM for Apple platforms in Swift. -* [atala-prism-wallet-sdk-ts](https://github.com/input-output-hk/atala-prism-wallet-sdk-ts) - Repo that implements Atala PRISM for Browser and Node.js platforms in Typescript. +* [atala-prism-wallet-sdk-swift](https://github.com/input-output-hk/atala-prism-wallet-sdk-swift) - Repo that implements Identus for Apple platforms in Swift. +* [atala-prism-wallet-sdk-ts](https://github.com/input-output-hk/atala-prism-wallet-sdk-ts) - Repo that implements Identus for Browser and Node.js platforms in Typescript. * [atala-prism-building-blocks](https://github.com/hyperledger-labs/open-enterprise-agent) - Repo that contains the platform Building Blocks. * [atala-prism-mediator](https://github.com/input-output-hk/atala-prism-mediator) - Repo for DIDComm V2 Mediator ### Modules / APIs -Atala PRISM Kotlin multiplatform 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. +Identus Kotlin multiplatform 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. * __Apollo__: Building block that provides a suite of cryptographic operations. * __Castor__: Building block that provides a suite 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. -* __PrismAgent__: PrismAgent using all the building blocks provides an agent that can provide a set of high level DID functionalities. +* __EdgeAgent__: EdgeAgent using all the building blocks provides an agent that can provide a set of high level DID functionalities. ## Getting started ### Setup -To get started with the Atala PRISM kotlin multiplatform SDK, you can set up the SDK and start a new project or integrate it into an existing project. Before you start, make sure you have the following installed on your development machine: +To get started with the Identus kotlin multiplatform SDK, you can set up the SDK and start a new project or integrate it into an existing project. Before you start, make sure you have the following installed on your development machine: - Android: API level 21 and above. - Kotlin 1.9.22 or later. @@ -50,7 +48,7 @@ To get started with the Atala PRISM kotlin multiplatform SDK, you can set up the To integrate the SDK into an existing project, you have to import the SDK into your project: ```kotlin -implementation("io.iohk.atala.prism.walletsdk:atala-prism-sdk:") +implementation("org.hyperledger.identus:edge-agent-sdk:") ``` diff --git a/atala-prism-sdk/build.gradle.kts b/atala-prism-sdk/build.gradle.kts deleted file mode 100644 index 32f29b0d4..000000000 --- a/atala-prism-sdk/build.gradle.kts +++ /dev/null @@ -1,312 +0,0 @@ -import com.android.build.gradle.tasks.PackageAndroidArtifact -import com.android.build.gradle.tasks.SourceJarTask -import org.gradle.internal.os.OperatingSystem -import org.jetbrains.dokka.gradle.DokkaTask -import org.jetbrains.kotlin.gradle.tasks.KotlinCompile -import java.net.URL - -val currentModuleName: String = "AtalaPrismSDK" -val os: OperatingSystem = OperatingSystem.current() -val apolloVersion = project.property("apollo_version") -val didpeerVersion = project.property("didpeer_version") - -plugins { - id("app.cash.sqldelight") version "2.0.1" - kotlin("multiplatform") - kotlin("plugin.serialization") - id("com.android.library") - id("org.jetbrains.dokka") - id("org.jetbrains.kotlinx.kover") version "0.7.6" -} - -kover { - useJacoco("0.8.11") - excludeJavaCode() - excludeInstrumentation { - packages("androidx.test.espresso", "androidx.test.ext") - } -} - -koverReport { - filters { - excludes { - packages( - "io.iohk.atala.prism.protos", - "io.iohk.atala.prism.walletsdk.domain", - "io.iohk.atala.prism.walletsdk.pluto.data" - ) - } - } - - defaults { - xml { - setReportFile(layout.buildDirectory.file("reports/jvm/result.xml")) - } - html { - title = "Wallet SDK - JVM" - setReportDir(layout.buildDirectory.dir("reports/jvm/html")) - } - } - - androidReports("release") { - xml { - setReportFile(layout.buildDirectory.file("reports/android/result.xml")) - } - html { - title = "Wallet SDK - Android" - setReportDir(layout.buildDirectory.dir("reports/android/html")) - } - } -} - -/** - * The `javadocJar` variable is used to register a `Jar` task to generate a Javadoc JAR file. - * The Javadoc JAR file is created with the classifier "javadoc" and it includes the HTML documentation generated - * by the `dokkaHtml` task. - */ -val javadocJar by tasks.registering(Jar::class) { - archiveClassifier.set("javadoc") - from(tasks.dokkaHtml) -} - -kotlin { - androidTarget { - publishAllLibraryVariants() - } - - jvm { - compilations.all { - kotlinOptions { - jvmTarget = "17" - } - } - testRuns["test"].executionTask.configure { - useJUnitPlatform() - } - publishing { - publications { - withType { - artifact(javadocJar) - } - } - } - } - applyDefaultHierarchyTemplate() - - sourceSets { - val commonMain by getting { - kotlin.srcDir("${project(":protosLib").layout.buildDirectory.asFile.get()}/generated/source/proto/main/kotlin") - resources.srcDir("${project(":protosLib").projectDir}/src/main") - dependencies { - implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.8.0") - implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.5.0") - implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.2") - - implementation("io.ktor:ktor-client-core:2.3.4") - implementation("io.ktor:ktor-client-content-negotiation:2.3.4") - implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.4") - implementation("io.ktor:ktor-client-logging:2.3.4") - implementation("io.ktor:ktor-websockets:2.3.4") - - implementation("io.iohk.atala.prism.didcomm:didpeer:$didpeerVersion") - - implementation("io.iohk.atala.prism.apollo:apollo:$apolloVersion") - implementation("org.kotlincrypto.hash:sha2:0.4.0") - - implementation("pro.streem.pbandk:pbandk-runtime:0.14.2") - - implementation("org.didcommx:didcomm:0.3.2") - - implementation("com.google.protobuf:protoc:3.12.0") { - exclude("com.google.protobuf") - } - - implementation("app.cash.sqldelight:coroutines-extensions:2.0.1") - - api("org.lighthousegames:logging:1.1.2") - - implementation("io.iohk.atala.prism.anoncredskmp:anoncreds-kmp:0.4.6") - implementation("com.ionspin.kotlin:bignum:0.3.9") - implementation("org.bouncycastle:bcprov-jdk15on:1.68") - } - } - val commonTest by getting { - dependencies { - implementation(kotlin("test")) - implementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.8.0") - implementation("io.ktor:ktor-client-mock:2.3.4") - implementation("junit:junit:4.13.2") - implementation("org.mockito:mockito-core:4.4.0") - implementation("org.mockito.kotlin:mockito-kotlin:4.0.0") - } - } - val jvmMain by getting { - dependencies { - implementation("io.ktor:ktor-client-okhttp:2.3.4") - implementation("app.cash.sqldelight:sqlite-driver:2.0.1") - implementation("io.ktor:ktor-client-java:2.3.4") - } - } - val jvmTest by getting - val androidMain by getting { - dependencies { - implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.0") - implementation("io.ktor:ktor-client-okhttp:2.3.4") - implementation("app.cash.sqldelight:android-driver:2.0.1") - implementation("io.ktor:ktor-client-android:2.3.4") - } - } - val androidInstrumentedTest by getting { - dependencies { - implementation("androidx.test.espresso:espresso-core:3.5.1") - implementation("androidx.test.ext:junit:1.1.5") - implementation("junit:junit:4.13.2") - } - } - /* - Not going to support JS for the time being - val jsMain by getting - val jsTest by getting - */ - - all { - languageSettings { - optIn("kotlin.RequiresOptIn") - optIn("kotlin.ExperimentalStdlibApi") - } - } - } -} - -android { - compileSdk = 34 - sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml") - namespace = "io.iohk.atala.prism.walletsdk" - defaultConfig { - minSdk = 21 - testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - } - compileOptions { - sourceCompatibility = JavaVersion.VERSION_17 - targetCompatibility = JavaVersion.VERSION_17 - } - /** - * Because Software Components will not be created automatically for Maven publishing from - * Android Gradle Plugin 8.0. To opt-in to the future behavior, set the Gradle property android. - * disableAutomaticComponentCreation=true in the `gradle.properties` file or use the new - * publishing DSL. - */ - publishing { - multipleVariants { - withSourcesJar() - withJavadocJar() - allVariants() - } - } - - packaging { - resources { - merges += "**/**.proto" - } - } -} - -sqldelight { - databases { - create("PrismPlutoDb") { - packageName.set("io.iohk.atala.prism.walletsdk") - srcDirs.setFrom("src/commonMain/sqldelight") - } - } -} - -// Dokka implementation -tasks.withType().configureEach { - moduleName.set(currentModuleName) - moduleVersion.set(rootProject.version.toString()) - description = "This is a Kotlin Multiplatform implementation of AtalaPrismSDK" - dokkaSourceSets { - configureEach { - jdkVersion.set(17) - languageVersion.set("1.9.22") - apiVersion.set("2.0") - includes.from( - "docs/AtalaPrismSDK.md", - "docs/Apollo.md", - "docs/Castor.md", - "docs/Mercury.md", - "docs/Pluto.md", - "docs/Pollux.md", - "docs/PrismAgent.md" - ) - sourceLink { - localDirectory.set(projectDir.resolve("src")) - remoteUrl.set(URL("https://github.com/input-output-hk/atala-prism-wallet-sdk-kmm/tree/main/src")) - remoteLineSuffix.set("#L") - } - externalDocumentationLink { - url.set(URL("https://kotlinlang.org/api/latest/jvm/stdlib/")) - } - externalDocumentationLink { - url.set(URL("https://kotlinlang.org/api/kotlinx.serialization/")) - } - externalDocumentationLink { - url.set(URL("https://api.ktor.io/")) - } - externalDocumentationLink { - url.set(URL("https://kotlinlang.org/api/kotlinx-datetime/")) - packageListUrl.set(URL("https://kotlinlang.org/api/kotlinx-datetime/")) - } - externalDocumentationLink { - url.set(URL("https://kotlinlang.org/api/kotlinx.coroutines/")) - } - } - } -} - -val buildProtoLibsGen: Task by tasks.creating { - group = "build" - this.dependsOn(":protosLib:generateProto") -} - -afterEvaluate { - tasks.getByName("runKtlintCheckOverCommonMainSourceSet") { - dependsOn(buildProtoLibsGen) - } - tasks.getByName("build") { - dependsOn(buildProtoLibsGen) - } - tasks.withType { - dependsOn(buildProtoLibsGen) - } - tasks.withType { - dependsOn(buildProtoLibsGen) - } - tasks.withType { - dependsOn(buildProtoLibsGen) - } - tasks.withType { - dependsOn(buildProtoLibsGen) - } - tasks.withType { - dependsOn(buildProtoLibsGen) - } - tasks.named("packageDebugResources") { - dependsOn(buildProtoLibsGen) - } - tasks.named("packageReleaseResources") { - dependsOn(buildProtoLibsGen) - } - tasks.named("androidReleaseSourcesJar") { - dependsOn(buildProtoLibsGen) - } - tasks.named("androidDebugSourcesJar") { - dependsOn(buildProtoLibsGen) - } - tasks.named("jvmSourcesJar") { - dependsOn(buildProtoLibsGen) - } - tasks.named("sourcesJar") { - dependsOn(buildProtoLibsGen) - } -} diff --git a/atala-prism-sdk/docs/Apollo.md b/atala-prism-sdk/docs/Apollo.md deleted file mode 100644 index 67780e61f..000000000 --- a/atala-prism-sdk/docs/Apollo.md +++ /dev/null @@ -1,35 +0,0 @@ -# Package io.iohk.atala.prism.walletsdk.apollo - -Apollo is a suite of cryptographic primitives designed to ensure the integrity, authenticity, and confidentiality of stored and processed data. 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 ensures data integrity. Hashing is frequently used to build more complex schemes, such as Merkle trees or digital signatures. Hashes can be used independently to ensure the integrity of large chunks of data or as a fundamental 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 an essential 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 mainly 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's trees are the most common type of accumulator used in the cryptocurrency domain. Accumulators make it possible to check (and prove) whether a given value has been accumulated. - -### 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 their exchange messages. 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. - -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. diff --git a/atala-prism-sdk/docs/AtalaPrismSDK.md b/atala-prism-sdk/docs/AtalaPrismSDK.md deleted file mode 100644 index 9618bab38..000000000 --- a/atala-prism-sdk/docs/AtalaPrismSDK.md +++ /dev/null @@ -1,60 +0,0 @@ -# Module AtalaPrismSDK - -Atala PRISM KMP SDK is a library and documentation that helps developers build KMM/JVM/Android 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 fundamental considerations around the project. - -## What is Atala PRISM? - -Atala PRISM is a self-sovereign identity (SSI) platform and service suite for verifiable data and digital identity. Built on Cardano, it offers the core infrastructure for issuing DIDs and verifiable credentials alongside tools and frameworks to help expand your ecosystem. - -## Technical Considerations - -The architecture of the SDK results from a careful evaluation of different software development methodologies and patterns. We chose a modular, clean architecture based on interface/protocol-oriented programming, domain-oriented programming principles, and dependency injection for several reasons that we will explain in this document. - -### Overview - -#### Modular Clean Architecture - -Modular clean architecture is a software development methodology that emphasizes separating concerns and the creation of independent modules that can be easily tested and maintained. This approach promotes using small, reusable components that can be combined differently 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. - -#### Interface/Protocol-Oriented Programming - -Protocol-oriented programming is a programming paradigm that focuses on the behaviour of objects rather than their structure. This approach promotes the use of protocols to define the behaviour of objects, allowing for more flexible and extensible code. The SDK architecture uses this approach to ensure 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 a system's domain-specific requirements rather than the implementation's technical details. This approach promotes the use of domain-specific models and concepts, which can 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 system components. This approach encourages the use of interfaces and dependency injection containers to ensure that each element 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 separately, making it easier for developers to add new functionality to the system without affecting the existing code. - -## Building Blocks - -The building blocks are the core components of Atala PRISM, and they are designed to work together seamlessly to provide a comprehensive identity management solution. - -### Overview - -Each building block serves a specific purpose, providing a solid foundation for building decentralized identity applications. - -Let's take a closer look at each building block: - -- **Apollo**: Apollo is a building block that provides a suite of cryptographic operations. This includes secure hash algorithms, digital signatures, and encryption, all essential for creating a safe and tamper-proof identity system. Apollo ensures that all data within the Atala PRISM system is securely encrypted and digitally signed, making it resistant to tampering and unauthorized access. -- **Castor**: Castor is a building block that provides a suite of decentralized identifier (DID) operations in a user-controlled manner. DIDs are a vital component of decentralized identity, as they provide a way to uniquely identify individuals and entities in a decentralized manner. Castor allows users to create, manage, and control their DIDs and associated cryptographic keys. -- **Pollux**: Pollux is a building block that provides a suite of credential operations in a privacy-preserving manner. Credentials are a way to prove claims about an individual or entity, and they are an essential part of decentralized identity. Pollux allows users to create, manage, and share credentials in a privacy-preserving way to ensure that sensitive information is not revealed. -- **Mercury**: Mercury is a building block that provides a set of secure, standards-based communications protocols that are transport-agnostic and interoperable. Mercury allows different Atala PRISM components to communicate securely using HTTP, WebSocket, and MQTT protocols. -- **Pluto**: Pluto is a building block that provides an interface for storage operations in a portable, storage-agnostic manner. Pluto allows data to be stored and retrieved in a way independent of the underlying storage technology, allowing Atala PRISM to work with various storage solutions. - -Together, these building blocks provide a solid foundation for building decentralized identity applications that are secure, privacy-preserving, and interoperable. Using Atala PRISM, developers can focus on creating innovative identity solutions without worrying about the underlying infrastructure. - -### Prism Agent - -Prism Agent is a comprehensive library that combines all the Prism platform's building blocks - Apollo, Castor, Pluto, Mercury, and Pollux - to provide a seamless experience for developers working with decentralized identifiers (DIDs) on the Prism platform. - -## Documentation - -#### General information and articles - -- [Getting Started](https://docs.atalaprism.io/docs/getting-started) -- [What is identity?](https://docs.atalaprism.io/docs/concepts/what-is-identity) -- [Digital wallets](https://docs.atalaprism.io/docs/concepts/digital-wallets) -- [Atala PRISM Overview](https://docs.atalaprism.io/docs/atala-prism/overview) diff --git a/atala-prism-sdk/docs/Castor.md b/atala-prism-sdk/docs/Castor.md deleted file mode 100644 index 5e6e8a21d..000000000 --- a/atala-prism-sdk/docs/Castor.md +++ /dev/null @@ -1,13 +0,0 @@ -# Package io.iohk.atala.prism.walletsdk.castor - -Castor is a powerful and flexible library for working with DIDs. Whether you are building a decentralised application or a more traditional system requiring secure and private identity management, Castor provides the tools and features you need to easily create, manage, and resolve DIDs. - -## A Decentralised 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 various decentralised applications and systems. - -Decentralised Identifiers (DIDs) are new identifier that allows individuals and organisations to create and manage their own digital identity. DIDs provide a secure, decentralised, and privacy-preserving way to authenticate and verify identity without relying on centralised 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 creating and resolving 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 related data. Castor also provides a range of advanced features, such as support for multiple key types and encryption methods and a flexible API for customising and extending its functionality. \ No newline at end of file diff --git a/atala-prism-sdk/docs/Mercury.md b/atala-prism-sdk/docs/Mercury.md deleted file mode 100644 index 117e5fe01..000000000 --- a/atala-prism-sdk/docs/Mercury.md +++ /dev/null @@ -1,13 +0,0 @@ -# Package io.iohk.atala.prism.walletsdk.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 a more complex decentralized system requiring trusted peer-to-peer connections, Mercury provides the tools and features you need to establish, manage, and secure your communications easily. - -## 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. It can be used across a wide range of communication channels and platforms. - -DIDCommV2 is a secure, privacy-preserving messaging protocol that securely and efficiently exchanges information between DIDs. 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 various platforms and use cases. Mercury provides the tools and features you need to get the job done, whether you are building a messaging app, a decentralized social network, or any other application that requires secure and private communications. - -Mercury also provides a range of advanced features, including support for message threading, priority levels, and message expiration and support for a range of transport protocols, including HTTP. diff --git a/atala-prism-sdk/docs/Pluto.md b/atala-prism-sdk/docs/Pluto.md deleted file mode 100644 index 29e2e18b2..000000000 --- a/atala-prism-sdk/docs/Pluto.md +++ /dev/null @@ -1,15 +0,0 @@ -# Package io.iohk.atala.prism.walletsdk.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 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 do the job 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. It can be used with many 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 robust 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 securely and privately. Pluto provides a range of advanced security features, including support for private key storage and encryption and support for multiple storage backends for added redundancy and resilience. - -Pluto also supports a range of DID-related data types, including DIDPairs, which store the public and private keys associated with a DID, and DIDComm messages, which store the encrypted messages sent and received between DIDs. diff --git a/atala-prism-sdk/docs/Pollux.md b/atala-prism-sdk/docs/Pollux.md deleted file mode 100644 index 720570367..000000000 --- a/atala-prism-sdk/docs/Pollux.md +++ /dev/null @@ -1,12 +0,0 @@ -# Package io.iohk.atala.prism.walletsdk.pollux - -A credential contains a set of claims about the subject of the credential. Those claims are made by a single authority called the credential issuer. The entity (person, organization) to whom the credential is issued, i.e., the one who keeps it in their digital wallet, is called the credential holder. Apart from claims, the credential contains the subject identifier (DID) to whom the credential is issued. - -- **Verifiable Credential**: a digital credential that can be cryptographically signed and verified. -- **Issuer**: The entity that issues VCs to holders -- **Holder**: The entity that is currently holding the VC -- **Subject**: An entity to which the credential is issued. Often the holder will be the subject of the credential. -- **Verifier**: An entity that receives and verifies the credential validity and credential ownership of the holder if necessary -- **Wallet**: a hardware/software that enables an issuer to manage credentials (create them, issue, revoke), a holder to receive and store credentials, and a verifier to verify them. A single wallet application can support all the functions. - -There can be wallets for issuers, holders, and verifiers, accessible via mobile/ web apps, browser extensions, or desktop applications. The wallet can enable the functionality of all parties (Issuer, verifier, holder) or be intended to be used by only one party. One entity (person, organization) can be an issuer, verifier, or holder in different scenarios if their wallet supports all these functionalities. diff --git a/atala-prism-sdk/docs/PrismAgent.md b/atala-prism-sdk/docs/PrismAgent.md deleted file mode 100644 index 4a54ad9b1..000000000 --- a/atala-prism-sdk/docs/PrismAgent.md +++ /dev/null @@ -1,13 +0,0 @@ -# Package io.iohk.atala.prism.walletsdk.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 working with a more traditional system that requires reliable and resilient communication between DIDs, Prism Agent provides the tools and features you need to do the job with ease. - -## Overview - -Prism Agent is a comprehensive library that combines all the Prism platform's building blocks - 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 DID management, DIDComm mediation management, and support for various DIDComm protocols, including mediation, proof presentation, issue credentials, and out-of-band messages. - -With Prism Agent, developers can easily manage and communicate with DIDs seamlessly and efficiently. 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 supports receiving messages through the mediator, allowing developers to easily manage and respond to incoming messages securely and efficiently. diff --git a/atala-prism-sdk/karma.config.d/timeout.js b/atala-prism-sdk/karma.config.d/timeout.js deleted file mode 100644 index 2c29ef748..000000000 --- a/atala-prism-sdk/karma.config.d/timeout.js +++ /dev/null @@ -1,9 +0,0 @@ -config.set({ - browserDisconnectTimeout: 5000, - processKillTimeout: 5000, - client: { - mocha: { - timeout: 5000 - } - } -}); diff --git a/atala-prism-sdk/src/androidInstrumentedTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/AndroidIgnore.android.kt b/atala-prism-sdk/src/androidInstrumentedTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/AndroidIgnore.android.kt deleted file mode 100644 index 66be643dc..000000000 --- a/atala-prism-sdk/src/androidInstrumentedTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/AndroidIgnore.android.kt +++ /dev/null @@ -1,5 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent - -import org.junit.Ignore - -actual typealias AndroidIgnore = Ignore diff --git a/atala-prism-sdk/src/androidInstrumentedTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/AnoncredsTests.kt b/atala-prism-sdk/src/androidInstrumentedTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/AnoncredsTests.kt deleted file mode 100644 index aa26904a0..000000000 --- a/atala-prism-sdk/src/androidInstrumentedTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/AnoncredsTests.kt +++ /dev/null @@ -1,186 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent - -import androidx.test.ext.junit.runners.AndroidJUnit4 -import anoncreds_wrapper.LinkSecret -import io.iohk.atala.prism.walletsdk.domain.models.Api -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentBase64 -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentDescriptor -import io.iohk.atala.prism.walletsdk.domain.models.ClaimType -import io.iohk.atala.prism.walletsdk.domain.models.CredentialType -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.logger.PrismLoggerMock -import io.iohk.atala.prism.walletsdk.mercury.ApiMock -import io.iohk.atala.prism.walletsdk.pollux.PolluxImpl -import io.iohk.atala.prism.walletsdk.pollux.models.CredentialRequestMeta -import io.iohk.atala.prism.walletsdk.pollux.models.LinkSecretBlindingData -import io.iohk.atala.prism.walletsdk.prismagent.protocols.issueCredential.CredentialPreview -import io.iohk.atala.prism.walletsdk.prismagent.protocols.issueCredential.IssueCredential -import io.iohk.atala.prism.walletsdk.prismagent.protocols.issueCredential.OfferCredential -import io.ktor.http.HttpStatusCode -import junit.framework.TestCase.assertEquals -import junit.framework.TestCase.assertTrue -import kotlinx.coroutines.flow.flow -import kotlinx.coroutines.test.runTest -import kotlinx.serialization.json.Json -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith - -@RunWith(AndroidJUnit4::class) -class AnoncredsTests { - - lateinit var apolloMock: ApolloMock - lateinit var castorMock: CastorMock - lateinit var plutoMock: PlutoMock - lateinit var mercuryMock: MercuryMock - lateinit var polluxMock: PolluxMock - lateinit var mediationHandlerMock: MediationHandlerMock - lateinit var connectionManager: ConnectionManager - lateinit var json: Json - - val getCredentialDefinitionResponse = - "{\"schemaId\":\"http://host.docker.internal:8000/prism-agent/schema-registry/schemas/5e0d5a93-4bfd-3111-a956-5d5bc82f76cc\",\"type\":\"CL\",\"tag\":\"licence\",\"value\":{\"primary\":{\"n\":\"105195159277979097653318357586659371305119697478469834190626350283715795188687389523188659352120689851168860621983864738336838773213022505168653440146374011050277159372491059901432822905781969400722059341786498751125483895348734607382548396665339315322605154516776326303787844694026898270194867398625429469096229269732265502538641116512214652017416624138065704599041020588805936844771273861390913500753293895219370960892829297672575154196820931047049021760519166121287056337193413235473255257349024671869248216238831094979209384406168241010010012567685965827447177652200129684927663161550376084422586141212281146491949\",\"s\":\"85376740935726732134199731472843597191822272986425414914465211197069650618238336366149699822721009443794877925725075553195071288777117865451699414058058985000654277974066307286552934230286237253977472401290858765904161191229985245519871949378628131263513153683765553672655918133136828182050729012388157183851720391379381006921499997765191873729408614024320763554099291141052786589157823043612948619201525441997065264492145372001259366749278235381762443117203343617927241093647322654346302447381494008414208398219626199373278313446814209403507903682881070548386699522575055488393512785511441688197244526708647113340516\",\"r\":{\"dateofissuance\":\"16159515692057558658031632775257139859912833740243870833808276956469677196577164655991169139545328065546186056342530531355718904597216453319851305621683589202769847381737819412615902541110462703838858425423753481085962114120185123089078513531045426316918036549403698066078445947881055316312848598741184161901260446303171175343050250045452903485086185722998336149005743485268486377824763449026501058416292877646187105446333888525480394665310217044483841168928926515929150167890936706159800372381200383816724043496032886366767166850459338411710056171379538841845247931898550165532492578625954615979453881721709564750235\",\"drivingclass\":\"83649701835078373520097916558245060224505938113940626586910000950978790663411517512280043632278010831292224659523658613504637416710001103641231226266903556936380105758523760424939825687213460920436570466066231912959327201876189240504388424799892400351592593406285436824571943165913587899115814843543998396726679289422080229750418336051741708013580146373647528674381958028243228435161765957312248113519708734663989428761879029086059388435772829434952754093999424834120341657211221855300108096057633128467059590470639772605075954658131680801785637700237403873940041665483384938586320674338994185073499523485570537331062\",\"emailaddress\":\"96995643129591814391344614133120459563648002327749700279517548454036811217735867585059116635583558148259032071807493674533230465312311981127622542797279917256478867847832932893748528200469349058284133058865149153179959849308383505167342565738382180666525211256221655129861213392455759272915565057394420728271409215556596974900718332893753172173500744392522771654048192448229319313386967045678744665093451560743782910263014930200762027209565313884859542996067229707388839912195826334964819133016500346618083969320902775088800287566711941842968839787149808739739233388585677095545116231323172342995837636586249573194609\",\"drivinglicenseid\":\"102840929811153624977554462471309185033977661854754815794111114507549576719389525167082631547450413573293352276930065480432301200611396989595571202142654033217842162456070556560693402484110499573693863745648118310258284468114751958738878996458420605301017450868522680454545537837403398645500541915771765220093329728663621098538954397330411649083351383375839056527007892276284168437065687748085384178113959961057476582871100422859953560730152958588610850909069434658487744782540788968302663076149478487413357533660817020800754493642858564081116318655661240523146995256712471572605700346459123074377380656921337264554594\",\"familyname\":\"2428690037146701497427424649573806616639612325136606164619283916796880313617677563507218774958436668407050506838114136163250163675016510113975582318007560622124292458766639319715064358235569650961433812439763343736699708535945693241909905707497180931492818502593885932421170612418693515054756633264933222189766691632082890045477718331705366111669009551578289182848340651375008362238266590844461708981816856194045325523248527964502118319210042254240848590574645476930113881493472578612352948284862674703949781070309344526122291448990325949065193279599181502524961004046979227803224474342778516917124487012958845744311\",\"master_secret\":\"96236339155824229583363924057798366491998077727991424922911165403434522806469328114407334094535810942859512352089785125683335350062474092708044674085769524387654467267128528564551803293661877480971961092735622606052503557881856409855812611523475975566606131897917979412576797874632169829901968854843162299366867885636535326810998541141840561418097240137120398317445832694001031827068485975315937269024666370665530455146256019590700349556357390218401217383173228376078058967743472704019765210324846681867991543267171763037513180046865961560351035005185946817643006206395175857900512245900162751815626427008481585714891\"},\"rctxt\":\"54359809198312125478916383106913469635175253891208897419510030559787479974126666313900084654632259260010008369569778456071591398552341004538623276997178295939490854663263886825856426285604332554317424030793691008221895556474599466123873279022389276698551452690414982831059651505731449763128921782866843113361548859434294057249048041670761184683271568216202174527891374770703485794299697663353847310928998125365841476766767508733046891626759537001358973715760759776149482147060701775948253839125589216812475133616408444838011643485797584321993661048373877626880635937563283836661934456534313802815974883441215836680800\",\"z\":\"99592262675748359673042256590146366586480829950402370244401571195191609039150608482506917768910598228167758026656953725016982562881531475875469671976107506976812319765644401707559997823702387678953647104105378063905395973550729717937712350758544336716556268064226491839700352305793370980462034813589488455836259737325502578253339820590260554457468082536249525493340350556649403477875367398139579018197084796440810685458274393317299082017275568964540311198115802021902455672385575542594821996060452628805634468222196284384514736044680778624637228114693554834388824212714580770066729185685978935409859595244639193538156\"}},\"issuerId\":\"did:prism:604ba1764ab89993f9a74625cc4f3e04737919639293eb382cc7adc53767f550\"}" - - @Before - fun setup() { - apolloMock = ApolloMock() - castorMock = CastorMock() - plutoMock = PlutoMock() - mercuryMock = MercuryMock() - polluxMock = PolluxMock() - mediationHandlerMock = MediationHandlerMock() - // Pairing will be removed in the future - connectionManager = ConnectionManager(mercuryMock, castorMock, plutoMock, mediationHandlerMock, mutableListOf(), polluxMock) - json = Json { - ignoreUnknownKeys = true - prettyPrint = true - isLenient = true - } - } - - @Test - fun testAnoncreds_whenOfferReceived_thenProcessed() = runTest { - val fromDID = DID("did:prism:asdf42sf") - val toDID = DID("did:prism:asdf42sf") - - val apiMock: Api = ApiMock( - HttpStatusCode(200, "Ok"), - getCredentialDefinitionResponse - ) - val pollux = PolluxImpl(castorMock, apiMock) - plutoMock.getLinkSecretReturn = flow { emit(LinkSecret().getValue()) } - - val agent = PrismAgent( - apollo = apolloMock, - castor = castorMock, - pluto = plutoMock, - mercury = mercuryMock, - pollux = pollux, - connectionManager = connectionManager, - seed = null, - api = ApiMock(statusCode = HttpStatusCode.OK, response = "{\"success\":\"true\"}"), - logger = PrismLoggerMock() - ) - - val attachmentDescriptor = - AttachmentDescriptor( - mediaType = "application/json", - format = CredentialType.ANONCREDS_OFFER.type, - data = AttachmentBase64( - "eyJzY2hlbWFfaWQiOiJodHRwOi8vaG9zdC5kb2NrZXIuaW50ZXJuYWw6ODAwMC9wcmlzbS1hZ2VudC9zY2hlbWEtcmVnaXN0cnkvc2NoZW1hcy81ZTBkNWE5My00YmZkLTMxMTEtYTk1Ni01ZDViYzgyZjc2Y2MiLCJjcmVkX2RlZl9pZCI6Imh0dHA6Ly8xOTIuMTY4LjY4LjEwMjo4MDAwL3ByaXNtLWFnZW50L2NyZWRlbnRpYWwtZGVmaW5pdGlvbi1yZWdpc3RyeS9kZWZpbml0aW9ucy81ZTI5NWNmMi00MjI2LTNjN2QtYjI3Zi04N2JlMTYwNjQ3NmQvZGVmaW5pdGlvbiIsImtleV9jb3JyZWN0bmVzc19wcm9vZiI6eyJjIjoiMTAyNTI4NDk1NTgzODg5MzkwMDcxMzk2OTI1ODg2NzI1MDk2MDMwNjY4ODgwOTMzNzQ5NTUzODEyNTY3MzE0NjQ0ODE0ODU2Nzk2NjI4IiwieHpfY2FwIjoiMTA4NzM1NDQ3NTAzNTQwNDc2MDIyOTAzNTYxNDY1Nzk4NzExMDA5MTU3MDcwOTY1MjMzNzIyNTAzMzg1NDY2NjIyNjYxNDgyMDkzMjAyMjg2ODcxMDQ5MDM3MDA5NzA1ODg3OTUzMDY5NjczNjA4Mzg5MTQ4NzY5ODI1NjMyNTU3NTk0Mzg3NDI2MjkzODY5OTIxNTg4MTM0MzI1OTczODg5NDY1NjYzNzM4ODA4ODg5NTE3Njc4MzIwOTYxNTk0NDg5MjYxNzI3ODAxMTc1OTMxMTQ2MjcwNDk3MzE5NTc4MTc4NDg3Nzg3MTAxNzg1ODMwMjE2NjgzODk2ODE1ODUyNjgzNDc5NjUxMzQ5NDY3MzUzNzM4MjM0NjE4NTMyODIyMzU1MTQ3ODcxOTU5NTU5ODgzNTUxOTQ5OTkwODY0ODEzNTYyODU3NzU5NDU4MTg1MDI5MDI3NTI1NTMzMDQyMDQ5MjEwMDA4NTg3MTc2MzQwNTg4Nzc2Mjc0MzgxMDU2MzM5ODE0OTAzMTMyNjI2MzIyMzc3MjAwMjYwMjM4NDcwNjcyMzI4NDQ4NzIyOTk4NDc1MDIwMzA4MjY2NDIzODUyNzA3Njk2OTQyNjk3NDc3MzI0MDUzOTM0MjQ3NDU4MDcxNjkyMDM5OTQ4MDkxMDg5MjA0NDQ2MDkyODY0Njc1NTQyMDA0Nzk1MDUyNjMzNzczMTQyMDc4Mzg0MTA1MDQzMDY4NjQ3Nzg3NzY3MDE1MDc5MjE1OTEzNTIzODIxOTU4NDQ2NTAxODY2ODY1OTE1NzEwNjY1NDU1MzU4ODEwNTY0OTk3MDUwNjAzNDc4NDE0MzA4NDQzMzc3Njg3ODUyMzc4NDgwNzg3MTQ1MDY2MTQ5MzA5MTM0NzMyNDg4NzQzMTg1NDgxMzU5MzA1NTM3MiIsInhyX2NhcCI6W1siZGF0ZW9maXNzdWFuY2UiLCIxODg0NTYwNDI1ODExNzgxNjE2Njc5NjAyMzA5ODExOTI5NzEyNDA4MDA0MzkxMDEyNzk3ODAxODA0MzU0MzQ0MTI3NDI2MTk0ODg5NDI3MjU3NjQzMzg2MTkxNTY0NDM5ODUzOTQ2NTg4MzkyNjMwNzEwMzA1OTM2OTAxNDA3NjYwOTk2NDc5ODkxNTgzNDE2NDkxODYyNzA3MTczOTA2OTg4ODEzNDE5ODQyMDg1MDM1MTg1OTA0MzQ2MTU4OTM2NDIyOTY5OTMwODg4Njg3NTc0MDcyMzY5MDc2NjkxNTk4MjkyMDkwNDA3Mjg5ODM2NDc2ODQyNTc2MjI3MzAzNDAwOTI4MjkwMDM0NTYwNjk5NTg1NTMzMzkxNDg0OTMwMDQ3NTEwMzMxNDQxNjAyMzEwNjM3NDg2MjY2OTIyNTIyNTIxMzQ2ODM5ODkxMDg1ODM3NTczMzAzMjkyNzMyNTA5Mzc0MTI0ODgzMTA0MjEzNzYzMDA3NzMwOTY4Mzg4MDc0NzE3ODc5NDM5NjE5Njg1NzY4MjU1OTg4MjY0NjMxMTk1MTU3MjE3NjExMTE0NzE3Njc4NjUzMTc0NDc2MTc4MjA4NTIwNzk2MDkwNzI2MzE1MjIzMDU4MTk4NjM3NjU4NDU2NTA3NDcyNzA4MDI0OTgzMjUzNjQyMDAwNDI0MjQyNTUyMDcwNzUzMTg3MDI3MTE0MTI1NzQ0MzExNzMxOTM1NjgwNDE1MTk5NzI4OTE2NjgxNTY2MzY2NjkxNDQyMzE4OTE3NDAxMzA0MzMzNzI5ODU0MzQ2MTAwNDI2NDE1MzEwMzYwNjQ4NDg3NDYzNzgxNjI5NDQ2ODU3ODg2NjgzNTIzODk2ODcyMTExNDg3MjUwNjgwMDQzOTIxMzgyMDM1MDkxMTg4NzE1MDAwNTIzIl0sWyJlbWFpbGFkZHJlc3MiLCIxNTUwMTI2ODAwMjA1MzI5Mzg3NzcyNjA4OTY3NDk0NDIyOTc0MjU1MTI1NDU0NTEyOTc3NjExNTgyNDE2Nzc1MDg2OTA1NjIzNDUzMTIxNDg0NzM0MzkyNDQ4NzEyNTQyNTYwODUyMjUzNzcyODI2NTYyNjg5NzY1NjYwMzM3OTUyNTEyODQ4MDA1Mzk1NTQxMzcwMTI1Mzk4NDg4OTIxNDM4NDUwNzMxMzYwNTcwMzQ2MjMyNDEyODgzMzQ5NjU4MjMxOTQ5OTgwMTUwMTI2NTQ3Nzg0NTM2ODE2NzM0Njc2Mzg1NDA2OTM1MDQ4NDQ0NDM1ODY2MzYwNTk2MjE3NTM4Njg1NTg5MDE3NDY1NTg2MzI1MDQxNzc1OTcwMzQ1NjY1MjM3MzcyMDA3MjAxNTczNDAwODk3NDA3MDA0OTY1Nzk1MDE3MDQ2NDI5MzM5MzMwMTg2NjAwNzE1MjE3Mjg3ODk3Mjg1MDk1MTEwMzExMDYxODU1OTE1NjQ3Nzk3MTkyNTc4NDI1MDgzMjAwMTIwNDEyNTU4NDM2MjQyNTc0ODIzNjE4NTAxODY5NTQxNzAwMTU5NjMyNDkwNDgxMzY3ODU2NjA5MTAwNjA4MzI0MDcyODk3MjA3NDQxNzgwNDc1Njg4MTk4ODI3MDE1MjE2MDA5OTA4NjY0NTYwODk5MDMzODYxNjk1NTg2OTE1NzI4NjYwMDkzMjM3Njk4NzUzODMwOTAxODQ2MDE1OTU0NzEzNTc5MTc5NDgyMDMyNjIxMTEyNjA3NDcyOTM5NzYyNjM4OTgzMDkyNDE0NTgzMzMyODI2MjUzMTE3NDMwNTAwOTI2NTcwODcxNjI2MzYyMTQxNTM0NzUwMDQwMTkxNzEzMzE4OTQ1NTIwNDUzOTI5Mjk5Nzk3ODc2NDEyNzI3MzgiXSxbImZhbWlseW5hbWUiLCIyMDM1NjQzMjQ2ODM3MTA2MDc3MzEzNTkwOTY1Nzc2ODc1ODkwMjM0MTI0MDQ2MjcyOTc0OTQ0MDMxOTIxNzQ4NjQ1ODA0NDc2MjExODc4NTA1MTEzODE5NzYzMjM3MjczMTM4MjgzNDE1MTE2ODYyMzMwNTg0Mjc4NzcxNjg5NjMyNTIyNzE4NjYzMzkwOTg2MjI0NTA3NDg3OTc3MDk2MDMxMTAzMDY1MDQzNjI5Nzk3NjAzMjM2MTc1ODczOTA0MzUwMjMyNjU1Mjc2NzEzNjIxOTUwNzExNjExMzMzODM5OTE0OTU2MzEyNzM4NDkyNjI5NjQ3Nzk2NTk4NDUzOTM2MTY1NjIwNDI1MTc4OTU0NzE2MjE1OTUzNzQyNjM4NDk0NzA3NzMxNjM2NTc0OTI0Njc4MTk5NDQzMjY1MDU4NDM4MTc3NjE0NTM3NjE5NTI0NzY0MDkxNTY1NzUxODg0OTkzMTU4ODc3NjIxMjMxNzc5MDkzOTIyNzQ0NzM4Nzk5OTEwOTg0OTczOTMyMzYwNzM0OTA3NTQ1NTAxOTE2OTUyOTU3MTEwNTczMjQzODA5MDA1NzE5MjU5MTg1MzgwODI4NTU2MzgwMDA1NzU4MTkzNjIwMzc5MzA5NTk1NTgyMTAxMDEwOTg2MDkyNTE3NjM4Njc3NDYwMTQ5MzQ5ODc5NjYyMzc0MTQ0NzUwMDkyODAzNTE1OTUwMzc0MzkzMTAzMTY5MDYzNTE4ODczNTMzMjAxMjAxMjg4NzU3NjczNzk2OTAzOTAzMTEyNzYyMDgxNjE0MzY1NjgwNjEyNzQ1OTEyMTQ4Mjg0NTQ2MzgxOTA4NDAzNzExMDYwNzc0NDQzNDQyMjc3NTU5MjcyMjkzMDg2MzEzMzg5MDQ4ODA0MzA5OTg0NjgyMDA4MDgxMTYiXSxbImRyaXZpbmdsaWNlbnNlaWQiLCIyMzg0Nzk3NTUyNDQ2NTQ0Nzk3NjQyNTc0NjMyMDU3MjgwODIyODkwODgxNjY4NDQyMTczNDY5OTQ4MDYwOTU0ODU2MjY4MDU2MzQ4MTEyMjQ3MzA4NzYwMDQwNTAxODY4NzE3NDQ4MTI1MDI0NDc2MTcwOTU5Njg0Njc1NzY0MjAwMjc5MTcyMzAwOTgzMTQ1MjgzMDAwMzQzNjIxOTEzNTYwNjA5MzQzNTQyNDM2ODQzNDI0NzkwMzUxNjgwMjg3MDAwNzc4ODM5ODQwMDI0NjA4NDg4NTA5MDQ3MjU3MDI0ODU1Njc5ODk3ODc3NTk5NjU2MTc2NDAwMzk1MTQ0MzY5NjkyNzU4MzIxOTc0MzQyODk2MzY4NzEwMTA3ODIyMTQ4NTM2MzIwMDI0NjYwMzUzNTk1MzA5MDgxMTIwNDQyMTgzNDQ3NzE5NzA5Nzc4MjQxNTI2NDQ4MjU5NTY1NTYyNDUxODYyMDk2OTQzMTUwMzk4ODQ1OTM0ODA3OTM4NjE0MTE4Mzk2MjA5NTc5NDM0OTU2MDk2NzY3OTAzMTE4MDc4MTk1NjE1NzI4MDgwNjA3NzMyOTczMTg2NzU0MTA3Mjc2MTM4OTk1NDQzMzQxNzAxMDQ5OTY3NTc0ODA1MjM2MjEyNTIyNDc0MDI5NTcyOTc0OTk4MjA2NDExMDM5MzQxODY4MzIwMTgwMDU5MzQ4ODE4MDQ5NTgyNjU4ODg0OTI2Nzk2OTAzMzc1OTY4NjMwNjA0MDgwOTE2MTc1ODIzMDIyNjc3ODc5MzE4MDgyODUwNzgwMzQyNDU0ODI4OTEzMTA4Nzk1MDg4NjA1Mzk1NjUxMzM0NTMyNDU3NzUxNjQxNTUwOTE5NDQ4NDAzODM1OTI0NDg5NzYzMjE4NDUyNzUzMzY0NjAzMzE3NzgxMDA0Il0sWyJkcml2aW5nY2xhc3MiLCI3MTMwODIxMTg0NjAwNjAwNjE1Nzk1NDU5NjkyNDYwMzE1NzM4ODA5NTU0MjA0NTQ4OTI1NjA2MzkyNzQ2MjE3MDQyMDI1OTExNjE2NTM4ODQ0ODgyMDgwNjM5MTQ0MjAwMDA2NzIwMzY4MjUzNzMzMzM0ODk1NTQ0NjU5ODU1ODk3MzQzNjc1MzMxNjUwMDI2NjgwNzc1MjgxMzgxMzY0MzcyNTE3ODgzMDI5NTE1MDM2MjQ1ODIyOTUwNzU3MDYwNTk2Nzc5MDE0ODUzODIzMTczNTU0NjczMTk0NjAxODU0MTk2NDQ1NDI3MzIxNTk1Mjk4NTg0OTI5MDM3NTMyMzk3NDMxODE1MDk0Mzk3MjQyODUwMTQ3NjY3NTc0NDM1OTY5ODMzMzE2NDc1MTY0MDM4NjIxMzk1Mzk0ODAxOTg3MzIyOTc0NDY0MjYxNTQyODMxNzI0OTQwNDQ5NjQyMjI5OTA3MzIwNzY2Njg0Nzk0NTgwMDExNzc4NzM0NzI5OTk0MjkxMjAxMDA3NTY5NTE5ODg0ODU3MzU2OTY5NzIwMDUwMTk5OTE3MDk3MjIzOTU3Mjc0MzI2MjkxNjc2Mjc1OTIzOTI1NTQ2MTMxODIxNDE2NDc3MDE3OTk2NzE1OTU3MzAxOTM4MzMyNzU0MzE5OTA0ODkxNDExNDU0MjkzNjMwMDU1NTg4MTUwNjA3ODQ4MTM1MDU1Njk5OTM2OTAxNzAzNTAwNjM2MzgxNDQ5ODAzMTM2NzAyODQwNDcyMjY1MDAzNTczNzk4MDM1NzYyNjIzMzAwOTQzNTQ3Mjk1NDA4OTkxODgyNDMxODEwNzIwNzE3NDE3NjIxNjYxNzUyNzEzNzM2ODQ2MDY4NzExNDk4OTkxMjc2NDcyMDgxNDAzMjEyMzUwNDEzNDA0MjQyNDQiXSxbIm1hc3Rlcl9zZWNyZXQiLCIxNDQ0ODk0NjYyMjg1MjAwNjE4ODEwMjI2MTUxMTk3NjIwMjc0OTgwNTk0NzkzMzU3ODY0MDg1NDA0MzcxNzY2MTA0NzI5OTg0ODI3MjgyNzA4NTkzODUyMDU1NDUwNTUzOTc3MzA3MDQwMTY5NDA1ODgwMTEwMzMxMDU3MDMxNjc4OTM2NDQ2MDQ3NDE4NzE0NDc5OTA3Mjg5MTExMTkxMzA5MDQ2MTMzMzAxMTIzNTk4MTAyMzg0NjQ5ODA3NTQwOTY4NjQ5NzU2MjY4NDAwNDc2NDk5ODY2NDg1MjMxNjkzMDEyMjUxNzA5ODE3OTE3MTMyNjUxNjExNDM0NzkzMTI4NDM5MjQ1NjY3ODE1NjQ2NDUxOTg1ODAyNTg3NDYwMDk4ODk2MDc3OTA3ODUwNTE4NzI4MzMxNzAyMTQ2OTk0NzQzMDUxMDM5ODkwNjA3MzE5NzYyNjkyNTY4NjcwOTY5NDA1OTU2NDU5ODMxMTU5Njg2MTk1OTM3ODM0OTUyNzM2NjY4MDU5NDUxNDM5MTQ3NDI0Njg0ODY2OTg1ODE0Nzg5MzY5NTE0NDczOTExNTA1NjM1OTUwMjg1OTU0NzI3ODE4OTk2MjI4NDI4NTU5NjY3MjM5MDcxNTkwMTI2NzYxOTQ4MDQ5NTE2OTY1MTg4OTE1MTkzMTYxMjk4MDU4NDAwMjk3MDQ2MzQ0NTg2ODk5OTQ2MTA0MDM0ODc2MjkxMjU1NDMxNzYyMTcyMTc3MTEwODk5OTgxOTU1MjM0MDE0NzM2ODgzNTczMjQ1OTA3MTUxNzAzMjM1MDY2MjU0NDU2NzU5NDUxNDIzODcxNTA5NzgwMzA5NDAxODYzNDc4OTgxMjU0MDMwNjE2NDYxNTg4NjU0NjgxMDg5OTk4OTE4NjA2NTc4MjM0ODc5OTg1NjcxIl1dfSwibm9uY2UiOiIxMTE2NzA0MDg4NDcyOTA3NTIzNjkwNDkwIn0=" - ) - ) - - val offerCredential = OfferCredential( - body = OfferCredential.Body( - credentialPreview = CredentialPreview( - attributes = arrayOf( - CredentialPreview.Attribute(name = "Name", value = "Value", mediaType = "application/json") - ) - ) - ), - attachments = arrayOf(attachmentDescriptor), - thid = "1", - from = fromDID, - to = toDID - ) - val requestCredential = agent.prepareRequestCredentialWithIssuer(did = toDID, offer = offerCredential) - - assertEquals(offerCredential.from, requestCredential.to) - assertEquals(offerCredential.to, requestCredential.from) - assertTrue(requestCredential.attachments.size == 1) - assertEquals(requestCredential.attachments[0].format, CredentialType.ANONCREDS_REQUEST.type) - assertEquals(offerCredential.thid, requestCredential.thid) - } - - @Test - fun testAnoncreds_whenCredentialIssued_thenProcessed() = runTest { - val fromDID = DID("did:prism:asdf42sf") - val toDID = DID("did:prism:asdf42sf") - - val apiMock: Api = ApiMock( - HttpStatusCode(200, "Ok"), - getCredentialDefinitionResponse - ) - val pollux = PolluxImpl(castorMock, apiMock) - plutoMock.getLinkSecretReturn = flow { emit(LinkSecret().getValue()) } - val meta = CredentialRequestMeta( - linkSecretBlindingData = LinkSecretBlindingData( - vPrime = "25640768589781180388780947458530942508097609060195936083325202836425537796105863532996457182896416190370043209557677698887790935151362153536943154068082466343529339252470449056527102073900035205398743827912718037139005903291819127500631482122295491777147526837712271367909449810555177615439256541701422814752128559601153332207720895418174855363389532697304935246097129194680107532713993463598420823365761867328806906368762890406604820633668919158697683127114469035627228895027952792675790305070772499052052690434104276748788760647551842035459213572765697025729553350526825112536685989553872204362324245819081933885546131268965572563884162204", - vrPrime = null - ), - linkSecretName = "1", - nonce = "519571990522308752875135" - ) - plutoMock.getCredentialMetadataReturn = flow { emit(meta) } - - val agent = PrismAgent( - apollo = apolloMock, - castor = castorMock, - pluto = plutoMock, - mercury = mercuryMock, - pollux = pollux, - connectionManager = connectionManager, - seed = null, - api = ApiMock(HttpStatusCode.OK, "{\"success\":\"true\"}"), - logger = PrismLoggerMock() - ) - - val attachmentDescriptor = - AttachmentDescriptor( - mediaType = "application/json", - format = CredentialType.ANONCREDS_ISSUE.type, - data = AttachmentBase64( - "eyJzY2hlbWFfaWQiOiJodHRwOi8vaG9zdC5kb2NrZXIuaW50ZXJuYWw6ODAwMC9wcmlzbS1hZ2VudC9zY2hlbWEtcmVnaXN0cnkvc2NoZW1hcy81ZTBkNWE5My00YmZkLTMxMTEtYTk1Ni01ZDViYzgyZjc2Y2MiLCJjcmVkX2RlZl9pZCI6Imh0dHA6Ly8xOTIuMTY4LjY4LjEwMjo4MDAwL3ByaXNtLWFnZW50L2NyZWRlbnRpYWwtZGVmaW5pdGlvbi1yZWdpc3RyeS9kZWZpbml0aW9ucy81ZTI5NWNmMi00MjI2LTNjN2QtYjI3Zi04N2JlMTYwNjQ3NmQvZGVmaW5pdGlvbiIsInJldl9yZWdfaWQiOm51bGwsInZhbHVlcyI6eyJkcml2aW5nTGljZW5zZUlEIjp7InJhdyI6IjEyMzQ1IiwiZW5jb2RlZCI6IjEyMzQ1In0sImVtYWlsQWRkcmVzcyI6eyJyYXciOiJhbGljZUB3b25kZXJsYW5kLmNvbSIsImVuY29kZWQiOiI3NTEwNzA0NjM0MDE2NTY3NzAxMTk0MjA3NTY0NDAwOTA2NjU0MTY2MTE0ODgyMjU4OTAzMzY3OTg2MTIwOTE4NjQ5Mjc2ODY2OTkyNCJ9LCJkYXRlT2ZJc3N1YW5jZSI6eyJyYXciOiIyMDIwLTExLTEzVDIwOjIwOjM5KzAwOjAwIiwiZW5jb2RlZCI6IjUzODY4NTU5NTMxNzQ4NDY3MDk3NTIwODU5MDUzMDgxODM1NzQ3NDM1NjExNjA2ODQyMDQxMTQ3NTgyMDA0ODc0MzQ4MDQ2MTY0Njg1In0sImZhbWlseU5hbWUiOnsicmF3IjoiV29uZGVybGFuZCIsImVuY29kZWQiOiIxNjc5MDg0OTMxMjM3NDc5NDczNjgxMzM3NzU2NzI1Mzg1MTM3MzYwNzk3MDQ3MzM3NzcwMTQ3NzI2OTE5NDAxOTU1NzY1NDU2MjAzNSJ9LCJkcml2aW5nQ2xhc3MiOnsicmF3IjoiMyIsImVuY29kZWQiOiIzIn19LCJzaWduYXR1cmUiOnsicF9jcmVkZW50aWFsIjp7Im1fMiI6IjExMTI0OTQwODk5NTQ2MzQ0NTY2MjA3NjExNTQyODEwMzAyNDE1ODY5Njg4MDE3NTMyNDYwMzM3MDY0NTk2Mjk1NjIxNzkwMDk2MTUxNSIsImEiOiIxNjk5NjYwOTQ5MDE3NjQ2MzAzOTIxMTc4MjgyNDkxODM5MjE4MzUwNjk5MjM4Nzk2NDQxOTg4OTI0NzA1MzI0NjMzNTQ0MzM0Mzc1ODQwNjgyODY3Nzc3MDQ5NDY2ODM3NjcyMjQxMzgxMjgwMjE0OTIxMDI1NDcyNTAwNDAwMjYyMjA1NTE1MzQxOTQxOTEyMjc2ODIxMTcwNzYwNDAwNzkzMzA3NDY3MDQzOTAzMTAzMDI3MTI2NjU4MDM3MDg1MTExMDU1NDczOTI2MTc2ODU2ODY1MTg3Njc3OTAzMTQzODkzNzg2NTU0NjA2MDQ1MDYyMDQxMzAxMzM3MDQ0NTQzMTk2NTM0NzMwNjczODc4Njg3MjUxMjc3NzEyMzEwODUzNDU4MTYxMjg1NzE1MDIxNTk4OTkxODgxNjE5OTI0NTU5NzY0NTU3NDQzMjUxMDcwNzg5NDAzMTQ2MzMxODE4Njk4NTU1MzIzMDU0NTUzNDI0NzkyNjk5OTE2MzIzODg2NzA0MjE0NDY0ODcwMTI5NTkwODcwODIxOTc1MDkwNjQ4MTkzNjExNjY5MjMxMTk2NzY2Nzg5ODU5NDQ3MTMwOTMwNDIxMjI0NTE0MTI1ODYyMzI5OTU5NTIyNjkxMTE0Mzc3MzA4MzYyNjY2OTY2NzQ3NTQxNjU2NzkzOTc4ODc4Mzc0NTQ4MzcwODgyMDMzMTk2MDQxMjE5NDQ1MjAxOTIxNDYzNzEwMjM4OTUyMjkzNDkyODg0OTU5MDgxMDU3MDc2NzAwOTI1OTI2NTYyODg4MTcwODk5NzIzNDA2MjMzMzc0OSIsImUiOiIyNTkzNDQ3MjMwNTUwNjIwNTk5MDcwMjU0OTE0ODA2OTc1NzE5MzgyNzc4ODk1MTUxNTIzMDYyNDk3Mjg1ODMxMDU2NjU4MDA3MTMzMDY3NTkxNDk5ODE2OTA1NTkxOTM5ODcxNDMwMTIzNjc5MTMyMDYyOTkzMjM4OTk2OTY5NDIyMTMyMzU5NTY3NDI5MzAxMzgxMDE1NDA1MjExMzIyOTAyMjgyNzk3NjM0NDM3NTAxNDkiLCJ2IjoiOTI3MjIxODI0NzE5ODYxNzc0Nzk0ODU4NTgzNDAwNjY1MDM4NDQ2MjE4ODE4MDU2MDY3NjYwNzA5MTE5NDg1NTg4OTY3MDY0OTU1NTM0MjA2MDkyOTQ1MjU3NzgwMzMzMzQwMTAyNTA0MzI3OTMzNjYwNzA5NTUzMzk5MzE4OTE4NTQxNjUxMTgxMDM2NjgwOTMzNzM0MjUyNDA2NDYzMTg2OTQxODk3MDQ1NTA1OTUyMDYwNzI5NTExODM3NzA1OTM3MjQxMzYwMzcyNjM4NTEwODk1MDMxNzc5NjMxODUyNjQyOTIyNTQwNzkxOTc2NzgzMDc2OTk3MTI5MzIyNjA1NjAzNzIyMjA4ODMwOTAyNzcwNTM5Njk2ODA3MTI0MzQ0MzY0NDk1ODAzNDgxNTg4MzczMTk5Mjg3OTgyMjM2MTE5MjIwODU3OTk2NzQwNzI3MjA2OTc4NjMyMjU1NDY0NTk5NDE2NTMwOTYwOTc0ODg0NjczMDgzMzk5NjY1NDI2Mjg1NzY0NDI0NjMwMDMxODA1ODEwNjE5MDI3Njc3MjY4NDAzNzA3NzIzOTAzNDMzOTAxMzg3NDkyMzEyNzA3Nzk4MTcxMzk5ODI0NjM5NDQ1MjI4ODAxNDQ0OTIwMzk5OTkwMzAzMDYzNzg1NDg1NDU3NDIyODQwNjI1NjYyMDg5MzM3NzYxNTIzODUyMTUzMTMwMTIzMzA2NzExNjkzMTkxNTI4MTUzNzk4MjQ0ODE5OTAzMTQ4NjM0MTYzMDg2NDQ4ODkyOTc0ODgzMzQyMzUzMDI0MTA4MjM3MzY1MjI0NTI5MTA5NzEyNjE4ODc4MzY3OTc4Njg3NTY3NTM1MTEzODg1NzU4MTg0ODU2NTU1NzI3MTY0MTk0MTAyODg3MDQ1OTg4NDc2NTI0OTE2NTA0NzM5NDY1Mzk1MjQzMDc0NTY4OTU2MzExODY3OTA5ODc4NDE2MDMwODY1MjY4NDQzNTg2NzI5NjQ3NzA2NjUzNzcwNDU1NjcwOTc4NzkyNDE0Mjc5MzM1NDk0NTE1OTUxMTQ4ODg3MjAzMDg2NjYyMTEwODc1NjA5NjM4NjMxNCJ9LCJyX2NyZWRlbnRpYWwiOm51bGx9LCJzaWduYXR1cmVfY29ycmVjdG5lc3NfcHJvb2YiOnsic2UiOiIyMzQ0OTA4OTM4ODc3NDk2OTAwMTU1NzIzNTE5NzU1OTc2NDEzMzYzMDI4NzE1NTY4Nzc3MzgwNDM4NTA5NDQ0MDE0MjIzMTk5OTg4NDA1NDM0OTU3NzkzMzY5NzE0ODg3OTA4MDI1MDgwNjc0NDQ2MDQ2ODIyNDM2NTQ5Mzg1OTk3NzA5OTc3MTYwMDE1MTM0MTAzMjQ4OTkyNTI3OTYyNTk2OTIwMTA3ODUyNzYzMDUxNDUyMjM5MzEwOTQyODU1OTk3OTEwNzA0ODgxMTQ1OTE4NjI4MTU2NjA4NDUzNzc5MzcyMDIyMzI5ODM3MzYzOTQ2MDgzNTQ2OTE5NjY1OTA4MzY5NzAxMTc2NTk2Njk5MzQ1MDU2NzQ1MjI3MjY0MzczMTYyMTM4NTE0MDQxMTU3NjY5ODAzNjQ5ODgzNjg0NTA4NjQyNTc4OTM2MDc2Mjg2NDk1NzgzMTY2MTM4NjAyNjIzMDU4Nzk2OTk4NzA5NzYyODAzNzYxNzkyODI2NDUzNjIzODg4MjQ3ODkzMzc1MDQxODY0NTU0MDIwMzY5OTY0MzQwMDQ4Njg2NzAzMDM5NzkyODkzMzA1NzQ2MDE4NDkyMTIxMjk5ODI4MTYwNTU1Njg5MDQ4MzgyNTQ4OTU4NjY2OTI2MzMwMzU3OTczMDc0OTY2MzA5OTUwMDczMTMwMjA0NjgxNjI2MjQ5ODIxNTA0MjY0MTU3ODkwMzg3MTQ4OTk4MjU5NTc1MTE3NDI2MTM1MjU5MjMwMTE5MTY3NDE2MTAxNTIzMTA0NTQ1NjU4MTkyMjE2NzY5NTA5MTkxMzMxOSIsImMiOiIzNjU3Nzg5MjU2Mjk4NTIzNDUxNDYzODU4ODIxODcwNDgzOTI5MDAyNTI5NTUxMTI5ODc1NTI3NzY5NDQ2NjE5MDUyODMxMzE3ODkifSwicmV2X3JlZyI6bnVsbCwid2l0bmVzcyI6bnVsbH0" - ) - ) - - val issuedCredential = IssueCredential( - body = IssueCredential.Body(), - attachments = arrayOf(attachmentDescriptor), - thid = "1", - from = fromDID, - to = toDID - ) - - val credential = agent.processIssuedCredentialMessage(issuedCredential) - - credential.claims.map { - if (it.key == "emailAddress") { - assertEquals("alice@wonderland.com", (it.value as ClaimType.StringValue).value) - } - if (it.key == "familyName") { - assertEquals("Wonderland", (it.value as ClaimType.StringValue).value) - } - if (it.key == "dateOfIssuance") { - assertEquals("2020-11-13T20:20:39+00:00", (it.value as ClaimType.StringValue).value) - } - if (it.key == "drivingLicenseID") { - assertEquals("12345", (it.value as ClaimType.StringValue).value) - } - if (it.key == "drivingClass") { - assertEquals("3", (it.value as ClaimType.StringValue).value) - } - } - } -} diff --git a/atala-prism-sdk/src/androidMain/AndroidManifest.xml b/atala-prism-sdk/src/androidMain/AndroidManifest.xml deleted file mode 100644 index 7b0709047..000000000 --- a/atala-prism-sdk/src/androidMain/AndroidManifest.xml +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/atala-prism-sdk/src/androidMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/HttpClient.kt b/atala-prism-sdk/src/androidMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/HttpClient.kt deleted file mode 100644 index d9dd7d2e9..000000000 --- a/atala-prism-sdk/src/androidMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/HttpClient.kt +++ /dev/null @@ -1,14 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import io.ktor.client.HttpClientConfig -import io.ktor.client.engine.okhttp.OkHttp - -/** - * Creates an HTTP client with the specified configuration. - * - * @param config The configuration block for the HTTP client. - * @return The created HTTP client. - */ -actual fun httpClient(config: HttpClientConfig<*>.() -> Unit) = io.ktor.client.HttpClient(OkHttp) { - config(this) -} diff --git a/atala-prism-sdk/src/androidMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Platform.kt b/atala-prism-sdk/src/androidMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Platform.kt deleted file mode 100644 index dc0d47372..000000000 --- a/atala-prism-sdk/src/androidMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Platform.kt +++ /dev/null @@ -1,34 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -/** - * The `Platform` object represents the platform on which the code is running. - */ -actual object Platform { - /** - * This variable represents the operating system on which the code is currently running. - * - * On Android, it returns a string with the Android version followed by the SDK level. - * For example: "Android 10" - * - * @return The operating system of the device. - */ - actual val OS: String - get() = "Android ${android.os.Build.VERSION.SDK_INT}" - - /** - * Represents the platform type. - * - * This actual property represents the current platform type. It is used to determine the type of the platform on which - * the application is being executed. The possible platform types are JVM, ANDROID, IOS, and WEB. - * - * This property is read-only and can be accessed using the `type` property of the `PlatformType` class. - * - * Example usage: - * ``` - * val platformType = PlatformType.ANDROID - * ``` - * - * @see PlatformType - */ - actual val type: PlatformType = PlatformType.ANDROID -} diff --git a/atala-prism-sdk/src/androidMain/kotlin/io/iohk/atala/prism/walletsdk/pluto/data/DbConnection.kt b/atala-prism-sdk/src/androidMain/kotlin/io/iohk/atala/prism/walletsdk/pluto/data/DbConnection.kt deleted file mode 100644 index 7f8975131..000000000 --- a/atala-prism-sdk/src/androidMain/kotlin/io/iohk/atala/prism/walletsdk/pluto/data/DbConnection.kt +++ /dev/null @@ -1,33 +0,0 @@ -package io.iohk.atala.prism.walletsdk.pluto.data - -import android.content.Context -import app.cash.sqldelight.db.SqlDriver -import app.cash.sqldelight.driver.android.AndroidSqliteDriver -import io.iohk.atala.prism.walletsdk.PrismPlutoDb -import io.iohk.atala.prism.walletsdk.domain.models.PlutoError - -/** - * DbConnection class represents a connection to the database. - */ -actual class DbConnection actual constructor() { - actual var driver: SqlDriver? = null - actual suspend fun connectDb(context: Any?): SqlDriver { - val androidContext: Context = (context as? Context) ?: throw PlutoError.DatabaseContextError() - val driver = AndroidSqliteDriver(PrismPlutoDb.Schema, androidContext, "prism.db") - this.driver = driver - return driver - } -} - -/** - * Represents the connection status of an SQL driver. - */ -actual val SqlDriver.isConnected: Boolean - get() { - try { - return this.execute(null, "SELECT 1", 0).value == 1L - // return this.executeQuery(null, "SELECT 1", 0).next() - } catch (ex: Exception) { - return false - } - } diff --git a/atala-prism-sdk/src/androidUnitTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/AndroidIgnore.android.kt b/atala-prism-sdk/src/androidUnitTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/AndroidIgnore.android.kt deleted file mode 100644 index 66be643dc..000000000 --- a/atala-prism-sdk/src/androidUnitTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/AndroidIgnore.android.kt +++ /dev/null @@ -1,5 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent - -import org.junit.Ignore - -actual typealias AndroidIgnore = Ignore diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/ApolloImpl.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/ApolloImpl.kt deleted file mode 100644 index 0f18dd181..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/ApolloImpl.kt +++ /dev/null @@ -1,249 +0,0 @@ -package io.iohk.atala.prism.walletsdk.apollo - -import io.iohk.atala.prism.apollo.derivation.HDKey -import io.iohk.atala.prism.apollo.derivation.MnemonicHelper -import io.iohk.atala.prism.apollo.derivation.MnemonicLengthException -import io.iohk.atala.prism.walletsdk.apollo.helpers.BytesOps -import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519KeyPair -import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519PrivateKey -import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519PublicKey -import io.iohk.atala.prism.walletsdk.apollo.utils.Secp256k1PrivateKey -import io.iohk.atala.prism.walletsdk.apollo.utils.Secp256k1PublicKey -import io.iohk.atala.prism.walletsdk.apollo.utils.X25519KeyPair -import io.iohk.atala.prism.walletsdk.apollo.utils.X25519PrivateKey -import io.iohk.atala.prism.walletsdk.apollo.utils.X25519PublicKey -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Apollo -import io.iohk.atala.prism.walletsdk.domain.models.ApolloError -import io.iohk.atala.prism.walletsdk.domain.models.Curve -import io.iohk.atala.prism.walletsdk.domain.models.Seed -import io.iohk.atala.prism.walletsdk.domain.models.SeedWords -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.CurveKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.DerivationPathKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.IndexKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.KeyTypes -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PrivateKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PublicKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.RawKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.SeedKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.StorableKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.TypeKey - -/** - * Apollo defines the set of cryptographic operations that are used in the Atala PRISM. - */ -class ApolloImpl : Apollo { - - /** - * Creates a random set of mnemonic phrases that can be used as a seed for generating a private key. - * - * @return An array of mnemonic phrases. - */ - override fun createRandomMnemonics(): Array { - return MnemonicHelper.createRandomMnemonics().toTypedArray() - } - - /** - * Takes in a set of mnemonics and a passphrase, and returns a seed object used to generate a private key. - * - * @param mnemonics An array of mnemonic phrases. - * @param passphrase A passphrase used to enhance the security of the seed. - * @return A seed object. - * @throws [MnemonicLengthException] if the mnemonics or passphrase are invalid. - */ - @Throws(MnemonicLengthException::class) - override fun createSeed(mnemonics: Array, passphrase: String): Seed { - return Seed(MnemonicHelper.createSeed(mnemonics.asList(), passphrase)) - } - - /** - * Creates a random seed and a corresponding set of mnemonic phrases. - * - * @param passphrase A passphrase used to enhance the security of the seed. - * @return [SeedWords]. - */ - override fun createRandomSeed(passphrase: String?): SeedWords { - val mnemonics = createRandomMnemonics() - return SeedWords( - mnemonics, - Seed( - value = MnemonicHelper.createSeed( - mnemonics = mnemonics.asList(), - passphrase = passphrase ?: "" - ) - ) - ) - } - - /** - * Creates a private key based on the provided properties. - * - * @param properties A map of properties used to create the private key. The map should contain the following keys: - * - "type" (String): The type of the key ("EC" or "Curve25519"). - * - "curve" (String): The curve of the key. - * - "rawKey" (ByteArray): The raw key data (optional). - * - "index" (Int): The index for the key (only applicable for EC keys with curve "secp256k1"). - * - "derivationPath" (String): The derivation path for the key (only applicable for EC keys with curve "secp256k1"). - * - "seed" (String): The seed for the key (only applicable for EC keys with curve "secp256k1"). - * - * @return The created private key. - * - * @throws ApolloError.InvalidKeyType If the provided key type is invalid. - * @throws ApolloError.InvalidKeyCurve If the provided key curve is invalid. - * @throws ApolloError.InvalidRawData If the provided raw key data is invalid. - * @throws ApolloError.InvalidIndex If the provided index is invalid. - * @throws ApolloError.InvalidDerivationPath If the provided derivation path is invalid. - * @throws ApolloError.InvalidSeed If the provided seed is invalid. - */ - override fun createPrivateKey(properties: Map): PrivateKey { - if (!properties.containsKey(TypeKey().property)) { - throw ApolloError.InvalidKeyType(TypeKey().property) - } - if (!properties.containsKey(CurveKey().property)) { - throw ApolloError.InvalidKeyCurve(CurveKey().property) - } - - val keyType = properties[TypeKey().property] - val curve = properties[CurveKey().property] - - val keyData = properties[RawKey().property] - - when (keyType) { - KeyTypes.EC -> { - when (curve) { - Curve.ED25519.value -> { - keyData?.let { - if (it !is ByteArray) { - throw ApolloError.InvalidRawData("KeyData must be a ByteArray") - } - return Ed25519PrivateKey(it) - } - val keyPair = Ed25519KeyPair.generateKeyPair() - return keyPair.privateKey - } - - Curve.SECP256K1.value -> { - keyData?.let { - if (it !is ByteArray) { - throw Exception("KeyData must be a ByteArray") - } - return Secp256k1PrivateKey(it) - } - val index = properties[IndexKey().property] ?: 0 - if (index !is Int) { - throw ApolloError.InvalidIndex("Index must be an integer") - } - val derivationPath = - if (properties[DerivationPathKey().property] != null && properties[DerivationPathKey().property] !is String) { - throw ApolloError.InvalidDerivationPath("Derivation path must be a string") - } else { - "m/$index'/0'/0'" - } - - val seed = properties[SeedKey().property] ?: throw Exception("Seed must provide a seed") - if (seed !is String) { - throw ApolloError.InvalidSeed("Seed must be a string") - } - - val seedByteArray = BytesOps.hexToBytes(seed) - - val hdKey = HDKey(seedByteArray, 0, 0) - val derivedHdKey = hdKey.derive(derivationPath) - val private = Secp256k1PrivateKey(derivedHdKey.getKMMSecp256k1PrivateKey().raw) - private.keySpecification[SeedKey().property] = seed - private.keySpecification[DerivationPathKey().property] = derivationPath - private.keySpecification[IndexKey().property] = "0" - return private - } - } - } - - KeyTypes.Curve25519 -> { - keyData?.let { - if (it !is ByteArray) { - throw ApolloError.InvalidRawData("KeyData must be a ByteArray") - } - return X25519PrivateKey(it) - } - val keyPair = X25519KeyPair.generateKeyPair() - return keyPair.privateKey - } - } - throw ApolloError.InvalidKeyType(TypeKey().property) - } - - /** - * Checks if the provided data is associated with a private key identified by the given identifier. - * - * @param identifier The identifier for the private key. - * @param data The data to check. - * @return True if the data is associated with a private key, false otherwise. - */ - override fun isPrivateKeyData(identifier: String, data: ByteArray): Boolean { - return identifier.endsWith("priv") - } - - /** - * Checks if the provided data is associated with a public key identified by the given identifier. - * - * @param identifier The identifier for the public key. - * @param data The data to check. - * @return True if the data is associated with a public key, false otherwise. - */ - override fun isPublicKeyData(identifier: String, data: ByteArray): Boolean { - return identifier.endsWith("pub") - } - - /** - * Restores a private key based on the provided storable key. - * - * @param key The storable key to restore the private key from. - * @return The restored private key. - * @throws ApolloError.RestorationFailedNoIdentifierOrInvalid If the restoration identifier is missing or invalid. - */ - override fun restorePrivateKey(key: StorableKey): PrivateKey { - return when (key.restorationIdentifier) { - "secp256k1+priv" -> { - Secp256k1PrivateKey(key.storableData) - } - - "x25519+priv" -> { - X25519PrivateKey(key.storableData) - } - - "ed25519+priv" -> { - Ed25519PrivateKey(key.storableData) - } - - else -> { - throw ApolloError.RestorationFailedNoIdentifierOrInvalid() - } - } - } - - /** - * Restores a public key based on the provided storable key. - * - * @param key The storable key to restore the public key from. - * @return The restored public key. - * @throws ApolloError.RestorationFailedNoIdentifierOrInvalid If the restoration identifier is missing or invalid. - */ - override fun restorePublicKey(key: StorableKey): PublicKey { - return when (key.restorationIdentifier) { - "secp256k1+pub" -> { - Secp256k1PublicKey(key.storableData) - } - - "x25519+pub" -> { - X25519PublicKey(key.storableData) - } - - "ed25519+pub" -> { - Ed25519PublicKey(key.storableData) - } - - else -> { - throw ApolloError.RestorationFailedNoIdentifierOrInvalid() - } - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/config/ECConfig.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/config/ECConfig.kt deleted file mode 100644 index f331ee744..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/config/ECConfig.kt +++ /dev/null @@ -1,21 +0,0 @@ -package io.iohk.atala.prism.walletsdk.apollo.config - -import com.ionspin.kotlin.bignum.integer.BigInteger - -/** - * The ECConfig object provides configuration properties and constants related to elliptic curve cryptography (ECC). - */ -object ECConfig { - const val PRIVATE_KEY_BYTE_SIZE: Int = 32 - internal const val PUBLIC_KEY_COORDINATE_BYTE_SIZE: Int = 32 - internal const val PUBLIC_KEY_COMPRESSED_BYTE_SIZE: Int = PUBLIC_KEY_COORDINATE_BYTE_SIZE + 1 - const val SIGNATURE_MAX_BYTE_SIZE: Int = 72 - const val PUBLIC_KEY_BYTE_SIZE: Int = PUBLIC_KEY_COORDINATE_BYTE_SIZE * 2 + 1 - - // Field characteristic p (prime) is equal to 2^256 - 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1 - internal val p = BigInteger.parseString("115792089237316195423570985008687907853269984665640564039457584007908834671663", 10) - internal val b = BigInteger(7) - - // n curve order (The order of secp256k1 is n) - internal val n = BigInteger.parseString("115792089237316195423570985008687907852837564279074904382605163141518161494337", 10) -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/helpers/ByteArrayExt.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/helpers/ByteArrayExt.kt deleted file mode 100644 index 4cc2f8d08..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/helpers/ByteArrayExt.kt +++ /dev/null @@ -1,19 +0,0 @@ -package io.iohk.atala.prism.walletsdk.apollo.helpers - -/** - * Pads the current ByteArray with the specified padValue at the beginning, - * making it equal to or larger than the specified length. - * - * @param length The desired length for the new ByteArray. - * @param padValue The value used to pad the ByteArray. - * @return The padded ByteArray with the specified length. - */ -fun ByteArray.padStart(length: Int, padValue: Byte): ByteArray { - return if (size >= length) { - this - } else { - val result = ByteArray(length) { padValue } - copyInto(result, length - size) - result - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/helpers/BytesOps.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/helpers/BytesOps.kt deleted file mode 100644 index 87f4366e8..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/helpers/BytesOps.kt +++ /dev/null @@ -1,51 +0,0 @@ -package io.iohk.atala.prism.walletsdk.apollo.helpers - -/** - * This represents the conversion from and to [ByteArray] to Hex. - */ -object BytesOps { - /** - * List of hex characters - */ - private val HEX_ARRAY = "0123456789abcdef".toCharArray() - - /** - * Conversion of [ByteArray] to Hex. - * - * @param bytes the bytes to convert to Hex - * @return Hex String - */ - @OptIn(ExperimentalUnsignedTypes::class) - fun bytesToHex(bytes: ByteArray): String { - val ubytes = bytes.toUByteArray() - val hexChars = CharArray(bytes.size * 2) - for (j in ubytes.indices) { - val v = (ubytes[j] and 0xFF.toUByte()).toInt() - - hexChars[j * 2] = HEX_ARRAY[v ushr 4] - hexChars[j * 2 + 1] = HEX_ARRAY[v and 0x0F] - } - return hexChars.concatToString() - } - - /** - * Conversion of Hex to [ByteArray]. - * - * @param string Hex string. - * @return [ByteArray]. - */ - @OptIn(ExperimentalUnsignedTypes::class) - fun hexToBytes(string: String): ByteArray { - val result = UByteArray(string.length / 2) { UByte.MIN_VALUE } - - for (i in string.indices step 2) { - val firstIndex = HEX_ARRAY.indexOf(string[i]) - val secondIndex = HEX_ARRAY.indexOf(string[i + 1]) - - val octet = firstIndex.shl(4).or(secondIndex) - result[i.shr(1)] = octet.toUByte() - } - - return result.toByteArray() - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/helpers/JVMBigIntegerExt.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/helpers/JVMBigIntegerExt.kt deleted file mode 100644 index c718dfeeb..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/helpers/JVMBigIntegerExt.kt +++ /dev/null @@ -1,12 +0,0 @@ -package io.iohk.atala.prism.walletsdk.apollo.helpers - -import java.math.BigInteger - -/** - * Converts a Kotlin BigInteger to a Java BigInteger. - * - * @return the converted Java BigInteger. - */ -fun com.ionspin.kotlin.bignum.integer.BigInteger.toJavaBigInteger(): BigInteger { - return BigInteger(this.signum(), this.toByteArray()) -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/Ed25519KeyPair.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/Ed25519KeyPair.kt deleted file mode 100644 index 005aa4167..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/Ed25519KeyPair.kt +++ /dev/null @@ -1,32 +0,0 @@ -package io.iohk.atala.prism.walletsdk.apollo.utils - -import io.iohk.atala.prism.apollo.utils.KMMEdKeyPair -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.KeyPair -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PrivateKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PublicKey - -/** - * Represents a pair of Ed25519 private and public keys. - */ -class Ed25519KeyPair( - override var privateKey: PrivateKey, - override var publicKey: PublicKey -) : KeyPair() { - - companion object { - /** - * Generates a pair of Ed25519 private and public keys. - * - * @return The generated Ed25519KeyPair. - */ - @JvmStatic - fun generateKeyPair(): Ed25519KeyPair { - val pair = KMMEdKeyPair.generateKeyPair() - - return Ed25519KeyPair( - privateKey = Ed25519PrivateKey(nativeValue = pair.privateKey.raw), - publicKey = Ed25519PublicKey(nativeValue = pair.publicKey.raw) - ) - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/Ed25519PrivateKey.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/Ed25519PrivateKey.kt deleted file mode 100644 index 423f9758e..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/Ed25519PrivateKey.kt +++ /dev/null @@ -1,123 +0,0 @@ -package io.iohk.atala.prism.walletsdk.apollo.utils - -import io.iohk.atala.prism.apollo.base64.base64UrlEncoded -import io.iohk.atala.prism.apollo.utils.KMMEdPrivateKey -import io.iohk.atala.prism.walletsdk.domain.models.Curve -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.CurveKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.ExportableKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.JWK -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.KeyTypes -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PEMKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PEMKeyType -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PrivateKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PublicKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.SignableKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.StorableKey - -/** - * Represents a private key for the Ed25519 algorithm. - * - * This class extends the abstract class PrivateKey and implements the interfaces SignableKey, StorableKey, and ExportableKey. - * - * @param nativeValue The raw byte array representing the private key. - * @property size The size of the private key in bytes. - * @property raw The raw byte array representing the private key. - * @property type The type of the key. Always set to KeyTypes.EC. - * @property keySpecification A mutable map representing the key specification. - * - * @constructor Creates an instance of Ed25519PrivateKey and initializes its properties. - * - * @param nativeValue The raw byte array representing the private key. - */ -class Ed25519PrivateKey(nativeValue: ByteArray) : PrivateKey(), SignableKey, StorableKey, ExportableKey { - - override val type: KeyTypes = KeyTypes.EC - override val keySpecification: MutableMap = mutableMapOf() - override val size: Int - override val raw: ByteArray = nativeValue - - init { - size = raw.size - keySpecification[CurveKey().property] = Curve.ED25519.value - } - - /** - * Returns the public key corresponding to this private key. - * @return the public key as a PublicKey object - */ - override fun publicKey(): PublicKey { - val public = KMMEdPrivateKey(raw).publicKey() - return Ed25519PublicKey(public.raw) - } - - /** - * Signs a byte array message using the private key. - * - * @param message The message to be signed. - * @return The signature as a byte array. - */ - override fun sign(message: ByteArray): ByteArray { - val private = KMMEdPrivateKey(raw) - return private.sign(message) - } - - /** - * Returns the PEM (Privacy-Enhanced Mail) representation of the private key. - * The key is encoded in base64 and wrapped with "BEGIN" and "END" markers. - * - * @return the PEM representation of the private key as a String - */ - override fun getPem(): String { - return PEMKey( - keyType = PEMKeyType.EC_PRIVATE_KEY, - keyData = raw - ).pemEncoded() - } - - /** - * Retrieves the JWK (JSON Web Key) representation of the private key. - * - * @return The JWK instance representing the private key. - */ - override fun getJwk(): JWK { - return JWK( - kty = "OKP", - crv = getProperty(CurveKey().property), - x = raw.base64UrlEncoded - ) - } - - /** - * Retrieves the JWK (JSON Web Key) representation of the private key with the specified key identifier (kid). - * - * @param kid The key identifier to be associated with the JWK. - * @return The JWK object representing the private key. - */ - override fun jwkWithKid(kid: String): JWK { - return JWK( - kty = "OKP", - kid = kid, - crv = getProperty(CurveKey().property), - x = raw.base64UrlEncoded - ) - } - - /** - * Represents the storable data of a key. - * - * @property storableData The byte array representing the storable data. - * @see StorableKey - */ - override val storableData: ByteArray - get() = raw - - /** - * This variable represents the restoration identifier for a key. - * It is a unique identifier used for restoring the key from storage. - * - * @property restorationIdentifier The restoration identifier for the key. - * @see StorableKey - */ - override val restorationIdentifier: String - get() = "ed25519+priv" -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/Ed25519PublicKey.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/Ed25519PublicKey.kt deleted file mode 100644 index afa7f5e39..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/Ed25519PublicKey.kt +++ /dev/null @@ -1,109 +0,0 @@ -package io.iohk.atala.prism.walletsdk.apollo.utils - -import io.iohk.atala.prism.apollo.base64.base64UrlEncoded -import io.iohk.atala.prism.apollo.utils.KMMEdPublicKey -import io.iohk.atala.prism.walletsdk.domain.models.Curve -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.CurveKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.ExportableKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.JWK -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.KeyTypes -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PEMKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PEMKeyType -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PublicKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.StorableKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.VerifiableKey - -/** - * Represents an Ed25519 public key. - * - * This class implements the [PublicKey], [VerifiableKey], [StorableKey], and [ExportableKey] interfaces. - * - * @param nativeValue The native value of the public key. - * @property type The type of the key, which is [KeyTypes.EC]. - * @property keySpecification The specification of the key. - * @property size The size of the key. - * @property raw The raw bytes of the key. - */ -class Ed25519PublicKey(nativeValue: ByteArray) : PublicKey(), VerifiableKey, StorableKey, ExportableKey { - override val type: KeyTypes = KeyTypes.EC - override val keySpecification: MutableMap = mutableMapOf() - override val size: Int - override val raw: ByteArray = nativeValue - - init { - size = raw.size - keySpecification[CurveKey().property] = Curve.ED25519.value - } - - /** - * Verifies the authenticity of a signature using a given message and signature. - * - * @param message The message to verify. - * @param signature The signature data to verify. - * @return A boolean value indicating whether the signature is valid or not. - */ - override fun verify(message: ByteArray, signature: ByteArray): Boolean { - val public = KMMEdPublicKey(raw) - return public.verify(message, signature) - } - - /** - * Returns the PEM (Privacy-Enhanced Mail) representation of the public key. - * The key is encoded in base64 and wrapped with "BEGIN" and "END" markers. - * - * @return the PEM representation of the private key as a String - */ - override fun getPem(): String { - return PEMKey( - keyType = PEMKeyType.EC_PUBLIC_KEY, - keyData = raw - ).pemEncoded() - } - - /** - * Retrieves the JWK (JSON Web Key) representation of the public key. - * - * @return The JWK instance representing the private key. - */ - override fun getJwk(): JWK { - return JWK( - kty = "OKP", - crv = getProperty(CurveKey().property), - x = raw.base64UrlEncoded - ) - } - - /** - * Retrieves the JWK (JSON Web Key) representation of the private key with the specified key identifier (kid). - * - * @param kid The key identifier to be associated with the JWK. - * @return The JWK object representing the private key. - */ - override fun jwkWithKid(kid: String): JWK { - return JWK( - kty = "OKP", - kid = kid, - crv = getProperty(CurveKey().property), - x = raw.base64UrlEncoded - ) - } - - /** - * Represents the storable data of a key. - * - * @property storableData The byte array representing the storable data. - * @see StorableKey - */ - override val storableData: ByteArray - get() = raw - - /** - * This variable represents the restoration identifier for a key. - * It is a unique identifier used for restoring the key from storage. - * - * @property restorationIdentifier The restoration identifier for the key. - * @see StorableKey - */ - override val restorationIdentifier: String - get() = "ed25519+pub" -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/JVMBigIntegerExt.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/JVMBigIntegerExt.kt deleted file mode 100644 index 935b22cc1..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/JVMBigIntegerExt.kt +++ /dev/null @@ -1,30 +0,0 @@ -package io.iohk.atala.prism.walletsdk.apollo.utils - -import com.ionspin.kotlin.bignum.integer.Sign -import java.math.BigInteger - -/** - * Converts a `BigInteger` to an unsigned byte array. - * - * @return The unsigned byte array representation of the `BigInteger`. - */ -fun BigInteger.toUnsignedByteArray(): ByteArray { - val comparedValue = 0.toByte() - return toByteArray().dropWhile { it == comparedValue }.toByteArray() -} - -/** - * Converts a `java.math.BigInteger` to a `com.ionspin.kotlin.bignum.integer.BigInteger` object. - * - * @return The converted `com.ionspin.kotlin.bignum.integer.BigInteger` object. - * @throws IllegalStateException if the sign of the original `java.math.BigInteger` is invalid. - */ -fun BigInteger.toKotlinBigInteger(): com.ionspin.kotlin.bignum.integer.BigInteger { - val sign = when (this.signum()) { - -1 -> Sign.NEGATIVE - 0 -> Sign.ZERO - 1 -> Sign.POSITIVE - else -> throw IllegalStateException("Illegal BigInteger sign") - } - return com.ionspin.kotlin.bignum.integer.BigInteger.fromByteArray(this.toUnsignedByteArray(), sign) -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/Secp256k1KeyPair.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/Secp256k1KeyPair.kt deleted file mode 100644 index 90c421714..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/Secp256k1KeyPair.kt +++ /dev/null @@ -1,36 +0,0 @@ -package io.iohk.atala.prism.walletsdk.apollo.utils - -import io.iohk.atala.prism.apollo.derivation.HDKey -import io.iohk.atala.prism.walletsdk.domain.models.KeyCurve -import io.iohk.atala.prism.walletsdk.domain.models.Seed -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.KeyPair -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PrivateKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PublicKey - -/** - * Represents a key pair consisting of a private key and public key. - * - * @property privateKey The private key of the key pair. - * @property publicKey The public key of the key pair. - */ -class Secp256k1KeyPair(override var privateKey: PrivateKey, override var publicKey: PublicKey) : KeyPair() { - companion object { - /** - * Generates a key pair using a given seed and key curve. - * - * @param seed The seed used for key generation. - * @param curve The key curve to use for key generation. - * @return A key pair consisting of a private key and public key. - */ - @JvmStatic - fun generateKeyPair(seed: Seed, curve: KeyCurve): Secp256k1KeyPair { - val path = "m/${curve.index}'/0'/0'" - val hdKey = HDKey(seed.value, 0, 0) - val derivedHdKey = hdKey.derive(path) - return Secp256k1KeyPair( - privateKey = Secp256k1PrivateKey(derivedHdKey.getKMMSecp256k1PrivateKey().raw), - publicKey = Secp256k1PublicKey(derivedHdKey.getKMMSecp256k1PrivateKey().getPublicKey().raw) - ) - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/Secp256k1PrivateKey.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/Secp256k1PrivateKey.kt deleted file mode 100644 index b0e02c8e5..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/Secp256k1PrivateKey.kt +++ /dev/null @@ -1,158 +0,0 @@ -package io.iohk.atala.prism.walletsdk.apollo.utils - -import io.iohk.atala.prism.apollo.base64.base64UrlEncoded -import io.iohk.atala.prism.apollo.derivation.DerivationPath -import io.iohk.atala.prism.apollo.derivation.HDKey -import io.iohk.atala.prism.apollo.utils.KMMECSecp256k1PrivateKey -import io.iohk.atala.prism.walletsdk.apollo.helpers.BytesOps -import io.iohk.atala.prism.walletsdk.domain.models.Curve -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.CurveKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.CurvePointXKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.CurvePointYKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.DerivableKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.ExportableKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.JWK -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.KeyTypes -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PEMKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PEMKeyType -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PrivateKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PublicKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.SeedKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.SignableKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.StorableKey - -/** - * The `Secp256k1PrivateKey` class represents a private key that uses the secp256k1 elliptic curve. - * It extends the `PrivateKey` class and implements the `SignableKey`, `StorableKey`, `ExportableKey`, and `DerivableKey` interfaces. - * - * @param nativeValue The raw byte array value of the private key. - * @property type The type of the key, which is set to `KeyTypes.EC`. - * @property keySpecification A mutable map that contains additional key specifications. - * @property size The size of the private key in bytes. - * @property raw The raw byte array value of the private key. - * - * @constructor Creates a `Secp256k1PrivateKey` object with the specified `nativeValue`. - * - * @param nativeValue The raw byte array value of the private key. - * - * - * @see PrivateKey - * @see SignableKey - * @see StorableKey - * @see ExportableKey - * @see DerivableKey - */ -class Secp256k1PrivateKey(nativeValue: ByteArray) : - PrivateKey(), - SignableKey, - StorableKey, - ExportableKey, - DerivableKey { - override val type: KeyTypes = KeyTypes.EC - override val keySpecification: MutableMap = mutableMapOf() - override val size: Int - override val raw: ByteArray = nativeValue - - init { - size = raw.size - keySpecification[CurveKey().property] = Curve.SECP256K1.value - } - - /** - * Returns the public key corresponding to this private key. - * @return the public key as a PublicKey object - */ - override fun publicKey(): PublicKey { - return Secp256k1PublicKey(KMMECSecp256k1PrivateKey.secp256k1FromByteArray(raw).getPublicKey().raw) - } - - /** - * Signs a byte array message using the private key. - * - * @param message The message to be signed. - * @return The signature as a byte array. - */ - override fun sign(message: ByteArray): ByteArray { - val kmmPrivateKey = KMMECSecp256k1PrivateKey.secp256k1FromByteArray(raw) - return kmmPrivateKey.sign(data = message) - } - - /** - * Returns the PEM (Privacy-Enhanced Mail) representation of the private key. - * The key is encoded in base64 and wrapped with "BEGIN" and "END" markers. - * - * @return the PEM representation of the private key as a String - */ - override fun getPem(): String { - return PEMKey( - keyType = PEMKeyType.EC_PRIVATE_KEY, - keyData = raw - ).pemEncoded() - } - - /** - * Retrieves the JWK (JSON Web Key) representation of the private key. - * - * @return The JWK instance representing the private key. - */ - override fun getJwk(): JWK { - return JWK( - kty = "OKP", - crv = getProperty(CurveKey().property), - x = getProperty(CurvePointXKey().property).base64UrlEncoded, - y = getProperty(CurvePointYKey().property).base64UrlEncoded - ) - } - - /** - * Retrieves the JWK (JSON Web Key) representation of the private key with the specified key identifier (kid). - * - * @param kid The key identifier to be associated with the JWK. - * @return The JWK object representing the private key. - */ - override fun jwkWithKid(kid: String): JWK { - return JWK( - kty = "OKP", - kid = kid, - crv = getProperty(CurveKey().property), - x = getProperty(CurvePointXKey().property).base64UrlEncoded, - y = getProperty(CurvePointYKey().property).base64UrlEncoded - ) - } - - /** - * Represents the storable data of a key. - * - * @property storableData The byte array representing the storable data. - * @see StorableKey - */ - override val storableData: ByteArray - get() = raw - - /** - * This variable represents the restoration identifier for a key. - * It is a unique identifier used for restoring the key from storage. - * - * @property restorationIdentifier The restoration identifier for the key. - * @see StorableKey - */ - override val restorationIdentifier: String - get() = "secp256k1+priv" - - /** - * Derives a private key using the given derivation path. - * - * @param derivationPath the derivation path used to derive the key - * @return the derived private key - * @throws Exception if the key specification does not contain the required properties - */ - override fun derive(derivationPath: DerivationPath): PrivateKey { - val seed = getProperty(SeedKey().property) - - val seedByteArray = BytesOps.hexToBytes(seed) - - val hdKey = HDKey(seedByteArray, 0, 0) - val derivedHdKey = hdKey.derive(derivationPath.toString()) - return Secp256k1PrivateKey(derivedHdKey.getKMMSecp256k1PrivateKey().raw) - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/Secp256k1PublicKey.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/Secp256k1PublicKey.kt deleted file mode 100644 index b0cf69069..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/Secp256k1PublicKey.kt +++ /dev/null @@ -1,126 +0,0 @@ -package io.iohk.atala.prism.walletsdk.apollo.utils - -import io.iohk.atala.prism.apollo.base64.base64UrlEncoded -import io.iohk.atala.prism.apollo.utils.KMMECSecp256k1PublicKey -import io.iohk.atala.prism.walletsdk.apollo.config.ECConfig -import io.iohk.atala.prism.walletsdk.domain.models.Curve -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.CurveKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.CurvePointXKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.CurvePointYKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.CustomKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.ExportableKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.JWK -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.KeyTypes -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PEMKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PEMKeyType -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PublicKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.StorableKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.VerifiableKey - -/** - * Represents a public key in the Secp256k1 elliptic curve algorithm. - * - * @param nativeValue The raw byte array representing the public key. - */ -class Secp256k1PublicKey(nativeValue: ByteArray) : PublicKey(), VerifiableKey, StorableKey, ExportableKey { - override val type: KeyTypes = KeyTypes.EC - override val keySpecification: MutableMap = mutableMapOf() - override val size: Int - override val raw: ByteArray = nativeValue - - init { - size = raw.size - if (size == ECConfig.PUBLIC_KEY_COMPRESSED_BYTE_SIZE) { - keySpecification[CustomKey("compressed").property] = "true" - } else { - keySpecification[CustomKey("compressed").property] = "false" - } - keySpecification[CurveKey().property] = Curve.SECP256K1.value - } - - /** - * Verifies the authenticity of a signature using a given message and signature. - * - * @param message The message to verify. - * @param signature The signature data to verify. - * @return A boolean value indicating whether the signature is valid or not. - */ - override fun verify(message: ByteArray, signature: ByteArray): Boolean { - val kmmPublicKey = KMMECSecp256k1PublicKey.secp256k1FromBytes(raw) - return kmmPublicKey.verify( - signature = signature, - data = message - ) - } - - /** - * Returns the PEM (Privacy-Enhanced Mail) representation of the public key. - * The key is encoded in base64 and wrapped with "BEGIN" and "END" markers. - * - * @return the PEM representation of the private key as a String - */ - override fun getPem(): String { - return PEMKey( - keyType = PEMKeyType.EC_PUBLIC_KEY, - keyData = raw - ).pemEncoded() - } - - /** - * Retrieves the JWK (JSON Web Key) representation of the public key. - * - * @return The JWK instance representing the private key. - */ - override fun getJwk(): JWK { - return JWK( - kty = "OKP", - crv = getProperty(CurveKey().property), - x = getProperty(CurvePointXKey().property).base64UrlEncoded, - y = getProperty(CurvePointYKey().property).base64UrlEncoded - ) - } - - /** - * Retrieves the JWK (JSON Web Key) representation of the private key with the specified key identifier (kid). - * - * @param kid The key identifier to be associated with the JWK. - * @return The JWK object representing the private key. - */ - override fun jwkWithKid(kid: String): JWK { - return JWK( - kty = "OKP", - kid = kid, - crv = getProperty(CurveKey().property), - x = getProperty(CurvePointXKey().property).base64UrlEncoded, - y = getProperty(CurvePointYKey().property).base64UrlEncoded - ) - } - - /** - * Represents the storable data of a key. - * - * @property storableData The byte array representing the storable data. - * @see StorableKey - */ - override val storableData: ByteArray - get() = raw - - /** - * This variable represents the restoration identifier for a key. - * It is a unique identifier used for restoring the key from storage. - * - * @property restorationIdentifier The restoration identifier for the key. - * @see StorableKey - */ - override val restorationIdentifier: String - get() = "secp256k1+pub" - - /** - * Retrieves the encoded and compressed representation of the public key. - * - * @return The encoded and compressed public key as a ByteArray. - */ - fun getEncodedCompressed(): ByteArray { - return KMMECSecp256k1PublicKey(raw).getCompressed() - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/X25519KeyPair.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/X25519KeyPair.kt deleted file mode 100644 index b1dbe9153..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/X25519KeyPair.kt +++ /dev/null @@ -1,32 +0,0 @@ -package io.iohk.atala.prism.walletsdk.apollo.utils - -import io.iohk.atala.prism.apollo.utils.KMMX25519KeyPair -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.KeyPair -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PrivateKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PublicKey - -/** - * Represents a pair of X25519 private and public keys. - * - * @property privateKey The X25519 private key. - * @property publicKey The X25519 public key. - */ -class X25519KeyPair(override var privateKey: PrivateKey, override var publicKey: PublicKey) : KeyPair() { - - companion object { - /** - * Generates a pair of X25519 private and public keys. - * - * @return The generated X25519 key pair. - */ - @JvmStatic - fun generateKeyPair(): X25519KeyPair { - val pair = KMMX25519KeyPair.generateKeyPair() - - return X25519KeyPair( - privateKey = X25519PrivateKey(pair.privateKey.raw), - publicKey = X25519PublicKey(pair.publicKey.raw) - ) - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/X25519PrivateKey.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/X25519PrivateKey.kt deleted file mode 100644 index 885eb7d57..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/X25519PrivateKey.kt +++ /dev/null @@ -1,100 +0,0 @@ -package io.iohk.atala.prism.walletsdk.apollo.utils - -import io.iohk.atala.prism.apollo.base64.base64UrlEncoded -import io.iohk.atala.prism.apollo.utils.KMMX25519PrivateKey -import io.iohk.atala.prism.walletsdk.domain.models.Curve -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.CurveKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.ExportableKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.JWK -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.KeyTypes -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PEMKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PEMKeyType -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PrivateKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PublicKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.StorableKey - -/** - * Represents a private key for the X25519 elliptic curve. - * - * @param nativeValue The raw private key value in byte array format. - */ -class X25519PrivateKey(nativeValue: ByteArray) : PrivateKey(), StorableKey, ExportableKey { - override val type: KeyTypes = KeyTypes.EC - override val keySpecification: MutableMap = mutableMapOf() - override val size: Int - override val raw: ByteArray = nativeValue - - init { - size = raw.size - keySpecification[CurveKey().property] = Curve.X25519.value - } - - /** - * Returns the public key corresponding to this private key. - * @return the public key as a PublicKey object - */ - override fun publicKey(): PublicKey { - val private = KMMX25519PrivateKey(raw) - return X25519PublicKey(private.publicKey().raw) - } - - /** - * Returns the PEM (Privacy-Enhanced Mail) representation of the private key. - * The key is encoded in base64 and wrapped with "BEGIN" and "END" markers. - * - * @return the PEM representation of the private key as a String - */ - override fun getPem(): String { - return PEMKey( - keyType = PEMKeyType.EC_PRIVATE_KEY, - keyData = raw - ).pemEncoded() - } - - /** - * Retrieves the JWK (JSON Web Key) representation of the private key. - * - * @return The JWK instance representing the private key. - */ - override fun getJwk(): JWK { - return JWK( - kty = "OKP", - crv = getProperty(CurveKey().property), - x = raw.base64UrlEncoded - ) - } - - /** - * Retrieves the JWK (JSON Web Key) representation of the private key with the specified key identifier (kid). - * - * @param kid The key identifier to be associated with the JWK. - * @return The JWK object representing the private key. - */ - override fun jwkWithKid(kid: String): JWK { - return JWK( - kty = "OKP", - kid = kid, - crv = getProperty(CurveKey().property), - x = raw.base64UrlEncoded - ) - } - - /** - * Represents the storable data of a key. - * - * @property storableData The byte array representing the storable data. - * @see StorableKey - */ - override val storableData: ByteArray - get() = raw - - /** - * This variable represents the restoration identifier for a key. - * It is a unique identifier used for restoring the key from storage. - * - * @property restorationIdentifier The restoration identifier for the key. - * @see StorableKey - */ - override val restorationIdentifier: String - get() = "x25519+priv" -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/X25519PublicKey.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/X25519PublicKey.kt deleted file mode 100644 index 8603e0f9f..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/X25519PublicKey.kt +++ /dev/null @@ -1,89 +0,0 @@ -package io.iohk.atala.prism.walletsdk.apollo.utils - -import io.iohk.atala.prism.apollo.base64.base64UrlEncoded -import io.iohk.atala.prism.walletsdk.domain.models.Curve -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.CurveKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.ExportableKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.JWK -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.KeyTypes -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PEMKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PEMKeyType -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PublicKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.StorableKey - -/** - * Class representing a public key for the X25519 curve. - * - * @param nativeValue The raw byte array representing the public key - */ -class X25519PublicKey(nativeValue: ByteArray) : PublicKey(), ExportableKey, StorableKey { - override val type: KeyTypes = KeyTypes.EC - override val keySpecification: MutableMap = mutableMapOf() - override val size: Int - override val raw: ByteArray = nativeValue - - init { - size = raw.size - keySpecification[CurveKey().property] = Curve.X25519.value - } - - /** - * Returns the PEM (Privacy-Enhanced Mail) representation of the public key. - * The key is encoded in base64 and wrapped with "BEGIN" and "END" markers. - * - * @return the PEM representation of the private key as a String - */ - override fun getPem(): String { - return PEMKey( - keyType = PEMKeyType.EC_PUBLIC_KEY, - keyData = raw - ).pemEncoded() - } - - /** - * Retrieves the JWK (JSON Web Key) representation of the public key. - * - * @return The JWK instance representing the private key. - */ - override fun getJwk(): JWK { - return JWK( - kty = "OKP", - crv = getProperty(CurveKey().property), - x = raw.base64UrlEncoded - ) - } - - /** - * Retrieves the JWK (JSON Web Key) representation of the private key with the specified key identifier (kid). - * - * @param kid The key identifier to be associated with the JWK. - * @return The JWK object representing the private key. - */ - override fun jwkWithKid(kid: String): JWK { - return JWK( - kty = "OKP", - kid = kid, - crv = getProperty(CurveKey().property), - x = raw.base64UrlEncoded - ) - } - - /** - * Represents the storable data of a key. - * - * @property storableData The byte array representing the storable data. - * @see StorableKey - */ - override val storableData: ByteArray - get() = raw - - /** - * This variable represents the restoration identifier for a key. - * It is a unique identifier used for restoring the key from storage. - * - * @property restorationIdentifier The restoration identifier for the key. - * @see StorableKey - */ - override val restorationIdentifier: String - get() = "x25519+pub" -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/ec/KMMECCoordinate.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/ec/KMMECCoordinate.kt deleted file mode 100644 index bbd25e1a8..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/ec/KMMECCoordinate.kt +++ /dev/null @@ -1,25 +0,0 @@ -package io.iohk.atala.prism.walletsdk.apollo.utils.ec - -import com.ionspin.kotlin.bignum.integer.BigInteger -import io.iohk.atala.prism.walletsdk.apollo.helpers.padStart - -/** - * Represents a coordinate in the elliptic curve cryptography (ECC) system. - * - * @property coordinate The coordinate value represented as a BigInteger. - */ -class KMMECCoordinate(val coordinate: BigInteger) { - - /** - * Returns a ByteArray representation of the coordinate. - * The returned ByteArray will be padded with zeroes at the beginning if necessary - * to match the specified length. - * - * @return The ByteArray representation of the coordinate. - */ - fun bytes(): ByteArray = coordinate.toByteArray().padStart(PRIVATE_KEY_BYTE_SIZE, 0) - - companion object { - internal const val PRIVATE_KEY_BYTE_SIZE: Int = 32 - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/ec/KMMECPoint.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/ec/KMMECPoint.kt deleted file mode 100644 index c5630ab42..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/apollo/utils/ec/KMMECPoint.kt +++ /dev/null @@ -1,37 +0,0 @@ -package io.iohk.atala.prism.walletsdk.apollo.utils.ec - -import com.ionspin.kotlin.bignum.integer.BigInteger - -/** - * Represents a point in the elliptic curve cryptography (ECC) system. - * - * @property x The x-coordinate of the point. - * @property y The y-coordinate of the point. - */ -class KMMECPoint(val x: KMMECCoordinate, val y: KMMECCoordinate) { - /** - * Represents a point in the elliptic curve cryptography (ECC) system. - * - * @property x The x-coordinate of the point. - * @property y The y-coordinate of the point. - */ - constructor(x: String, y: String) : this( - KMMECCoordinate(BigInteger.parseString(x)), - KMMECCoordinate(BigInteger.parseString(y)) - ) - - /** - * Represents a point in the elliptic curve cryptography (ECC) system. - * - * @property x The x-coordinate of the point. - * @property y The y-coordinate of the point. - * - * @constructor Creates a new instance of KMMECPoint with the provided x and y coordinates. - * @param x The x-coordinate as a BigInteger. - * @param y The y-coordinate as a BigInteger. - */ - constructor(x: BigInteger, y: BigInteger) : this( - KMMECCoordinate(x), - KMMECCoordinate(y) - ) -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/CastorConstants.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/CastorConstants.kt deleted file mode 100644 index 2dfcb79e3..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/CastorConstants.kt +++ /dev/null @@ -1,7 +0,0 @@ -package io.iohk.atala.prism.walletsdk.castor - -const val DID_SEPARATOR = ":" -const val PATH_SEPARATOR = "/" -const val PRISM = "prism" -const val PEER = "peer" -const val DID = "did" diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/CastorImpl.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/CastorImpl.kt deleted file mode 100644 index 17de86507..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/CastorImpl.kt +++ /dev/null @@ -1,154 +0,0 @@ -package io.iohk.atala.prism.walletsdk.castor - -import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519PublicKey -import io.iohk.atala.prism.walletsdk.apollo.utils.Secp256k1PublicKey -import io.iohk.atala.prism.walletsdk.castor.resolvers.LongFormPrismDIDResolver -import io.iohk.atala.prism.walletsdk.castor.resolvers.PeerDIDResolver -import io.iohk.atala.prism.walletsdk.castor.shared.CastorShared -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Apollo -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Castor -import io.iohk.atala.prism.walletsdk.domain.models.CastorError -import io.iohk.atala.prism.walletsdk.domain.models.Curve -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.DIDDocument -import io.iohk.atala.prism.walletsdk.domain.models.DIDResolver -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.KeyPair -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PublicKey -import io.iohk.atala.prism.walletsdk.logger.LogComponent -import io.iohk.atala.prism.walletsdk.logger.LogLevel -import io.iohk.atala.prism.walletsdk.logger.Metadata -import io.iohk.atala.prism.walletsdk.logger.PrismLogger -import io.iohk.atala.prism.walletsdk.logger.PrismLoggerImpl -import kotlin.jvm.Throws - -/** - * Castor is a powerful and flexible library for working with DIDs. Whether you are building a decentralised application - * or a more traditional system requiring secure and private identity management, Castor provides the tools and features - * you need to easily create, manage, and resolve DIDs. - */ -class CastorImpl -@JvmOverloads -constructor( - val apollo: Apollo, - private val logger: PrismLogger = PrismLoggerImpl(LogComponent.CASTOR) -) : Castor { - var resolvers: Array = arrayOf( - PeerDIDResolver(), - LongFormPrismDIDResolver(this.apollo) - ) - - /** - * Parses a string representation of a Decentralized Identifier (DID) into a DID object. - * - * @param did The string representation of the DID. - * @return The [DID] object. - * @throws [CastorError.InvalidDIDString] if the string is not a valid DID. - */ - @Throws(CastorError.InvalidDIDString::class) - override fun parseDID(did: String): DID { - return CastorShared.parseDID(did) - } - - /** - * 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. - * - * @param masterPublicKey The master public key of the prism - * @param services The list of services offered by the prism - * @return [DID] - */ - override fun createPrismDID( - masterPublicKey: PublicKey, - services: Array? - ): DID { - return CastorShared.createPrismDID( - apollo = apollo, - masterPublicKey = masterPublicKey, - services = services - ) - } - - /** - * 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. - * - * @param keyPairs The key pair used for key agreement (establishing secure communication between peers) and - * authentication (verifying the identity of a peer) - * @param services The list of services offered by the peer - * @return The [DID] of the peer - */ - @Throws(CastorError.InvalidKeyError::class) - override fun createPeerDID( - keyPairs: Array, - services: Array - ): DID { - return CastorShared.createPeerDID( - keyPairs = keyPairs, - services = services - ) - } - - /** - * 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. - * - * @param did The DID to resolve. - * @return The DID Document associated with the DID. - * @throws CastorError.NotPossibleToResolveDID if the DID is invalid or the document cannot be retrieved. - */ - @Throws(CastorError.NotPossibleToResolveDID::class) - override suspend fun resolveDID(did: String): DIDDocument { - logger.debug( - message = "Trying to resolve DID", - metadata = arrayOf( - Metadata.MaskedMetadataByLevel( - key = "DID", - value = did, - level = LogLevel.DEBUG - ) - ) - ) - val resolver = CastorShared.getDIDResolver(did, resolvers) - return resolver.resolve(did) - } - - /** - * 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. - * - * @param did The DID associate with the signature. - * @param challenge The challenge used to generate the signature. - * @param signature The signature data to verify. - * @return A [Boolean] value indicating whether the signature is valid or not. - * @throws [CastorError.InvalidKeyError] if the DID or signature data are invalid. - */ - @Throws(CastorError.InvalidKeyError::class) - override suspend fun verifySignature( - did: DID, - challenge: ByteArray, - signature: ByteArray - ): Boolean { - val document = resolveDID(did.toString()) - val publicKeys: List = - CastorShared.getKeyPairFromCoreProperties(document.coreProperties) - - if (publicKeys.isEmpty()) { - throw CastorError.InvalidKeyError("KeyPairs is empty") - } - - for (publicKey in publicKeys) { - when (publicKey.getCurve()) { - Curve.SECP256K1.value -> { - return (publicKey as Secp256k1PublicKey).verify(challenge, signature) - } - - Curve.ED25519.value -> { - return (publicKey as Ed25519PublicKey).verify(challenge, signature) - } - } - } - - return false - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/did/DIDParser.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/did/DIDParser.kt deleted file mode 100644 index b3e818e77..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/did/DIDParser.kt +++ /dev/null @@ -1,33 +0,0 @@ -package io.iohk.atala.prism.walletsdk.castor.did - -import io.iohk.atala.prism.walletsdk.domain.models.CastorError -import io.iohk.atala.prism.walletsdk.domain.models.DID -import kotlin.jvm.Throws - -/** - * The DIDParser class provides methods for parsing a string representation of a Decentralized Identifier (DID) into a DID object. - */ -object DIDParser { - - /** - * Parses a string representation of a Decentralized Identifier (DID) into a DID object. - * - * @param didString The string representation of the DID. - * @return The [DID] object. - * @throws [CastorError.InvalidDIDString] if the string is not a valid DID. - */ - @Throws(CastorError.InvalidDIDString::class) - fun parse(didString: String): DID { - val regex = - """^did:(?[a-z0-9]+):(?[a-z0-9.\-_%]+:*[a-z0-9.\-_%]+[^#?:]+)$""".toRegex(RegexOption.IGNORE_CASE) - val matchResult = regex.find(didString) - matchResult?.let { - val scheme = "did" - val methodName = it.groups["method"]?.value - ?: throw CastorError.InvalidDIDString("Invalid DID string, missing method name") - val methodId = it.groups["idstring"]?.value - ?: throw CastorError.InvalidDIDString("Invalid DID string, missing method ID") - return DID(scheme, methodName, methodId) - } ?: throw CastorError.InvalidDIDString("DID string does not match the expected structure.") - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/did/DIDUrlParser.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/did/DIDUrlParser.kt deleted file mode 100644 index 8ed8a7fa1..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/did/DIDUrlParser.kt +++ /dev/null @@ -1,50 +0,0 @@ -package io.iohk.atala.prism.walletsdk.castor.did - -import io.iohk.atala.prism.walletsdk.domain.models.CastorError -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.DIDUrl - -/** - * Class responsible for parsing a DID URL string and returning a parsed [DIDUrl] object. - */ -object DIDUrlParser { - /** - * Parses a DID URL string and returns a `DIDUrl` object. - * - * @param didUrlString The input DID URL string to parse. - * @return A `DIDUrl` object representing the parsed DID URL. - * @throws CastorError.InvalidDIDString if the input DID string does not match the expected structure. - */ - @Throws(CastorError.InvalidDIDString::class) - fun parse(didUrlString: String): DIDUrl { - val regex = - """^did:(?[a-z0-9]+)(?::(?[^#?/]*))?(?[^#?]*)?(?\?[^#]*)?(?#.*)?$""".toRegex( - RegexOption.IGNORE_CASE - ) - val matchResult = regex.find(didUrlString) - - matchResult?.let { it -> - val method = it.groups["method"]?.value - ?: throw CastorError.InvalidDIDString("Invalid DID string, missing method name") - val idString = it.groups["idstring"]?.value - ?: throw CastorError.InvalidDIDString("Invalid DID string, missing method ID") - val path = - it.groups["path"]?.value ?: throw CastorError.InvalidDIDString("Invalid DID string, missing path") - val query = it.groups["query"]?.value ?: "" - val fragment = it.groups["fragment"]?.value ?: "" - val attributes = if (query.isNotEmpty()) { - query.removePrefix("?").split("&") - .associate { - val (key, value) = it.split("=") - key to value - } - } else { - mapOf() - } - val paths = path.split("/").filter { it.isNotEmpty() }.toTypedArray() - val did = DID("did", method, idString) - val fragmentValue = if (fragment.isNotEmpty()) fragment.removePrefix("#") else null - return DIDUrl(did, paths, attributes, fragmentValue) - } ?: throw CastorError.InvalidDIDString("DID string does not match the expected structure.") - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/did/prismdid/LongFormPrismDID.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/did/prismdid/LongFormPrismDID.kt deleted file mode 100644 index 740f66106..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/did/prismdid/LongFormPrismDID.kt +++ /dev/null @@ -1,39 +0,0 @@ -package io.iohk.atala.prism.walletsdk.castor.did.prismdid - -import io.iohk.atala.prism.walletsdk.domain.models.CastorError -import io.iohk.atala.prism.walletsdk.domain.models.DID -import kotlin.jvm.Throws - -/** - * Represents a LongFormPrismDID. - * - * @property did The DID associated with the LongFormPrismDID. - * @property prismMethodId The PrismDIDMethodId instance associated with the LongFormPrismDID. - * @property stateHash The state hash of the LongFormPrismDID. - * @property encodedState The encoded state of the LongFormPrismDID. - * @throws CastorError.InvalidLongFormDID if the methodId of the DID does not have 2 sections. - */ -data class LongFormPrismDID -@Throws(CastorError.InvalidLongFormDID::class) -constructor(val did: DID) { - private val prismMethodId: PrismDIDMethodId - val stateHash: String - val encodedState: String - - init { - val methodId = PrismDIDMethodId( - did.methodId - ) - - if (methodId.sections.size != 2) { - throw CastorError.InvalidLongFormDID() - } - - val stateHash = methodId.sections.first() - val encodedState = methodId.sections.last() - - this.prismMethodId = methodId - this.stateHash = stateHash - this.encodedState = encodedState - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/did/prismdid/PrismDIDMethodId.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/did/prismdid/PrismDIDMethodId.kt deleted file mode 100644 index f6b24195b..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/did/prismdid/PrismDIDMethodId.kt +++ /dev/null @@ -1,41 +0,0 @@ -package io.iohk.atala.prism.walletsdk.castor.did.prismdid - -import io.iohk.atala.prism.walletsdk.castor.DID_SEPARATOR -import io.iohk.atala.prism.walletsdk.domain.models.CastorError -import kotlin.jvm.Throws - -/** - * Represents a Prism DID Method ID. - * - * @property value The string value of the Prism DID Method ID. - */ -data class PrismDIDMethodId(private val value: String) { - val sections: List - get() = value.split(DID_SEPARATOR).map { it } - - /** - * Represents a Prism DID Method ID. - * - * @property value The string value of the Prism DID Method ID. - */ - @Throws(CastorError.MethodIdIsDoesNotSatisfyRegex::class) - constructor(sections: List) : this(sections.joinToString(DID_SEPARATOR)) { - val sectionRegex = Regex("^[A-Za-z0-9_-]+$") - if (!sections.all { sectionRegex.matches(it) }) { - throw CastorError.MethodIdIsDoesNotSatisfyRegex("^[A-Za-z0-9_-]+$") - } - val methodSpecificIdRegex = Regex("^([A-Za-z0-9_-]*:)*[A-Za-z0-9_-]+$") - if (!methodSpecificIdRegex.matches(value)) { - throw CastorError.MethodIdIsDoesNotSatisfyRegex("^([A-Za-z0-9_-]*:)*[A-Za-z0-9_-]+\$") - } - } - - /** - * Returns a string representation of the Prism DID Method ID. - * - * @return The string representation of the Prism DID Method ID. - */ - override fun toString(): String { - return value - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/did/prismdid/PrismDIDPublicKey.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/did/prismdid/PrismDIDPublicKey.kt deleted file mode 100644 index d7c85f93e..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/did/prismdid/PrismDIDPublicKey.kt +++ /dev/null @@ -1,176 +0,0 @@ -package io.iohk.atala.prism.walletsdk.castor.did.prismdid - -import io.iohk.atala.prism.apollo.secp256k1.Secp256k1Lib -import io.iohk.atala.prism.protos.CompressedECKeyData -import io.iohk.atala.prism.protos.KeyUsage -import io.iohk.atala.prism.walletsdk.apollo.utils.Secp256k1PublicKey -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Apollo -import io.iohk.atala.prism.walletsdk.domain.models.CastorError -import io.iohk.atala.prism.walletsdk.domain.models.Curve -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PublicKey -import pbandk.ByteArr -import kotlin.jvm.Throws - -/** - * Represents a public key for the Atala PRISM system. - * - * @property apollo The instance of [Apollo] used for cryptographic operations. - * @property id The ID of the public key. - * @property usage The intended usage of the public key. - * @property keyData The actual public key data. - */ -class PrismDIDPublicKey { - private val apollo: Apollo - val id: String - val usage: Usage - val keyData: PublicKey - - /** - * Represents a PrismDIDPublicKey. - * - * @param apollo The cryptography suite representation. - * @param id The ID of the public key. - * @param usage The usage of the public key. - * @param keyData The actual public key data. - */ - constructor(apollo: Apollo, id: String, usage: Usage, keyData: PublicKey) { - this.apollo = apollo - this.id = id - this.usage = usage - this.keyData = keyData - } - - /** - * Constructs a PrismDIDPublicKey object. - * - * @param apollo The Apollo object used for cryptographic operations in the Atala PRISM. - * @param proto The protobuf representation of the public key. - * @throws CastorError.InvalidPublicKeyEncoding if the encoding of the key is invalid. - */ - @Throws(CastorError.InvalidPublicKeyEncoding::class) - constructor(apollo: Apollo, proto: io.iohk.atala.prism.protos.PublicKey) { - this.apollo = apollo - this.id = proto.id - this.usage = proto.usage.fromProto() - this.keyData = when (proto.keyData) { - is io.iohk.atala.prism.protos.PublicKey.KeyData.CompressedEcKeyData -> { - Secp256k1PublicKey(proto.keyData.value.data.array) - } - - else -> { - throw CastorError.InvalidPublicKeyEncoding("prism", "secp256k1") - } - } - } - - /** - * Converts the PublicKey object to a Protobuf PublicKey object. - * - * @return the converted Protobuf PublicKey object - */ - fun toProto(): io.iohk.atala.prism.protos.PublicKey { - val compressedPublicKey = Secp256k1PublicKey(Secp256k1Lib().compressPublicKey(keyData.getValue())) - return io.iohk.atala.prism.protos.PublicKey( - id = id, - usage = usage.toProto(), - keyData = io.iohk.atala.prism.protos.PublicKey.KeyData.CompressedEcKeyData( - compressedPublicKey.toProto() - ) - ) - } - - /** - * Enumeration representing the possible usages of a public key. - * - * @property value The string representation of the usage. - * @constructor Creates an instance of the Usage enum with the given value. - */ - enum class Usage(val value: String) { - MASTER_KEY("masterKey"), - ISSUING_KEY("issuingKey"), - AUTHENTICATION_KEY("authenticationKey"), - REVOCATION_KEY("revocationKey"), - CAPABILITY_DELEGATION_KEY("capabilityDelegationKey"), - CAPABILITY_INVOCATION_KEY("capabilityInvocationKey"), - KEY_AGREEMENT_KEY("keyAgreementKey"), - UNKNOWN_KEY("unknownKey") - } -} - -/** - * Converts a `KeyUsage` object to a `PrismDIDPublicKey.Usage` object. - * - * @return The corresponding `PrismDIDPublicKey.Usage` object. - */ -fun KeyUsage.fromProto(): PrismDIDPublicKey.Usage { - return when (this) { - is KeyUsage.MASTER_KEY -> PrismDIDPublicKey.Usage.MASTER_KEY - is KeyUsage.ISSUING_KEY -> PrismDIDPublicKey.Usage.ISSUING_KEY - is KeyUsage.AUTHENTICATION_KEY -> PrismDIDPublicKey.Usage.AUTHENTICATION_KEY - is KeyUsage.REVOCATION_KEY -> PrismDIDPublicKey.Usage.REVOCATION_KEY - is KeyUsage.CAPABILITY_DELEGATION_KEY -> PrismDIDPublicKey.Usage.CAPABILITY_DELEGATION_KEY - is KeyUsage.CAPABILITY_INVOCATION_KEY -> PrismDIDPublicKey.Usage.CAPABILITY_INVOCATION_KEY - is KeyUsage.KEY_AGREEMENT_KEY -> PrismDIDPublicKey.Usage.KEY_AGREEMENT_KEY - is KeyUsage.UNKNOWN_KEY -> PrismDIDPublicKey.Usage.UNKNOWN_KEY - is KeyUsage.UNRECOGNIZED -> PrismDIDPublicKey.Usage.UNKNOWN_KEY - } -} - -/** - * Converts a Secp256k1PublicKey object to a CompressedECKeyData object. - * - * @return the converted CompressedECKeyData object. - */ -fun Secp256k1PublicKey.toProto(): CompressedECKeyData { - return CompressedECKeyData( - curve = Curve.SECP256K1.value, - data = ByteArr(raw) - ) -} - -/** - * Generates the identifier for a PrismDIDPublicKey.Usage based on the given index. - * - * @param index The index used to generate the identifier. - * @return The generated identifier. - */ -fun PrismDIDPublicKey.Usage.id(index: Int): String { - return when (this) { - PrismDIDPublicKey.Usage.MASTER_KEY -> "master$index" - PrismDIDPublicKey.Usage.ISSUING_KEY -> "issuing$index" - PrismDIDPublicKey.Usage.AUTHENTICATION_KEY -> "authentication$index" - PrismDIDPublicKey.Usage.REVOCATION_KEY -> "revocation$index" - PrismDIDPublicKey.Usage.CAPABILITY_DELEGATION_KEY -> "capabilityDelegation$index" - PrismDIDPublicKey.Usage.CAPABILITY_INVOCATION_KEY -> "capabilityInvocation$index" - PrismDIDPublicKey.Usage.KEY_AGREEMENT_KEY -> "keyAgreement$index" - PrismDIDPublicKey.Usage.UNKNOWN_KEY -> "unknown$index" - } -} - -/** - * Converts the Usage value of a PrismDIDPublicKey to the corresponding KeyUsage enum value. - * - * @return The KeyUsage enum value corresponding to the Usage value of the PrismDIDPublicKey. - */ -fun PrismDIDPublicKey.Usage.toProto(): KeyUsage { - return when (this) { - PrismDIDPublicKey.Usage.MASTER_KEY -> KeyUsage.MASTER_KEY - PrismDIDPublicKey.Usage.ISSUING_KEY -> KeyUsage.ISSUING_KEY - PrismDIDPublicKey.Usage.AUTHENTICATION_KEY -> KeyUsage.AUTHENTICATION_KEY - PrismDIDPublicKey.Usage.REVOCATION_KEY -> KeyUsage.REVOCATION_KEY - PrismDIDPublicKey.Usage.CAPABILITY_DELEGATION_KEY -> KeyUsage.CAPABILITY_DELEGATION_KEY - PrismDIDPublicKey.Usage.CAPABILITY_INVOCATION_KEY -> KeyUsage.CAPABILITY_INVOCATION_KEY - PrismDIDPublicKey.Usage.KEY_AGREEMENT_KEY -> KeyUsage.KEY_AGREEMENT_KEY - PrismDIDPublicKey.Usage.UNKNOWN_KEY -> KeyUsage.UNKNOWN_KEY - } -} - -/** - * Returns the default ID for the current usage of the PrismDIDPublicKey. - * This method generates an ID based on the usage enum value. - * - * @return The default ID for the current usage. - */ -fun PrismDIDPublicKey.Usage.defaultId(): String { - return this.id(0) -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/resolvers/LongFormPrismDIDResolver.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/resolvers/LongFormPrismDIDResolver.kt deleted file mode 100644 index 6622478d8..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/resolvers/LongFormPrismDIDResolver.kt +++ /dev/null @@ -1,34 +0,0 @@ -package io.iohk.atala.prism.walletsdk.castor.resolvers - -import io.iohk.atala.prism.walletsdk.castor.PRISM -import io.iohk.atala.prism.walletsdk.castor.shared.CastorShared -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Apollo -import io.iohk.atala.prism.walletsdk.domain.models.DIDDocument -import io.iohk.atala.prism.walletsdk.domain.models.DIDResolver - -/** - * The LongFormPrismDIDResolver class is an implementation of the DIDResolver interface - * for resolving DID document using the LongForm PRISM method. - * - * @param apollo The Apollo instance used for cryptographic operations. - * - * @see Apollo - */ -class LongFormPrismDIDResolver( - private val apollo: Apollo -) : DIDResolver { - override val method: String = PRISM - - /** - * Resolves a DID document using the LongForm PRISM method. - * - * @param didString The string representation of the DID. - * @return The resolved DID document. - */ - override suspend fun resolve(didString: String): DIDDocument { - return CastorShared.resolveLongFormPrismDID( - apollo = apollo, - didString = didString - ) - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/resolvers/PeerDIDResolver.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/resolvers/PeerDIDResolver.kt deleted file mode 100644 index 4c9f7f7ed..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/resolvers/PeerDIDResolver.kt +++ /dev/null @@ -1,25 +0,0 @@ -package io.iohk.atala.prism.walletsdk.castor.resolvers - -import io.iohk.atala.prism.walletsdk.castor.PEER -import io.iohk.atala.prism.walletsdk.castor.shared.CastorShared -import io.iohk.atala.prism.walletsdk.domain.models.DIDDocument -import io.iohk.atala.prism.walletsdk.domain.models.DIDResolver - -/** - * The [PeerDIDResolver] class is an implementation of the [DIDResolver] interface for resolving DID document using the Peer DID method. - * - * @see DIDResolver - */ -class PeerDIDResolver : DIDResolver { - override val method: String = PEER - - /** - * Resolves a DID document using the Peer DID method. - * - * @param didString the string representation of the DID - * @return the resolved DID document - */ - override suspend fun resolve(didString: String): DIDDocument { - return CastorShared.resolvePeerDID(didString) - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/shared/CastorShared.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/shared/CastorShared.kt deleted file mode 100644 index 171e1da2c..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/castor/shared/CastorShared.kt +++ /dev/null @@ -1,575 +0,0 @@ -package io.iohk.atala.prism.walletsdk.castor.shared - -import io.iohk.atala.prism.apollo.base64.base64Encoded -import io.iohk.atala.prism.apollo.base64.base64UrlDecodedBytes -import io.iohk.atala.prism.apollo.base64.base64UrlEncoded -import io.iohk.atala.prism.didcomm.didpeer.DIDCommServicePeerDID -import io.iohk.atala.prism.didcomm.didpeer.DIDDocPeerDID -import io.iohk.atala.prism.didcomm.didpeer.MalformedPeerDIDException -import io.iohk.atala.prism.didcomm.didpeer.ServiceEndpoint -import io.iohk.atala.prism.didcomm.didpeer.VerificationMaterialAgreement -import io.iohk.atala.prism.didcomm.didpeer.VerificationMaterialAuthentication -import io.iohk.atala.prism.didcomm.didpeer.VerificationMaterialFormatPeerDID -import io.iohk.atala.prism.didcomm.didpeer.VerificationMethodPeerDID -import io.iohk.atala.prism.didcomm.didpeer.VerificationMethodTypeAgreement -import io.iohk.atala.prism.didcomm.didpeer.VerificationMethodTypeAuthentication -import io.iohk.atala.prism.didcomm.didpeer.core.toJsonElement -import io.iohk.atala.prism.didcomm.didpeer.createPeerDIDNumalgo2 -import io.iohk.atala.prism.protos.AtalaOperation -import io.iohk.atala.prism.protos.CreateDIDOperation -import io.iohk.atala.prism.protos.Service -import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519KeyPair -import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519PublicKey -import io.iohk.atala.prism.walletsdk.apollo.utils.Secp256k1KeyPair -import io.iohk.atala.prism.walletsdk.apollo.utils.Secp256k1PublicKey -import io.iohk.atala.prism.walletsdk.apollo.utils.X25519KeyPair -import io.iohk.atala.prism.walletsdk.apollo.utils.X25519PublicKey -import io.iohk.atala.prism.walletsdk.castor.DID -import io.iohk.atala.prism.walletsdk.castor.PRISM -import io.iohk.atala.prism.walletsdk.castor.did.DIDParser -import io.iohk.atala.prism.walletsdk.castor.did.DIDUrlParser -import io.iohk.atala.prism.walletsdk.castor.did.prismdid.LongFormPrismDID -import io.iohk.atala.prism.walletsdk.castor.did.prismdid.PrismDIDMethodId -import io.iohk.atala.prism.walletsdk.castor.did.prismdid.PrismDIDPublicKey -import io.iohk.atala.prism.walletsdk.castor.did.prismdid.defaultId -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Apollo -import io.iohk.atala.prism.walletsdk.domain.models.CastorError -import io.iohk.atala.prism.walletsdk.domain.models.Curve -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.DIDDocument -import io.iohk.atala.prism.walletsdk.domain.models.DIDDocumentCoreProperty -import io.iohk.atala.prism.walletsdk.domain.models.DIDResolver -import io.iohk.atala.prism.walletsdk.domain.models.DIDUrl -import io.iohk.atala.prism.walletsdk.domain.models.OctetPublicKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.KeyPair -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PublicKey -import io.iohk.atala.prism.walletsdk.logger.LogComponent -import io.iohk.atala.prism.walletsdk.logger.LogLevel -import io.iohk.atala.prism.walletsdk.logger.Metadata -import io.iohk.atala.prism.walletsdk.logger.PrismLoggerImpl -import kotlinx.serialization.decodeFromString -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json -import org.kotlincrypto.hash.sha2.SHA256 -import pbandk.decodeFromByteArray -import pbandk.encodeToByteArray -import kotlin.jvm.Throws -import io.iohk.atala.prism.didcomm.didpeer.resolvePeerDID as mercuryPeerDIDResolve - -/** - * The `CastorShared` class provides a set of logging methods for the Castor module. - */ -internal class CastorShared { - companion object { - - /** - * The logger property is a PrismLoggerImpl instance for logging purposes. - * It is used to log debug, info, warning, and error messages, along with the associated metadata. - * - * @property logger The logger instance. - */ - private val logger = PrismLoggerImpl(LogComponent.CASTOR) - - /** - * parseDID parses a string representation of a Decentralized Identifier (DID) into a DID object. - * - * @param did The string representation of the DID. - * @return The [DID] object. - * @throws [CastorError.InvalidDIDString] if the string is not a valid DID. - */ - @JvmStatic - @Throws(CastorError.InvalidDIDString::class) - fun parseDID(did: String): DID { - return DIDParser.parse(did) - } - - /** - * 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. - * - * @param apollo the cryptography suit representation. - * @param masterPublicKey master public key used in creating the Prism DID. - * @param services list of services. - * @return [DID]. - */ - @JvmStatic - internal fun createPrismDID( - apollo: Apollo, - masterPublicKey: PublicKey, - services: Array? - ): DID { - val atalaOperation = AtalaOperation( - operation = AtalaOperation.Operation.CreateDid( - CreateDIDOperation( - didData = CreateDIDOperation.DIDCreationData( - publicKeys = listOf( - PrismDIDPublicKey( - apollo = apollo, - id = PrismDIDPublicKey.Usage.MASTER_KEY.defaultId(), - usage = PrismDIDPublicKey.Usage.MASTER_KEY, - keyData = masterPublicKey - ).toProto(), - PrismDIDPublicKey( - apollo = apollo, - id = PrismDIDPublicKey.Usage.AUTHENTICATION_KEY.defaultId(), - usage = PrismDIDPublicKey.Usage.AUTHENTICATION_KEY, - keyData = masterPublicKey - ).toProto() - ), - services = services?.map { - Service( - id = it.id, - type = it.type.first(), - serviceEndpoint = listOf(it.serviceEndpoint.uri) - ) - } ?: emptyList() - ) - ) - ) - ) - - val encodedState = atalaOperation.encodeToByteArray() - val stateHash = SHA256().digest(encodedState).toHexString() - val base64State = encodedState.base64UrlEncoded - val methodSpecificId = PrismDIDMethodId( - sections = listOf( - stateHash, - base64State - ) - ) - - return DID( - schema = DID, - method = PRISM, - methodId = methodSpecificId.toString() - ) - } - - /** - * Resolve PeerDID String to [DIDDocument]. - * - * @param didString that we need to resolve. - * @return [DIDDocument] - * @throws [CastorError.InvalidPeerDIDError] when the provided DID is invalid. - * @throws [CastorError.NotPossibleToResolveDID] when unable to resolve the provided DID. - */ - @JvmStatic - @Throws(CastorError.InvalidPeerDIDError::class, CastorError.NotPossibleToResolveDID::class) - internal suspend fun resolvePeerDID(didString: String): DIDDocument { - val peerDIDDocument = try { - DIDDocPeerDID.fromJson(mercuryPeerDIDResolve(didString)) - } catch (e: MalformedPeerDIDException) { - throw CastorError.InvalidPeerDIDError(e.message, e.cause) - } catch (e: Throwable) { - throw CastorError.NotPossibleToResolveDID( - did = didString, - reason = "Method or method id are invalid", - e - ) - } - - val coreProperties: MutableList = mutableListOf() - - coreProperties.add( - DIDDocument.Authentication( - urls = arrayOf(), - verificationMethods = peerDIDDocument.authentication.map { - fromVerificationMethodPeerDID(it.id, it) - }.toTypedArray() - ) - ) - coreProperties.add( - DIDDocument.KeyAgreement( - urls = arrayOf(), - verificationMethods = peerDIDDocument.keyAgreement.map { - fromVerificationMethodPeerDID(it.id, it) - }.toTypedArray() - ) - ) - - val peerDIDServices = peerDIDDocument.service ?: listOf() - val services: MutableList = mutableListOf() - - peerDIDServices.forEach { service -> - run { - if (service is DIDCommServicePeerDID) { - services.add( - DIDDocument.Service( - id = service.id, - type = arrayOf(service.type), - serviceEndpoint = DIDDocument.ServiceEndpoint( - uri = service.serviceEndpoint.uri, - accept = service.serviceEndpoint.accept.toTypedArray(), - routingKeys = service.serviceEndpoint.routingKeys.toTypedArray() - ) - ) - ) - } - } - } - - coreProperties.add( - DIDDocument.Services( - services.toTypedArray() - ) - ) - - val did = DIDParser.parse(didString) - - return DIDDocument( - id = did, - coreProperties = coreProperties.toTypedArray() - ) - } - - /** - * Extract the [DIDDocument.VerificationMethod] for the [did] based on the [verificationMethod]. - * - * @param did string of the PeerDID - * @param verificationMethod of the PeerDID - * @return [DIDDocument.VerificationMethod] - * @throws [CastorError.InvalidKeyError] if provided [verificationMethod] is not supported. - */ - @JvmStatic - @Throws(CastorError.InvalidKeyError::class) - private fun fromVerificationMethodPeerDID( - did: String, - verificationMethod: VerificationMethodPeerDID - ): DIDDocument.VerificationMethod { - val didUrl = DIDUrlParser.parse(did) - val controller = DIDParser.parse(verificationMethod.controller) - val type = when (verificationMethod.verMaterial.type.value) { - VerificationMethodTypeAuthentication.ED25519VerificationKey2020.value, - VerificationMethodTypeAuthentication.ED25519VerificationKey2018.value -> { - Curve.ED25519.value - } - - VerificationMethodTypeAgreement.X25519KeyAgreementKey2020.value, - VerificationMethodTypeAgreement.X25519KeyAgreementKey2019.value -> { - Curve.X25519.value - } - - else -> { - throw CastorError.InvalidKeyError() - } - } - - return when (verificationMethod.verMaterial.format) { - VerificationMaterialFormatPeerDID.JWK -> { - DIDDocument.VerificationMethod( - didUrl, - controller, - type, - Json.decodeFromString>(verificationMethod.verMaterial.value as String) - ) - } - - VerificationMaterialFormatPeerDID.BASE58 -> { - DIDDocument.VerificationMethod( - didUrl, - controller, - type, - null, - verificationMethod.verMaterial.value as String - ) - } - - VerificationMaterialFormatPeerDID.MULTIBASE -> { - DIDDocument.VerificationMethod( - didUrl, - controller, - type, - null, - verificationMethod.verMaterial.value as String - ) - } - } - } - - /** - * Resolve Long Form of Prism DID. - * - * @param apollo the cryptography suit representation. - * @param didString The DID string we want to resolve. - * @return [DIDDocument] - * @throws [CastorError.InitialStateOfDIDChanged] when decoding the state fails. - */ - @JvmStatic - @Throws(CastorError.InitialStateOfDIDChanged::class) - internal suspend fun resolveLongFormPrismDID(apollo: Apollo, didString: String): DIDDocument { - val did = DIDParser.parse(didString) - val prismDID = LongFormPrismDID(did) - - val (verificationMethods, services) = try { - decodeState( - apollo = apollo, - did = did, - stateHash = prismDID.stateHash, - encodedData = prismDID.encodedState.base64UrlDecodedBytes - ) - } catch (e: Throwable) { - logger.error( - message = "The DID state hash does not match the state", - metadata = arrayOf( - Metadata.MaskedMetadataByLevel( - key = "DID", - value = didString, - level = LogLevel.DEBUG - ) - ) - ) - throw CastorError.InitialStateOfDIDChanged(e.message) - } - - val servicesProperty = DIDDocument.Services(services.toTypedArray()) - val verificationMethodsProperty = DIDDocument.VerificationMethods(verificationMethods.values.toTypedArray()) - val coreProperties = mutableListOf() - - val authenticate = verificationMethods.entries.map { - DIDDocument.Authentication( - urls = arrayOf(it.key), - verificationMethods = verificationMethods.values.toTypedArray() - ) - } - - authenticate.forEach { - coreProperties.add(it) - } - - coreProperties.add(servicesProperty) - coreProperties.add(verificationMethodsProperty) - - return DIDDocument( - id = did, - coreProperties = coreProperties.toTypedArray() - ) - } - - /** - * Decode the provided [encodedData] to [Pair] of a [Map] and of List<[DIDDocument.Service]> where the [Map] is - * key as [String] and its value [DIDDocument.VerificationMethod]. - * - * @param apollo the cryptography suit representation. - * @param did the DID that is used in to decode. - * @param stateHash the hashed version of the [encodedData] in Hex string format. - * @param encodedData the [ByteArray] - * @return [Pair] of a [Map] and of List<[DIDDocument.Service]> where the [Map] is key as [String] and its value - * [DIDDocument.VerificationMethod]. - * @throws [CastorError.InitialStateOfDIDChanged] - * @throws [Exception] - */ - @JvmStatic - @Throws(CastorError.InitialStateOfDIDChanged::class, Exception::class) - private fun decodeState( - apollo: Apollo, - did: DID, - stateHash: String, - encodedData: ByteArray - ): Pair, List> { - val sha256 = SHA256() - val verifyEncodedState = sha256.digest(encodedData) - val verifyEncodedStateHex = verifyEncodedState.toHexString() - - require(stateHash == verifyEncodedStateHex) { - throw CastorError.InitialStateOfDIDChanged() - } - - val operation = AtalaOperation.decodeFromByteArray(encodedData) - - val publicKeys = operation.createDid?.didData?.publicKeys?.map { - try { - PrismDIDPublicKey(apollo, it) - } catch (e: Exception) { - logger.error( - message = "Failed to decode public key from document", - metadata = arrayOf( - Metadata.MaskedMetadataByLevel( - key = "DID", - value = did.toString(), - level = LogLevel.DEBUG - ) - ) - ) - throw e - } - } ?: listOf() - - val services = operation.createDid?.didData?.services?.map { - DIDDocument.Service( - it.id, - arrayOf(it.type), - DIDDocument.ServiceEndpoint( - uri = it.serviceEndpoint.first() - ) - ) - } ?: listOf() - - val verificationMethods = - publicKeys.fold(emptyMap()) { partialResult, publicKey -> - val didUrl = DIDUrl( - did = did, - fragment = publicKey.id - ) - val method = DIDDocument.VerificationMethod( - id = didUrl, - controller = did, - type = publicKey.keyData.getCurve(), - publicKeyMultibase = publicKey.keyData.getValue().base64Encoded - ) - partialResult + (didUrl.string() to method) - } - - return Pair(verificationMethods, services) - } - - /** - * Get a DID resolver based on the provided DID string. - * - * @param did the DID string. - * @param resolvers list of available resolvers. - * @throws [CastorError.NotPossibleToResolveDID] if no resolver was found. - */ - @JvmStatic - @Throws(CastorError.NotPossibleToResolveDID::class) - internal fun getDIDResolver(did: String, resolvers: Array): DIDResolver { - val parsedDID = parseDID(did) - return resolvers.find { it.method == parsedDID.method } ?: throw CastorError.NotPossibleToResolveDID( - did, - "Method or method id are invalid" - ) - } - - /** - * Extract list of [PublicKey] from a list of [DIDDocumentCoreProperty]. - * - * @param coreProperties list of [DIDDocumentCoreProperty] that we are going to extract a list of [DIDDocumentCoreProperty]. - * @return List<[PublicKey]> - */ - @JvmStatic - internal fun getKeyPairFromCoreProperties(coreProperties: Array): List { - return coreProperties - .filterIsInstance() - .flatMap { it.verificationMethods.toList() } - .mapNotNull { - it.publicKeyMultibase?.let { publicKey -> - when (DIDDocument.VerificationMethod.getCurveByType(it.type)) { - Curve.SECP256K1 -> { - Secp256k1PublicKey(publicKey.encodeToByteArray()) - } - - Curve.ED25519 -> { - Ed25519PublicKey(publicKey.encodeToByteArray()) - } - - Curve.X25519 -> { - X25519PublicKey(publicKey.encodeToByteArray()) - } - } - } - } - } - - /** - * Create [OctetPublicKey] from a [KeyPair]. - * - * @param keyPair keyPair to be used in creating [OctetPublicKey]. - * @return [OctetPublicKey]. - */ - @JvmStatic - private fun octetPublicKey(keyPair: KeyPair): OctetPublicKey { - val curve = when (keyPair::class) { - Secp256k1KeyPair::class -> { - Curve.SECP256K1 - } - - Ed25519KeyPair::class -> { - Curve.ED25519 - } - - X25519KeyPair::class -> { - Curve.X25519 - } - - else -> { - throw CastorError.KeyCurveNotSupported(KeyPair::class.simpleName ?: "") - } - } - return OctetPublicKey(crv = curve.value, x = keyPair.publicKey.getValue().base64UrlEncoded) - } - - /** - * 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. - * - * @param keyPairs The key pair used for key agreement (establishing secure communication between peers) and - * authentication (verifying the identity of a peer) - * @param services The list of services offered by the peer - * @return The [DID] of the peer - */ - @JvmStatic - @Throws(CastorError.InvalidKeyError::class) - internal fun createPeerDID( - keyPairs: Array, - services: Array - ): DID { - val encryptionKeys: MutableList = mutableListOf() - val signingKeys: MutableList = mutableListOf() - - keyPairs.forEach { - when (it::class) { - X25519KeyPair::class -> { - val octetString = Json.encodeToString(octetPublicKey(it)) - encryptionKeys.add( - VerificationMaterialAgreement( - format = VerificationMaterialFormatPeerDID.JWK, - value = octetString, - type = VerificationMethodTypeAgreement.JsonWebKey2020 - ) - ) - } - - Ed25519KeyPair::class -> { - val octetString = Json.encodeToString(octetPublicKey(it)) - signingKeys.add( - VerificationMaterialAuthentication( - format = VerificationMaterialFormatPeerDID.JWK, - value = octetString, - type = VerificationMethodTypeAuthentication.JsonWebKey2020 - ) - ) - } - - else -> { - throw CastorError.InvalidKeyError() - } - } - } - - if (signingKeys.isEmpty() || encryptionKeys.isEmpty()) { - throw CastorError.InvalidKeyError() - } - - val peerDID = createPeerDIDNumalgo2( - encryptionKeys = encryptionKeys, - signingKeys = signingKeys, - service = services.map { - val serviceEndpoint = ServiceEndpoint( - uri = it.serviceEndpoint.uri, - routingKeys = it.serviceEndpoint.routingKeys?.toList() ?: listOf(), - accept = it.serviceEndpoint.accept?.asList() ?: listOf() - ) - - Json.encodeToString( - DIDCommServicePeerDID( - id = it.id, - type = it.type[0], - serviceEndpoint = serviceEndpoint - ).toDict().toJsonElement() - ) - }.firstOrNull() - ) - - return DIDParser.parse(peerDID) - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/DomainConstants.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/DomainConstants.kt deleted file mode 100644 index d3bf3cae1..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/DomainConstants.kt +++ /dev/null @@ -1,29 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain - -const val DID = "did" -const val DID_SEPARATOR = ":" -const val DID_URL_SEPARATOR = "/" -const val VC = "vc" -const val CREDENTIAL_TYPE = "credentialType" -const val ID = "id" -const val CONTEXT = "context" -const val TYPE = "type" -const val ISSUER = "issuer" -const val CREDENTIAL_SCHEMA = "credentialSchema" -const val CREDENTIAL_SUBJECT = "credentialSubject" -const val CREDENTIAL_STATUS = "credentialStatus" -const val REFRESH_SERVICE = "refreshService" -const val EVIDENCE = "evidence" -const val TERMS_OF_USE = "termsOfUse" -const val ISSUANCE_DATE = "issuanceDate" -const val EXPIRATION_DATE = "expirationDate" -const val VALID_FROM = "validFrom" -const val VALID_UNTIL = "validUntil" -const val PROOF = "proof" -const val AUD = "aud" -const val ISS = "iss" -const val SUB = "sub" -const val NBF = "nbf" -const val EXP = "exp" -const val JTI = "jti" -const val OKP = "OKP" diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/buildingblocks/Apollo.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/buildingblocks/Apollo.kt deleted file mode 100644 index a969e69e8..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/buildingblocks/Apollo.kt +++ /dev/null @@ -1,53 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.buildingblocks - -import io.iohk.atala.prism.apollo.derivation.MnemonicLengthException -import io.iohk.atala.prism.walletsdk.domain.models.Seed -import io.iohk.atala.prism.walletsdk.domain.models.SeedWords -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.KeyRestoration -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PrivateKey -import kotlin.jvm.Throws - -/** - * Apollo defines the set of cryptographic operations that are used in the Atala PRISM. - */ -interface Apollo : KeyRestoration { - - /** - * Creates a random set of mnemonic phrases that can be used as a seed for generating - * a private key. - * - * @return An array of mnemonic phrases. - */ - fun createRandomMnemonics(): Array - - /** - * Takes in a set of mnemonics and a passphrase, and returns a seed object used to generate a private key. - * - * @param mnemonics An array of mnemonic phrases. - * @param passphrase A passphrase used to enhance the security of the seed. - * @return A seed object. - * @throws [MnemonicLengthException] if the mnemonics or passphrase are invalid. - */ - @Throws(MnemonicLengthException::class) - fun createSeed(mnemonics: Array, passphrase: String): Seed - - /** - * Creates a random seed and a corresponding set of mnemonic phrases. - * - * @param passphrase A passphrase used to enhance the security of the seed. - * @return [SeedWords]. - */ - fun createRandomSeed(passphrase: String? = ""): SeedWords - - /** - * Creates a private key using the provided properties. - * - * @param properties A map containing the properties of the private key. - * The supported properties are: - * - "type": The type of the private key. Use KeyTypes.EC for elliptic curve keys. - * - "seed": The seed used for key generation. Must be a byte array. - * - "curve": The key curve. Use Curve.SECP256K1 for secp256k1 curve. - * @return A PrivateKey object representing the created private key. - */ - fun createPrivateKey(properties: Map): PrivateKey -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/buildingblocks/Castor.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/buildingblocks/Castor.kt deleted file mode 100644 index 45a8168eb..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/buildingblocks/Castor.kt +++ /dev/null @@ -1,81 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.buildingblocks - -import io.iohk.atala.prism.walletsdk.domain.models.CastorError -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.DIDDocument -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.KeyPair -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PublicKey - -/** - * Castor is a powerful and flexible library for working with DIDs. Whether you are building a decentralised application - * or a more traditional system requiring secure and private identity management, Castor provides the tools and features - * you need to easily create, manage, and resolve DIDs. - */ -interface Castor { - - /** - * Parses a string representation of a Decentralized Identifier (DID) into a DID object. - * - * @param did The string representation of the DID. - * @return The [DID] object. - * @throws [CastorError.InvalidDIDString] if the string is not a valid DID. - */ - @Throws(CastorError.InvalidDIDString::class) - fun parseDID(did: String): DID - - /** - * 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. - * - * @param masterPublicKey The master public key of the prism - * @param services The list of services offered by the prism - * @return [DID] - */ - fun createPrismDID( - masterPublicKey: PublicKey, - services: Array? - ): DID - - /** - * 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. - * - * @param keyPairs The key pair used for key agreement (establishing secure communication between peers) and - * authentication (verifying the identity of a peer) - * @param services The list of services offered by the peer - * @return The [DID] of the peer - */ - fun createPeerDID( - keyPairs: Array, - services: Array - ): DID - - /** - * 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. - * - * @param did The DID to resolve. - * @return The DID Document associated with the DID. - * @throws CastorError.NotPossibleToResolveDID if the DID is invalid or the document cannot be retrieved. - */ - @Throws(CastorError.NotPossibleToResolveDID::class) - suspend fun resolveDID(did: String): DIDDocument - - /** - * 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. - * - * @param did The DID associate with the signature. - * @param challenge The challenge used to generate the signature. - * @param signature The signature data to verify. - * @return A [Boolean] value indicating whether the signature is valid or not. - * @throws [CastorError.InvalidKeyError] if the DID or signature data are invalid. - */ - @Throws(CastorError.InvalidKeyError::class) - suspend fun verifySignature( - did: DID, - challenge: ByteArray, - signature: ByteArray - ): Boolean -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/buildingblocks/Mercury.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/buildingblocks/Mercury.kt deleted file mode 100644 index 4d50b342d..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/buildingblocks/Mercury.kt +++ /dev/null @@ -1,54 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.buildingblocks - -import io.iohk.atala.prism.walletsdk.domain.models.MercuryError -import io.iohk.atala.prism.walletsdk.domain.models.Message -import kotlin.jvm.Throws - -/** - * 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 a more complex - * decentralized system requiring trusted peer-to-peer connections, Mercury provides the tools and features you need to - * establish, manage, and secure your communications easily. - */ -interface Mercury { - - /** - * Asynchronously packs a given message object into a string representation. This function may throw an error if the - * message object is invalid. - * - * @param message The message object to pack - * @return The string representation of the packed message - * @throws [MercuryError.NoDIDReceiverSetError] if DIDReceiver is invalid. - * @throws [MercuryError.NoDIDSenderSetError] if DIDSender is invalid. - */ - @Throws(MercuryError.NoDIDReceiverSetError::class, MercuryError.NoDIDSenderSetError::class) - fun packMessage(message: Message): String - - /** - * 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. - * - * @param message The string representation of the message to unpack - * @return The message object - */ - fun unpackMessage(message: String): Message - - /** - * Asynchronously sends a given message and returns the response data. - * - * @param message The message to send - * @return The response data - * @throws [MercuryError.NoDIDReceiverSetError] if DIDReceiver is invalid. - * @throws [MercuryError.NoDIDSenderSetError] if DIDSender is invalid. - */ - @Throws(MercuryError.NoDIDReceiverSetError::class, MercuryError.NoDIDSenderSetError::class) - suspend fun sendMessage(message: Message): ByteArray? - - /** - * Asynchronously sends a given message and returns the response message object. - * - * @param message The message to send - * @return The response message object or null - */ - suspend fun sendMessageParseResponse(message: Message): Message? -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/buildingblocks/Pluto.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/buildingblocks/Pluto.kt deleted file mode 100644 index 642e66ab4..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/buildingblocks/Pluto.kt +++ /dev/null @@ -1,342 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.buildingblocks - -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.DIDPair -import io.iohk.atala.prism.walletsdk.domain.models.Mediator -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.domain.models.PeerDID -import io.iohk.atala.prism.walletsdk.domain.models.PrismDIDInfo -import io.iohk.atala.prism.walletsdk.domain.models.StorableCredential -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PrivateKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.StorableKey -import io.iohk.atala.prism.walletsdk.pluto.CredentialRecovery -import io.iohk.atala.prism.walletsdk.pluto.data.AvailableClaims -import io.iohk.atala.prism.walletsdk.pollux.models.CredentialRequestMeta -import kotlinx.coroutines.flow.Flow - -/** - * The `Pluto` interface defines the contract for storing and retrieving various data related to Atala PRISM architecture. - */ -interface Pluto { - - /** - * Stores the Prism DID, key path index, alias, and private keys. - * - * @param did The Prism DID to store. - * @param keyPathIndex The key path index. - * @param alias The optional alias for the Prism DID. - * @param privateKeys The list of private keys to store. - */ - fun storePrismDIDAndPrivateKeys( - did: DID, - keyPathIndex: Int, - alias: String?, - privateKeys: List - ) - - /** - * Stores the PeerDID in the system. - * - * @param did The PeerDID to store. - */ - fun storePeerDID(did: DID) - - /** - * Stores a pair of Distributed Identifier (DID) and a receiver DID with a given name. - * - * @param host The host DID to store. - * @param receiver The receiver DID to store. - * @param name The name of the stored pair. - */ - fun storeDIDPair(host: DID, receiver: DID, name: String) - - /** - * Stores a message in the system. - * - * @param message The message to store. - */ - fun storeMessage(message: Message) - - /** - * Stores a list of messages in the system. - * - * @param messages The list of messages to store. - */ - fun storeMessages(messages: List) - - /** - * Stores the private key along with additional information. - * - * @param storableKey The private key to store. Must implement the [StorableKey] interface. - * @param did The DID associated with the private key. - * @param keyPathIndex The key path index. - * @param metaId The optional metadata ID. - */ - fun storePrivateKeys(storableKey: StorableKey, did: DID, keyPathIndex: Int, metaId: String? = null) - - /** - * Stores a mediator in the system. - * - * @param mediator The mediator DID to store. - * @param host The host DID associated with the mediator. - * @param routing The routing DID for the mediator. - */ - fun storeMediator(mediator: DID, host: DID, routing: DID) - - /** - * Stores a credential in the system. - * - * @param storableCredential The credential to store. It must implement the [StorableCredential] interface. - */ - fun storeCredential(storableCredential: StorableCredential) - - /** - * Stores a link secret in the system. - * - * @param linkSecret The link secret to store. - */ - fun storeLinkSecret(linkSecret: String) - - /** - * Stores the metadata associated with a credential request. - * - * @param metadata The metadata to store. It must be an instance of [CredentialRequestMeta]. - */ - fun storeCredentialMetadata(metadata: CredentialRequestMeta) - - /** - * Retrieves all PrismDIDs and their associated information. - * - * @return A flow of lists of [PrismDIDInfo] objects representing the PrismDIDs and their information. - */ - fun getAllPrismDIDs(): Flow> - - /** - * Retrieves the [PrismDIDInfo] associated with a given [DID]. - * - * @param did The [DID] for which to retrieve the [PrismDIDInfo]. - * @return A [Flow] that emits a nullable [PrismDIDInfo] object representing the [PrismDIDInfo] associated - * with the specified [DID]. If no [PrismDIDInfo] is found, null is emitted. - */ - fun getDIDInfoByDID(did: DID): Flow - - /** - * Retrieves the [PrismDIDInfo] objects associated with a given alias. - * - * @param alias The alias for which to retrieve the [PrismDIDInfo] objects. - * @return A [Flow] that emits a list of [PrismDIDInfo] objects representing the - * [PrismDIDInfo] associated with the specified alias. - */ - fun getDIDInfoByAlias(alias: String): Flow> - - /** - * Retrieves the key path index associated with a given Prism DID. - * - * @param did The Prism DID for which to retrieve the key path index. - * @return A [Flow] that emits a nullable [Int] representing the key path index associated with the specified Prism DID. - * If no key path index is found, null is emitted. - */ - fun getPrismDIDKeyPathIndex(did: DID): Flow - - /** - * Retrieves the last key path index associated with the Prism DID. - * - * @return A [Flow] that emits an [Int] representing the last key path index associated with the Prism DID. - */ - fun getPrismLastKeyPathIndex(): Flow - - /** - * Retrieves all PeerDIDs. - * - * @return A flow of lists of PeerDIDs. - */ - fun getAllPeerDIDs(): Flow> - - /** - * Retrieves a list of private keys associated with a given DID. - * - * @param did The DID for which to retrieve private keys. - * @return A flow that emits a list of nullable [PrivateKey] objects. In case a private key is not found, null is emitted. - */ - fun getDIDPrivateKeysByDID(did: DID): Flow> - - /** - * Retrieves the private key associated with a given ID. - * - * @param id The ID of the private key. - * @return A [Flow] that emits the private key as a nullable [PrivateKey] object. If no private key is found, - * null is emitted. - */ - fun getDIDPrivateKeyByID(id: String): Flow - - /** - * Retrieves all the pairs of DIDs stored in the system. - * - * @return a [Flow] emitting a list of [DIDPair] objects representing the pairs of DIDs. - */ - fun getAllDidPairs(): Flow> - - /** - * Retrieves a DIDPair object using the provided DID. - * - * @param did The DID to search for. - * @return A Flow of DIDPair objects. If a match is found, the flow emits the matching DIDPair. - * If no match is found, the flow emits null. - */ - fun getPairByDID(did: DID): Flow - - /** - * Retrieve a [DIDPair] from a flow by its name. - * - * @param name The name of the [DIDPair] to retrieve. - * @return A [Flow] emitting the [DIDPair] object that matches the given name, - * or `null` if no matching [DIDPair] is found. - */ - fun getPairByName(name: String): Flow - - /** - * Retrieves all the messages. - * - * @return a Flow of List of Message objects representing all the messages. - */ - fun getAllMessages(): Flow> - - /** - * Retrieves all messages based on the provided DID. - * - * @param did The DID (Direct Inward Dialing) to filter messages by. - * @return A flow of list of messages. - */ - fun getAllMessages(did: DID): Flow> - - /** - * Retrieves all the messages that have been sent. - * - * @return A [Flow] of type [List] containing the sent messages. - */ - fun getAllMessagesSent(): Flow> - - /** - * Retrieves all messages received by the user. - * - * @return A [Flow] emitting a list of [Message] objects representing all the messages received. - */ - fun getAllMessagesReceived(): Flow> - - /** - * Retrieves all messages sent to the specified DID. - * - * @param did the destination DID to filter the messages by - * @return a [Flow] of [List] of [Message] objects containing all the messages sent to the specified DID - */ - fun getAllMessagesSentTo(did: DID): Flow> - - /** - * Returns a Flow of lists of all messages received from the specified DID. - * - * @param did the DID (Decentralized Identifier) to get the received messages from - * @return a Flow of lists of messages received from the specified DID - */ - fun getAllMessagesReceivedFrom(did: DID): Flow> - - /** - * Retrieves all messages of a specific type that are related to a given DID. - * - * @param type The type of the messages to retrieve. - * @param relatedWithDID The optional DID to which the messages are related. - * @return A [Flow] emitting a list of [Message] objects that match the given type and are related to the specified DID. - */ - fun getAllMessagesOfType(type: String, relatedWithDID: DID?): Flow> - - /** - * Retrieves all messages exchanged between the specified 'from' and 'to' DIDs. - * - * @param from the sender DID - * @param to the receiver DID - * @return a Flow emitting a list of messages exchanged between the 'from' and 'to' DIDs - */ - fun getAllMessages(from: DID, to: DID): Flow> - - /** - * Retrieves the message with the specified ID. - * - * @param id The unique ID of the message. - * @return A [Flow] that emits the message with the specified ID, or null if no such message exists. - * The [Flow] completes when the message is successfully retrieved, or when an error occurs. - */ - fun getMessage(id: String): Flow - - /** - * Returns a Flow of lists of [Mediator] objects representing all the available mediators. - * - * @return a Flow of lists of [Mediator] objects. - */ - fun getAllMediators(): Flow> - - /** - * Retrieves all credentials for credential recovery. - * - * @return A flow of a list of [CredentialRecovery] objects representing the credentials for recovery. - */ - fun getAllCredentials(): Flow> - - /** - * Inserts an available claim for a specific credential. - * - * @param credentialId The ID of the credential. - * @param claim The claim to insert. - */ - fun insertAvailableClaim(credentialId: String, claim: String) - - /** - * Inserts the available claims for a given credential ID. - * - * @param credentialId the ID of the credential - * @param claims an array of available claims to be inserted - */ - fun insertAvailableClaims(credentialId: String, claims: Array) - - /** - * Retrieves the available claims for a given credential ID. - * - * @param credentialId The ID of the credential. - * @return A flow that emits an array of AvailableClaims. - */ - fun getAvailableClaimsByCredentialId(credentialId: String): Flow> - - /** - * Retrieves the available claims for a given claim. - * - * @param claim The claim for which the available claims are to be retrieved. - * @return A flow of arrays of AvailableClaims representing the available claims for the given claim. - */ - fun getAvailableClaimsByClaim(claim: String): Flow> - - /** - * Retrieves the secret link associated with the current instance. - * - * @return A [Flow] emitting the secret link as a nullable [String]. - */ - fun getLinkSecret(): Flow - - /** - * Retrieves the metadata associated with a credential request. - * - * @param linkSecretName The name of the link secret used for the credential request. - * @return A [Flow] emitting the [CredentialRequestMeta] object for the specified link secret name, - * or null if no metadata is found. - */ - fun getCredentialMetadata(linkSecretName: String): Flow - - /** - * Revokes an existing credential using the credential ID. - * - * @param credentialId The ID of the credential to be revoked - */ - fun revokeCredential(credentialId: String) - - /** - * Provides a flow to listen for revoked credentials. - */ - fun observeRevokedCredentials(): Flow> -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/buildingblocks/Pollux.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/buildingblocks/Pollux.kt deleted file mode 100644 index e36ce789d..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/buildingblocks/Pollux.kt +++ /dev/null @@ -1,128 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.buildingblocks - -import anoncreds_wrapper.CredentialDefinition -import anoncreds_wrapper.CredentialOffer -import anoncreds_wrapper.CredentialRequest -import anoncreds_wrapper.CredentialRequestMetadata -import anoncreds_wrapper.LinkSecret -import anoncreds_wrapper.Presentation -import anoncreds_wrapper.Schema -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentDescriptor -import io.iohk.atala.prism.walletsdk.domain.models.Credential -import io.iohk.atala.prism.walletsdk.domain.models.CredentialType -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.StorableCredential -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PrivateKey -import io.iohk.atala.prism.walletsdk.pollux.models.AnonCredential -import io.iohk.atala.prism.walletsdk.prismagent.protocols.proofOfPresentation.RequestPresentation -import kotlinx.serialization.json.JsonObject - -/** - * The `Pollux` interface represents a set of operations for working with verifiable credentials. - */ -interface Pollux { - - /** - * Parses the given JSON data into a verifiable credential of the specified type. - * - * @param jsonData The JSON data representing the verifiable credential. - * @param type The type of the verifiable credential. - * @param linkSecret The optional link secret for the credential. - * @param credentialMetadata The metadata for the credential request. - * @return The parsed credential. - */ - suspend fun parseCredential( - jsonData: String, - type: CredentialType, - linkSecret: LinkSecret? = null, - credentialMetadata: CredentialRequestMetadata? - ): Credential - - /** - * Processes the JWT credential request and returns a string representation of the processed result. - * - * @param subjectDID The DID of the subject for whom the request is being processed. - * @param privateKey The private key used for signing the JWT. - * @param offerJson The JSON object representing the credential offer. - * @return The string representation of the processed result. - */ - fun processCredentialRequestJWT( - subjectDID: DID, - privateKey: PrivateKey, - offerJson: JsonObject - ): String - - /** - * Processes a credential request for anonymous credentials. - * - * @param did The DID of the subject requesting the credential. - * @param offer The credential offer. - * @param linkSecret The link secret for the credential. - * @param linkSecretName The name of the link secret. - * @return A pair containing the credential request and its metadata. - */ - suspend fun processCredentialRequestAnoncreds( - did: DID, - offer: CredentialOffer, - linkSecret: LinkSecret, - linkSecretName: String - ): Pair - - /** - * Creates a verifiable presentation JSON Web Token (JWT) for the given subjectDID, privateKey, credential, and requestPresentationJson. - * - * @param subjectDID The DID of the subject for whom the presentation is being created. - * @param privateKey The private key used to sign the JWT. - * @param credential The credential to be included in the presentation. - * @param requestPresentationJson The JSON object representing the request presentation. - * @return The created verifiable presentation JWT. - */ - fun createVerifiablePresentationJWT( - subjectDID: DID, - privateKey: PrivateKey, - credential: Credential, - requestPresentationJson: JsonObject - ): String - - suspend fun createVerifiablePresentationAnoncred( - request: RequestPresentation, - credential: AnonCredential, - linkSecret: LinkSecret - ): Presentation - - /** - * Restores a credential using the provided restoration identifier and credential data. - * - * @param restorationIdentifier The restoration identifier of the credential. - * @param credentialData The byte array containing the credential data. - * @return The restored credential. - */ - fun restoreCredential(restorationIdentifier: String, credentialData: ByteArray, revoked: Boolean): Credential - - /** - * Converts a [Credential] object to a [StorableCredential] object of the specified [CredentialType]. - * - * @param type The type of the [StorableCredential]. - * @param credential The [Credential] object to be converted. - * @return The converted [StorableCredential]. - */ - fun credentialToStorableCredential(type: CredentialType, credential: Credential): StorableCredential - - /** - * Extracts the credential format from the given array of attachment descriptors. - * - * @param formats The array of attachment descriptors. - * @return The credential format as a CredentialType enum value. - */ - fun extractCredentialFormatFromMessage(formats: Array): CredentialType - - /** - * Retrieves the credential definition for the specified ID. - * - * @param id The ID of the credential definition. - * @return The credential definition. - */ - suspend fun getCredentialDefinition(id: String): CredentialDefinition - - suspend fun getSchema(schemaId: String): Schema -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Api.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Api.kt deleted file mode 100644 index 7dbb1c56c..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Api.kt +++ /dev/null @@ -1,29 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import io.iohk.atala.prism.walletsdk.prismagent.shared.KeyValue -import io.ktor.client.HttpClient as KtorClient - -/** - * Interface that defines an API request - */ -interface Api { - var client: KtorClient - - /** - * Makes an HTTP request using the specified HTTP method, URL, URL parameters, HTTP headers, and request body. - * - * @param httpMethod the HTTP method to be used for the request (e.g., "GET", "POST", "PUT", "DELETE", etc.) - * @param url the URL to send the request to - * @param urlParameters the array of URL parameters to be included in the request (default is an empty array) - * @param httpHeaders the array of HTTP headers to be included in the request (default is an empty array) - * @param body the request body to be sent with the request (default is null) - * @return the HttpResponse object representing the response received from the server - */ - suspend fun request( - httpMethod: String, - url: String, - urlParameters: Array = emptyArray(), - httpHeaders: Array = emptyArray(), - body: Any? - ): HttpResponse -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/ApiImpl.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/ApiImpl.kt deleted file mode 100644 index e5e5e9912..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/ApiImpl.kt +++ /dev/null @@ -1,46 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import io.iohk.atala.prism.walletsdk.prismagent.shared.KeyValue -import io.iohk.atala.prism.walletsdk.prismagent.shared.PrismShared -import io.ktor.client.HttpClient -import io.ktor.client.request.request -import io.ktor.client.statement.bodyAsText -import io.ktor.http.HttpMethod -import io.ktor.http.Url - -/** - * Implementation of API interface for http requests. - */ -open class ApiImpl(override var client: HttpClient) : Api { - - /** - * Makes an HTTP request using the specified HTTP method, URL, URL parameters, HTTP headers, and request body. - * - * @param httpMethod the HTTP method to be used for the request (e.g., "GET", "POST", "PUT", "DELETE", etc.) - * @param url the URL to send the request to - * @param urlParameters the array of URL parameters to be included in the request (default is an empty array) - * @param httpHeaders the array of HTTP headers to be included in the request (default is an empty array) - * @param body the request body to be sent with the request (default is null) - * @return the HttpResponse object representing the response received from the server - */ - override suspend fun request( - httpMethod: String, - url: String, - urlParameters: Array, - httpHeaders: Array, - body: Any? - ): HttpResponse { - val request = PrismShared.getRequestBuilder( - httpMethod = HttpMethod(httpMethod), - url = Url(url), - urlParametersArray = urlParameters, - httpHeadersArray = httpHeaders, - body = body - ) - val response = client.request(request) - return HttpResponse( - status = response.status.value, - jsonString = response.bodyAsText() - ) - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Claim.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Claim.kt deleted file mode 100644 index e86b40760..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Claim.kt +++ /dev/null @@ -1,109 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import kotlinx.serialization.Serializable - -/** - * Represents a claim in a verifiable credential. - * - * @property key The key of the claim. - * @property value The value of the claim. - */ -@Serializable -class Claim( - val key: String, - val value: ClaimType -) - -/** - * A sealed class representing different types of claims. - */ -@Serializable -sealed class ClaimType : Comparable { - /** - * A data class representing a string value. - * - * @property value The string value. - */ - data class StringValue(val value: String) : ClaimType() - - /** - * Represents a boolean value as a claim type. - * - * @property value The boolean value. - */ - data class BoolValue(val value: Boolean) : ClaimType() - - /** - * Represents a data value with a byte array. - * - * @property value the byte array value of the data - * @constructor Creates a [DataValue] instance with the specified byte array value. - */ - data class DataValue(val value: ByteArray) : ClaimType() { - - /** - * Compares this [DataValue] object with the specified object for equality. Returns `true` if the objects are the same, - * have the same runtime class, and their values are equal. - * - * @param other the object to compare for equality - * @return `true` if the objects are the same, have the same runtime class, and their values are equal, `false` otherwise - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (javaClass != other?.javaClass) return false - - other as DataValue - - return value.contentEquals(other.value) - } - - /** - * Generates a hash code value for the [DataValue] object. - * - * The hash code value is calculated by invoking the [contentHashCode] method on the [value] property. - * - * @return the hash code value for the [DataValue] object - */ - override fun hashCode(): Int { - return value.contentHashCode() - } - } - - /** - * Represents a numeric value for a claim. - * - * @property value The numeric value. - * @constructor Creates a new NumberValue instance with the specified value. - */ - data class NumberValue(val value: Double) : ClaimType() - - /** - * Compares this [ClaimType] object with the specified [other] object for order. - * - * @param other the object to compare with - * @return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the - * specified object - * - * @throws IllegalArgumentException if [other] is not of the same type as this object - * @throws IllegalArgumentException if [this] and [other] are not comparable - */ - override fun compareTo(other: ClaimType): Int { - return when (this) { - is StringValue -> { - if (other is StringValue) { - value.compareTo(other.value) - } else { - throw IllegalArgumentException("Cannot compare different types") - } - } - is NumberValue -> { - if (other is NumberValue) { - value.compareTo(other.value) - } else { - throw IllegalArgumentException("Cannot compare different types") - } - } - else -> throw IllegalArgumentException("Cannot compare non-comparable types") - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Credential.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Credential.kt deleted file mode 100644 index 7667da3d7..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Credential.kt +++ /dev/null @@ -1,15 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -/** - * Represents a verifiable credential that contains information about an entity or identity. - * - * Implementing classes are expected to provide implementation for all properties and functions defined in this interface. - */ -interface Credential { - val id: String - val issuer: String - val subject: String? - val claims: Array - val properties: Map - var revoked: Boolean? -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/CredentialIssueOptions.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/CredentialIssueOptions.kt deleted file mode 100644 index 5c706eaed..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/CredentialIssueOptions.kt +++ /dev/null @@ -1,12 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -/** - * Represents the options for issuing credentials. - * - * @property type The type of verifiable credential to issue. - * @property linkSecret The optional link secret used for linking credentials to a specific issuer. - */ -data class CredentialIssueOptions( - val type: CredentialType, - val linkSecret: String? = null -) diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/DID.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/DID.kt deleted file mode 100644 index fc0193d23..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/DID.kt +++ /dev/null @@ -1,80 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import io.iohk.atala.prism.walletsdk.domain.DID -import io.iohk.atala.prism.walletsdk.domain.DID_SEPARATOR -import kotlinx.serialization.Serializable -import kotlin.jvm.JvmOverloads -import kotlin.jvm.JvmStatic - -/** - * A DID is a unique and persistent identifier for a subject or object, such as a person, organization, or device. - * It is created and managed using a specific DID method, and consists of a schema, method, and method ID. - * The schema indicates the type of DID (e.g. "did"), the method indicates the specific interface or process used to resolve - * and manage the DID (e.g. "prism"), and the method ID is a unique identifier within the DID method. - * As specified in the [W3C DID standards](https://www.w3.org/TR/did-core/#dfn-did-schemes). - */ -@Serializable -data class DID @JvmOverloads constructor( - val schema: String = DID, - val method: String, - val methodId: String -) { - /** - * Constructor overload for creating a [DID] object based on a [String]. - * - * @param string The input [String] from which the [DID] object will be created. - * The [String] should have the format "schema:method:methodId". - */ - constructor( - string: String - ) : this(getSchemaFromString(string), getMethodFromString(string), getMethodIdFromString(string)) - - /** - * Returns a string representation of the DID object. - * - * @return The string representation of the DID in the format "schema:method:methodId". - */ - override fun toString(): String { - return "$schema:$method:$methodId" - } - - companion object { - /** - * Extracts the schema from the given string representation of a DID. - * - * @param string The input string in the format "schema:method:methodId". - * @return The extracted schema from the input string. - */ - @JvmStatic - fun getSchemaFromString(string: String): String { - val split = string.split(DID_SEPARATOR) - return split[0] - } - - /** - * Retrieves the method component from a given string representation of a DID. - * - * @param string The input string in the format "schema:method:methodId". - * @return The extracted method component from the input string. - */ - @JvmStatic - fun getMethodFromString(string: String): String { - val split = string.split(DID_SEPARATOR) - return split[1] - } - - /** - * Retrieves the methodId component from a given string representation of a DID. - * - * @param string The input string in the format "schema:method:methodId". - * @return The extracted methodId component from the input string. - */ - @JvmStatic - fun getMethodIdFromString(string: String): String { - val split = string.split(DID_SEPARATOR).toMutableList() - split.removeFirst() - split.removeFirst() - return split.joinToString(DID_SEPARATOR) - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/DIDDocument.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/DIDDocument.kt deleted file mode 100644 index a6807d137..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/DIDDocument.kt +++ /dev/null @@ -1,545 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import kotlinx.serialization.Serializable - -/** - * Represents a Core Property in a DID Document. - * This allows for extensibility of the properties. - * As specified in [w3 standards](https://www.w3.org/TR/did-core/#data-model) - **/ -interface DIDDocumentCoreProperty - -/** - * Represents a DIDDocument with [DID] and [DIDDocumentCoreProperty] - * As specified in [w3 standards](https://www.w3.org/TR/did-core/#data-model) - * A DID Document consists of a DID, public keys, authentication protocols, service endpoints, and other metadata. - * It is used to verify the authenticity and identity of the DID, and to discover and interact with the associated - * subjects or objects. - */ -@Serializable -data class DIDDocument( - val id: DID, - val coreProperties: Array -) { - - val services: Array - get() = coreProperties.fold(arrayOf()) { acc, property -> - if (property is DIDDocument.Services) acc.plus(property.values) else acc - } - - /** - * Overrides the equals method to compare two instances of DIDDocument. - * - * @param other The object to compare with. - * @return true if the objects are equal, false otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as DIDDocument - - if (id != other.id) return false - if (!coreProperties.contentEquals(other.coreProperties)) return false - - return true - } - - /** - * Calculates the hash code for the DIDDocument object. - * - * The hash code is calculated based on the id field and the content hash code of the coreProperties array. - * - * @return The hash code of the DIDDocument object. - */ - override fun hashCode(): Int { - var result = id.hashCode() - result = 31 * result + coreProperties.contentHashCode() - return result - } - - /** - * Represents a Verification Method, which is a public key or other evidence used to authenticate the identity of a - * Decentralized Identifier (DID) or other subject or object. - * A Verification Method consists of a type (indicating the type of key or evidence), a public key or other data, and - * optional metadata such as a controller (the DID that controls the verification method) and purpose (the intended - * use of the verification method). It is typically included in a DID Document or other authentication credential. - **/ - data class VerificationMethod @JvmOverloads constructor( - val id: DIDUrl, - val controller: DID, - val type: String, - val publicKeyJwk: Map? = null, - val publicKeyMultibase: String? = null - ) { - companion object { - /** - * Returns the Curve value based on the given type. - * - * @param type The type of the curve. - * @return The Curve object corresponding to the given type. - * @throws CastorError.InvalidKeyError if the given type is not supported. - */ - @JvmStatic - fun getCurveByType(type: String): Curve { - return when (type) { - Curve.X25519.value -> { - Curve.X25519 - } - - Curve.ED25519.value -> { - Curve.ED25519 - } - - Curve.SECP256K1.value -> { - Curve.SECP256K1 - } - - else -> { - throw CastorError.InvalidKeyError() - } - } - } - } - } - - /** - * Represents a Service, which is a capability or endpoint offered by a Decentralized Identifier (DID) or other subject or object. - * A Service consists of an ID, type, and service endpoint, as well as optional metadata such as a priority and a description. - * It is typically included in a DID Document and can be used to discover and interact with the associated DID or subject or object. - */ - @Serializable - data class Service( - val id: String, - val type: Array, - val serviceEndpoint: ServiceEndpoint - ) : DIDDocumentCoreProperty { - /** - * Determines whether the current object is equal to another object. - * - * @param other The object to compare with the current object. - * @return true if the current object is equal to the other object, otherwise false. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as Service - - if (id != other.id) return false - if (!type.contentEquals(other.type)) return false - if (serviceEndpoint != other.serviceEndpoint) return false - - return true - } - - /** - * Calculates the hash code for the Service object. - * The hash code is calculated based on the id, type, and serviceEndpoint properties. - * - * @return The hash code of the Service object. - */ - override fun hashCode(): Int { - var result = id.hashCode() - result = 31 * result + (type.contentHashCode()) - result = 31 * result + serviceEndpoint.hashCode() - return result - } - } - - /** - * Represents a service endpoint, which is a URI and other information that indicates how to access the service. - */ - @Serializable - data class ServiceEndpoint @JvmOverloads constructor( - val uri: String, - val accept: Array? = arrayOf(), - val routingKeys: Array? = arrayOf() - ) { - /** - * Determines whether the current object is equal to another object. - * - * @param other The object to compare with the current object. - * @return true if the current object is equal to the other object, otherwise false. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as ServiceEndpoint - - if (uri != other.uri) return false - if (accept != null) { - if (other.accept == null) return false - if (!accept.contentEquals(other.accept)) return false - } else if (other.accept != null) return false - if (routingKeys != null) { - if (other.routingKeys == null) return false - if (!routingKeys.contentEquals(other.routingKeys)) return false - } else if (other.routingKeys != null) return false - - return true - } - - /** - * Calculates the hash code for the ServiceEndpoint object. - * The hash code is calculated based on the uri, accept, and routingKeys properties. - * - * @return The hash code of the ServiceEndpoint object. - */ - override fun hashCode(): Int { - var result = uri.hashCode() - result = 31 * result + (accept?.contentHashCode() ?: 0) - result = 31 * result + (routingKeys?.contentHashCode() ?: 0) - return result - } - } - - /** - * Represents a "also known as" property, which is a list of alternative names or identifiers for a - * Decentralized Identifier (DID) or other subject or object. - * The "also known as" property is typically included in a DID Document and can be used to associate the DID or - * subject or object with other names or identifiers. - */ - data class AlsoKnownAs( - val values: Array - ) : DIDDocumentCoreProperty { - /** - * Checks if the current object is equal to the given object. - * - * The current object is considered equal to the given object if and only if: - * - They refer to the same instance - * - The given object is not null and belongs to the same class as the current object - * - The values of the `values` property of both objects are equal - * - * @param other The object to compare with the current object - * - * @return `true` if the objects are equal, `false` otherwise - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as AlsoKnownAs - - return values.contentEquals(other.values) - } - - /** - * Generates the hash code value for the current object. - * The hash code is computed based on the values of the `values` property. - * - * @return The hash code value for the object - */ - override fun hashCode(): Int { - return values.contentHashCode() - } - } - - /** - * Represents a "controller" property, which is a list of Decentralized Identifiers (DIDs) that control the associated - * DID or subject or object. - * The "controller" property is typically included in a DID Document and can be used to indicate who has the authority - * to update or deactivate the DID or subject or object. - */ - data class Controller(val values: Array) : DIDDocumentCoreProperty { - /** - * Compares this Controller object with the specified object for equality. - * - * @param other The object to compare for equality. - * @return true if the given object is equal to this Controller object, false otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as Controller - - return values.contentEquals(other.values) - } - - /** - * Calculates the hash code for the Controller object. - * - * @return The hash code value for the Controller object. - */ - override fun hashCode(): Int { - return values.contentHashCode() - } - } - - /** - * Represents a "verification methods" property, which is a list of Verification Methods associated with a - * Decentralized Identifier (DID) or other subject or object. - * The "verification methods" property is typically included in a DID Document and can be used to authenticate the - * identity of the DID or subject or object. - */ - data class VerificationMethods(val values: Array) : DIDDocumentCoreProperty { - /** - * Compares this `VerificationMethods` object with the specified object for equality. - * - * The comparison is based on the `values` property of the `VerificationMethods` object. If the specified object is - * `null`, or is not an instance of `VerificationMethods`, or the `values` arrays are not equal, then the method - * returns `false`. Otherwise, it returns `true`. - * - * @param other The object to compare for equality. - * @return `true` if this `VerificationMethods` object is equal to the specified object, `false` otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as VerificationMethods - - return values.contentEquals(other.values) - } - - /** - * Calculates the hash code for the VerificationMethods object. - * - * This method calculates the hash code based on the content of the values array in the VerificationMethods object. - * If two VerificationMethods objects have the same values array, their hash codes will be equal. - * - * @return The hash code for the VerificationMethods object. - */ - override fun hashCode(): Int { - return values.contentHashCode() - } - } - - /** - * Represents a "services" property, which is a list of Services associated with a Decentralized Identifier (DID) - * or other subject or object. - * The "services" property is typically included in a DID Document and can be used to discover and interact with the - * associated DID or subject or object. - */ - data class Services(val values: Array) : DIDDocumentCoreProperty { - /** - * Determines whether the current object is equal to another object. - * - * @param other The object to compare with the current object. - * @return true if the current object is equal to the other object, otherwise false. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as Services - - return values.contentEquals(other.values) - } - - /** - * Calculates the hash code for the Services object. - * The hash code is calculated based on the content of the values array property. - * - * @return The hash code of the Services object. - */ - override fun hashCode(): Int { - return values.contentHashCode() - } - } - - /** - * Represents an "authentication" property, which is a list of URIs and Verification Methods that can be used to - * authenticate the associated DID or subject or object. - * The "authentication" property is typically included in a DID Document and can be used to verify the - * identity of the DID or subject or object. - */ - data class Authentication( - val urls: Array, - val verificationMethods: Array - ) : DIDDocumentCoreProperty { - /** - * Checks if the current instance of [Authentication] is equal to the provided [other] object. - * - * @param other The object to compare with. - * @return `true` if the objects are equal, `false` otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as Authentication - - if (!urls.contentEquals(other.urls)) return false - if (!verificationMethods.contentEquals(other.verificationMethods)) return false - - return true - } - - /** - * - */ - override fun hashCode(): Int { - var result = urls.contentHashCode() - result = 31 * result + verificationMethods.contentHashCode() - return result - } - } - - /** - * Represents an "assertion method" property, which is a list of URIs and Verification Methods that can be used to - * assert the authenticity of a message or credential associated with a DID or other subject or object. - * The "assertion method" property is typically included in a DID Document and can be used to verify the - * authenticity of messages or credentials related to the DID or subject or object. - */ - data class AssertionMethod( - val urls: Array, - val verificationMethods: Array - ) : DIDDocumentCoreProperty { - /** - * Checks if the current AssertionMethod object is equal to the provided object. - * - * @param other The object to compare with the current AssertionMethod. - * @return true if the objects are equal, false otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as AssertionMethod - - if (!urls.contentEquals(other.urls)) return false - if (!verificationMethods.contentEquals(other.verificationMethods)) return false - - return true - } - - /** - * Calculates the hash code for the AssertionMethod object. - * - * @return The hash code value for the AssertionMethod object. - */ - override fun hashCode(): Int { - var result = urls.contentHashCode() - result = 31 * result + verificationMethods.contentHashCode() - return result - } - } - - /** - * Represents a "key agreement" property, which is a list of URIs and Verification Methods that can be used to establish a - * secure communication channel with a DID or other subject or object. - * The "key agreement" property is typically included in a DID Document and can be used to establish a secure - * communication channel with the DID or subject or object. - */ - data class KeyAgreement( - val urls: Array, - val verificationMethods: Array - ) : DIDDocumentCoreProperty { - /** - * Checks whether the current instance is equal to the given object. - * - * @param other The object to compare with the current instance. - * @return Returns true if the current instance is equal to the given object, false otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as KeyAgreement - - if (!urls.contentEquals(other.urls)) return false - if (!verificationMethods.contentEquals(other.verificationMethods)) return false - - return true - } - - /** - * Calculates the hash code for the `KeyAgreement` instance. - * - * @return The hash code value calculated based on the `urls` and `verificationMethods` properties. - */ - override fun hashCode(): Int { - var result = urls.contentHashCode() - result = 31 * result + verificationMethods.contentHashCode() - return result - } - } - - /** - * Represents a "capability invocation" property, which is a list of URIs and Verification Methods that can - * be used to invoke a specific capability or service provided by a DID or other subject or object. - * The "capability invocation" property is typically included in a DID Document and can be used to invoke a - * specific capability or service provided by the DID or subject or object. - */ - data class CapabilityInvocation( - val urls: Array, - val verificationMethods: Array - ) : DIDDocumentCoreProperty { - /** - * Compares this object with the specified object for equality. - * Returns true if the specified object is also a [CapabilityInvocation] and has the same values for the `urls` and `verificationMethods` properties. - * - * @param other The object to compare for equality. - * @return True if the objects are equal, false otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as CapabilityInvocation - - if (!urls.contentEquals(other.urls)) return false - if (!verificationMethods.contentEquals(other.verificationMethods)) return false - - return true - } - - /** - * Calculates the hash code for a CapabilityInvocation object. - * - * @return The calculated hash code. - */ - override fun hashCode(): Int { - var result = urls.contentHashCode() - result = 31 * result + verificationMethods.contentHashCode() - return result - } - } - - /** - * Represents a "capability delegation" property, which is a list of URIs and Verification Methods that can be used - * to delegate a specific capability or service provided by a DID or other subject or object to another subject or object. - * The "capability delegation" property is typically included in a DID Document and can be used to delegate a - * specific capability or service provided by the DID or subject or object. - */ - data class CapabilityDelegation( - val urls: Array, - val verificationMethods: Array - ) : DIDDocumentCoreProperty { - /** - * Determines whether the current `CapabilityDelegation` object is equal to the provided object. - * - * @param other The object to compare with the current `CapabilityDelegation` object. - * @return `true` if the objects are equal, `false` otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as CapabilityDelegation - - if (!urls.contentEquals(other.urls)) return false - if (!verificationMethods.contentEquals(other.verificationMethods)) return false - - return true - } - - /** - * Calculates the hash code value for the `CapabilityDelegation` object. - * - * The hash code is calculated based on the `urls` and `verificationMethods` properties of the `CapabilityDelegation`. - * Both properties are used to calculate the hash code by invoking the `contentHashCode()` method on the corresponding arrays. - * The resulting hash codes are combined using the formula: `result = 31 * result + secondHashCode`. - * - * @return The hash code value for the `CapabilityDelegation` object. - */ - override fun hashCode(): Int { - var result = urls.contentHashCode() - result = 31 * result + verificationMethods.contentHashCode() - return result - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/DIDPair.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/DIDPair.kt deleted file mode 100644 index c3bb8d991..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/DIDPair.kt +++ /dev/null @@ -1,13 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import kotlinx.serialization.Serializable - -/** - * Represents a pair of DIDs, typically used for secure communication or delegation of capabilities or services. - */ -@Serializable -data class DIDPair( - val host: DID, - val receiver: DID, - val name: String? -) diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/DIDResolver.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/DIDResolver.kt deleted file mode 100644 index 2db92f0fe..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/DIDResolver.kt +++ /dev/null @@ -1,10 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -/** - * The [DIDResolver] protocol defines the interface for resolving DID document using a specific DID method. - * Implementations of this interface provide a [resolve] method that can be used to retrieve the DID document for a given DID. - */ -interface DIDResolver { - val method: String - suspend fun resolve(didString: String): DIDDocument -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/DIDUrl.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/DIDUrl.kt deleted file mode 100644 index ab9f88e19..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/DIDUrl.kt +++ /dev/null @@ -1,98 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import io.iohk.atala.prism.walletsdk.domain.DID_URL_SEPARATOR -import kotlin.jvm.JvmOverloads - -/** - * Represents a DIDUrl with "did", "path", "parameters", "fragment" - * As specified in [w3 standards](https://www.w3.org/TR/did-core/#dfn-did-urls) - */ -data class DIDUrl @JvmOverloads constructor( - val did: DID, - val path: Array? = arrayOf(), - val parameters: Map? = mapOf(), - val fragment: String? = null -) { - - /** - * Returns a string representation of the DID URL. - * - * @return The string representation of the DID URL. - */ - fun string(): String { - return "${did}${fragmentString()}" - } - - /** - * Returns the path portion of a DID URL as a string. - * If the path is null, an empty string is returned. - * - * @return The path portion of a DID URL. - */ - fun pathString(): String { - return "/${path?.joinToString(DID_URL_SEPARATOR)}" - } - - /** - * Generates a query string based on the provided parameters. - * - * @return The query string in the format "?key1=value1&key2=value2&..." - */ - fun queryString(): String { - return "?${parameters?.map { "${it.key}=${it.value}" }?.joinToString("&")}" - } - - /** - * Returns the fragment portion of a DID URL as a string. - * - * @return The fragment portion of a DID URL. - */ - fun fragmentString(): String { - return "#$fragment" - } - - /** - * Checks if the current [DIDUrl] instance is equal to the specified [other] object. - * - * @param other The object to compare with the current [DIDUrl]. - * @return `true` if the objects are equal, `false` otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as DIDUrl - - if (did != other.did) return false - if (path != null) { - if (other.path == null) return false - if (!path.contentEquals(other.path)) return false - } else if (other.path != null) return false - if (parameters != other.parameters) return false - if (fragment != other.fragment) return false - - return true - } - - /** - * Calculates the hash code for the current [DIDUrl] instance. - * - * @return The hash code value for the [DIDUrl] object. - */ - override fun hashCode(): Int { - var result = did.hashCode() - result = 31 * result + (path?.contentHashCode() ?: 0) - result = 31 * result + (parameters?.hashCode() ?: 0) - result = 31 * result + (fragment?.hashCode() ?: 0) - return result - } - - /** - * Returns a string representation of the current [DIDUrl] instance. - * - * @return The string representation of the DID URL. - */ - override fun toString(): String { - return string() - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Errors.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Errors.kt deleted file mode 100644 index 0b7f77340..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Errors.kt +++ /dev/null @@ -1,762 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.KeyTypes - -/** - * An interface that represents a base error in the Prism SDK. - */ -abstract interface Error { - val code: Int? - val underlyingErrors: Array? - val errorDescription: String? -} - -/** - * A class representing an unknown error in a PRISM. - * - * @see Error - * @see Throwable - */ -abstract class UnknownPrismError -@JvmOverloads -constructor( - message: String? = null, - cause: Throwable? = null -) : Error, Throwable(message, cause) { - override val code: Int? - get() = null - - override val underlyingErrors: Array? - get() = emptyArray() - - override val errorDescription: String? - get() = null -} - -/** - * A class representing a known error in a PRISM. - * - * @see Error - * @see Throwable - */ -abstract class KnownPrismError -@JvmOverloads -constructor( - message: String? = null, - cause: Throwable? = null -) : Error, Throwable(message, cause) { - override val code: Int? - get() = null - - override val underlyingErrors: Array? - get() = emptyArray() - - override val errorDescription: String? - get() = null -} - -/** - * A class representing an unknown error if the error received does not conform to the [KnownPrismError], it will be - * classified as an [UnknownPrismError]. - * - * @see UnknownPrismError - */ -abstract class UnknownError -@JvmOverloads -constructor( - message: String? = null, - cause: Throwable? = null -) : UnknownPrismError(message, cause) { - - /** - * A class representing an error that occurs when something goes wrong in the SDK. - * - * @param message The error message. - * @param cause The underlying cause of the error. - * - * @see UnknownError - */ - class SomethingWentWrongError - @JvmOverloads - constructor( - message: String? = null, - cause: Throwable? = null - ) : UnknownError(message, cause) { - override val code: Int - get() = -1 - } -} - -/** - * A class representing a common error in a PRISM. - * - * @see KnownPrismError - */ -sealed class CommonError -@JvmOverloads -constructor( - message: String? = null, - cause: Throwable? = null -) : KnownPrismError(message, cause) { - - /** - * A class representing an error that occurs when an invalid URL is encountered while trying to send a message. - * - * @param url The invalid URL that caused the error. - * - * @see CommonError - */ - class InvalidURLError(url: String) : CommonError("Invalid url while trying to send message: $url") { - override val code: Int - get() = -2 - } - - /** - * Represents an HTTP error encountered during an API request. - * - * @param code The HTTP status code of the error. - * @param message The error message. - * - * @see CommonError - */ - class HttpError - @JvmOverloads - constructor( - override val code: Int, - message: String? = null - ) : CommonError("HTTP Request Error $code: $message") { - override val errorDescription: String - get() = "Code $code: $message" - } -} - -/** - * A class representing a known error in an Apollo. - * - * @see KnownPrismError - */ -sealed class ApolloError -@JvmOverloads -constructor( - message: String? = null, - cause: Throwable? = null -) : KnownPrismError(message, cause) { - - /** - * An implementation of the [ApolloError] class that represents an error caused by invalid mnemonic words. - * This error occurs when one or more mnemonic words are invalid in a PRISM API response. - * - * @param invalidWords The array of invalid mnemonic words. - * @property message The error message for this error, which is determined based on the presence of invalid words. - * If `invalidWords` is not null, the message will be "The following mnemonic words are invalid: [invalidWords]". - * If `invalidWords` is null, the message will be "The seed cannot be null". - * - * @see ApolloError - */ - class InvalidMnemonicWord - @JvmOverloads - constructor( - invalidWords: Array? = null - ) : ApolloError( - if (invalidWords.isNullOrEmpty()) { - "The following mnemonic words are invalid: $invalidWords" - } else { - "The seed cannot be null" - } - ) { - override val code: Int - get() = 11 - } - - /** - * Class representing an error when the message string cannot be parsed to UTF8 data. - * - * @property code The error code for CouldNotParseMessageString, which is 12. - * - * @see ApolloError - */ - class CouldNotParseMessageString : ApolloError("Could not get UTF8 Data from message string") { - override val code: Int - get() = 12 - } - - /** - * A class representing an invalid JSON Web Key (JWK) error in the PRISM SDK. - * - * This error indicates that the JWK provided is not in a valid format. - * - * @property code The error - * - * @see ApolloError - */ - class InvalidJWKError : ApolloError("JWK is not in a valid format") { - override val code: Int - get() = 13 - } - - /** - * Represents an error that occurs when an invalid key curve is provided. - * - * @param invalidCurve The invalid key curve that was provided. - * - * @see ApolloError - */ - class InvalidKeyCurve( - invalidCurve: String - ) : ApolloError( - message = "Invalid key curve $invalidCurve. Valid options are: ${Curve.entries.map { it.value }.toTypedArray().joinToString(", ")}" - ) { - override val code: Int - get() = 14 - } - - /** - * Represents an error indicating that a specific key curve is invalid. - * - * @param invalidCurve The invalid key curve. - * @param validCurves An array of valid key curves. - * - * @see ApolloError - */ - class InvalidSpecificKeyCurve( - invalidCurve: String, - validCurves: Array - ) : ApolloError( - "Invalid key curve $invalidCurve. Valid options are: ${validCurves.joinToString(", ")}" - ) { - override val code: Int - get() = 14 - } - - /** - * Represents an error that occurs when an invalid key type is used. - * - * @param invalidType The invalid key type. - * - * @see ApolloError - */ - class InvalidKeyType( - invalidType: String - ) : ApolloError( - message = "Invalid key type $invalidType. Valid options are: ${KeyTypes.values().map { it.type }.toTypedArray().joinToString(", ")}" - ) { - override val code: Int - get() = 15 - } - - /** - * Represents an error that occurs when an invalid index is provided. - * - * @param message The error message associated with the exception. - * - * @see ApolloError - */ - class InvalidIndex(message: String) : ApolloError(message) { - override val code: Int - get() = 16 - } - - /** - * A class representing an invalid derivation path error. - * - * @property message The error message. - * - * @see ApolloError - */ - class InvalidDerivationPath(message: String) : ApolloError(message) { - override val code: Int - get() = 17 - } - - /** - * A class representing an error that occurs when an invalid seed is used. - * - * @param message The error message. - * - * @see ApolloError - */ - class InvalidSeed(message: String) : ApolloError(message) { - override val code: Int - get() = 18 - } - - /** - * Represents an error that occurs due to invalid raw data. - * - * @param message A detailed error message. - * - * @see ApolloError - */ - class InvalidRawData(message: String) : ApolloError(message) { - override val code: Int - get() = 19 - } - - /** - * Represents an error that occurs when restoration fails due to no identifier or invalid identifier. - * - * @see ApolloError - */ - class RestorationFailedNoIdentifierOrInvalid : ApolloError("Restoration failed: no identifier or invalid") { - override val code: Int - get() = 20 - } -} - -/** - * A class representing a known error in a Castor. - * - * @see KnownPrismError - */ -sealed class CastorError -@JvmOverloads -constructor( - message: String? = null, - cause: Throwable? = null -) : KnownPrismError(message, cause) { - - /** - * An error that indicates that the given key curve is not supported for a specific functionality. - * - * @param curve The unsupported key curve. - * - * @see CastorError - */ - class KeyCurveNotSupported(curve: String) : CastorError( - "Key curve $curve is not supported for this functionality" - ) { - override val code: Int - get() = 21 - } - - /** - * Represents an error that occurs when the long form PRISM DID is invalid or changed. - * - * @property code The error code associated with the InvalidLongFormDID error. - * - * @see CastorError - */ - class InvalidLongFormDID : CastorError("Long form prism DID is invalid or changed") { - override val code: Int - get() = 22 - } - - /** - * Represents an error that occurs when the provided method ID does not satisfy a given regex pattern. - * - * @param regex The regex pattern that the method ID should satisfy. - * - * @see CastorError - */ - class MethodIdIsDoesNotSatisfyRegex(regex: String) : CastorError( - "The Prism DID provided is not passing the regex validation: $regex" - ) { - override val code: Int - get() = 23 - } - - /** - * Represents an error that occurs when there is an invalid encoding or decoding - * of a public key. - * - * @param didMethod The DID method being used when the error occurred. - * @param curve The curve of the key when the error occurred. - * - * @see CastorError - */ - class InvalidPublicKeyEncoding( - didMethod: String, - curve: String - ) : CastorError("Invalid encoding/decoding of key $curve while trying to compute $didMethod") { - override val code: Int - get() = 24 - } - - /** - * Represents an error that occurs when trying to parse an invalid DID string. - * - * @param did The invalid DID string. - * - * @see CastorError - */ - class InvalidDIDString(did: String) : CastorError("Trying to parse invalid DID String: $did") { - override val code: Int - get() = 25 - } - - /** - * Represents an error that occurs when the initial state of a PRISM DID changes, - * making it invalid. - * - * @see CastorError - */ - class InitialStateOfDIDChanged(message: String? = null) : CastorError( - "While trying to resolve Prism DID state changed making it invalid. $message" - ) { - override val code: Int - get() = 26 - } - - /** - * Represents an error that occurs when it is not possible to resolve a Decentralized Identifier (DID) due to a specific reason. - * - * @param did The DID that could not be resolved. - * @param reason The reason why the DID could not be resolved. - * - * @see CastorError - */ - class NotPossibleToResolveDID(did: String, reason: String, cause: Throwable? = null) : - CastorError("Not possible to resolve DID $did due to $reason", cause) { - override val code: Int - get() = 27 - } - - /** - * Represents an error that occurs when the JWK (JSON Web Key) keys are not in a valid format. - * - * @property code The error code associated with the `InvalidJWKKeysError`. - * - * @see CastorError - */ - class InvalidJWKKeysError : CastorError("JWK is not in a valid format") { - override val code: Int - get() = 28 - } - - /** - * Represents an error that occurs when an invalid key is encountered. - * - * @see CastorError - */ - class InvalidKeyError @JvmOverloads constructor(message: String? = null) : CastorError(message) - - /** - * An error that occurs when the provided PeerDID is invalid. - * - * @see CastorError - */ - class InvalidPeerDIDError @JvmOverloads constructor(message: String? = null, cause: Throwable? = null) : - CastorError(message, cause) - - /** - * Class representing an error thrown when no resolvers are available to resolve a given DID method. - * - * @param method The method that couldn't be resolved. - * - * @see CastorError - */ - class NoResolversAvailableForDIDMethod(method: String) : CastorError( - "No resolvers in castor are able to resolve the method $method, please provide a resolver" - ) { - override val code: Int - get() = 29 - } -} - -/** - * A class representing a known error in a Mercury. - * - * @see KnownPrismError - */ -sealed class MercuryError -@JvmOverloads -constructor( - message: String? = null, - cause: Throwable? = null -) : KnownPrismError(message, cause) { - - /** - * Error class representing a message that has no recipient set. - * To send a message, please set the "to" field. - * - * @see MercuryError - */ - class NoDIDReceiverSetError : - MercuryError("Message has no recipient set, to send a message please set the \"to\"") { - override val code: Int - get() = 31 - } - - /** - * An error class that indicates that no valid service is found for a given DID. - * - * @constructor Creates an instance of NoValidServiceFoundError. - * @param did The DID that has no valid services - * - * @see MercuryError - */ - class NoValidServiceFoundError - @JvmOverloads - constructor( - did: String? = null - ) : MercuryError(did?.let { "The did ($did) has no valid services" } ?: "No valid services") { - override val code: Int - get() = 32 - } - - /** - * Represents an error that occurs when a message does not have a sender set. - * - * @see MercuryError - */ - class NoDIDSenderSetError : MercuryError( - "Message has no sender set, to send a message please set the \"from\"" - ) { - override val code: Int - get() = 33 - } - - /** - * Represents an error that occurs when an unknown AttachmentData type is found while decoding a message. - * - * @see MercuryError - */ - class UnknownAttachmentDataError : MercuryError( - "Unknown AttachmentData type was found while decoding message" - ) { - override val code: Int - get() = 34 - } - - /** - * Represents an error that occurs when decoding a message and a message attachment is found without an "id". - * - * @see MercuryError - */ - class MessageAttachmentWithoutIDError : MercuryError( - "While decoding a message, a message attachment was found without \"id\" this is invalid" - ) { - override val code: Int - get() = 35 - } - - /** - * A class representing an error that occurs when decoding a message with an invalid body. - * - * @see MercuryError - */ - class MessageInvalidBodyDataError : MercuryError( - "While decoding a message, a body was found to be invalid while decoding" - ) { - override val code: Int - get() = 36 - } - - /** - * A class representing a DIDComm error in the PRISM SDK. - * - * @param customMessage The custom message associated with the error. Defaults to null. - * @param customUnderlyingErrors The array of underlying errors associated with the error. - * - * @see MercuryError - */ - class DidCommError - @JvmOverloads - constructor( - customMessage: String? = null, - customUnderlyingErrors: Array - ) : MercuryError( - message = "DIDComm error has occurred with message: $customMessage\nErrors: ${ - customUnderlyingErrors.joinToString( - separator = "\n" - ) { it.errorDescription ?: "" } - }" - ) { - override val code: Int - get() = 37 - } -} - -/** - * A class representing a known error in a Pluto. - * - * @see KnownPrismError - */ -sealed class PlutoError -@JvmOverloads -constructor( - message: String? = null, - cause: Throwable? = null -) : KnownPrismError(message, cause) { - - /** - * Represents an error that occurs when data is not persisted for a specific type while adding or making changes to another object. - * - * @param type The type of data that is not persisted. - * @param affecting The object to which the data is being added or modified. - * - * @see PlutoError - */ - class MissingDataPersistence(type: String, affecting: String) : - PlutoError("$type is not persisted while trying to add or make changes to $affecting") { - override val code: Int - get() = 41 - } - - /** - * Represents a specific error that occurs when required fields are missing. - * - * @param type The type that requires the fields. - * @param fields The array of missing fields. - * - * @see PlutoError - */ - class MissingRequiredFields(type: String, fields: Array) : - PlutoError("$type requires the following fields: ${fields.joinToString(", ")}") { - - override val code: Int - get() = 42 - } - - /** - * Represents a duplication error when trying to save an object with an existing ID. - * - * @param type The type of object that is being duplicated. - * - * @see PlutoError - */ - class Duplication(type: String) : PlutoError("Trying to save $type with an ID that already exists") { - override val code: Int - get() = 43 - } - - /** - * A class representing an unknown credential type error in the Pluto SDK. - * - * @see PlutoError - */ - class UnknownCredentialTypeError : PlutoError("The credential type needs to be JWT or W3C") { - override val code: Int - get() = 44 - } - - /** - * Represents an error that occurs when the credential JSON cannot be decoded. - * - * @see PlutoError - */ - class InvalidCredentialJsonError : PlutoError("Could not decode the credential JSON") { - override val code: Int - get() = 45 - } - - /** - * An error class representing a database connection error. - * - * @see PlutoError - */ - class DatabaseConnectionError(message: String? = "Database connection error") : PlutoError(message) { - override val code: Int - get() = 46 - } - - /** - * Custom error class that represents an error when a context is required to be initialized in Pluto. - * - * @see PlutoError - */ - class DatabaseContextError : PlutoError("Pluto requires a context to be initialized") { - override val code: Int - get() = 47 - } - - /** - * Class representing an error that occurs when the database service is already running. - * - * @see PlutoError - */ - class DatabaseServiceAlreadyRunning : PlutoError("Database service already running.") { - override val code: Int - get() = 48 - } - - /** - * Represents an error that occurs when an invalid restoration identifier is encountered. - * - * @see PlutoError - */ - class InvalidRestorationIdentifier : PlutoError("Invalid restoration identifier") { - override val code: Int - get() = 49 - } -} - -/** - * A class representing a known error in a Pollux. - * - * @see KnownPrismError - */ -sealed class PolluxError -@JvmOverloads -constructor( - message: String? = null, - cause: Throwable? = null -) : KnownPrismError(message, cause) { - - /** - * Represents an error that occurs when attempting to create a JWT presentation without providing a PRISM DID. - * - * @see PolluxError - */ - class InvalidPrismDID(message: String? = "To create a JWT presentation a Prism DID is required") : - PolluxError(message) { - override val code: Int - get() = 53 - } - - /** - * Represents an error encountered when invalid credentials are provided. - * - * @see PolluxError - */ - class InvalidCredentialError - @JvmOverloads - constructor( - cause: Throwable? = null - ) : PolluxError("Invalid credential, could not decode", cause) { - override val code: Int - get() = 51 - } - - /** - * Represents an error that occurs when an invalid JWT string is encountered while decoding a credential. - * - * @see PolluxError - */ - class InvalidJWTString : PolluxError("Invalid JWT while decoding credential") { - override val code: Int - get() = 52 - } - - /** - * A class representing an error when creating a JSON Web Token (JWT) presentation with an invalid JWTCredential. - * - * This error occurs when the provided JWTCredential is not valid or is missing required information. - * - * @see PolluxError - */ - class InvalidJWTCredential : PolluxError("To create a JWT presentation please provide a valid JWTCredential") { - override val code: Int - get() = 54 - } - - /** - * A class representing an error when no domain or challenge is found as part of the offer JSON. - * - * @see PolluxError - */ - class NoDomainOrChallengeFound : PolluxError("No domain or challenge found as part of the offer json") { - override val code: Int - get() = 55 - } - - /** - * Represents an error that occurs when there is an invalid credential definition. - * - * @see PolluxError - */ - class InvalidCredentialDefinitionError : PolluxError("Invalid credential definition") { - override val code: Int - get() = 56 - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/HttpClient.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/HttpClient.kt deleted file mode 100644 index 1919c0d95..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/HttpClient.kt +++ /dev/null @@ -1,12 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import io.ktor.client.HttpClient -import io.ktor.client.HttpClientConfig - -/** - * Creates a new instance of HttpClient with the given configuration. - * - * @param config The configuration block for HttpClient. If not provided, default configuration will be used. - * @return A new instance of HttpClient. - */ -expect fun httpClient(config: HttpClientConfig<*>.() -> Unit = {}): HttpClient diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/HttpResponse.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/HttpResponse.kt deleted file mode 100644 index 5a0048584..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/HttpResponse.kt +++ /dev/null @@ -1,12 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import kotlinx.serialization.Serializable - -/** - * Represents an HTTP response. - * - * @param status The status code of the response. - * @param jsonString The JSON string representing the response body. - */ -@Serializable -data class HttpResponse(val status: Int, val jsonString: JsonString) diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/JWTPayload.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/JWTPayload.kt deleted file mode 100644 index da3d09668..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/JWTPayload.kt +++ /dev/null @@ -1,166 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import io.iohk.atala.prism.walletsdk.domain.VC -import kotlinx.serialization.EncodeDefault -import kotlinx.serialization.ExperimentalSerializationApi -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable -import kotlinx.serialization.json.JsonArray -import kotlinx.serialization.json.JsonObject -import kotlinx.serialization.json.JsonPrimitive -import kotlinx.serialization.json.jsonPrimitive - -/** - * A data class representing a JWT credential payload. - * This payload includes the issuer (`iss`), subject (`sub`), and the verifiable credential (`verifiableCredential`). - * - * Note: This data class conforms to the JSON Web Token (JWT) format. For more information, see https://jwt.io/introduction/. - */ -@OptIn(ExperimentalSerializationApi::class) -@Serializable -data class JWTPayload -@JvmOverloads constructor( - val iss: String, - val sub: String?, - @SerialName(VC) - val verifiableCredential: JWTVerifiableCredential, - val nbf: Long?, - @EncodeDefault - val exp: Long? = null, - @EncodeDefault - val jti: String? = null, - @EncodeDefault - val aud: Array? = null, - @EncodeDefault - val originalJWTString: String? = null -) { - - /** - * A struct representing the verifiable credential in a JWT credential payload. - */ - @Serializable - data class JWTVerifiableCredential @JvmOverloads constructor( - val context: Array = arrayOf(), - val type: Array = arrayOf(), - val credentialSchema: VerifiableCredentialTypeContainer? = null, - val credentialSubject: Map, - val credentialStatus: VerifiableCredentialTypeContainer? = null, - val refreshService: VerifiableCredentialTypeContainer? = null, - val evidence: VerifiableCredentialTypeContainer? = null, - val termsOfUse: VerifiableCredentialTypeContainer? = null - ) { - /** - * Checks if this JWTVerifiableCredential object is equal to the specified object. - * - * @param other The object to compare this JWTVerifiableCredential object against. - * @return true if the objects are equal, false otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as JWTVerifiableCredential - - if (!context.contentEquals(other.context)) return false - if (!type.contentEquals(other.type)) return false - if (credentialSchema != other.credentialSchema) return false - if (credentialSubject != other.credentialSubject) return false - if (credentialStatus != other.credentialStatus) return false - if (refreshService != other.refreshService) return false - if (evidence != other.evidence) return false - if (termsOfUse != other.termsOfUse) return false - - return true - } - - /** - * Calculates the hash code value for the current object. The hash code is computed - * based on the values of the object's properties. - * - * @return The hash code value for the object. - */ - override fun hashCode(): Int { - var result = context.contentHashCode() - result = 31 * result + type.contentHashCode() - result = 31 * result + (credentialSchema?.hashCode() ?: 0) - result = 31 * result + credentialSubject.hashCode() - result = 31 * result + (credentialStatus?.hashCode() ?: 0) - result = 31 * result + (refreshService?.hashCode() ?: 0) - result = 31 * result + (evidence?.hashCode() ?: 0) - result = 31 * result + (termsOfUse?.hashCode() ?: 0) - return result - } - } - - /** - * Checks if this JWTPayload object is equal to the specified object. - * - * @param other The object to compare this JWTPayload object against. - * @return true if the objects are equal, false otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (javaClass != other?.javaClass) return false - - other as JWTPayload - - if (iss != other.iss) return false - if (sub != other.sub) return false - if (verifiableCredential != other.verifiableCredential) return false - if (nbf != other.nbf) return false - if (exp != other.exp) return false - if (jti != other.jti) return false - if (aud != null) { - if (other.aud == null) return false - if (!aud.contentEquals(other.aud)) return false - } else if (other.aud != null) return false - if (originalJWTString != other.originalJWTString) return false - - return true - } - - /** - * Calculates the hash code value for the current `JWTPayload` object. - * The hash code is computed based on the values of the object's properties. - * - * @return The hash code value for the object. - */ - override fun hashCode(): Int { - var result = iss.hashCode() - result = 31 * result + (sub?.hashCode() ?: 0) - result = 31 * result + verifiableCredential.hashCode() - result = 31 * result + (nbf?.hashCode() ?: 0) - result = 31 * result + (exp?.hashCode() ?: 0) - result = 31 * result + (jti?.hashCode() ?: 0) - result = 31 * result + (aud?.contentHashCode() ?: 0) - result = 31 * result + (originalJWTString?.hashCode() ?: 0) - return result - } -} - -/** - * Retrieves the value of the specified credential field from a JsonObject. - * - * @param name The name of the credential field. - * @param isOptional Indicates whether the field is optional. If set to false and the field is not found, a [PolluxError.InvalidJWTString] error is thrown. - * @return The value of the credential field. The return type is inferred based on the actual type of the field in the JsonObject. - * @throws PolluxError.InvalidJWTString if the field is not found and isOptional is set to false. - */ -inline fun JsonObject.getCredentialField(name: String, isOptional: Boolean = false): T { - if (!isOptional && this[name] == null) throw PolluxError.InvalidJWTString() - return when (val field = this[name]) { - is JsonPrimitive -> { - field.content as T - } - - is JsonObject -> { - field as T - } - - is JsonArray -> { - field.map { it.jsonPrimitive.content } as T - } - - else -> null as T - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/JsonString.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/JsonString.kt deleted file mode 100644 index 5712aec1d..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/JsonString.kt +++ /dev/null @@ -1,6 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -/** - * Alias for a JSON string. - */ -typealias JsonString = String diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/KeyCurve.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/KeyCurve.kt deleted file mode 100644 index 94219f0c2..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/KeyCurve.kt +++ /dev/null @@ -1,26 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import kotlinx.serialization.Serializable - -/** - * Data class representing supported key curves for key generation. - */ -@Serializable -data class KeyCurve @JvmOverloads constructor( - val curve: Curve, - val index: Int? = 0 -) - -/** - * Enumeration representing supported key curves. - * - * @property value The string value of the curve. - * - * @constructor Creates a Curve object with the given value. - */ -@Serializable -enum class Curve(val value: String) { - X25519("X25519"), - ED25519("Ed25519"), - SECP256K1("secp256k1") -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Mediator.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Mediator.kt deleted file mode 100644 index d6875ad90..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Mediator.kt +++ /dev/null @@ -1,20 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import kotlinx.serialization.Serializable - -/** - * Mediator is a data class that represents a mediator entity. - * It contains the mediator's ID, mediator DID, host DID, and routing DID. - * - * @property id The ID of the mediator. - * @property mediatorDID The DID of the mediator. - * @property hostDID The DID of the host. - * @property routingDID The DID used for routing messages. - */ -@Serializable -data class Mediator( - val id: String, - val mediatorDID: DID, - val hostDID: DID, - val routingDID: DID -) diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Message.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Message.kt deleted file mode 100644 index df38c2bfc..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Message.kt +++ /dev/null @@ -1,152 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Mercury -import kotlinx.datetime.Clock -import kotlinx.serialization.EncodeDefault -import kotlinx.serialization.ExperimentalSerializationApi -import kotlinx.serialization.Serializable -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json -import java.util.UUID -import kotlin.jvm.JvmOverloads -import kotlin.time.Duration.Companion.days - -/** - * The [Message] data class represents a DIDComm message, which is used for secure, decentralized communication in the - * Atala PRISM architecture. A [Message] object includes information about the sender, recipient, message body, and other metadata. - * [Message] objects are typically exchanged between DID controllers using the [Mercury] building block. - */ -@Serializable -data class Message -@OptIn(ExperimentalSerializationApi::class) -@JvmOverloads -constructor( - @EncodeDefault - val id: String = UUID.randomUUID().toString(), - val piuri: String, - @EncodeDefault val from: DID? = null, - @EncodeDefault val to: DID? = null, - @EncodeDefault val fromPrior: String? = null, - val body: String, - val extraHeaders: Map = emptyMap(), - val createdTime: String = Clock.System.now().toString(), - val expiresTimePlus: String = Clock.System.now().plus(1.days).toString(), - val attachments: Array = arrayOf(), - val thid: String? = null, - val pthid: String? = null, - val ack: Array? = emptyArray(), - val direction: Direction = Direction.RECEIVED -) { - /** - * The `equals` method compares this `Message` object with another object for equality. - * - * @param other The object to compare with this `Message` object. - * @return `true` if the objects are equal, `false` otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as Message - - if (id != other.id) return false - if (piuri != other.piuri) return false - if (from != other.from) return false - if (to != other.to) return false - if (fromPrior != other.fromPrior) return false - if (body != other.body) return false - if (createdTime != other.createdTime) return false - if (expiresTimePlus != other.expiresTimePlus) return false - if (!attachments.contentEquals(other.attachments)) return false - if (thid != other.thid) return false - if (pthid != other.pthid) return false - if (!ack.contentEquals(other.ack)) return false - - return true - } - - /** - * Calculates the hash code for the Message object. - * The hash code is calculated based on the values of the object's id, piuri, from, to, fromPrior, - * body, extraHeaders, createdTime, expiresTimePlus, attachments, thid, pthid, and ack properties. - * If any of these properties is null, it is treated as 0 in the calculation. - * - * @return The hash code for the Message object. - */ - override fun hashCode(): Int { - var result = id.hashCode() - result = 31 * result + piuri.hashCode() - result = 31 * result + (from?.hashCode() ?: 0) - result = 31 * result + (to?.hashCode() ?: 0) - result = 31 * result + (fromPrior?.hashCode() ?: 0) - result = 31 * result + body.hashCode() - result = 31 * result + extraHeaders.hashCode() - result = 31 * result + createdTime.hashCode() - result = 31 * result + expiresTimePlus.hashCode() - result = 31 * result + attachments.contentHashCode() - result = 31 * result + (thid?.hashCode() ?: 0) - result = 31 * result + (pthid?.hashCode() ?: 0) - result = 31 * result + ack.contentHashCode() - return result - } - - /** - * Converts the current object to a JSON string representation. - * - * @return The JSON string representation of the object. - */ - fun toJsonString(): String { - return Json.encodeToString(this) - } - - /** - * Enumeration representing the direction of a message. - * - * @param value The numeric value representing the direction. - */ - enum class Direction(val value: Int) { - SENT(0), - RECEIVED(1) - } - - companion object { - /** - * Checks if the given [AttachmentData] is of type [AttachmentBase64]. - * - * @param data The [AttachmentData] object to check. - * @return `true` if the [AttachmentData] is of type [AttachmentBase64], `false` otherwise. - */ - @JvmStatic - fun isBase64Attachment(data: AttachmentData): Boolean { - return data is AttachmentBase64 - } - - /** - * Checks if the given [AttachmentData] is of type [AttachmentJsonData]. - * - * @param data The attachment data to check. - * @return `true` if the attachment data is of type [AttachmentJsonData], `false` otherwise. - */ - @JvmStatic - fun isJsonAttachment(data: AttachmentData): Boolean { - return data is AttachmentJsonData - } - } -} - -/** - * Retrieves the direction of a message based on the given value. - * - * @param value The value representing the direction of the message. - * 0 indicates SENT direction. - * 1 indicates RECEIVED direction. - * Any other value defaults to SENT direction. - * @return The message direction, either SENT or RECEIVED. - */ -fun getDirectionByValue(value: Int): Message.Direction { - return when (value) { - 0 -> Message.Direction.SENT - 1 -> Message.Direction.RECEIVED - else -> Message.Direction.SENT - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/MessageAttachment.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/MessageAttachment.kt deleted file mode 100644 index 06fb12d59..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/MessageAttachment.kt +++ /dev/null @@ -1,166 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import kotlinx.serialization.Serializable -import java.util.UUID -import kotlin.jvm.JvmOverloads - -/** - * The [AttachmentData] interface represents a generic attachment for a DIDComm [Message]. Any type that conforms to - * [AttachmentData] can be used as an attachment. - */ -@Serializable -sealed interface AttachmentData - -/** - * The [AttachmentHeader] data class represents the header for a DIDComm attachment. - */ -@Serializable -data class AttachmentHeader( - val children: String -) : AttachmentData - -/** - * The [AttachmentJws] data class represents a DIDComm attachment containing a JWS (JSON Web Signature). - */ -@Serializable -data class AttachmentJws( - val header: AttachmentHeader, - val protected: String, - val signature: String -) : AttachmentData - -/** - * The [AttachmentJwsData] data class represents a DIDComm attachment containing JWS data. - */ -@Serializable -data class AttachmentJwsData( - val base64: String, - val jws: AttachmentJws -) : AttachmentData - -/** - * The [AttachmentBase64] data class represents a DIDComm attachment containing base64-encoded data. - */ -@Serializable -data class AttachmentBase64( - val base64: String -) : AttachmentData - -/** - * The [AttachmentLinkData] data class represents a DIDComm attachment containing a link to external data. - */ -@Serializable -data class AttachmentLinkData( - val links: Array, - val hash: String -) : AttachmentData { - /** - * Overrides the equals method of the [Any] class. - * - * Two [AttachmentLinkData] instances are considered equal if all of their properties have the same values. - * - * @param other the object to compare for equality - * @return true if the objects are equal, false otherwise - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as AttachmentLinkData - - if (!links.contentEquals(other.links)) return false - if (hash != other.hash) return false - - return true - } - - /** - * Calculates the hash code for the [AttachmentLinkData] instance. - * - * The hash code is calculated by combining the hash codes of the `links` array and the `hash` property using the formula: - * `result = 31 * result + hash.hashCode()`. - * - * @return the hash code value for the [AttachmentLinkData] instance - */ - override fun hashCode(): Int { - var result = links.contentHashCode() - result = 31 * result + hash.hashCode() - return result - } -} - -/** - * The [AttachmentJsonData] data class represents a DIDComm attachment containing JSON data. - */ -@Serializable -data class AttachmentJsonData( - val data: String -) : AttachmentData - -/** - * The [AttachmentDescriptor] data class represents metadata for a DIDComm attachment. - */ -@Serializable -data class AttachmentDescriptor @JvmOverloads constructor( - val id: String = UUID.randomUUID().toString(), - val mediaType: String? = null, - val data: AttachmentData, - val filename: Array? = null, - val format: String? = null, - // TODO(Date format) - val lastModTime: String? = null, - val byteCount: Int? = null, - val description: String? = null -) : AttachmentData { - - /** - * Checks if this [AttachmentDescriptor] object is equal to the specified [other] object. - * - * Two [AttachmentDescriptor] objects are considered equal if they have the same values for the following properties: - * - [id] (unique identifier) - * - [mediaType] (media type of the attachment) - * - [data] (attachment data) - * - [filename] (array of filenames associated with the attachment) - * - [format] (format of the attachment) - * - [lastModTime] (last modification time of the attachment) - * - [byteCount] (byte count of the attachment) - * - [description] (description of the attachment) - * - * @param other The object to compare with this [AttachmentDescriptor] object. - * @return true if the specified [other] object is equal to this [AttachmentDescriptor] object, false otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as AttachmentDescriptor - - if (id != other.id) return false - if (mediaType != other.mediaType) return false - if (data != other.data) return false - if (!filename.contentEquals(other.filename)) return false - if (format != other.format) return false - if (lastModTime != other.lastModTime) return false - if (byteCount != other.byteCount) return false - if (description != other.description) return false - - return true - } - - /** - * Calculates the hash code for the AttachmentDescriptor object. - * - * @return The hash code value for the AttachmentDescriptor object. - */ - override fun hashCode(): Int { - var result = id.hashCode() - result = 31 * result + (mediaType?.hashCode() ?: 0) - result = 31 * result + data.hashCode() - result = 31 * result + filename.contentHashCode() - result = 31 * result + (format?.hashCode() ?: 0) - result = 31 * result + (lastModTime?.hashCode() ?: 0) - result = 31 * result + (byteCount ?: 0) - result = 31 * result + (description?.hashCode() ?: 0) - return result - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/OctetPublicKey.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/OctetPublicKey.kt deleted file mode 100644 index 80e42c3af..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/OctetPublicKey.kt +++ /dev/null @@ -1,30 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import io.iohk.atala.prism.walletsdk.mercury.OKP -import kotlinx.serialization.EncodeDefault -import kotlinx.serialization.ExperimentalSerializationApi -import kotlinx.serialization.Serializable - -/** - * Represents an Octet Key Pair (OKP) public key. - * - * @property kty The key type. Must be "OKP". - * @property crv The curve for the key. - * @property x The value of the public key. - */ -@Serializable -internal data class OctetPublicKey -@OptIn(ExperimentalSerializationApi::class) -@JvmOverloads -internal constructor(@EncodeDefault val kty: String = OKP, val crv: String, val x: String) - -/** - * Represents an Octet Key Pair (OKP) private key. - * - * @property kty The key type. - * @property crv The curve for the key. - * @property x The public key value. - * @property d The private key value. - */ -@Serializable -internal data class OctetPrivateKey(val kty: String, val crv: String, val x: String, val d: String) diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/PeerDID.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/PeerDID.kt deleted file mode 100644 index 70d46bfc6..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/PeerDID.kt +++ /dev/null @@ -1,48 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PrivateKey - -/** - * Represents a PeerDID, which is used as a unique and persistent identifier for a subject or object. - * It consists of a [DID] and an array of [PrivateKey]s. - * - * @property did The [DID] associated with the PeerDID. - * @property privateKeys The array of [PrivateKey]s associated with the PeerDID. - */ -data class PeerDID( - val did: DID, - val privateKeys: Array -) { - /** - * Compares this [PeerDID] object with the specified [other] object for equality. - * - * @param other The object to compare with this [PeerDID] object. - * @return `true` if the [other] object is equal to this [PeerDID] object, `false` otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as PeerDID - - if (did != other.did) return false - if (!privateKeys.contentEquals(other.privateKeys)) return false - - return true - } - - /** - * Calculates the hash code value for this PeerDID object. - * - * The hash code is calculated using the `did` and `privateKeys` properties of the PeerDID object. - * The hash code value is obtained by adding the hash code of the `did` property to the result variable, - * then multiplying the result by 31 and adding the hash code of the `privateKeys` array using the `contentHashCode()` method. - * - * @return The hash code value for this PeerDID object. - */ - override fun hashCode(): Int { - var result = did.hashCode() - result = 31 * result + privateKeys.contentHashCode() - return result - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Platform.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Platform.kt deleted file mode 100644 index 1a06c0bdb..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Platform.kt +++ /dev/null @@ -1,22 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -/** - * The `Platform` class provides information about the current platform. - * - * This class is used for determining the type of platform and the operating system being used. - * It provides the following properties: - * - * - `OS`: The name of the operating system as a string. - * - `type`: The type of platform as an instance of the `PlatformType` enum class. - * - * Usage example: - * - * ``` - * val osName = Platform.OS - * val platformType = Platform.type - * ``` - */ -expect object Platform { - val OS: String - val type: PlatformType -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/PlatformType.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/PlatformType.kt deleted file mode 100644 index 066a3ac9c..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/PlatformType.kt +++ /dev/null @@ -1,19 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -/** - * Represents the type of platform. - * - * This enum class defines the different supported platform types: - * - JVM: Represents the Java Virtual Machine platform. - * - ANDROID: Represents the Android platform. - * - IOS: Represents the iOS platform. - * - WEB: Represents the web platform. - * - * @property value The string representation of the platform type. - */ -enum class PlatformType(val value: String) { - JVM("JVM"), - ANDROID("ANDROID"), - IOS("IOS"), - WEB("WEB") -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/PrismDIDInfo.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/PrismDIDInfo.kt deleted file mode 100644 index c4a4120bd..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/PrismDIDInfo.kt +++ /dev/null @@ -1,13 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import kotlinx.serialization.Serializable - -/** - * A data class representing a conjunction of DID, keyPathIndex and alias. - */ -@Serializable -data class PrismDIDInfo( - val did: DID, - val keyPathIndex: Int? = 0, - val alias: String? = null -) diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/PrivateKey.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/PrivateKey.kt deleted file mode 100644 index 3a3a825d7..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/PrivateKey.kt +++ /dev/null @@ -1,30 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -// import kotlinx.serialization.Serializable - -/** - * Represents a private key with a specific key curve and value. - */ -// @Serializable -// data class PrivateKey( -// val keyCurve: KeyCurve, -// val value: ByteArray -// ) { -// override fun equals(other: Any?): Boolean { -// if (this === other) return true -// if (other == null || this::class != other::class) return false -// -// other as PrivateKey -// -// if (keyCurve != other.keyCurve) return false -// if (!value.contentEquals(other.value)) return false -// -// return true -// } -// -// override fun hashCode(): Int { -// var result = keyCurve.hashCode() -// result = 31 * result + value.contentHashCode() -// return result -// } -// } diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/PublicKey.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/PublicKey.kt deleted file mode 100644 index ae1f88870..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/PublicKey.kt +++ /dev/null @@ -1,89 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import kotlinx.serialization.Serializable - -/** - * Represents a public key with a specific key curve and value. - */ -@Serializable -data class PublicKey( - val curve: KeyCurve, - val value: ByteArray -) { - /** - * Checks whether the current [PublicKey] object is equal to the specified [other] object. - * - * Two [PublicKey] objects are considered equal if they have the same key curve and value. - * - * @param other The object to compare for equality. - * @return `true` if the objects are equal, `false` otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as PublicKey - - if (curve != other.curve) return false - if (!value.contentEquals(other.value)) return false - - return true - } - - /** - * Computes the hash code value for this [PublicKey] object. - * - * The hash code is computed based on the key curve and value of the [PublicKey] object. - * Two [PublicKey] objects that are equal according to the [equals] method will have the same hash code. - * - * @return The hash code value for this [PublicKey] object. - */ - override fun hashCode(): Int { - var result = curve.hashCode() - result = 31 * result + value.contentHashCode() - return result - } -} - -/** - * Represents a compressed public key and its uncompressed version. - */ -@Serializable -data class CompressedPublicKey( - val uncompressed: PublicKey, - val value: ByteArray -) { - /** - * Checks whether the current [CompressedPublicKey] object is equal to the specified [other] object. - * - * Two [CompressedPublicKey] objects are considered equal if they have the same uncompressed key and value. - * - * @param other The object to compare for equality. - * @return `true` if the objects are equal, `false` otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as CompressedPublicKey - - if (uncompressed != other.uncompressed) return false - if (!value.contentEquals(other.value)) return false - - return true - } - - /** - * Computes the hash code value for this [CompressedPublicKey] object. - * - * The hash code is computed based on the uncompressed key and value of the [CompressedPublicKey] object. - * Two [CompressedPublicKey] objects that are equal according to the [equals] method will have the same hash code. - * - * @return The hash code value for this [CompressedPublicKey] object. - */ - override fun hashCode(): Int { - var result = uncompressed.hashCode() - result = 31 * result + value.contentHashCode() - return result - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Secret.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Secret.kt deleted file mode 100644 index 1b887b9d7..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Secret.kt +++ /dev/null @@ -1,26 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -/** - * Represents a secret material in the form of a JSON Web Key (JWK). - * - * @param value The string value of the JWK. - */ -data class SecretMaterialJWK(val value: String) - -/** - * Represents a type of secret. - * - * @property value The value associated with the secret type. - */ -enum class SecretType(val value: String) { - JsonWebKey2020("JsonWebKey2020") -} - -/** - * Represents a secret, which is a piece of secret material and its type. - */ -data class Secret( - val id: String, - val type: SecretType, - val secretMaterial: SecretMaterialJWK -) diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/SecretResolver.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/SecretResolver.kt deleted file mode 100644 index 8d26b73f9..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/SecretResolver.kt +++ /dev/null @@ -1,8 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -/** - * Interface for resolving secrets by their ID. - */ -interface SecretResolver { - fun resolve(secretIds: Array) -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Seed.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Seed.kt deleted file mode 100644 index e180dea3b..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Seed.kt +++ /dev/null @@ -1,35 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import kotlinx.serialization.Serializable - -/** - * Represents a seed used for key generation. - */ -@Serializable -data class Seed( - val value: ByteArray -) { - /** - * Compares this Seed object to the specified [other] object for equality. - * - * Two Seed objects are considered equal if they have the same [value] property. - * - * @param other The object to compare for equality. - * @return `true` if the objects are equal, `false` otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as Seed - - return value.contentEquals(other.value) - } - - /** - * - */ - override fun hashCode(): Int { - return value.contentHashCode() - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/SeedWords.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/SeedWords.kt deleted file mode 100644 index 5ff5f8e32..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/SeedWords.kt +++ /dev/null @@ -1,45 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import kotlinx.serialization.Serializable - -/** - * Represents a set of seed words along with the corresponding seed object. - * - * @property mnemonics An array of seed words. - * @property seed The seed object used for key generation. - */ -@Serializable -data class SeedWords(val mnemonics: Array, val seed: Seed) { - /** - * Compares this SeedWords object to the specified [other] object for equality. - * - * Two SeedWords objects are considered equal if they have the same [mnemonics] and [seed] properties. - * - * @param other The object to compare for equality. - * @return `true` if the objects are equal, `false` otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as SeedWords - - if (!mnemonics.contentEquals(other.mnemonics)) return false - if (seed != other.seed) return false - - return true - } - - /** - * Calculates the hash code for the SeedWords object. - * - * The hash code is calculated based on the array of mnemonics and the seed object. - * - * @return The hash code value for the SeedWords object. - */ - override fun hashCode(): Int { - var result = mnemonics.contentHashCode() - result = 31 * result + seed.hashCode() - return result - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Session.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Session.kt deleted file mode 100644 index fd266d604..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Session.kt +++ /dev/null @@ -1,16 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import java.util.UUID -import kotlin.jvm.JvmOverloads - -/** - * Represents a session between two entities. - * - * @property uuid The unique identifier for the session. - * @property seed The seed used for key generation. - * @constructor Creates a Session object with the specified [uuid] and [seed]. - */ -data class Session @JvmOverloads constructor( - val uuid: UUID = UUID.randomUUID(), - val seed: Seed -) diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Signature.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Signature.kt deleted file mode 100644 index 7585150bb..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Signature.kt +++ /dev/null @@ -1,35 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import kotlinx.serialization.Serializable - -/** - * Represents a digital signature. - */ -@Serializable -data class Signature( - val value: ByteArray -) { - /** - * Check whether this Signature is equal to the specified object. - * - * @param other the object to compare with - * @return true if the given object is a Signature and has the same content as this Signature, false otherwise - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as Signature - - return value.contentEquals(other.value) - } - - /** - * Calculates the hash code value of the Signature object. - * - * @return the hash code value of the Signature object - */ - override fun hashCode(): Int { - return value.contentHashCode() - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/StorableCredential.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/StorableCredential.kt deleted file mode 100644 index e2035c3bd..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/StorableCredential.kt +++ /dev/null @@ -1,21 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -/** - * Represents a storable credential that can be stored and retrieved from a storage system. - */ -interface StorableCredential : Credential { - val recoveryId: String - val credentialData: ByteArray - val credentialCreated: String? - val credentialUpdated: String? - val credentialSchema: String? - val validUntil: String? - val availableClaims: Array - - /** - * Converts a storable credential to a regular credential. - * - * @return The converted Credential object. - */ - fun fromStorableCredential(): Credential -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/VerifiableCredential.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/VerifiableCredential.kt deleted file mode 100644 index 9dd5de8b8..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/VerifiableCredential.kt +++ /dev/null @@ -1,72 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import kotlinx.serialization.Serializable -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json - -/** - * A data class representing a container for verifiable credential types. - * This data class is used to encode and decode verifiable credential types for use with JSON. - * The VerifiableCredentialTypeContainer contains properties for the ID and type of the verifiable credential. - * ::: info - * The VerifiableCredentialTypeContainer is used to encode and decode verifiable credential types for use with JSON. - * ::: - */ -@Serializable -data class VerifiableCredentialTypeContainer( - val id: String, - val type: String -) - -/** - * Enum class representing different types of verifiable credentials. - * The CredentialType is used to indicate the type of verifiable credential. - * The possible values of the enum are jwt, w3c, and unknown. - * - * ::: info - * The CredentialType enum is used to indicate the type of verifiable credential. - * ::: - */ -@Serializable -enum class CredentialType(val type: String) { - JWT("prism/jwt"), - W3C("w3c"), - ANONCREDS_OFFER("anoncreds/credential-offer@v1.0"), - ANONCREDS_REQUEST("anoncreds/credential-request@v1.0"), - ANONCREDS_ISSUE("anoncreds/credential@v1.0"), - ANONCREDS_PROOF_REQUEST("anoncreds/proof-request@v1.0"), - Unknown("Unknown") -} - -/** - * Interface for objects representing verifiable credentials. - */ -@Serializable -sealed interface VerifiableCredential { - val id: String - val credentialType: CredentialType - val context: Array - val type: Array - val credentialSchema: VerifiableCredentialTypeContainer? - val credentialSubject: String - val credentialStatus: VerifiableCredentialTypeContainer? - val refreshService: VerifiableCredentialTypeContainer? - val evidence: VerifiableCredentialTypeContainer? - val termsOfUse: VerifiableCredentialTypeContainer? - val issuer: DID? - val issuanceDate: String // TODO(Date) - val expirationDate: String? // TODO(Date) - val validFrom: VerifiableCredentialTypeContainer? - val validUntil: VerifiableCredentialTypeContainer? - val proof: JsonString? - val aud: Array - - /** - * Converts the object to a JSON string representation. - * - * @return The JSON string representation of the object. - */ - fun toJsonString(): String { - return Json.encodeToString(this) - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/DerivableKey.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/DerivableKey.kt deleted file mode 100644 index 521d0e075..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/DerivableKey.kt +++ /dev/null @@ -1,15 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models.keyManagement - -import io.iohk.atala.prism.apollo.derivation.DerivationPath - -/** - * This interface defines the functionality of a derivable key. - */ -interface DerivableKey { - /** - * Method to derive a key - * @param derivationPath the derivation path used to dervie a key - * @return a PrivateKey after being derived - */ - fun derive(derivationPath: DerivationPath): PrivateKey -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/ExportableImportableKey.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/ExportableImportableKey.kt deleted file mode 100644 index 1b316026c..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/ExportableImportableKey.kt +++ /dev/null @@ -1,174 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models.keyManagement - -import io.iohk.atala.prism.apollo.base64.base64PadEncoded -import io.iohk.atala.prism.apollo.base64.base64UrlDecodedBytes -import kotlinx.serialization.Serializable - -/** - * This interface defines what is required for a key to be exportable - */ -interface ExportableKey { - /** - * The key exported in PEM (Privacy-Enhanced Mail) format. - * @return PEM string - */ - fun getPem(): String - - /** - * They key exported as a JWK (JSON Web Key) - * @return JWD instance - */ - fun getJwk(): JWK - - /** - * Returns the key as a JWD with a specific kid (key identifier) - * @return JWK instnace - */ - fun jwkWithKid(kid: String): JWK -} - -/** - * This interface defines what is required for a key to be importable - */ -interface ImportableKey { - /** - * Initializes key from PEM string - * @param pem string - */ - @Throws(Exception::class) - fun initializeFromPem(pem: String) - - /** - * Initializes key from JWK - */ - @Throws(Exception::class) - fun initializeFromJwk(jwk: JWK) -} - -/** - * Representation of a JWK (JSON Web Key) - */ -@Serializable -data class JWK( - val kty: String, - val alg: String? = null, - val kid: String? = null, - val use: String? = null, - val n: String? = null, - val e: String? = null, - val d: String? = null, - val p: String? = null, - val q: String? = null, - val dp: String? = null, - val dq: String? = null, - val qi: String? = null, - val crv: String? = null, - val x: String? = null, - val y: String? = null, - val k: String? = null -) - -/** - * Representation of a cryptographic key in PEM format. - */ -data class PEMKey(val keyType: PEMKeyType, val keyData: ByteArray) { - constructor(keyType: PEMKeyType, keyData: String) : this(keyType, keyData.base64UrlDecodedBytes) - - /** - * Encodes the PEM into base 64 - * @return pem encoded string - */ - fun pemEncoded(): String { - val base64Data = keyData.base64PadEncoded.chunked(64).joinToString("\n") - val beginMarker = "-----BEGIN $keyType-----" - val endMarker = "-----END $keyType-----" - - return "$beginMarker\n$base64Data\n$endMarker" - } - - /** - * Overrides the `equals` method of the `Any` class. - * - * This method checks if the current `PEMKey` object is equal to the specified `other` object. - * Two `PEMKey` objects are considered equal if they have the same `keyType` and `keyData`. - * - * @param other The object to compare for equality. - * @return `true` if the `other` object is equal to the current `PEMKey` object, `false` otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (javaClass != other?.javaClass) return false - - other as PEMKey - - if (keyType != other.keyType) return false - if (!keyData.contentEquals(other.keyData)) return false - - return true - } - - /** - * Calculates the hash code for the PEMKey instance. - * The hash code is calculated based on the keyType and keyData properties of the PEMKey. - * - * @return The hash code value for the PEMKey. - */ - override fun hashCode(): Int { - var result = keyType.hashCode() - result = 31 * result + keyData.contentHashCode() - return result - } - - companion object { - /** - * Decodes a PEM-encoded string into a PEMKey object. - * - * @param pemString The PEM-encoded string to decode. - * @return A PEMKey object if the decoding was successful, or null otherwise. - */ - @JvmStatic - fun fromPemEncoded(pemString: String): PEMKey? { - val lines = pemString.split("\n") - if (lines.size < 3) { - return null - } - - val beginMarker = lines[0] - val endMarker = lines[lines.size - 1] - - if (beginMarker.startsWith("-----BEGIN ").not() || beginMarker.endsWith("-----").not() || - endMarker.startsWith("-----END ").not() || endMarker.endsWith("-----").not() - ) { - return null - } - - val keyType = PEMKeyType.fromString(beginMarker) ?: throw Exception("Unknown PEM Key type") - - val base64Data = lines.subList(1, lines.size - 1).joinToString("") - val keyData = base64Data.base64PadEncoded - - return PEMKey(keyType = keyType, keyData = keyData) - } - } -} - -/** - * Definition of the PEM key types available - */ -enum class PEMKeyType(val value: Pair) { - EC_PRIVATE_KEY(Pair("-----BEGIN EC PRIVATE KEY-----", "-----END EC PRIVATE KEY-----")), - EC_PUBLIC_KEY(Pair("-----BEGIN EC PUBLIC KEY-----", "-----END EC PUBLIC KEY-----")); - - companion object { - /** - * Converts a string value to the corresponding PEMKeyType enum value. - * - * @param value The string value to convert. - * @return The PEMKeyType enum value if the conversion was successful, or null otherwise. - */ - @JvmStatic - fun fromString(value: String): PEMKeyType? { - return values().firstOrNull { it.value.first == value || it.value.second == value } - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/Key.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/Key.kt deleted file mode 100644 index c5540b230..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/Key.kt +++ /dev/null @@ -1,140 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models.keyManagement - -import io.iohk.atala.prism.apollo.base64.base64UrlEncoded -import io.iohk.atala.prism.walletsdk.domain.models.ApolloError -import io.iohk.atala.prism.walletsdk.domain.models.Curve -import io.iohk.atala.prism.walletsdk.domain.models.KeyCurve - -/** - * Abstraction defining the base of what a Key is. - */ -abstract class Key { - abstract val type: KeyTypes - abstract val keySpecification: MutableMap - abstract val size: Int - abstract val raw: ByteArray - - /** - * Checks if the current Key object is equal to the provided object. - * Two Key objects are considered equal if the following conditions are met: - * - The objects are references to the same memory location (this === other). - * - The other object is not null and is of the same class as Key. - * - The raw byte arrays of the keys are equal (raw.contentEquals(other.raw)). - * - The keySpecification map contains the CurveKey property and its value is equal to the value of the other key's CurveKey property. - * - * @param other The object to compare with the current Key. - * @return True if the objects are equal, false otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as Key - - if (!raw.contentEquals(other.raw)) { - return false - } - if (!keySpecification.containsKey(CurveKey().property) || - keySpecification[CurveKey().property] != other.getProperty(CurveKey().property) - ) { - return false - } - return true - } - - /** - * Computes the hash code of the Key object. - * The hash code is calculated based on the properties of the keySpecification map and the raw byte array. - * Two Key objects with the same keySpecification map and the raw byte array are guaranteed to have the same hash code. - * - * @return The hash code of the Key object. - */ - override fun hashCode(): Int { - var result = keySpecification[CurveKey().property].hashCode() - result = 31 * result + raw.contentHashCode() - return result - } - - /** - * Returns the encoded raw value into base 64 url - */ - fun getEncoded(): ByteArray { - return raw.base64UrlEncoded.encodeToByteArray() - } - - /** - * Evaluates if this key implements ExportableKey - */ - fun isExportable(): Boolean { - return this is ExportableKey - } - - /** - * Evaluates if this key implements ImportableKey - */ - fun isImportable(): Boolean { - return this is ImportableKey - } - - /** - * Evaluates if this key implements SignableKey - */ - fun isSignable(): Boolean { - return this is SignableKey - } - - /** - * Evaluates if this key implements DerivableKey - */ - fun isDerivable(): Boolean { - return this is DerivableKey - } - - /** - * Evaluates if this key implements VerifiableKey - */ - fun canVerify(): Boolean { - return this is VerifiableKey - } - - /** - * Searches the value based on the input key, if it exists - */ - fun getProperty(name: String): String { - if (!keySpecification.containsKey(name)) { - throw Exception("KeySpecification do not contain $name") - } - return this.keySpecification[name].toString() - } - - /** - * Evaluates if the input curve matches the actual curve this key has - */ - fun isCurve(curve: String): Boolean { - val keyCurve = keySpecification[CurveKey().property] - return keyCurve == curve - } -} - -/** - * Method to get a KeyCurve instance based on a key String name. - */ -fun getKeyCurveByNameAndIndex(name: String, index: Int?): KeyCurve { - return when (name) { - Curve.X25519.value -> { - KeyCurve(Curve.X25519) - } - - Curve.ED25519.value -> { - KeyCurve(Curve.ED25519) - } - - Curve.SECP256K1.value -> { - KeyCurve(Curve.SECP256K1, index) - } - - else -> { - throw ApolloError.InvalidKeyCurve(name) - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/KeyPair.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/KeyPair.kt deleted file mode 100644 index 117f64420..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/KeyPair.kt +++ /dev/null @@ -1,21 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models.keyManagement - -import kotlinx.serialization.Serializable - -/** - * Data class representing a pair of private and public keys for a specific key curve. - */ -@Serializable -abstract class KeyPair { - abstract var privateKey: PrivateKey - abstract var publicKey: PublicKey - - /** - * Returns the value of the key curve for this key pair. - * - * @return The value of the key curve. - */ - fun getCurve(): String { - return this.privateKey.getProperty(CurveKey().property) - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/KeyProperties.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/KeyProperties.kt deleted file mode 100644 index 16168c24f..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/KeyProperties.kt +++ /dev/null @@ -1,131 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models.keyManagement - -/** - * The `KeyProperties` class is an abstract class that provides a framework for defining key properties. - * Each subclass of `KeyProperties` must implement the `property` property. - */ -abstract class KeyProperties { - abstract val property: String -} - -/** - * Represents a key that holds an algorithm property. - * - * @property property The value of the algorithm property. - */ -class AlgorithmKey(override val property: String = "algorithm") : KeyProperties() - -/** - * Represents a key property for the curve. - * - * @property property The name of the key property. - */ -class CurveKey(override val property: String = "curve") : KeyProperties() - -/** - * Represents a seed key used for deriving private keys. - * - * @param property The property name for the seed key. Default value is "seed". - */ -class SeedKey(override val property: String = "seed") : KeyProperties() - -/** - * Represents a raw key with the property "raw". - * @property property The property of the raw key. - * @constructor Creates an instance of [RawKey] with the specified property, which defaults to "raw". - */ -class RawKey(override val property: String = "raw") : KeyProperties() - -/** - * Represents a derivation path key. - * Inherits from the KeyProperties class. - * - * @property property The property of the derivation path key. - */ -class DerivationPathKey(override val property: String = "derivationPath") : KeyProperties() - -/** - * Class representing an index key. - * @property property The property of the index key. - */ -class IndexKey(override val property: String = "index") : KeyProperties() - -/** - * Represents a specific type of key with a "type" property. - * Inherits from the abstract class KeyProperties. - * - * @param property The value of the "type" property. - */ -class TypeKey(override val property: String = "type") : KeyProperties() - -/** - * Class representing the CurvePointXKey. - * - * @property property The property associated with CurvePointXKey. - * @constructor Creates a CurvePointXKey object. - */ -class CurvePointXKey(override val property: String = "curvePoint.x") : KeyProperties() - -/** - * Represents a key property for the y-coordinate of a curve point. - * - * @property property The name of the property. - */ -class CurvePointYKey(override val property: String = "curvePoint.y") : KeyProperties() - -/** - * Represents a custom key with a specific property. - * - * @param property The property associated with the key. - */ -class CustomKey(override val property: String) : KeyProperties() - -/** - * Returns a KeyProperties object based on the given name. - * - * @param name The name of the key property. - * @return A KeyProperties object corresponding to the given name. - */ -fun getKeyPropertyByName(name: String): KeyProperties { - when (name) { - AlgorithmKey().property -> { - return AlgorithmKey() - } - - CurveKey().property -> { - return CurveKey() - } - - SeedKey().property -> { - return SeedKey() - } - - RawKey().property -> { - return RawKey() - } - - DerivationPathKey().property -> { - return DerivationPathKey() - } - - IndexKey().property -> { - return IndexKey() - } - - TypeKey().property -> { - return TypeKey() - } - - CurvePointXKey().property -> { - return CurvePointXKey() - } - - CurvePointYKey().property -> { - return CurvePointYKey() - } - - else -> { - return CustomKey(name) - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/KeyRestoration.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/KeyRestoration.kt deleted file mode 100644 index 8e78199e7..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/KeyRestoration.kt +++ /dev/null @@ -1,37 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models.keyManagement - -/** -* This interface defines the functionality to verify and restore cryptographic keys -*/ -interface KeyRestoration { - - /** - * Determines if the input data corresponds to a private key - * @param identifier a string that identifies the key - * @param data a ByteArray that represents the raw data - * @return a boolean value that tells if the identifier represents the private key - */ - fun isPrivateKeyData(identifier: String, data: ByteArray): Boolean - - /** - * Determines if the input data corresponds to a public key - * @param identifier a string that identifies the key - * @param data a ByteArray that represents the raw data - * @return a boolean value that tells if the identifier represents the public key - */ - fun isPublicKeyData(identifier: String, data: ByteArray): Boolean - - /** - * A method to restore a private key from a StorableKey - * @param key a StorableKey instance - * @return a PrivateKey - */ - fun restorePrivateKey(key: StorableKey): PrivateKey - - /** - * A method to restore a public key from a StorableKey - * @param key a StorableKey instance - * @return a PublicKey - */ - fun restorePublicKey(key: StorableKey): PublicKey -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/KeyTypes.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/KeyTypes.kt deleted file mode 100644 index 364f97b4f..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/KeyTypes.kt +++ /dev/null @@ -1,11 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models.keyManagement - -/** - * Enumeration class representing different types of keys. - * - * @property type The string representation of the key type. - */ -enum class KeyTypes(val type: String) { - EC("EC"), - Curve25519("Curve25519") -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/PrivateKey.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/PrivateKey.kt deleted file mode 100644 index d875ffe66..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/PrivateKey.kt +++ /dev/null @@ -1,46 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models.keyManagement - -import io.iohk.atala.prism.walletsdk.domain.models.Curve - -/** - * Abstraction of what a PrivateKey is and what functionality provides. - */ -abstract class PrivateKey : Key() { - - /** - * Returns the value of the key curve for this private key - */ - fun getCurve(): String { - return this.getProperty(CurveKey().property) - } - - /** - * Returns an instance of the key curve for this private key - */ - fun getCurveInstance(): Curve? { - return try { - Curve.valueOf(this.getProperty(CurveKey().property)) - } catch (e: Exception) { - null - } - } - - /** - * Returns the index for this private key - */ - fun getIndex(): String { - return this.getProperty(IndexKey().property) - } - - /** - * Returns the value of this private key - */ - fun getValue(): ByteArray { - return this.raw - } - - /** - * Defines a method to fetch the public key of this private key - */ - abstract fun publicKey(): PublicKey -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/PublicKey.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/PublicKey.kt deleted file mode 100644 index 7b2994df0..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/PublicKey.kt +++ /dev/null @@ -1,34 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models.keyManagement - -import io.iohk.atala.prism.walletsdk.domain.models.Curve - -/** - * Abstraction of what a PublicKey is and the functionality it provides. - */ -abstract class PublicKey : Key() { - - /** - * Returns the value of the key curve for this private key - */ - fun getCurve(): String { - return this.getProperty(CurveKey().property) - } - - /** - * Returns an instance of the key curve for this private key - */ - fun getCurveInstance(): Curve? { - return try { - Curve.valueOf(this.getProperty(CurveKey().property)) - } catch (e: Exception) { - null - } - } - - /** - * Returns the value of this private key - */ - fun getValue(): ByteArray { - return this.raw - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/SignableKey.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/SignableKey.kt deleted file mode 100644 index cdb706e24..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/SignableKey.kt +++ /dev/null @@ -1,14 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models.keyManagement - -/** - * This interface defines the functionality of a signable key. - */ -interface SignableKey { - - /** - * Method to sign a message using a key. - * @param message the ByteArray to be signed - * @return the signed message as a ByteArray - */ - fun sign(message: ByteArray): ByteArray -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/StorableKey.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/StorableKey.kt deleted file mode 100644 index e201413fc..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/StorableKey.kt +++ /dev/null @@ -1,9 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models.keyManagement - -/** - * This interface defines what a key requires to be storable. - */ -interface StorableKey { - val storableData: ByteArray - val restorationIdentifier: String -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/VerifiableKey.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/VerifiableKey.kt deleted file mode 100644 index 08a4cebf0..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/VerifiableKey.kt +++ /dev/null @@ -1,14 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models.keyManagement - -/** - * This interface defines the functionality of a verifiable key. - */ -interface VerifiableKey { - /** - * Method to verify a message with a signature. - * @param message in ByteArray - * @param signature in byteArray - * @return a boolean which tell us if message and signature match - */ - fun verify(message: ByteArray, signature: ByteArray): Boolean -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/logger/PrismLogger.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/logger/PrismLogger.kt deleted file mode 100644 index 98613ecbd..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/logger/PrismLogger.kt +++ /dev/null @@ -1,345 +0,0 @@ -package io.iohk.atala.prism.walletsdk.logger - -import org.kotlincrypto.hash.sha2.SHA256 -import org.lighthousegames.logging.logging -import java.util.UUID - -/** - * Constant value used to represent the privacy of metadata. - * - * This constant is used in the [Metadata] class to hide sensitive information - * based on the provided [LogLevel]. When the [LogLevel] is lower than the required level - * for accessing private metadata, this constant is returned instead of the actual value. - * - * @see Metadata - */ -private const val METADATA_PRIVACY_STR = "------" - -/** - * Property representing the unique identifier for the hashing log. - * The value is generated as a random UUID string. - * - * @see UUID.randomUUID - */ -private val hashingLog = UUID.randomUUID().toString() - -/** - * PrismLogger is an interface that defines methods for logging messages - * with different log levels and metadata. - */ -interface PrismLogger { - /** - * Logs a debug message with optional metadata. - * - * @param message The debug message. - * @param metadata An array of metadata objects associated with the message (optional). - */ - fun debug(message: String, metadata: Array = arrayOf()) - - /** - * Logs an information message with optional metadata. - * - * @param message The information message to be logged. - * @param metadata Optional metadata to be associated with the information message. - */ - fun info(message: String, metadata: Array = arrayOf()) - - /** - * Logs a warning message with optional metadata. - * - * @param message The warning message to log. - * @param metadata An array of metadata objects associated with the warning message. - */ - fun warning(message: String, metadata: Array = arrayOf()) - - /** - * Logs an error message with optional metadata. - * - * @param message The error message to be logged - * @param metadata An array of Metadata objects containing additional information (optional) - */ - fun error(message: String, metadata: Array = arrayOf()) - - /** - * This function is used to log an error with optional metadata. - * - * @param error The error to be logged. - * @param metadata An array of metadata objects to be included in the log message. Defaults to an empty array if not provided. - * - * @see PrismLogger.error - * @see Metadata - */ - fun error(error: Error, metadata: Array = arrayOf()) -} - -/** - * Implementation of the PrismLogger interface. - * - * @property category the LogComponent category for this logger - */ -class PrismLoggerImpl(category: LogComponent) : PrismLogger { - - private val log = logging("[io.prism.kmm.sdk.$category]") - - private var logLevel: LogLevel = LogLevel.INFO - - /** - * Logs a debug message with optional metadata. - * - * @param message The debug message. - * @param metadata An array of metadata objects associated with the message (optional). - */ - override fun debug(message: String, metadata: Array) { - if (logLevel != LogLevel.NONE) { - log.debug { message } - if (metadata.isNotEmpty()) { - log.debug { "Metadata: ${arrayToString(metadata)}" } - } - } - } - - /** - * Logs an information message with optional metadata. - * - * @param message The information message to be logged. - * @param metadata An array of metadata objects to be associated with the information message. - */ - override fun info(message: String, metadata: Array) { - if (logLevel != LogLevel.NONE) { - log.info { message } - if (metadata.isNotEmpty()) { - log.info { "Metadata: ${arrayToString(metadata)}" } - } - } - } - - /** - * Logs a warning message with optional metadata. - * - * @param message The warning message to log. - * @param metadata An array of metadata objects associated with the warning message. - */ - override fun warning(message: String, metadata: Array) { - if (logLevel != LogLevel.NONE) { - log.warn { message } - if (metadata.isNotEmpty()) { - log.warn { "Metadata: ${arrayToString(metadata)}" } - } - } - } - - /** - * Logs an error message with optional metadata. - * - * @param message The error message to be logged. - * @param metadata An array of metadata objects to be associated with the error message (optional). - */ - override fun error(message: String, metadata: Array) { - if (logLevel != LogLevel.NONE) { - log.error { message } - if (metadata.isNotEmpty()) { - log.error { "Metadata: ${arrayToString(metadata)}" } - } - } - } - - /** - * Logs an error with optional metadata. - * - * @param error The error object to be logged. - * @param metadata An array of metadata objects associated with the error (optional). - */ - override fun error(error: Error, metadata: Array) { - if (logLevel != LogLevel.NONE) { - log.error { error.message } - if (metadata.isNotEmpty()) { - log.error { "Metadata: ${arrayToString(metadata)}" } - } - } - } - - /** - * Converts an array of Metadata objects to a String representation. - * - * @param array An array of Metadata objects to be converted. - * @return The converted String representation of the Metadata objects, with each object's value separated by a new line. - */ - private fun arrayToString(array: Array): String { - return array.joinToString { "${it.getValue(logLevel)}\n" } - } -} - -/** - * Sealed class representing different types of metadata. - * This class has several subclasses: PublicMetadata, PrivateMetadata, PrivateMetadataByLevel, MaskedMetadata, - * and MaskedMetadataByLevel. - */ -sealed class Metadata { - /** - * Represents public metadata with a key-value pair. - * - * @property key The key for the metadata. - * @property value The value*/ - data class PublicMetadata(val key: String, val value: String) : Metadata() { - /** - * - */ - override fun toString(): String { - return value - } - } - - /** - * Data class representing private metadata. - * It extends the Metadata class. - * - * @property key The key of the metadata. - * @property value The value of the metadata. - * - * @constructor Creates a new instance of the PrivateMetadata class. - */ - data class PrivateMetadata(val key: String, val value: String) : Metadata() { - /** - * Returns a string representation of the object. In this case, it returns the value of the metadata. - * - * @return The value of the metadata as a string. - */ - override fun toString(): String { - return value - } - } - - /** - * Represents private metadata with a specific level. - * - * @property category The category of the log component. - * @property key The key of the metadata. - * @property value The value of the metadata. - * @property level The level of the metadata. - */ - data class PrivateMetadataByLevel( - val category: LogComponent, - val key: String, - val value: String, - val level: LogLevel - ) : Metadata() { - /** - * Returns a string representation of the object. In the case of the `toString` method, it returns the value of the metadata. - * - * @return The value of the metadata as a string. - */ - override fun toString(): String { - return value - } - } - - /** - * Represents metadata with masked value. - * - * This class extends the abstract class Metadata and provides a masked representation - * for the value of the metadata. The mask function used is SHA256 hashing. - * - * @property key The key of the metadata. - * @property value The value of the metadata. - * @constructor Creates an instance of MaskedMetadata. - */ - data class MaskedMetadata(val key: String, val value: String) : Metadata() { - /** - * Returns a string representation of the object. In this case, it returns the value of the metadata. - * - * @return The value of the metadata as a string. - */ - override fun toString(): String { - return value - } - } - - /** - * Represents masked metadata with a specific level of confidentiality. - * - * @property key The key of the metadata. - * @property value The value of the metadata. - * @property level The level of confidentiality associated with the metadata. - */ - data class MaskedMetadataByLevel( - val key: String, - val value: String, - val level: LogLevel - ) : Metadata() { - /** - * Returns a string representation of the object. The string representation is the value property of the object. - * - * @return The value of the object as a string. - */ - override fun toString(): String { - return value - } - } - - /** - * Returns the value associated with the given LogLevel. - * - * @param level The LogLevel to check against. - * @return The value associated with the given LogLevel as a String. - */ - fun getValue(level: LogLevel): String { - return when (this) { - is PublicMetadata -> value - is PrivateMetadata -> METADATA_PRIVACY_STR - is PrivateMetadataByLevel -> if (level.value < this.level.value) value else METADATA_PRIVACY_STR - is MaskedMetadata -> sha256Masked(value) - is MaskedMetadataByLevel -> if (level.value > this.level.value) value else sha256Masked(value) - } - } - - /** - * Computes the SHA256 hash of the input string with a masking algorithm. - * - * @param input The input string to be hashed. - * @return The SHA256 hash of the input string, represented as a hexadecimal string. - */ - private fun sha256Masked(input: String): String { - val sha256 = SHA256().digest((hashingLog + input).toByteArray()) - return sha256.joinToString("") { "%02x".format(it) } - } -} - -/** - * The `LogLevel` enum represents different levels of logging. - * - * The available values are: - * - INFO: Logs informational messages. - * - DEBUG: Logs debug messages, typically used for troubleshooting. - * - WARNING: Logs warning messages that indicate potential issues. - * - ERROR: Logs error messages that indicate failures or errors in the system. - * - NONE: Disables logging. - * - * @property value The numerical value associated with the log level. - */ -enum class LogLevel(val value: Int) { - INFO(0), - DEBUG(1), - WARNING(2), - ERROR(3), - NONE(4) -} - -/** - * The `LogComponent` enum represents the different logging components in the system. - * - * The available values are: - * - APOLLO - * - CASTOR - * - MERCURY - * - PLUTO - * - POLLUX - * - PRISM_AGENT - */ -enum class LogComponent { - APOLLO, - CASTOR, - MERCURY, - PLUTO, - POLLUX, - PRISM_AGENT -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/mercury/MercuryConstants.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/mercury/MercuryConstants.kt deleted file mode 100644 index 8e869ed0c..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/mercury/MercuryConstants.kt +++ /dev/null @@ -1,11 +0,0 @@ -package io.iohk.atala.prism.walletsdk.mercury - -const val OKP = "OKP" -const val MULTIBASE_BYTES_SIZE = 34 -const val CRV = "crv" -const val X = "x" -const val ATTACHMENT_SEPARATOR = "/" -const val BASE64 = "base64" -const val JSON = "json" -const val LINKS = "links" -const val HASH = "hash" diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/mercury/MercuryImpl.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/mercury/MercuryImpl.kt deleted file mode 100644 index 9176e2b91..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/mercury/MercuryImpl.kt +++ /dev/null @@ -1,295 +0,0 @@ -package io.iohk.atala.prism.walletsdk.mercury - -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Castor -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Mercury -import io.iohk.atala.prism.walletsdk.domain.models.Api -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.DIDDocument -import io.iohk.atala.prism.walletsdk.domain.models.MercuryError -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.logger.LogComponent -import io.iohk.atala.prism.walletsdk.logger.LogLevel -import io.iohk.atala.prism.walletsdk.logger.Metadata -import io.iohk.atala.prism.walletsdk.logger.PrismLogger -import io.iohk.atala.prism.walletsdk.logger.PrismLoggerImpl -import io.iohk.atala.prism.walletsdk.mercury.forward.ForwardMessage -import io.iohk.atala.prism.walletsdk.prismagent.DIDCOMM_MESSAGING -import io.iohk.atala.prism.walletsdk.prismagent.shared.KeyValue -import io.ktor.http.HttpHeaders -import io.ktor.http.HttpMethod -import org.didcommx.didcomm.common.Typ -import org.didcommx.didcomm.utils.isDID - -/** - * The DIDCommProtocol interface provides methods for packing and unpacking DIDComm messages. - */ -interface DIDCommProtocol { - /** - * Packs a given message object into a string representation. - * - * @param message The message object to pack. - * @return The string representation of the packed message. - * @throws [MercuryError.NoDIDReceiverSetError] if DIDReceiver is invalid. - * @throws [MercuryError.NoDIDSenderSetError] if DIDSender is invalid. - */ - fun packEncrypted(message: Message): String - - /** - * Unpacks a given string representation of a message into a [Message] object. - * - * @param message The string representation of the message to unpack. - * @return The unpacked [Message] object. - */ - fun unpack(message: String): Message -} - -/** - * 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 a more complex - * decentralized system requiring trusted peer-to-peer connections, Mercury provides the tools and features you need to - * establish, manage, and secure your communications easily. - */ -class MercuryImpl -@JvmOverloads -constructor( - private val castor: Castor, - private val protocol: DIDCommProtocol, - private val api: Api, - private val logger: PrismLogger = PrismLoggerImpl(LogComponent.MERCURY) -) : Mercury { - - /** - * Asynchronously packs a given message object into a string representation. This function may throw an error if the - * message object is invalid. - * - * @param message The message object to pack - * @return The string representation of the packed message - * @throws [MercuryError.NoDIDReceiverSetError] if DIDReceiver is invalid. - * @throws [MercuryError.NoDIDSenderSetError] if DIDSender is invalid. - */ - @Throws(MercuryError.NoDIDReceiverSetError::class, MercuryError.NoDIDSenderSetError::class) - override fun packMessage(message: Message): String { - if (message.to !is DID) { - throw MercuryError.NoDIDReceiverSetError() - } - - if (message.from !is DID) { - throw MercuryError.NoDIDSenderSetError() - } - - return protocol.packEncrypted(message) - } - - /** - * 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. - * - * @param message The string representation of the message to unpack - * @return The message object - */ - override fun unpackMessage(message: String): Message { - return protocol.unpack(message) - } - - /** - * Asynchronously sends a given message and returns the response data. - * - * @param message The message to send - * @return The response data - * @throws [MercuryError.NoDIDReceiverSetError] if DIDReceiver is invalid. - * @throws [MercuryError.NoDIDSenderSetError] if DIDSender is invalid. - */ - @Throws(MercuryError.NoDIDReceiverSetError::class, MercuryError.NoDIDSenderSetError::class) - override suspend fun sendMessage(message: Message): ByteArray? { - if (message.to !is DID) { - throw MercuryError.NoDIDReceiverSetError() - } - - if (message.from !is DID) { - throw MercuryError.NoDIDSenderSetError() - } - - val document = castor.resolveDID(message.to.toString()) - val packedMessage = packMessage(message) - val service = document.services.find { it.type.contains(DIDCOMM_MESSAGING) } - - getMediatorDID(service)?.let { mediatorDid -> - val mediatorDocument = castor.resolveDID(mediatorDid.toString()) - val mediatorUri = - mediatorDocument.services.find { it.type.contains(DIDCOMM_MESSAGING) }?.serviceEndpoint?.uri - try { - val forwardMsg = prepareForwardMessage(message, packedMessage, mediatorDid) - logger.debug( - message = "Sending forward message with internal message type ${message.piuri}", - metadata = arrayOf( - Metadata.MaskedMetadataByLevel( - key = "Sender", - value = forwardMsg.from.toString(), - level = LogLevel.DEBUG - ), - Metadata.MaskedMetadataByLevel( - key = "Receiver", - value = forwardMsg.to.toString(), - level = LogLevel.DEBUG - ) - ) - ) - val packedForwardMsg = packMessage(forwardMsg.makeMessage()) - logger.debug( - message = "Sending message with type ${message.piuri}", - metadata = arrayOf( - Metadata.MaskedMetadataByLevel( - key = "Sender", - value = message.from.toString(), - level = LogLevel.DEBUG - ), - Metadata.MaskedMetadataByLevel( - key = "Receiver", - value = message.to.toString(), - level = LogLevel.DEBUG - ) - ) - ) - return makeRequest(mediatorUri, packedForwardMsg) - } catch (e: Throwable) { - throw MercuryError.NoValidServiceFoundError(did = mediatorDid.toString()) - } - } - logger.debug( - message = "Sending message with type ${message.piuri}", - metadata = arrayOf( - Metadata.MaskedMetadataByLevel( - key = "Sender", - value = message.from.toString(), - level = LogLevel.DEBUG - ), - Metadata.MaskedMetadataByLevel( - key = "Receiver", - value = message.to.toString(), - level = LogLevel.DEBUG - ) - ) - ) - return makeRequest(service, packedMessage) - } - - /** - * Asynchronously sends a given message and returns the response message object. - * - * @param message The message to send - * @return The response message object or null - */ - override suspend fun sendMessageParseResponse(message: Message): Message? { - val msg = sendMessage(message) - msg?.let { - val msgString = String(msg) - if (msgString != "null" && msgString != "") { - return unpackMessage(msgString) - } - } - return null - } - - /** - * Prepares a [ForwardMessage] object to forward a message. - * - * @param message The original message to be forwarded. - * @param encrypted The encrypted representation of the message. - * @param mediatorDid The DID of the mediator. - * @return The [ForwardMessage] object with the necessary information for forwarding the message. - */ - private fun prepareForwardMessage(message: Message, encrypted: String, mediatorDid: DID): ForwardMessage { - return ForwardMessage( - body = ForwardMessage.ForwardBody(message.to.toString()), - encryptedMessage = encrypted, - from = message.from!!, - to = mediatorDid - ) - } - - /** - * Makes a request to the specified service. - * - * @param service The service to make the request to - * @param message The message to send in the request - * @return The response data as a byte array - * @throws MercuryError.NoValidServiceFoundError if no valid service is found for the given service - */ - @Throws(MercuryError.NoValidServiceFoundError::class) - private suspend fun makeRequest(service: DIDDocument.Service?, message: String): ByteArray? { - if (service !is DIDDocument.Service) { - throw MercuryError.NoValidServiceFoundError() - } - - val result = api.request( - HttpMethod.Post.value, - service.serviceEndpoint.uri, - emptyArray(), - arrayOf(KeyValue(HttpHeaders.ContentType, Typ.Encrypted.typ)), - message - ) - - if (result.status >= 400) { - logger.error( - "Calling api result in ${result.status} error", - arrayOf( - Metadata.PublicMetadata("statusCode", "${result.status}"), - Metadata.PublicMetadata("uri", service.serviceEndpoint.uri), - Metadata.PrivateMetadata("body", message) - ) - ) - } - - return result.jsonString.toByteArray() - } - - /** - * Makes a request to the specified URI. - * - * @param uri The URI of the service to make the request to - * @param message The message to send in the request - * @return The response data as a byte array, or null if the request fails - * @throws MercuryError.NoValidServiceFoundError if no valid service is found for the given service - */ - @Throws(MercuryError.NoValidServiceFoundError::class) - private suspend fun makeRequest(uri: String?, message: String): ByteArray? { - if (uri !is String) { - throw MercuryError.NoValidServiceFoundError() - } - - val result = api.request( - HttpMethod.Post.value, - uri, - emptyArray(), - arrayOf(KeyValue(HttpHeaders.ContentType, Typ.Encrypted.typ)), - message - ) - if (result.status >= 400) { - logger.error( - "Calling api result in ${result.status} error", - arrayOf( - Metadata.PublicMetadata("statusCode", "${result.status}"), - Metadata.PublicMetadata("uri", uri), - Metadata.PrivateMetadata("body", message) - ) - ) - } - return result.jsonString.toByteArray() - } - - /** - * Retrieves the Mediator DID (Decentralized Identifier) from the given service. - * - * @param service The service for which to retrieve the Mediator DID. - * @return The Mediator DID, or null if it could not be found or is invalid. - */ - private fun getMediatorDID(service: DIDDocument.Service?): DID? { - return service?.serviceEndpoint?.uri?.let { uri -> - if (isDID(uri)) { - castor.parseDID(uri) - } else { - null - } - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/mercury/forward/ForwardMessage.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/mercury/forward/ForwardMessage.kt deleted file mode 100644 index 73d5d50fa..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/mercury/forward/ForwardMessage.kt +++ /dev/null @@ -1,75 +0,0 @@ -package io.iohk.atala.prism.walletsdk.mercury.forward - -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentDescriptor -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentJsonData -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.ktor.http.ContentType -import kotlinx.serialization.EncodeDefault -import kotlinx.serialization.ExperimentalSerializationApi -import kotlinx.serialization.Serializable -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json -import java.util.UUID - -/** - * The ForwardMessage class represents a message for forwarding data using the DIDComm protocol. - * It contains the necessary information for creating a forward message, including the message body, - * sender and recipient DIDs, encrypted message, and an optional ID. - * - * @param body The body of the forward message. - * @param from The sender DID of the forward message. - * @param to The recipient DID of the forward message. - * @param encryptedMessage The encrypted message to be forwarded. - * @param id The optional ID of the forward message. If not provided, a random UUID will be generated. - */ -@OptIn(ExperimentalSerializationApi::class) -class ForwardMessage @JvmOverloads constructor( - val body: ForwardBody, - val from: DID, - val to: DID, - val encryptedMessage: String, - @EncodeDefault - val id: String = UUID.randomUUID().toString() -) { - /** - * Creates a [Message] object with the provided data. - * - * @return The created [Message] object. - */ - fun makeMessage(): Message { - val forwardBody = Json.encodeToString(body) - val attachmentData = AttachmentJsonData(encryptedMessage) - val attachment = - AttachmentDescriptor(UUID.randomUUID().toString(), ContentType.Application.Json.toString(), attachmentData) - - val message = Message( - id = id, - piuri = TYPE, - from = from, - to = to, - body = forwardBody, - attachments = arrayOf(attachment) - ) - - return message - } - - /** - * Represents the body of a forward message. - * - * @property next The next message recipient's DID. - */ - @Serializable - data class ForwardBody(val next: String) - - companion object { - /** - * The constant variable `TYPE` represents the URL of the type of forward message. - * - * @see ForwardMessage - * @see ForwardMessage.makeMessage - */ - const val TYPE = "https://didcomm.org/routing/2.0/forward" - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/mercury/resolvers/DIDCommDIDResolver.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/mercury/resolvers/DIDCommDIDResolver.kt deleted file mode 100644 index 35e05d919..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/mercury/resolvers/DIDCommDIDResolver.kt +++ /dev/null @@ -1,146 +0,0 @@ -package io.iohk.atala.prism.walletsdk.mercury.resolvers - -import io.iohk.atala.prism.didcomm.didpeer.core.fromMulticodec -import io.iohk.atala.prism.didcomm.didpeer.core.toJwk -import io.iohk.atala.prism.didcomm.didpeer.multibase.MultiBase -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Castor -import io.iohk.atala.prism.walletsdk.domain.models.CastorError -import io.iohk.atala.prism.walletsdk.domain.models.Curve -import io.iohk.atala.prism.walletsdk.domain.models.DIDDocument -import io.iohk.atala.prism.walletsdk.domain.models.OctetPublicKey -import io.iohk.atala.prism.walletsdk.mercury.CRV -import io.iohk.atala.prism.walletsdk.mercury.MULTIBASE_BYTES_SIZE -import io.iohk.atala.prism.walletsdk.mercury.X -import io.iohk.atala.prism.walletsdk.prismagent.DIDCOMM_MESSAGING -import kotlinx.coroutines.runBlocking -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json -import org.didcommx.didcomm.common.VerificationMaterial -import org.didcommx.didcomm.common.VerificationMaterialFormat -import org.didcommx.didcomm.common.VerificationMethodType -import org.didcommx.didcomm.diddoc.DIDCommService -import org.didcommx.didcomm.diddoc.DIDDoc -import org.didcommx.didcomm.diddoc.DIDDocResolver -import org.didcommx.didcomm.diddoc.VerificationMethod -import java.util.Optional - -/** - * A resolver that resolves a Decentralized Identifier (DID) to its corresponding DID Document. - * - * @param castor The instance of Castor used to resolve DIDs. - */ -class DIDCommDIDResolver(val castor: Castor) : DIDDocResolver { - /** - * Resolves a DID to its corresponding DID Document. - * - * @param did The DID to resolve. - * @return An optional containing the DID Document associated with the DID, or an empty optional if the document cannot be retrieved. - * @throws [CastorError.InvalidJWKKeysError] if the JWK keys are not in a valid format. - */ - @Throws(CastorError.InvalidJWKKeysError::class) - override fun resolve(did: String): Optional { - return runBlocking { - val doc = castor.resolveDID(did) - val authentications = mutableListOf() - val keyAgreements = mutableListOf() - val services = mutableListOf() - val verificationMethods = mutableListOf() - - doc.coreProperties.forEach { coreProperty -> - val methods = when (coreProperty) { - is DIDDocument.Authentication -> coreProperty.verificationMethods - is DIDDocument.AssertionMethod -> coreProperty.verificationMethods - is DIDDocument.KeyAgreement -> coreProperty.verificationMethods - is DIDDocument.CapabilityInvocation -> coreProperty.verificationMethods - is DIDDocument.CapabilityDelegation -> coreProperty.verificationMethods - else -> emptyArray() - } - - methods.forEach { method -> - val curve = DIDDocument.VerificationMethod.getCurveByType(method.type) - - if (curve === Curve.ED25519) { - authentications.add(method.id.string()) - } - - if (curve === Curve.X25519) { - keyAgreements.add(method.id.string()) - } - - // In this method we need to send th key as JWK while sometimes we get it as - // MultiBase, therefore the following lines of code convert it - val publicKeyJWK: Map - if (method.publicKeyMultibase != null) { - var keyBytes = MultiBase.decode(method.publicKeyMultibase) - // In the case of MultiBase make sure to remove the MultiCodec from the ByteArray - if (keyBytes.size == MULTIBASE_BYTES_SIZE) { - keyBytes = fromMulticodec(keyBytes).second - } - publicKeyJWK = when (curve) { - Curve.ED25519 -> { - toJwk( - keyBytes, - io.iohk.atala.prism.didcomm.didpeer.VerificationMethodTypeAuthentication.JsonWebKey2020 - ) - } - - Curve.X25519 -> { - toJwk( - keyBytes, - io.iohk.atala.prism.didcomm.didpeer.VerificationMethodTypeAgreement.JsonWebKey2020 - ) - } - - else -> throw RuntimeException("") - } - } else if (method.publicKeyJwk != null) { - publicKeyJWK = method.publicKeyJwk - } else { - throw RuntimeException("") - } - publicKeyJWK[CRV]?.let { crv -> - publicKeyJWK[X]?.let { x -> - verificationMethods.add( - VerificationMethod( - id = method.id.string(), - controller = method.controller.toString(), - type = VerificationMethodType.JSON_WEB_KEY_2020, - verificationMaterial = VerificationMaterial( - VerificationMaterialFormat.JWK, - Json.encodeToString( - OctetPublicKey( - crv = crv, - x = x - ) - ) - ) - ) - ) - } ?: throw CastorError.InvalidJWKKeysError() - } ?: throw CastorError.InvalidJWKKeysError() - } - - if (coreProperty is DIDDocument.Service && coreProperty.type.contains(DIDCOMM_MESSAGING)) { - services.add( - DIDCommService( - id = coreProperty.id, - serviceEndpoint = coreProperty.serviceEndpoint.uri, - routingKeys = coreProperty.serviceEndpoint.routingKeys?.toList() ?: emptyList(), - accept = coreProperty.serviceEndpoint.accept?.toList() ?: emptyList() - ) - ) - } - } - - Optional.of( - DIDDoc( - doc.id.toString(), - keyAgreements, - authentications, - verificationMethods, - services - ) - ) - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/mercury/resolvers/DIDCommSecretsResolver.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/mercury/resolvers/DIDCommSecretsResolver.kt deleted file mode 100644 index 5bc863166..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/mercury/resolvers/DIDCommSecretsResolver.kt +++ /dev/null @@ -1,69 +0,0 @@ -package io.iohk.atala.prism.walletsdk.mercury.resolvers - -import io.iohk.atala.prism.apollo.base64.base64UrlEncoded -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Apollo -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Pluto -import io.iohk.atala.prism.walletsdk.domain.models.OctetPrivateKey -import io.iohk.atala.prism.walletsdk.mercury.OKP -import kotlinx.coroutines.flow.firstOrNull -import kotlinx.coroutines.runBlocking -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json -import org.didcommx.didcomm.common.VerificationMaterial -import org.didcommx.didcomm.common.VerificationMaterialFormat -import org.didcommx.didcomm.common.VerificationMethodType -import org.didcommx.didcomm.secret.Secret -import org.didcommx.didcomm.secret.SecretResolver -import java.util.Optional - -/** - * DIDCommSecretsResolver is a class that implements the SecretResolver interface. - * It is responsible for resolving secrets using the Pluto and Apollo components. - * - * @property pluto The Pluto component used to get DID private keys. - * @property apollo The Apollo component used for some other functionality. - */ -class DIDCommSecretsResolver(val pluto: Pluto, val apollo: Apollo) : SecretResolver { - /** - * Finds the keys associated with the provided list of kid values. - * - * @param kids The list of kid values to search for. - * @return A set of keys that match the provided kid values. - */ - override fun findKeys(kids: List): Set { - return runBlocking { - kids.filter { pluto.getDIDPrivateKeyByID(it).firstOrNull() != null }.toSet() - } - } - - /** - * Finds a key associated with the provided kid value and returns it as an Optional. - * - * @param kid The kid value to search for. - * @return An Optional containing the key as a Secret object, or an empty Optional if no key is found. - */ - override fun findKey(kid: String): Optional { - return runBlocking { - pluto.getDIDPrivateKeyByID(kid) - .firstOrNull() - ?.let { privateKey -> - val octetJwk = OctetPrivateKey( - crv = privateKey.getCurve(), - kty = OKP, - d = privateKey.getValue().base64UrlEncoded, - x = privateKey.publicKey().getValue().base64UrlEncoded - ) - Optional.of( - Secret( - kid, - VerificationMethodType.JSON_WEB_KEY_2020, - VerificationMaterial( - VerificationMaterialFormat.JWK, - Json.encodeToString(octetJwk) - ) - ) - ) - } ?: Optional.empty() - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/mercury/resolvers/DIDCommWrapper.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/mercury/resolvers/DIDCommWrapper.kt deleted file mode 100644 index d114dbbb8..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/mercury/resolvers/DIDCommWrapper.kt +++ /dev/null @@ -1,337 +0,0 @@ -package io.iohk.atala.prism.walletsdk.mercury.resolvers - -import com.nimbusds.jose.shaded.json.JSONObject -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Apollo -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Castor -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Pluto -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentBase64 -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentData -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentDescriptor -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentJsonData -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentLinkData -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.MercuryError -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.logger.LogComponent -import io.iohk.atala.prism.walletsdk.logger.LogLevel -import io.iohk.atala.prism.walletsdk.logger.Metadata -import io.iohk.atala.prism.walletsdk.logger.PrismLoggerImpl -import io.iohk.atala.prism.walletsdk.mercury.ATTACHMENT_SEPARATOR -import io.iohk.atala.prism.walletsdk.mercury.BASE64 -import io.iohk.atala.prism.walletsdk.mercury.DIDCommProtocol -import io.iohk.atala.prism.walletsdk.mercury.HASH -import io.iohk.atala.prism.walletsdk.mercury.JSON -import io.iohk.atala.prism.walletsdk.mercury.LINKS -import kotlinx.datetime.Clock -import kotlinx.datetime.Instant -import kotlinx.serialization.json.Json -import kotlinx.serialization.json.JsonArray -import kotlinx.serialization.json.JsonElement -import kotlinx.serialization.json.JsonNull -import kotlinx.serialization.json.JsonObject -import kotlinx.serialization.json.JsonPrimitive -import kotlinx.serialization.json.boolean -import kotlinx.serialization.json.booleanOrNull -import kotlinx.serialization.json.double -import kotlinx.serialization.json.doubleOrNull -import kotlinx.serialization.json.int -import kotlinx.serialization.json.intOrNull -import kotlinx.serialization.json.jsonObject -import org.didcommx.didcomm.DIDComm -import org.didcommx.didcomm.common.Typ -import org.didcommx.didcomm.message.Attachment -import org.didcommx.didcomm.model.PackEncryptedParams -import org.didcommx.didcomm.model.UnpackParams -import org.didcommx.didcomm.utils.fromJsonToMap -import java.time.Instant.now -import kotlin.jvm.Throws - -/** - * Wrapper class for the DIDComm functionality. - * - * @param castor The instance of Castor used for DID resolution. - * @param pluto The instance of Pluto used for secrets resolution. - * @param apollo The instance of Apollo used for secrets resolution. - */ -class DIDCommWrapper(castor: Castor, pluto: Pluto, apollo: Apollo) : DIDCommProtocol { - private val didDocResolver = DIDCommDIDResolver(castor) - private val secretsResolver = DIDCommSecretsResolver(pluto, apollo) - private val didComm = DIDComm(didDocResolver, secretsResolver) - private val logger = PrismLoggerImpl(LogComponent.MERCURY) - - /** - * Converts a JSON element to a map. - * - * @param element The JSON element to convert. - * @return The resulting map. - */ - private fun jsonObjectToMap(element: JsonElement): Map { - val bodyMap = mutableMapOf() - return if (element is JsonPrimitive) { - bodyMap - } else { - val keys = element.jsonObject.keys - keys.forEach { key -> - when (val value = element.jsonObject[key]) { - is JsonObject -> { - bodyMap[key] = jsonObjectToMap(value) - } - - is JsonArray -> { - val array = mutableListOf() - value.forEach { - when (it) { - is JsonObject -> { - array.add(jsonObjectToMap(it)) - } - - is JsonPrimitive -> { - if (it.isString) { - array.add(it.content) - } else if (it.intOrNull != null) { - array.add(it.int) - } else if (it.doubleOrNull != null) { - array.add(it.double) - } else if (it.booleanOrNull != null) { - array.add(it.boolean) - } else { - array.add(it) - } - } - - else -> { - array.add(it) - } - } - } - bodyMap[key] = array - } - - is JsonPrimitive -> { - if (value.isString) { - bodyMap[key] = value.content - } else if (value.intOrNull != null) { - bodyMap[key] = value.int - } else if (value.doubleOrNull != null) { - bodyMap[key] = value.double - } else if (value.booleanOrNull != null) { - bodyMap[key] = value.boolean - } else { - bodyMap[key] = value - } - } - - is JsonNull -> { - bodyMap[key] = null - } - - else -> { - bodyMap[key] = value - } - } - } - bodyMap - } - } - - /** - * Packs a [Message] object into an encrypted string message. - * - * @param message The [Message] object to be packed. - * @return The packed message as a string. - */ - override fun packEncrypted(message: Message): String { - val toString = message.to.toString() - - val element: JsonElement = if (message.body.isBlank() || message.body.isEmpty()) { - Json.parseToJsonElement("{}") - } else { - Json.parseToJsonElement(message.body) - } - val map: Map = jsonObjectToMap(element) - - val didCommMsg = org.didcommx.didcomm.message.Message( - id = message.id, - body = map, - typ = Typ.Plaintext, - type = message.piuri, - to = listOf(toString), - from = message.from.toString(), - fromPrior = null, - fromPriorJwt = message.fromPrior, - attachments = parseAttachments(message.attachments), - createdTime = if (message.createdTime == "") Clock.System.now().epochSeconds else Instant.parse(message.createdTime).epochSeconds, - expiresTime = null, - thid = message.thid, - pthid = message.pthid, - ack = null, - pleaseAck = null, - customHeaders = message.extraHeaders - ) - val builder = PackEncryptedParams.builder(didCommMsg, toString).forward(false).protectSenderId(false) - didCommMsg.from?.let { builder.from(it) } - val params = builder.build() - logger.debug( - message = "Packing message ${message.piuri}", - metadata = arrayOf( - Metadata.MaskedMetadataByLevel(key = "Sender", value = message.from.toString(), LogLevel.DEBUG), - Metadata.MaskedMetadataByLevel(key = "Receiver", value = message.to.toString(), LogLevel.DEBUG) - ) - ) - val result = didComm.packEncrypted(params) - return result.packedMessage - } - - /** - * Parses an array of AttachmentDescriptors and converts them into a list of Attachments. - * - * @param attachments The array of AttachmentDescriptors to be parsed. - * @return The list of parsed Attachments. - */ - private fun parseAttachments(attachments: Array): List { - return attachments.fold(mutableListOf()) { acc, attachment -> - acc.add( - Attachment( - id = attachment.id, - byteCount = attachment.byteCount?.toLong(), - data = parseAttachmentData(attachment.data), - description = attachment.description, - filename = attachment.filename?.joinToString(ATTACHMENT_SEPARATOR), - format = attachment.format, - lastModTime = attachment.lastModTime?.toLong(), - mediaType = attachment.mediaType - ) - ) - - return acc - } - } - - /** - * Parse the given [AttachmentData] and return an instance of [Attachment.Data]. - * - * @throws MercuryError.UnknownAttachmentDataError if an unknown [AttachmentData] type is found - * @param data The [AttachmentData] to parse - * @return The parsed [Attachment.Data] - */ - @Throws(MercuryError.UnknownAttachmentDataError::class) - private fun parseAttachmentData(data: AttachmentData): Attachment.Data { - if (data is AttachmentBase64) { - return Attachment.Data.Base64(data.base64) - } - - if (data is AttachmentJsonData) { - return Attachment.Data.Json(fromJsonToMap(data.data)) - } - - if (data is AttachmentLinkData) { - return Attachment.Data.Links(data.links.toList(), data.hash) - } - - throw MercuryError.UnknownAttachmentDataError() - } - - /** - * Unpacks a packed message into a domain-specific [Message] object. - * - * @param message The packed message to unpack. - * @return The unpacked [Message] object. - */ - override fun unpack(message: String): Message { - val result = didComm.unpack( - UnpackParams( - packedMessage = message, - didDocResolver = didDocResolver, - secretResolver = secretsResolver, - expectDecryptByAllKeys = false, - unwrapReWrappingForward = false - ) - ) - - val domainMsg = Message( - id = result.message.id, - piuri = result.message.type, - from = result.message.from?.let { from -> DID(from) }, - to = result.message.to?.let { to -> DID(to.first()) }, - fromPrior = result.message.fromPrior.toString(), - body = result.message.body.toString(), - thid = result.message.thid, - pthid = result.message.pthid, - ack = result.message.ack?.let { arrayOf(it) } ?: emptyArray(), - createdTime = result.message.createdTime?.toString() ?: now().toEpochMilli().toString(), - // expiresTimePlus = result.message.expiresTime?.toString() - // extraHeaders = result.message.customHeaders, - attachments = parseAttachmentsToDomain(result.message.attachments) - ) - - return domainMsg - } - - /** - * Parses a list of attachments into an array of AttachmentDescriptors. - * - * @param attachments The list of attachments to be parsed. Can be null. - * @return An array of parsed AttachmentDescriptors. - * @throws MercuryError.MessageAttachmentWithoutIDError if a message attachment is found without an "id". - */ - @Throws(MercuryError.MessageAttachmentWithoutIDError::class) - private fun parseAttachmentsToDomain(attachments: List?): Array { - return (attachments ?: emptyList()).fold(arrayOf()) { acc, attachment -> - try { - if (attachment.id.isEmpty()) { - throw MercuryError.MessageAttachmentWithoutIDError() - } - - val attachmentDescriptor = AttachmentDescriptor( - id = attachment.id, - data = parseAttachmentDataToDomain(attachment.data), - byteCount = attachment.byteCount?.toInt(), - description = attachment.description, - filename = attachment.filename?.split(ATTACHMENT_SEPARATOR)?.toTypedArray(), - format = attachment.format, - lastModTime = attachment.lastModTime?.toString(), - mediaType = attachment.mediaType - ) - - return acc.plus(attachmentDescriptor) - } catch (e: Error) { - return acc - } - } - } - - /** - * Parses the given [Attachment.Data] and converts it into an instance of [AttachmentData]. - * If the [Attachment.Data] represents base64-encoded data, it creates an instance of [AttachmentBase64]. - * If the [Attachment.Data] represents JSON data, it creates an instance of [AttachmentJsonData]. - * If the [Attachment.Data] represents a link to external data, it creates an instance of [AttachmentLinkData]. - * - * @throws MercuryError.UnknownAttachmentDataError if an unknown [Attachment.Data] type is found - * @param data The [Attachment.Data] to parse - * @return The parsed [AttachmentData] - */ - @Throws(MercuryError.UnknownAttachmentDataError::class) - private fun parseAttachmentDataToDomain(data: Attachment.Data): AttachmentData { - val jsonObj = data.toJSONObject() - - val base64 = jsonObj[BASE64] - if (base64 is String) { - return AttachmentBase64(base64) - } - - val json = jsonObj[JSON] - if (json is JSONObject) { - @Suppress("UNCHECKED_CAST") // JSONObject can be always cast as Map - return AttachmentJsonData(JSONObject.toJSONString(json as Map)) - } - - val links = jsonObj[LINKS] - val hash = jsonObj[HASH] - if (links is Array<*> && links.isArrayOf() && hash is String) { - @Suppress("UNCHECKED_CAST") // checks are applied in the if condition - return AttachmentLinkData(links as Array, hash) - } - - throw MercuryError.UnknownAttachmentDataError() - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/mercury/resolvers/DefaultSecretsResolverImpl.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/mercury/resolvers/DefaultSecretsResolverImpl.kt deleted file mode 100644 index 7c2160f8e..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/mercury/resolvers/DefaultSecretsResolverImpl.kt +++ /dev/null @@ -1,70 +0,0 @@ -package io.iohk.atala.prism.walletsdk.mercury.resolvers - -import io.iohk.atala.prism.apollo.base64.base64UrlEncoded -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Pluto -import io.iohk.atala.prism.walletsdk.domain.models.Secret -import io.iohk.atala.prism.walletsdk.domain.models.SecretMaterialJWK -import io.iohk.atala.prism.walletsdk.domain.models.SecretType -import io.iohk.atala.prism.walletsdk.mercury.OKP -import kotlinx.coroutines.flow.firstOrNull -import kotlinx.serialization.Serializable - -/** - * Default implementation of the [SecretsResolver] interface. - * - * @property pluto Instance of the Pluto class used for resolving secrets. - */ -class DefaultSecretsResolverImpl(val pluto: Pluto) : SecretsResolver { - - /** - * Represents a Private JSON Web Key (JWK). - * This class is used to hold the necessary information for a private key used in JSON Web Signature (JWS). - * - * @property kty The key type. Default value is "OKP". - * @property kid The key ID. - * @property crv The cryptographic curve used by the key. - * @property d The private key value. It is nullable and defaults to null. - */ - @Serializable - data class PrivateJWK @JvmOverloads constructor( - val kty: String = OKP, - val kid: String, - val crv: String, - val d: String? = null - ) - - /** - * Finds secrets based on the provided secret IDs. - * - * @param secretIds An array of secret IDs. - * @return An array of secrets that match the provided secret IDs. - */ - override suspend fun findSecrets(secretIds: Array): Array { - return secretIds.filter { - pluto.getDIDPrivateKeyByID(it) - .firstOrNull() != null - }.toTypedArray() - } - - /** - * Retrieves a secret based on its ID. - * - * @param secretId The ID of the secret. - * @return The secret object if found, otherwise null. - */ - override suspend fun getSecret(secretId: String): Secret? { - return pluto.getDIDPrivateKeyByID(secretId).firstOrNull()?.let { privateKey -> - return Secret( - secretId, - SecretType.JsonWebKey2020, - SecretMaterialJWK( - PrivateJWK( - secretId, - privateKey.getCurve(), - privateKey.getValue().base64UrlEncoded - ).toString() - ) - ) - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/mercury/resolvers/SecretsResolver.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/mercury/resolvers/SecretsResolver.kt deleted file mode 100644 index 10a2ae551..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/mercury/resolvers/SecretsResolver.kt +++ /dev/null @@ -1,24 +0,0 @@ -package io.iohk.atala.prism.walletsdk.mercury.resolvers - -import io.iohk.atala.prism.walletsdk.domain.models.Secret - -/** - * Resolves secrets by finding secrets based on secret IDs or retrieving a specific secret by its ID. - */ -interface SecretsResolver { - /** - * Asynchronously finds secrets based on the provided secret IDs. - * - * @param secretIds An array of secret IDs to be searched. - * @return An array of strings representing the secret values found. - */ - suspend fun findSecrets(secretIds: Array): Array - - /** - * Suspends the execution until the secret with the given secretId is retrieved. - * - * @param secretId The ID of the secret to retrieve. - * @return The secret with the specified ID, or null if the secret does not exist. - */ - suspend fun getSecret(secretId: String): Secret? -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pluto/CredentialRecovery.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pluto/CredentialRecovery.kt deleted file mode 100644 index 6dcfea3a7..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pluto/CredentialRecovery.kt +++ /dev/null @@ -1,9 +0,0 @@ -package io.iohk.atala.prism.walletsdk.pluto - -/** - * Class representing a credential recovery object. - * - * @property restorationId The restoration ID associated with the credential recovery. - * @property credentialData The credential data as a byte array. - */ -class CredentialRecovery(val restorationId: String, val credentialData: ByteArray, val revoked: Boolean) diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pluto/PlutoImpl.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pluto/PlutoImpl.kt deleted file mode 100644 index 0e3bf5b17..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pluto/PlutoImpl.kt +++ /dev/null @@ -1,1054 +0,0 @@ -package io.iohk.atala.prism.walletsdk.pluto - -import app.cash.sqldelight.ColumnAdapter -import app.cash.sqldelight.coroutines.asFlow -import app.cash.sqldelight.coroutines.mapToList -import app.cash.sqldelight.db.AfterVersion -import io.iohk.atala.prism.apollo.base64.base64UrlDecodedBytes -import io.iohk.atala.prism.apollo.base64.base64UrlEncoded -import io.iohk.atala.prism.walletsdk.PrismPlutoDb -import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519PrivateKey -import io.iohk.atala.prism.walletsdk.apollo.utils.Secp256k1PrivateKey -import io.iohk.atala.prism.walletsdk.apollo.utils.X25519PrivateKey -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Pluto -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.DIDPair -import io.iohk.atala.prism.walletsdk.domain.models.Mediator -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.domain.models.PeerDID -import io.iohk.atala.prism.walletsdk.domain.models.PlutoError -import io.iohk.atala.prism.walletsdk.domain.models.PrismDIDInfo -import io.iohk.atala.prism.walletsdk.domain.models.StorableCredential -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PrivateKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.StorableKey -import io.iohk.atala.prism.walletsdk.pluto.data.DbConnection -import io.iohk.atala.prism.walletsdk.pluto.data.isConnected -import io.iohk.atala.prism.walletsdk.pollux.models.CredentialRequestMeta -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.map -import kotlinx.coroutines.flow.mapLatest -import kotlinx.serialization.json.Json -import java.util.UUID -import io.iohk.atala.prism.walletsdk.pluto.data.AvailableClaims as AvailableClaimsDB -import io.iohk.atala.prism.walletsdk.pluto.data.DID as DIDDB -import io.iohk.atala.prism.walletsdk.pluto.data.DIDPair as DIDPairDB -import io.iohk.atala.prism.walletsdk.pluto.data.LinkSecret as LinkSecretDB -import io.iohk.atala.prism.walletsdk.pluto.data.Mediator as MediatorDB -import io.iohk.atala.prism.walletsdk.pluto.data.Message as MessageDB -import io.iohk.atala.prism.walletsdk.pluto.data.PrivateKey as PrivateKeyDB -import io.iohk.atala.prism.walletsdk.pluto.data.StorableCredential as StorableCredentialDB - -/** - * `PlutoImpl` is a class that provides an implementation of the Pluto interface for interacting with the database. - * - * @property db The instance of `PrismPlutoDb` representing the connection to the database. - * @property isConnected A flag to indicate whether the database connection is established or not. - */ -class PlutoImpl(private val connection: DbConnection) : Pluto { - private var db: PrismPlutoDb? = null - - init { - this.connection.driver?.let { driver -> - PrismPlutoDb.Schema.migrate( - driver, - 1, - PrismPlutoDb.Schema.version, - AfterVersion(1) { - it.execute(null, "ALTER TABLE CredentialMetadata DROB COLUMN nonce;", 0) - it.execute( - null, - "ALTER TABLE CredentialMetadata DROB COLUMN linkSecretBlindingData;", - 0 - ) - it.execute(null, "ALTER TABLE CredentialMetadata ADD COLUMN json TEXT;", 0) - } - ) - } ?: { - throw PlutoError.DatabaseConnectionError("Database migration failed to: ${PrismPlutoDb.Schema.version}") - } - } - - /** - * isConnected indicates whether the connection to the database is currently established or not. - * - * @return true if the connection is established, false otherwise - */ - val isConnected: Boolean - get() { - return this.connection.driver?.isConnected ?: false - } - - /** - * Starts the database service. - * - * @param context The context data required for establishing the connection. This can be null in some cases. - * @throws PlutoError.DatabaseServiceAlreadyRunning if the database service is already running. - */ - @Throws(PlutoError.DatabaseServiceAlreadyRunning::class) - @JvmOverloads - public suspend fun start(context: Any? = null) { - if (this.db != null) { - throw PlutoError.DatabaseServiceAlreadyRunning() - } - this.db = PrismPlutoDb( - this.connection.connectDb(context), - io.iohk.atala.prism.walletsdk.pluto.data.Message.Adapter( - isReceivedAdapter = object : ColumnAdapter { - override fun decode(databaseValue: Long): Int { - return databaseValue.toInt() - } - - override fun encode(value: Int): Long { - return value.toLong() - } - } - ), - io.iohk.atala.prism.walletsdk.pluto.data.PrivateKey.Adapter( - keyPathIndexAdapter = object : ColumnAdapter { - override fun decode(databaseValue: Long): Int { - return databaseValue.toInt() - } - - override fun encode(value: Int): Long { - return value.toLong() - } - } - ), - io.iohk.atala.prism.walletsdk.pluto.data.StorableCredential.Adapter( - revokedAdapter = object : ColumnAdapter { - override fun decode(databaseValue: Long): Int { - return databaseValue.toInt() - } - - override fun encode(value: Int): Long { - return value.toLong() - } - } - ) - ) - } - - /** - * Closes the connection to the database. - * - * @throws PlutoError.DatabaseConnectionError if there is an error with the database connection - */ - @Throws(PlutoError.DatabaseConnectionError::class) - public fun stop() { - val driver = this.connection.driver ?: throw PlutoError.DatabaseConnectionError() - this.db = null - driver.close() - } - - /** - * Retrieves an instance of the PrismPlutoDb object. - * Throws DatabaseConnectionError if the database connection is not established. - * - * @throws PlutoError.DatabaseConnectionError if the database connection is not established - * @return the PrismPlutoDb instance - */ - @Throws(PlutoError.DatabaseConnectionError::class) - private fun getInstance(): PrismPlutoDb { - return this.db ?: throw PlutoError.DatabaseConnectionError() - } - - /** - * Stores the Prism DID, key path index, alias, and private keys. - * - * @param did The Prism DID to store. - * @param keyPathIndex The key path index. - * @param alias The optional alias for the Prism DID. - * @param privateKeys The list of private keys to store. - */ - override fun storePrismDIDAndPrivateKeys( - did: DID, - keyPathIndex: Int, - alias: String?, - privateKeys: List - ) { - getInstance().dIDQueries.insert( - DIDDB( - did.toString(), - did.method, - did.methodId, - did.schema, - alias - ) - ) - privateKeys.map { privateKey -> - storePrivateKeys(privateKey, did, keyPathIndex) - } - } - - /** - * Stores the PeerDID in the system. - * - * @param did The PeerDID to store. - */ - override fun storePeerDID(did: DID) { - getInstance().dIDQueries.insert( - DIDDB( - did.toString(), - did.method, - did.methodId, - did.schema, - null - ) - ) - } - - /** - * Stores a pair of Distributed Identifier (DID) and a receiver DID with a given name. - * - * @param host The host DID to store. - * @param receiver The receiver DID to store. - * @param name The name of the stored pair. - */ - override fun storeDIDPair(host: DID, receiver: DID, name: String) { - getInstance().dIDPairQueries.insert( - DIDPairDB( - "$host$receiver", - name, - host.toString(), - receiver.toString() - ) - ) - } - - /** - * Stores a message in the system. - * - * @param message The message to store. - */ - override fun storeMessage(message: Message) { - getInstance().messageQueries.insert( - MessageDB( - message.id, - message.createdTime, - message.toJsonString(), - message.from.toString(), - message.thid, - message.to.toString(), - message.piuri, - message.direction.value - ) - ) - } - - /** - * Stores the private key along with additional information. - * - * @param storableKey The private key to store. Must implement the [StorableKey] interface. - * @param did The DID associated with the private key. - * @param keyPathIndex The key path index. - * @param metaId The optional metadata ID. - */ - override fun storePrivateKeys( - storableKey: StorableKey, - did: DID, - keyPathIndex: Int, - metaId: String? - ) { - metaId?.let { id -> - val list = getInstance().privateKeyQueries.fetchPrivateKeyByID(id).executeAsList() - if (list.isEmpty()) { - getInstance().privateKeyQueries.insert( - PrivateKeyDB( - metaId, - storableKey.restorationIdentifier, - storableKey.storableData.base64UrlEncoded, - keyPathIndex, - did.toString() - ) - ) - } else { - // TODO: Implement Delete, Update - } - } ?: run { - getInstance().privateKeyQueries.insert( - PrivateKeyDB( - UUID.randomUUID().toString(), - storableKey.restorationIdentifier, - storableKey.storableData.base64UrlEncoded, - keyPathIndex, - did.toString() - ) - ) - } - } - - /** - * Stores a list of messages in the system. - * - * @param messages The list of messages to store. - */ - override fun storeMessages(messages: List) { - messages.map { message -> - storeMessage(message) - } - } - - /** - * Stores a mediator in the system. - * - * @param mediator The mediator DID to store. - * @param host The host DID associated with the mediator. - * @param routing The routing DID for the mediator. - */ - override fun storeMediator(mediator: DID, host: DID, routing: DID) { - val instance = getInstance() - instance.dIDQueries.insert( - DIDDB( - mediator.toString(), - mediator.method, - mediator.methodId, - mediator.schema, - null - ) - ) - instance.dIDQueries.insert( - DIDDB( - routing.toString(), - routing.method, - routing.methodId, - routing.schema, - null - ) - ) - instance.mediatorQueries.insert( - MediatorDB( - UUID.randomUUID().toString(), - mediator.methodId, - host.methodId, - routing.methodId - ) - ) - } - - /** - * Stores a credential in the system. - * - * @param storableCredential The credential to store. It must implement the [StorableCredential] interface. - */ - override fun storeCredential(storableCredential: StorableCredential) { - getInstance().storableCredentialQueries.insert( - StorableCredentialDB( - id = storableCredential.id, - recoveryId = storableCredential.recoveryId, - credentialSchema = storableCredential.credentialSchema ?: "", - credentialData = storableCredential.credentialData, - issuer = storableCredential.issuer, - subject = storableCredential.subject, - credentialCreated = storableCredential.credentialCreated, - credentialUpdated = storableCredential.credentialUpdated, - validUntil = storableCredential.validUntil, - revoked = if (storableCredential.revoked == true) 1 else 0 - ) - ) - getInstance().availableClaimsQueries.transaction { - storableCredential.availableClaims.forEach { claim -> - getInstance().availableClaimsQueries.insert(storableCredential.id, claim) - } - } - } - - /** - * Stores a link secret in the system. - * - * @param linkSecret The link secret to store. - */ - override fun storeLinkSecret(linkSecret: String) { - getInstance().linkSecretQueries - .insert(LinkSecretDB(linkSecret)) - } - - /** - * Stores the metadata associated with a credential request. - * - * @param metadata The metadata to store. It must be an instance of [CredentialRequestMeta]. - */ - override fun storeCredentialMetadata(metadata: CredentialRequestMeta) { - getInstance().credentialMetadataQueries.insert( - id = UUID.randomUUID().toString(), - linkSecretName = metadata.linkSecretName, - json = metadata.json - ) - } - - /** - * Retrieves all PrismDIDs and their associated information. - * - * @return A flow of lists of [PrismDIDInfo] objects representing the PrismDIDs and their information. - */ - override fun getAllPrismDIDs(): Flow> { - return getInstance().dIDQueries - .fetchAllPrismDID() - .asFlow() - .mapToList(Dispatchers.Default) - .map { list -> - list.map { - PrismDIDInfo(DID(it.did), it.keyPathIndex, it.alias) - } - } - } - - /** - * Retrieves the [PrismDIDInfo] associated with a given [DID]. - * - * @param did The [DID] for which to retrieve the [PrismDIDInfo]. - * @return A [Flow] that emits a nullable [PrismDIDInfo] object representing the [PrismDIDInfo] associated - * with the specified [DID]. If no [PrismDIDInfo] is found, null is emitted. - */ - @OptIn(ExperimentalCoroutinesApi::class) - override fun getDIDInfoByDID(did: DID): Flow { - return getInstance().dIDQueries - .fetchDIDInfoByDID(did.methodId) - .asFlow() - .mapLatest { - try { - val didInfo = it.executeAsOne() - PrismDIDInfo(DID(didInfo.did), didInfo.keyPathIndex, didInfo.alias) - } catch (e: NullPointerException) { - null - } - } - } - - /** - * Retrieves the [PrismDIDInfo] objects associated with a given alias. - * - * @param alias The alias for which to retrieve the [PrismDIDInfo] objects. - * @return A [Flow] that emits a list of [PrismDIDInfo] objects representing the - * [PrismDIDInfo] associated with the specified alias. - */ - override fun getDIDInfoByAlias(alias: String): Flow> { - return getInstance().dIDQueries - .fetchDIDInfoByAlias(alias) - .asFlow() - .map { - it.executeAsList() - .map { didInfo -> - PrismDIDInfo(DID(didInfo.did), didInfo.keyPathIndex, didInfo.alias) - } - } - } - - /** - * Retrieves a list of private keys associated with a given DID. - * - * @param did The DID for which to retrieve private keys. - * @return A flow that emits a list of nullable [PrivateKey] objects. In case a private key is not found, null is emitted. - */ - override fun getDIDPrivateKeysByDID(did: DID): Flow> { - return getInstance().privateKeyQueries - .fetchPrivateKeyByDID(did.toString()) - .asFlow() - .map { - it.executeAsList() - .map { storableKey -> - when (storableKey.restorationIdentifier) { - "secp256k1+priv" -> { - Secp256k1PrivateKey(storableKey.data_.base64UrlDecodedBytes) - } - - "ed25519+priv" -> { - Ed25519PrivateKey(storableKey.data_.base64UrlDecodedBytes) - } - - "x25519+priv" -> { - X25519PrivateKey(storableKey.data_.base64UrlDecodedBytes) - } - - else -> { - throw PlutoError.InvalidRestorationIdentifier() - } - } - } - } - } - - /** - * Retrieves the private key associated with a given ID. - * - * @param id The ID of the private key. - * @return A [Flow] that emits the private key as a nullable [PrivateKey] object. If no private key is found, - * null is emitted. - */ - override fun getDIDPrivateKeyByID(id: String): Flow { - return getInstance().privateKeyQueries - .fetchPrivateKeyByID(id) - .asFlow() - .map { - it.executeAsList().firstOrNull()?.let { storableKey -> - when (storableKey.restorationIdentifier) { - "secp256k1+priv" -> { - Secp256k1PrivateKey(storableKey.data_.base64UrlDecodedBytes) - } - - "ed25519+priv" -> { - Ed25519PrivateKey(storableKey.data_.base64UrlDecodedBytes) - } - - "x25519+priv" -> { - X25519PrivateKey(storableKey.data_.base64UrlDecodedBytes) - } - - else -> { - throw PlutoError.InvalidRestorationIdentifier() - } - } - } - } - } - - /** - * Retrieves the key path index associated with a given Prism DID. - * - * @param did The Prism DID for which to retrieve the key path index. - * @return A [Flow] that emits a nullable [Int] representing the key path index associated with the specified Prism DID. - * If no key path index is found, null is emitted. - */ - override fun getPrismDIDKeyPathIndex(did: DID): Flow { - return getInstance().privateKeyQueries.fetchKeyPathIndexByDID(did.toString()) - .asFlow() - .map { - try { - it.executeAsOne().keyPathIndex - } catch (e: NullPointerException) { - null - } - } - } - - /** - * Retrieves the last key path index associated with the Prism DID. - * - * @return A [Flow] that emits an [Int] representing the last key path index associated with the Prism DID. - */ - override fun getPrismLastKeyPathIndex(): Flow { - return getInstance().privateKeyQueries.fetchLastkeyPathIndex() - .asFlow() - .map { - it.executeAsList().firstOrNull()?.keyPathIndex ?: 0 - } - } - - /** - * Retrieves all PeerDIDs. - * - * @return A flow of lists of PeerDIDs. - */ - override fun getAllPeerDIDs(): Flow> { - return getInstance().dIDQueries.fetchAllPeerDID() - .asFlow() - .map { allDIDs -> - allDIDs.executeAsList() - .groupBy { allPeerDid -> allPeerDid.did } - .map { - println("Restoration ID: ${it.value[0].restorationIdentifier}") - val privateKeyList: Array = it.value.map { allPeerDID -> - when (allPeerDID.restorationIdentifier) { - "secp256k1+priv" -> { - Secp256k1PrivateKey(allPeerDID.data_.base64UrlDecodedBytes) - } - - "ed25519+priv" -> { - Ed25519PrivateKey(allPeerDID.data_.base64UrlDecodedBytes) - } - - "x25519+priv" -> { - X25519PrivateKey(allPeerDID.data_.base64UrlDecodedBytes) - } - - else -> { - throw PlutoError.InvalidRestorationIdentifier() - } - } - }.toTypedArray() - PeerDID(DID(it.key), privateKeyList) - } - } - } - - /** - * Retrieves all the pairs of DIDs stored in the system. - * - * @return a [Flow] emitting a list of [DIDPair] objects representing the pairs of DIDs. - */ - override fun getAllDidPairs(): Flow> { - return getInstance().dIDPairQueries.fetchAllDIDPairs() - .asFlow() - .map { didPair -> - didPair.executeAsList() - .map { DIDPair(DID(it.hostDID), DID(it.receiverDID), it.name) } - } - } - - /** - * Retrieves a DIDPair object using the provided DID. - * - * @param did The DID to search for. - * @return A Flow of DIDPair objects. If a match is found, the flow emits the matching DIDPair. - * If no match is found, the flow emits null. - */ - override fun getPairByDID(did: DID): Flow { - return getInstance().dIDPairQueries.fetchDIDPairByDID(did.toString()) - .asFlow() - .map { - try { - val didPair = it.executeAsOne() - DIDPair(DID(didPair.hostDID), DID(didPair.receiverDID), didPair.name) - } catch (e: NullPointerException) { - null - } - } - } - - /** - * Retrieve a [DIDPair] from a flow by its name. - * - * @param name The name of the [DIDPair] to retrieve. - * @return A [Flow] emitting the [DIDPair] object that matches the given name, - * or `null` if no matching [DIDPair] is found. - */ - override fun getPairByName(name: String): Flow { - return getInstance().dIDPairQueries.fetchDIDPairByName(name) - .asFlow() - .map { - try { - val didPair = it.executeAsOne() - DIDPair(DID(didPair.hostDID), DID(didPair.receiverDID), didPair.name) - } catch (e: NullPointerException) { - null - } - } - } - - /** - * Retrieves all the messages. - * - * @return a Flow of List of Message objects representing all the messages. - */ - override fun getAllMessages(): Flow> { - return getInstance().messageQueries.fetchAllMessages() - .asFlow() - .map { - it.executeAsList().map { message -> - val messageDb = Json.decodeFromString(message.dataJson) - Message( - messageDb.id, - messageDb.piuri, - messageDb.from, - messageDb.to, - messageDb.fromPrior, - messageDb.body, - messageDb.extraHeaders, - messageDb.createdTime, - messageDb.expiresTimePlus, - messageDb.attachments, - messageDb.thid, - messageDb.pthid, - messageDb.ack, - messageDb.direction - ) - } - } - } - - /** - * Retrieves all messages based on the provided DID. - * - * @param did The DID (Direct Inward Dialing) to filter messages by. - * @return A flow of list of messages. - */ - override fun getAllMessages(did: DID): Flow> { - return getAllMessages(did, did) - } - - /** - * Retrieves all messages exchanged between the specified 'from' and 'to' DIDs. - * - * @param from the sender DID - * @param to the receiver DID - * @return a Flow emitting a list of messages exchanged between the 'from' and 'to' DIDs - */ - override fun getAllMessages(from: DID, to: DID): Flow> { - return getInstance().messageQueries.fetchAllMessagesFromTo(from.toString(), to.toString()) - .asFlow() - .map { - it.executeAsList().map { message -> - val messageDb = Json.decodeFromString(message.dataJson) - Message( - messageDb.id, - messageDb.piuri, - messageDb.from, - messageDb.to, - messageDb.fromPrior, - messageDb.body, - messageDb.extraHeaders, - messageDb.createdTime, - messageDb.expiresTimePlus, - messageDb.attachments, - messageDb.thid, - messageDb.pthid, - messageDb.ack, - messageDb.direction - ) - } - } - } - - /** - * Retrieves all the messages that have been sent. - * - * @return A [Flow] of type [List] containing the sent messages. - */ - override fun getAllMessagesSent(): Flow> { - return getInstance().messageQueries.fetchAllSentMessages() - .asFlow() - .map { - it.executeAsList().map { message -> - val messageDb = Json.decodeFromString(message.dataJson) - Message( - messageDb.id, - messageDb.piuri, - messageDb.from, - messageDb.to, - messageDb.fromPrior, - messageDb.body, - messageDb.extraHeaders, - messageDb.createdTime, - messageDb.expiresTimePlus, - messageDb.attachments, - messageDb.thid, - messageDb.pthid, - messageDb.ack, - messageDb.direction - ) - } - } - } - - /** - * Retrieves all messages received by the user. - * - * @return A [Flow] emitting a list of [Message] objects representing all the messages received. - */ - override fun getAllMessagesReceived(): Flow> { - return getInstance().messageQueries.fetchAllReceivedMessages() - .asFlow() - .map { - it.executeAsList().map { message -> - val messageDb = Json.decodeFromString(message.dataJson) - Message( - messageDb.id, - messageDb.piuri, - messageDb.from, - messageDb.to, - messageDb.fromPrior, - messageDb.body, - messageDb.extraHeaders, - messageDb.createdTime, - messageDb.expiresTimePlus, - messageDb.attachments, - messageDb.thid, - messageDb.pthid, - messageDb.ack, - messageDb.direction - ) - } - } - } - - /** - * Retrieves all messages sent to the specified DID. - * - * @param did the destination DID to filter the messages by - * @return a [Flow] of [List] of [Message] objects containing all the messages sent to the specified DID - */ - override fun getAllMessagesSentTo(did: DID): Flow> { - return getInstance().messageQueries.fetchAllMessagesSentTo(did.toString()) - .asFlow() - .map { - it.executeAsList().map { message -> - val messageDb = Json.decodeFromString(message.dataJson) - Message( - messageDb.id, - messageDb.piuri, - messageDb.from, - messageDb.to, - messageDb.fromPrior, - messageDb.body, - messageDb.extraHeaders, - messageDb.createdTime, - messageDb.expiresTimePlus, - messageDb.attachments, - messageDb.thid, - messageDb.pthid, - messageDb.ack, - messageDb.direction - ) - } - } - } - - /** - * Returns a Flow of lists of all messages received from the specified DID. - * - * @param did the DID (Decentralized Identifier) to get the received messages from - * @return a Flow of lists of messages received from the specified DID - */ - override fun getAllMessagesReceivedFrom(did: DID): Flow> { - return getInstance().messageQueries.fetchAllMessagesReceivedFrom(did.toString()) - .asFlow() - .map { - it.executeAsList().map { message -> - val messageDb = Json.decodeFromString(message.dataJson) - Message( - messageDb.id, - messageDb.piuri, - messageDb.from, - messageDb.to, - messageDb.fromPrior, - messageDb.body, - messageDb.extraHeaders, - messageDb.createdTime, - messageDb.expiresTimePlus, - messageDb.attachments, - messageDb.thid, - messageDb.pthid, - messageDb.ack, - messageDb.direction - ) - } - } - } - - /** - * Retrieves all messages of a specific type that are related to a given DID. - * - * @param type The type of the messages to retrieve. - * @param relatedWithDID The optional DID to which the messages are related. - * @return A [Flow] emitting a list of [Message] objects that match the given type and are related to the specified DID. - */ - override fun getAllMessagesOfType(type: String, relatedWithDID: DID?): Flow> { - return getInstance().messageQueries.fetchAllMessagesOfType( - type, - relatedWithDID.toString() - ) - .asFlow() - .map { - it.executeAsList().map { message -> - val messageDb = Json.decodeFromString(message.dataJson) - Message( - messageDb.id, - messageDb.piuri, - messageDb.from, - messageDb.to, - messageDb.fromPrior, - messageDb.body, - messageDb.extraHeaders, - messageDb.createdTime, - messageDb.expiresTimePlus, - messageDb.attachments, - messageDb.thid, - messageDb.pthid, - messageDb.ack, - messageDb.direction - ) - } - } - } - - /** - * Retrieves the message with the specified ID. - * - * @param id The unique ID of the message. - * @return A [Flow] that emits the message with the specified ID, or null if no such message exists. - * The [Flow] completes when the message is successfully retrieved, or when an error occurs. - */ - override fun getMessage(id: String): Flow { - return getInstance().messageQueries.fetchMessageById(id) - .asFlow() - .map { - try { - val messageDb = Json.decodeFromString(it.executeAsOne().dataJson) - Message( - messageDb.id, - messageDb.piuri, - messageDb.from, - messageDb.to, - messageDb.fromPrior, - messageDb.body, - messageDb.extraHeaders, - messageDb.createdTime, - messageDb.expiresTimePlus, - messageDb.attachments, - messageDb.thid, - messageDb.pthid, - messageDb.ack, - messageDb.direction - ) - } catch (e: NullPointerException) { - null - } - } - } - - /** - * Returns a Flow of lists of [Mediator] objects representing all the available mediators. - * - * @return a Flow of lists of [Mediator] objects. - */ - override fun getAllMediators(): Flow> { - return getInstance().mediatorQueries.fetchAllMediators() - .asFlow() - .map { query -> - val fetchAllMediators = query.executeAsList() - fetchAllMediators.map { - Mediator( - it.id, - DID(it.MediatorDID), - DID(it.HostDID), - DID(it.RoutingDID) - ) - } - } - } - - /** - * Retrieves all credentials for credential recovery. - * - * @return A flow of a list of [CredentialRecovery] objects representing the credentials for recovery. - */ - override fun getAllCredentials(): Flow> { - return getInstance().storableCredentialQueries.fetchAllCredentials() - .asFlow() - .map { - it.executeAsList().map { credential -> - CredentialRecovery( - restorationId = credential.recoveryId, - credentialData = credential.credentialData, - revoked = credential.revoked != 0 - ) - } - } - } - - /** - * Inserts an available claim for a specific credential. - * - * @param credentialId The ID of the credential. - * @param claim The claim to insert. - */ - override fun insertAvailableClaim(credentialId: String, claim: String) { - getInstance().availableClaimsQueries.insert(credentialId, claim) - } - - /** - * Inserts the available claims for a given credential ID. - * - * @param credentialId the ID of the credential - * @param claims an array of available claims to be inserted - */ - override fun insertAvailableClaims(credentialId: String, claims: Array) { - getInstance().availableClaimsQueries.transaction { - claims.forEach { - getInstance().availableClaimsQueries.insert(credentialId, it) - } - } - } - - /** - * Retrieves the available claims for a given credential ID. - * - * @param credentialId The ID of the credential. - * @return A flow that emits an array of AvailableClaims. - */ - override fun getAvailableClaimsByCredentialId(credentialId: String): Flow> { - return getInstance().availableClaimsQueries.fetchAvailableClaimsByCredentialId(credentialId) - .asFlow() - .map { claims -> - claims.executeAsList().toTypedArray() - } - } - - /** - * Retrieves the available claims for a given claim. - * - * @param claim The claim for which the available claims are to be retrieved. - * @return A flow of arrays of AvailableClaims representing the available claims for the given claim. - */ - override fun getAvailableClaimsByClaim(claim: String): Flow> { - return getInstance().availableClaimsQueries.fetchAvailableClaimsByClaim(claim) - .asFlow() - .map { claims -> - claims.executeAsList().toTypedArray() - } - } - - /** - * Retrieves the secret link associated with the current instance. - * - * @return A [Flow] emitting the secret link as a nullable [String]. - */ - override fun getLinkSecret(): Flow { - return getInstance().linkSecretQueries.fetchLinkSecret() - .asFlow() - .map { - val result = it.executeAsList() - if (result.isEmpty()) { - null - } else { - it.executeAsOne() - } - } - } - - /** - * Retrieves the metadata associated with a credential request. - * - * @param linkSecretName The name of the link secret used for the credential request. - * @return A [Flow] emitting the [CredentialRequestMeta] object for the specified link secret name, - * or null if no metadata is found. - */ - override fun getCredentialMetadata(linkSecretName: String): Flow { - return getInstance().credentialMetadataQueries.fetchCredentialMetadata(linkSecretName = linkSecretName) - .asFlow() - .map { - val metadata = it.executeAsOne() - CredentialRequestMeta( - linkSecretName = metadata.linkSecretName, - json = metadata.json - ) - } - } - - /** - * Revokes an existing credential using the credential ID. - * - * @param credentialId The ID of the credential to be revoked - */ - override fun revokeCredential(credentialId: String) { - getInstance().storableCredentialQueries.revokeCredentialById(credentialId) - } - - /** - * Provides a flow to listen for revoked credentials. - */ - override fun observeRevokedCredentials(): Flow> { - return getInstance().storableCredentialQueries.observeRevokedCredential() - .asFlow() - .map { - it.executeAsList().map { credential -> - CredentialRecovery( - restorationId = credential.recoveryId, - credentialData = credential.credentialData, - revoked = true - ) - } - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pluto/data/DbConnection.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pluto/data/DbConnection.kt deleted file mode 100644 index 105547de5..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pluto/data/DbConnection.kt +++ /dev/null @@ -1,24 +0,0 @@ -package io.iohk.atala.prism.walletsdk.pluto.data - -import app.cash.sqldelight.db.SqlDriver - -/** - * DbConnection class represents a connection to the database. - */ -expect class DbConnection() { - var driver: SqlDriver? - - /** - * Establishes a connection to the database. - * - * @param context The context data required for establishing the connection. This can be null in some cases. - * - * @return The PrismPlutoDb instance representing the connection to the database. - */ - suspend fun connectDb(context: Any?): SqlDriver -} - -/** - * Represents the current connection status of the SQL driver. - */ -expect val SqlDriver.isConnected: Boolean diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/PolluxConstants.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/PolluxConstants.kt deleted file mode 100644 index 051d7bf01..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/PolluxConstants.kt +++ /dev/null @@ -1,17 +0,0 @@ -package io.iohk.atala.prism.walletsdk.pollux - -const val JWT_DELIMITER = "." -const val JWT_PARTS_SIZE = 3 -const val JWT_SECOND_PART = 1 -const val EC = "EC" -const val OPTIONS = "options" -const val DOMAIN = "domain" -const val CHALLENGE = "challenge" -const val CONTEXT = "@context" -const val CONTEXT_URL = "https://www.w3.org/2018/credentials/v1" -const val TYPE = "type" -const val VERIFIABLE_PRESENTATION = "VerifiablePresentation" -const val NONCE = "nonce" -const val VP = "vp" -const val VERIFIABLE_CREDENTIAL = "verifiableCredential" -const val VC = "vc" diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/PolluxImpl.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/PolluxImpl.kt deleted file mode 100644 index 9c7cfc2c2..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/PolluxImpl.kt +++ /dev/null @@ -1,576 +0,0 @@ -package io.iohk.atala.prism.walletsdk.pollux - -import anoncreds_wrapper.CredentialDefinition -import anoncreds_wrapper.CredentialDefinitionId -import anoncreds_wrapper.CredentialOffer -import anoncreds_wrapper.CredentialRequest -import anoncreds_wrapper.CredentialRequestMetadata -import anoncreds_wrapper.CredentialRequests -import anoncreds_wrapper.LinkSecret -import anoncreds_wrapper.Presentation -import anoncreds_wrapper.PresentationRequest -import anoncreds_wrapper.Prover -import anoncreds_wrapper.RequestedAttribute -import anoncreds_wrapper.RequestedPredicate -import anoncreds_wrapper.Schema -import anoncreds_wrapper.SchemaId -import com.nimbusds.jose.JWSAlgorithm -import com.nimbusds.jose.JWSHeader -import com.nimbusds.jose.crypto.ECDSASigner -import com.nimbusds.jose.crypto.bc.BouncyCastleProviderSingleton -import com.nimbusds.jwt.JWTClaimsSet -import com.nimbusds.jwt.SignedJWT -import io.iohk.atala.prism.apollo.base64.base64UrlDecoded -import io.iohk.atala.prism.apollo.utils.KMMEllipticCurve -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Castor -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Pollux -import io.iohk.atala.prism.walletsdk.domain.models.Api -import io.iohk.atala.prism.walletsdk.domain.models.ApiImpl -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentBase64 -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentDescriptor -import io.iohk.atala.prism.walletsdk.domain.models.Credential -import io.iohk.atala.prism.walletsdk.domain.models.CredentialType -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.PolluxError -import io.iohk.atala.prism.walletsdk.domain.models.StorableCredential -import io.iohk.atala.prism.walletsdk.domain.models.httpClient -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PrivateKey -import io.iohk.atala.prism.walletsdk.pollux.models.AnonCredential -import io.iohk.atala.prism.walletsdk.pollux.models.JWTCredential -import io.iohk.atala.prism.walletsdk.pollux.models.W3CCredential -import io.iohk.atala.prism.walletsdk.prismagent.protocols.proofOfPresentation.RequestPresentation -import io.iohk.atala.prism.walletsdk.prismagent.shared.KeyValue -import io.ktor.http.HttpHeaders -import io.ktor.http.HttpMethod -import kotlinx.serialization.json.Json -import kotlinx.serialization.json.JsonObject -import kotlinx.serialization.json.jsonArray -import kotlinx.serialization.json.jsonObject -import kotlinx.serialization.json.jsonPrimitive -import org.bouncycastle.jce.ECNamedCurveTable -import org.bouncycastle.jce.provider.BouncyCastleProvider -import org.bouncycastle.jce.spec.ECNamedCurveSpec -import org.didcommx.didcomm.common.Typ -import java.math.BigInteger -import java.security.KeyFactory -import java.security.interfaces.ECPrivateKey -import java.security.spec.ECParameterSpec -import java.security.spec.ECPrivateKeySpec - -/** - * Class representing the implementation of the Pollux interface. - * - * @property castor An API object for interacting with the Castor system. - */ -class PolluxImpl( - val castor: Castor, - private val api: Api = ApiImpl(httpClient()) -) : Pollux { - - /** - * Parses a verifiable credential from the given data. - * - * @param data The data representing the*/ - @Throws(PolluxError.InvalidCredentialError::class) - fun parseVerifiableCredential(data: String): Credential { - return try { - JWTCredential(data) - } catch (e: Exception) { - try { - Json.decodeFromString(data) - } catch (e: Exception) { - throw PolluxError.InvalidCredentialError(cause = e.cause) - } - } - } - - /** - * Parses the given JSON data into a verifiable credential of the specified type. - * - * @param jsonData The JSON data representing the verifiable credential. - * @param type The type of the verifiable credential. - * @param linkSecret The optional link secret for the credential. - * @param credentialMetadata The metadata for the credential request. - * @return The parsed credential. - */ - override suspend fun parseCredential( - jsonData: String, - type: CredentialType, - linkSecret: LinkSecret?, - credentialMetadata: CredentialRequestMetadata? - ): Credential { - return when (type) { - CredentialType.JWT -> { - JWTCredential(jsonData) - } - - CredentialType.ANONCREDS_ISSUE -> { - if (linkSecret == null) { - throw Error("LinkSecret is required") - } - if (credentialMetadata == null) { - throw Error("Invalid credential metadata") - } - - val cred = anoncreds_wrapper.Credential(jsonData) - - val values: Map = - cred.getValues().values.mapValues { - AnonCredential.Attribute(raw = it.value.raw, encoded = it.value.encoded) - } - - return AnonCredential( - schemaID = cred.getSchemaId(), - credentialDefinitionID = cred.getCredDefId(), - signatureJson = cred.getSignatureJson(), - signatureCorrectnessProofJson = cred.getSignatureCorrectnessProofJson(), - revocationRegistryId = cred.getRevRegId(), - revocationRegistryJson = cred.getRevRegJson(), - witnessJson = cred.getWitnessJson() ?: "", - json = cred.getJson(), - values = values - ) - } - - else -> { - throw PolluxError.InvalidCredentialError() - } - } - } - - /** - * Restores a credential using the provided restoration identifier and credential data. - * - * @param restorationIdentifier The restoration identifier of the credential. - * @param credentialData The byte array containing the credential data. - * @return The restored credential. - */ - override fun restoreCredential( - restorationIdentifier: String, - credentialData: ByteArray, - revoked: Boolean - ): Credential { - val cred: Credential - when (restorationIdentifier) { - "jwt+credential" -> { - cred = JWTCredential(credentialData.decodeToString()) - } - - "anon+credential" -> { - cred = AnonCredential.fromStorableData(credentialData) - } - - "w3c+credential" -> { - cred = Json.decodeFromString(credentialData.decodeToString()) - } - - else -> { - throw PolluxError.InvalidCredentialError() - } - } - cred.revoked = revoked - return cred - } - - /** - * Creates a verifiable presentation JSON Web Token (JWT) for the given subjectDID, privateKey, credential, and requestPresentationJson. - * - * @param subjectDID The DID of the subject for whom the presentation is being created. - * @param privateKey The private key used to sign the JWT. - * @param credential The credential to be included in the presentation. - * @param requestPresentationJson The JSON object representing the request presentation. - * @return The created verifiable presentation JWT. - */ - @Throws(PolluxError.NoDomainOrChallengeFound::class) - override fun processCredentialRequestJWT( - subjectDID: DID, - privateKey: PrivateKey, - offerJson: JsonObject - ): String { - val parsedPrivateKey = parsePrivateKey(privateKey) - val domain = getDomain(offerJson) ?: throw PolluxError.NoDomainOrChallengeFound() - val challenge = getChallenge(offerJson) ?: throw PolluxError.NoDomainOrChallengeFound() - return signClaimsRequestCredentialJWT(subjectDID, parsedPrivateKey, domain, challenge) - } - - /** - * Creates a verifiable presentation JSON Web Token (JWT) for the given subjectDID, privateKey, credential, and requestPresentationJson. - * - * @param subjectDID The DID of the subject for whom the presentation is being created. - * @param privateKey The private key used to sign the JWT. - * @param credential The credential to be included in the presentation. - * @param requestPresentationJson The JSON object representing the request presentation. - * @return The created verifiable presentation JWT. - */ - @Throws(PolluxError.NoDomainOrChallengeFound::class) - override fun createVerifiablePresentationJWT( - subjectDID: DID, - privateKey: PrivateKey, - credential: Credential, - requestPresentationJson: JsonObject - ): String { - val parsedPrivateKey = parsePrivateKey(privateKey) - val domain = - getDomain(requestPresentationJson) ?: throw PolluxError.NoDomainOrChallengeFound() - val challenge = - getChallenge(requestPresentationJson) ?: throw PolluxError.NoDomainOrChallengeFound() - return signClaimsProofPresentationJWT( - subjectDID, - parsedPrivateKey, - credential, - domain, - challenge - ) - } - - /** - * Converts the map of [anoncreds_wrapper.AttributeInfoValue] values to a list of [RequestedAttribute]. - * - * @return The list of [RequestedAttribute]. - */ - private fun Map.toListRequestedAttribute(): List { - return this.keys.toList().map { - RequestedAttribute( - referent = it, - revealed = true - ) - } - } - - /** - * Converts the map of [anoncreds_wrapper.PredicateInfoValue] values to a list of [RequestedPredicate]. - * - * @receiver The map of [anoncreds_wrapper.PredicateInfoValue] values. - * @return The list of [RequestedPredicate]. - */ - private fun Map.toListRequestedPredicate(): List { - return this.keys.toList().map { - RequestedPredicate(it) - } - } - - override suspend fun createVerifiablePresentationAnoncred( - request: RequestPresentation, - credential: AnonCredential, - linkSecret: LinkSecret - ): Presentation { - if (request.attachments.isEmpty() || request.attachments[0].data !is AttachmentBase64) { - throw Error("") - // TODO: Custom pollux error - } - val attachmentBase64 = request.attachments[0].data as AttachmentBase64 - val presentationRequest = PresentationRequest(attachmentBase64.base64.base64UrlDecoded) - val cred = anoncreds_wrapper.Credential(credential.id) - - val requestedAttributes = - presentationRequest.getRequestedAttributes().toListRequestedAttribute() - val requestedPredicate = - presentationRequest.getRequestedPredicates().toListRequestedPredicate() - - val credentialRequests = CredentialRequests( - credential = cred, - requestedAttribute = requestedAttributes, - requestedPredicate = requestedPredicate - ) - val schema = getSchema(credential.schemaID) - - val schemaId = credential.schemaID - val schemaMap: Map = mapOf(Pair(schemaId, schema)) - - val credentialDefinition = getCredentialDefinition(credential.credentialDefinitionID) - val credDefinition: Map = mapOf( - Pair(credential.credentialDefinitionID, credentialDefinition) - ) - - return Prover().createPresentation( - presentationRequest = presentationRequest, - credentials = listOf(credentialRequests), - selfAttested = null, - linkSecret = linkSecret, - schemas = schemaMap, - credentialDefinitions = credDefinition - ) - } - - /** - * Converts a [Credential] object to a [StorableCredential] object of the specified [CredentialType]. - * - * @param type The type of the [StorableCredential]. - * @param credential The [Credential] object to be converted. - * @return The converted [StorableCredential]. - */ - override fun credentialToStorableCredential( - type: CredentialType, - credential: Credential - ): StorableCredential { - return when (type) { - CredentialType.JWT -> { - (credential as JWTCredential).toStorableCredential() - } - - CredentialType.W3C -> { - (credential as W3CCredential).toStorableCredential() - } - - CredentialType.ANONCREDS_ISSUE -> { - (credential as AnonCredential).toStorableCredential() - } - - else -> { - throw PolluxError.InvalidCredentialError() - } - } - } - - /** - * Extracts the credential format from the given array of attachment descriptors. - * - * @param formats The array of attachment descriptors. - * @return The credential format as a CredentialType enum value. - */ - override fun extractCredentialFormatFromMessage(formats: Array): CredentialType { - val desiredFormats = setOf( - CredentialType.JWT.type, - CredentialType.ANONCREDS_OFFER.type, - CredentialType.ANONCREDS_REQUEST.type, - CredentialType.ANONCREDS_ISSUE.type, - CredentialType.ANONCREDS_PROOF_REQUEST.type - ) - val foundFormat = formats.find { it.format in desiredFormats } - return foundFormat?.format?.let { format -> - when (format) { - CredentialType.JWT.type -> CredentialType.JWT - CredentialType.ANONCREDS_OFFER.type -> CredentialType.ANONCREDS_OFFER - CredentialType.ANONCREDS_REQUEST.type -> CredentialType.ANONCREDS_REQUEST - CredentialType.ANONCREDS_ISSUE.type -> CredentialType.ANONCREDS_ISSUE - CredentialType.ANONCREDS_PROOF_REQUEST.type -> CredentialType.ANONCREDS_PROOF_REQUEST - else -> throw Error("$format is not a valid credential type") - } - } ?: throw Error("Unknown credential type") - } - - /** - * Processes a credential request for anonymous credentials. - * - * @param did The DID of the subject requesting the credential. - * @param offer The credential offer. - * @param linkSecret The link secret for the credential. - * @param linkSecretName The name of the link secret. - * @return A pair containing the credential request and its metadata. - */ - override suspend fun processCredentialRequestAnoncreds( - did: DID, - offer: CredentialOffer, - linkSecret: LinkSecret, - linkSecretName: String - ): Pair { - val credentialDefinition = getCredentialDefinition(offer.getCredDefId()) - - return createAnonCredentialRequest( - did = did, - credentialDefinition = credentialDefinition, - credentialOffer = offer, - linkSecret = linkSecret, - linkSecretId = linkSecretName - ) - } - - /** - * Creates a credential request for anonymous credentials. - * - * @param did The DID of the subject requesting the credential. - * @param credentialDefinition The credential definition. - * @param credentialOffer The credential offer. - * @param linkSecret The link secret for the credential. - * @param linkSecretId The name of the link secret. - * @return A Pair containing the CredentialRequest and CredentialRequestMetadata. - */ - private fun createAnonCredentialRequest( - did: DID, - credentialDefinition: CredentialDefinition, - credentialOffer: CredentialOffer, - linkSecret: LinkSecret, - linkSecretId: String - ): Pair { - val credentialRequest = Prover().createCredentialRequest( - entropy = did.toString(), - proverDid = null, - credDef = credentialDefinition, - linkSecret = linkSecret, - linkSecretId = linkSecretId, - credentialOffer = credentialOffer - ) - return Pair(credentialRequest.request, credentialRequest.metadata) - } - - /** - * Retrieves the credential definition for the specified ID. - * - * @param id The ID of the credential definition. - * @return The credential definition. - */ - override suspend fun getCredentialDefinition(id: String): CredentialDefinition { - val result = api.request( - HttpMethod.Get.value, - id, - emptyArray(), - arrayOf(KeyValue(HttpHeaders.ContentType, Typ.Encrypted.typ)), - null - ) - if (result.status == 200) { - return CredentialDefinition(result.jsonString) - } - throw PolluxError.InvalidCredentialDefinitionError() - } - - override suspend fun getSchema(schemaId: String): Schema { - val result = api.request( - HttpMethod.Get.value, - schemaId, - emptyArray(), - arrayOf(KeyValue(HttpHeaders.ContentType, Typ.Encrypted.typ)), - null - ) - - if (result.status == 200) { - val schema = (Json.parseToJsonElement(result.jsonString) as JsonObject) - if (schema.containsKey("attrNames") && schema.containsKey("issuerId")) { - val name = schema["name"]?.jsonPrimitive?.content - val version = schema["version"]?.jsonPrimitive?.content - val attrs = schema["attrNames"] - val attrNames = attrs?.jsonArray?.map { value -> value.jsonPrimitive.content } - val issuerId = - schema["issuerId"]?.jsonPrimitive?.content - return Schema( - name = name ?: throw PolluxError.InvalidCredentialError(), - version = version ?: throw PolluxError.InvalidCredentialError(), - attrNames = attrNames ?: throw PolluxError.InvalidCredentialError(), - issuerId = issuerId ?: throw PolluxError.InvalidCredentialError() - ) - } - } - throw PolluxError.InvalidCredentialDefinitionError() - } - - /** - * Parses a PrivateKey into an ECPrivateKey. - * - * @param privateKey The PrivateKey to parse. - * @return The parsed ECPrivateKey. - */ - private fun parsePrivateKey(privateKey: PrivateKey): ECPrivateKey { - val curveName = KMMEllipticCurve.SECP256k1.value - val sp = ECNamedCurveTable.getParameterSpec(curveName) - val params: ECParameterSpec = ECNamedCurveSpec(sp.name, sp.curve, sp.g, sp.n, sp.h) - val privateKeySpec = ECPrivateKeySpec(BigInteger(1, privateKey.getValue()), params) - val keyFactory = KeyFactory.getInstance(EC, BouncyCastleProvider()) - return keyFactory.generatePrivate(privateKeySpec) as ECPrivateKey - } - - /** - * Returns the domain from the given JsonObject. - * - * @param jsonObject The JsonObject from which to retrieve the domain. - * @return The domain as a String, or null if not found. - */ - private fun getDomain(jsonObject: JsonObject): String? { - return jsonObject[OPTIONS]?.jsonObject?.get(DOMAIN)?.jsonPrimitive?.content - } - - /** - * Retrieves the challenge value from the given JsonObject. - * - * @param jsonObject The JsonObject from which to retrieve the challenge. - * @return The challenge value as a String, or null if not found in the JsonObject. - */ - private fun getChallenge(jsonObject: JsonObject): String? { - return jsonObject[OPTIONS]?.jsonObject?.get(CHALLENGE)?.jsonPrimitive?.content - } - - /** - * Signs the claims for a request credential JWT. - * - * @param subjectDID The DID of the subject for whom the JWT is being created. - * @param privateKey The private key used to sign the JWT. - * @param domain The domain of the JWT. - * @param challenge The challenge value for the JWT. - * @return The signed JWT as a string. - */ - private fun signClaimsRequestCredentialJWT( - subjectDID: DID, - privateKey: ECPrivateKey, - domain: String, - challenge: String - ): String { - return signClaims(subjectDID, privateKey, domain, challenge) - } - - /** - * Signs the claims for a proof presentation JSON Web Token (JWT). - * - * @param subjectDID The DID of the subject for whom the JWT is being created. - * @param privateKey The private key used to sign the JWT. - * @param credential The credential to be included in the presentation. - * @param domain The domain of the JWT. - * @param challenge The challenge value for the JWT. - * @return The signed JWT as a string. - */ - private fun signClaimsProofPresentationJWT( - subjectDID: DID, - privateKey: ECPrivateKey, - credential: Credential, - domain: String, - challenge: String - ): String { - return signClaims(subjectDID, privateKey, domain, challenge, credential) - } - - /** - * Signs the claims for a JWT. - * - * @param subjectDID The DID of the subject for whom the JWT is being created. - * @param privateKey The private key used to sign the JWT. - * @param domain The domain of the JWT. - * @param challenge The challenge value for the JWT. - * @param credential The optional credential to be included in the JWT. - * @return The signed JWT as a string. - */ - private fun signClaims( - subjectDID: DID, - privateKey: ECPrivateKey, - domain: String, - challenge: String, - credential: Credential? = null - ): String { - val vp: MutableMap> = mutableMapOf( - CONTEXT to setOf(CONTEXT_URL), - TYPE to setOf(VERIFIABLE_PRESENTATION) - ) - credential?.let { - vp[VERIFIABLE_CREDENTIAL] = listOf(it.id) - } - val claims = JWTClaimsSet.Builder() - .issuer(subjectDID.toString()) - .audience(domain) - .claim(NONCE, challenge) - .claim(VP, vp) - .build() - - // Generate a JWS header with the ES256K algorithm - val header = JWSHeader.Builder(JWSAlgorithm.ES256K) - .build() - - // Sign the JWT with the private key - val jwsObject = SignedJWT(header, claims) - val signer = ECDSASigner( - privateKey as java.security.PrivateKey, - com.nimbusds.jose.jwk.Curve.SECP256K1 - ) - val provider = BouncyCastleProviderSingleton.getInstance() - signer.jcaContext.provider = provider - jwsObject.sign(signer) - - // Serialize the JWS object to a string - return jwsObject.serialize() - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/models/AnonCredential.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/models/AnonCredential.kt deleted file mode 100644 index 5886ab112..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/models/AnonCredential.kt +++ /dev/null @@ -1,154 +0,0 @@ -package io.iohk.atala.prism.walletsdk.pollux.models - -import io.iohk.atala.prism.walletsdk.domain.models.Claim -import io.iohk.atala.prism.walletsdk.domain.models.ClaimType -import io.iohk.atala.prism.walletsdk.domain.models.Credential -import io.iohk.atala.prism.walletsdk.domain.models.StorableCredential -import kotlinx.serialization.Serializable -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json - -/** - * Represents an anonymous verifiable credential that contains information about an entity or identity. - * - * This class implements the [Credential] interface and provides methods for converting the credential - * to a storable format and restoring it from a storable format. - * - * @param schemaID The ID of the credential's schema. - * @param credentialDefinitionID The ID of the credential's definition. - * @param values The values of the attributes in the credential. - * @param signatureJson The JSON representation of the credential's signature. - * @param signatureCorrectnessProofJson The JSON representation of the credential's signature correctness proof. - * @param revocationRegistryId The ID of the credential's revocation registry (optional). - * @param revocationRegistryJson The JSON representation of the credential's revocation registry (optional). - * @param witnessJson The JSON representation of the credential's witness. - * @param json The JSON representation of the credential. - */ -@Serializable -data class AnonCredential( - val schemaID: String, - val credentialDefinitionID: String, - val values: Map, - val signatureJson: String, - val signatureCorrectnessProofJson: String, - val revocationRegistryId: String?, - val revocationRegistryJson: String?, - val witnessJson: String, - private val json: String -) : Credential { - - /** - * Represents an attribute in a verifiable credential. - * - * @property raw The raw value of the attribute as a string. - * @property encoded The encoded value of the attribute as a string. - */ - @Serializable - data class Attribute( - val raw: String, - val encoded: String - ) - - override val id: String - get() = json - - override val issuer: String - get() = "" - - override val subject: String? - get() = null - - override val claims: Array - get() = values.map { - Claim(key = it.key, value = ClaimType.StringValue(it.value.raw)) - }.toTypedArray() - - override val properties: Map - get() { - val properties = mutableMapOf() - properties["schemaID"] = this.schemaID - properties["credentialDefinitionID"] = this.credentialDefinitionID - properties["signatureJson"] = this.signatureJson - properties["signatureCorrectnessProofJson"] = this.signatureCorrectnessProofJson - properties["witnessJson"] = this.witnessJson - - revocationRegistryId?.map { properties["revocationRegistryId"] = it } - revocationRegistryJson?.map { properties["revocationRegistryJson"] = it } - - return properties.toMap() - } - - override var revoked: Boolean? = null - - /** - * Converts the current credential object into a storable credential object. - * - * @return The converted storable credential object. - */ - fun toStorableCredential(): StorableCredential { - val c = this - return object : StorableCredential { - override val id: String - get() = c.id - - override val issuer: String - get() = c.issuer - - override val subject: String? - get() = c.subject - - override val claims: Array - get() = c.claims - - override val properties: Map - get() = c.properties - - override val recoveryId: String - get() = "anon+credential" - - override val credentialData: ByteArray - get() = Json.encodeToString(c).toByteArray() - - override val credentialCreated: String? - get() = null - - override val credentialUpdated: String? - get() = null - - override val credentialSchema: String? - get() = c.schemaID - - override val validUntil: String? - get() = null - - override var revoked: Boolean? = c.revoked - - override val availableClaims: Array - get() = c.claims.map { it.key }.toTypedArray() - - /** - * Converts a storable credential to a regular credential. - * - * @return The converted Credential object. - */ - override fun fromStorableCredential(): Credential { - return c - } - } - } - - companion object { - /** - * Converts a byte array of storable credential data to an AnonCredential object. - * - * @param data The byte array containing the storable credential data. - * @return The converted AnonCredential object. - */ - @JvmStatic - fun fromStorableData(data: ByteArray): AnonCredential { - val dataString = data.decodeToString() - val cred = Json.decodeFromString(dataString) - return cred - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/models/AnoncredPayload.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/models/AnoncredPayload.kt deleted file mode 100644 index 3accb535d..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/models/AnoncredPayload.kt +++ /dev/null @@ -1,24 +0,0 @@ -package io.iohk.atala.prism.walletsdk.pollux.models - -import kotlinx.serialization.SerialName - -/** - * Represents the payload of an anonymous credential. - * - * @property schemaId The ID of the schema associated with the credential. - * @property credDefId The ID of the credential definition associated with the credential. - * @property keyCorrectnessProof The proof of correctness of the public key used for signing the credential. - * @property nonce The cryptographic nonce used for the proof of correctness. - * @property methodName The method name for the anonymous credential. - */ -data class AnoncredPayload( - @SerialName("schema_id") - val schemaId: String, - @SerialName("cred_def_id") - val credDefId: String, - @SerialName("key_correctness_proof") - val keyCorrectnessProof: KeyCorrectnessProof, - val nonce: String, - @SerialName("method_name") - val methodName: String -) diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/models/CredentialRequest.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/models/CredentialRequest.kt deleted file mode 100644 index a709312f7..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/models/CredentialRequest.kt +++ /dev/null @@ -1,151 +0,0 @@ -package io.iohk.atala.prism.walletsdk.pollux.models - -import io.iohk.atala.prism.walletsdk.domain.models.Credential -import kotlinx.serialization.EncodeDefault -import kotlinx.serialization.ExperimentalSerializationApi -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable - -/** - * The `CredentialRequest` interface represents a request for verifiable credentials. - * - * @property cred_def_id The ID of the credential definition. - * @property blinded_ms The blinded master secret for the credential request. - * @property blinded_ms_correctness_proof The correctness proof for the blinded master secret. - * @property entropy The entropy for the credential request. - * @property nonce The nonce for the credential request. - */ -@Suppress("ktlint:standard:property-naming") -interface CredentialRequest { - val cred_def_id: String - val blinded_ms: CredentialRequestBlindedMS - val blinded_ms_correctness_proof: CredentialRequestBlindedMSCorrectnessProof - val entropy: String - val nonce: String -} - -/** - * Represents the blinded master secret used in the credential request. - */ -interface CredentialRequestBlindedMS { - val u: String - val ur: String -} - -/** - * This interface represents a blinded master secret correctness proof for a credential request. - * - * @property c The blinded master secret contribution to the proof. - * @property v_dash_cap The value used in the proof calculation. - * @property m_caps The map of attribute names to their corresponding blinded value commitments. - */ -@Suppress("ktlint:standard:property-naming") -interface CredentialRequestBlindedMSCorrectnessProof { - val c: String - val v_dash_cap: String - val m_caps: Map -} - -/** - * Represents the blinding data used in the Link-Secret protocol. - * This class is serialized and deserialized using Kotlinx Serialization library. - * - * @param vPrime The blinding factor generated by the Holder and sent to the Issuer. - * @param vrPrime The blinded master secret generated by the Holder. Default value is null. - */ -@Serializable -data class LinkSecretBlindingData -@OptIn(ExperimentalSerializationApi::class) -constructor( - @SerialName("v_prime") - var vPrime: String, - @SerialName("vr_prime") - @EncodeDefault - var vrPrime: String? = null -) - -/** - * Represents a credential definition. - * - * @property schemaId The unique identifier of the schema associated with the credential definition. - * @property type The type of the credential definition. - * @property tag The tag associated with the credential definition. - * @property value An array of values associated with the credential definition. - * @property issuerId The unique identifier of the issuer of the credential definition. - */ -data class CredentialDefinition( - val schemaId: String, - val type: String, - val tag: String, - val value: Array, - val issuerId: String -) { - /** - * Checks if this CredentialDefinition object is equal to the specified object. - * - * Two CredentialDefinition objects are considered equal if they have the same values for the following properties: - * - [schemaId] - * - [type] - * - [tag] - * - [value] - * - [issuerId] - * - * @param other The object to compare with this CredentialDefinition object. - * @return true if the specified object is equal to this CredentialDefinition object, false otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (javaClass != other?.javaClass) return false - - other as CredentialDefinition - - if (schemaId != other.schemaId) return false - if (type != other.type) return false - if (tag != other.tag) return false - if (!value.contentEquals(other.value)) return false - if (issuerId != other.issuerId) return false - - return true - } - - /** - * Calculates the hash code of the [CredentialDefinition] object. - * - * The hash code is computed based on the values of the following properties: - * - [schemaId] - * - [type] - * - [tag] - * - [value] - * - [issuerId] - * - * @return The hash code of the [CredentialDefinition] object. - */ - override fun hashCode(): Int { - var result = schemaId.hashCode() - result = 31 * result + type.hashCode() - result = 31 * result + tag.hashCode() - result = 31 * result + value.contentHashCode() - result = 31 * result + issuerId.hashCode() - return result - } -} - -/** - * Represents an interface for a verifiable credential that has been issued. - * - * Implementing classes are expected to provide implementation for all properties - * and functions defined in this interface. - */ -interface CredentialIssued : Credential { - val values: List> -} - -/** - * Represents a credential value, which consists of an encoded value and its raw value. - * - * Implementing classes are expected to provide implementation for both [encoded] and [raw] properties. - */ -interface CredentialValue { - val encoded: String - val raw: String -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/models/CredentialRequestMeta.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/models/CredentialRequestMeta.kt deleted file mode 100644 index 1857b3360..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/models/CredentialRequestMeta.kt +++ /dev/null @@ -1,31 +0,0 @@ -package io.iohk.atala.prism.walletsdk.pollux.models - -import anoncreds_wrapper.CredentialRequestMetadata - -/** - * Represents the metadata for a credential request. - * - * @property linkSecretName The name of the link secret. - * @property json The json string from the wrapper credential request metadata. - */ -data class CredentialRequestMeta( - var linkSecretName: String, - var json: String -) { - companion object { - /** - * Converts a [CredentialRequestMetadata] object into a [CredentialRequestMeta] object. - * - * @param metadata The [CredentialRequestMetadata] object to convert. - * @return The converted [CredentialRequestMeta] object. - */ - @JvmStatic - fun fromCredentialRequestMetadata(metadata: CredentialRequestMetadata): CredentialRequestMeta { - return CredentialRequestMeta( - // TODO: Remove the `replace` when anoncreds-kmp 0.4.3 is published. 0.4.2 has an issue where getLinkSecretName returns a string with double quotation. - linkSecretName = metadata.getLinkSecretName().replace("\"", ""), - json = metadata.getJson() - ) - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/models/JWTCredential.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/models/JWTCredential.kt deleted file mode 100644 index 5953f17e3..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/models/JWTCredential.kt +++ /dev/null @@ -1,158 +0,0 @@ -package io.iohk.atala.prism.walletsdk.pollux.models - -import io.iohk.atala.prism.walletsdk.domain.models.Claim -import io.iohk.atala.prism.walletsdk.domain.models.ClaimType -import io.iohk.atala.prism.walletsdk.domain.models.Credential -import io.iohk.atala.prism.walletsdk.domain.models.JWTPayload -import io.iohk.atala.prism.walletsdk.domain.models.StorableCredential -import kotlinx.serialization.decodeFromString -import kotlinx.serialization.json.Json -import java.util.Base64 - -/** - * Represents a JSON Web Token (JWT) credential. - * - * This class provides a way to parse and extract information from a JWT string. - * It implements the Credential interface and provides implementations for all its properties and functions. - * - * @property data The original JWT string representation of the credential. - * @property jwtString The JWT string representation of the credential. - * @property jwtPayload The parsed JWT payload containing the credential information. - */ -data class JWTCredential(val data: String) : Credential { - private var jwtString: String = data - var jwtPayload: JWTPayload - - init { - val jwtParts = jwtString.split(".") - require(jwtParts.size == 3) { "Invalid JWT string" } - val credentialString = jwtParts[1] - val base64Data = Base64.getUrlDecoder().decode(credentialString) - val jsonString = base64Data.toString(Charsets.UTF_8) - - val json = Json { ignoreUnknownKeys = true } - this.jwtPayload = json.decodeFromString(jsonString) - } - - override val id: String - get() = jwtString - - override val issuer: String - get() = jwtPayload.iss - - override val subject: String? - get() = jwtPayload.sub - - override val claims: Array - get() = jwtPayload.verifiableCredential.credentialSubject.map { - Claim(key = it.key, value = ClaimType.StringValue(it.value)) - }.toTypedArray() - - override val properties: Map - get() { - val properties = mutableMapOf() - properties["nbf"] = jwtPayload.nbf - properties["jti"] = jwtPayload.jti - properties["type"] = jwtPayload.verifiableCredential.type - properties["aud"] = jwtPayload.aud - properties["id"] = jwtString - - jwtPayload.exp?.let { properties["exp"] = it } - jwtPayload.verifiableCredential.credentialSchema?.let { - properties["schema"] = it.id - } - jwtPayload.verifiableCredential.credentialStatus?.let { - properties["credentialStatus"] = it.type - } - jwtPayload.verifiableCredential.refreshService?.let { - properties["refreshService"] = it.type - } - jwtPayload.verifiableCredential.evidence?.let { - properties["evidence"] = it.type - } - jwtPayload.verifiableCredential.termsOfUse?.let { - properties["termsOfUse"] = it.type - } - - return properties.toMap() - } - - override var revoked: Boolean? = null - - /** - * Converts the current instance of [JWTCredential] to a [StorableCredential]. - * - * @return The converted [StorableCredential]. - */ - fun toStorableCredential(): StorableCredential { - val c = this - return object : StorableCredential { - override val id: String - get() = jwtString - override val recoveryId: String - get() = "jwt+credential" - override val credentialData: ByteArray - get() = c.data.toByteArray() - - override val issuer: String - get() = c.issuer - - override val subject: String? - get() = c.subject - override val credentialCreated: String? - get() = null - override val credentialUpdated: String? - get() = null - override val credentialSchema: String? - get() = c.jwtPayload.verifiableCredential.credentialSchema?.type - override val validUntil: String? - get() = null - override var revoked: Boolean? = c.revoked - override val availableClaims: Array - get() = c.claims.map { it.key }.toTypedArray() - - override val claims: Array - get() = jwtPayload.verifiableCredential.credentialSubject.map { - Claim(key = it.key, value = ClaimType.StringValue(it.value)) - }.toTypedArray() - - override val properties: Map - get() { - val properties = mutableMapOf() - properties["nbf"] = jwtPayload.nbf - properties["jti"] = jwtPayload.jti - properties["type"] = jwtPayload.verifiableCredential.type - properties["aud"] = jwtPayload.aud - properties["id"] = jwtString - - jwtPayload.exp?.let { properties["exp"] = it } - jwtPayload.verifiableCredential.credentialSchema?.let { - properties["schema"] = it.id - } - jwtPayload.verifiableCredential.credentialStatus?.let { - properties["credentialStatus"] = it.type - } - jwtPayload.verifiableCredential.refreshService?.let { - properties["refreshService"] = it.type - } - jwtPayload.verifiableCredential.evidence?.let { - properties["evidence"] = it.type - } - jwtPayload.verifiableCredential.termsOfUse?.let { - properties["termsOfUse"] = it.type - } - - return properties.toMap() - } - - /** - * Converts the current instance of [JWTCredential] to a [Credential]. - * - * @return The converted [Credential]. - */ - override fun fromStorableCredential(): Credential { - return c - } - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/models/JWTJsonPayload.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/models/JWTJsonPayload.kt deleted file mode 100644 index ae08a2231..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/models/JWTJsonPayload.kt +++ /dev/null @@ -1,22 +0,0 @@ -package io.iohk.atala.prism.walletsdk.pollux.models - -import kotlinx.serialization.Serializable -import kotlinx.serialization.json.JsonElement - -/** - * Represents a JSON Web Token (JWT) payload as a Kotlin data class. - * - * @property iss The issuer of the token. It identifies the entity that issued the token. - * @property sub The subject of the token. It represents the entity that the token pertains to. - * @property nbf The "not before" time of the token. It specifies the time before which the token should not be considered valid. - * @property exp The expiration time of the token. It specifies the time after which the token should not be considered valid. - * @property vc The JSON payload contained within the token. - */ -@Serializable -data class JWTJsonPayload @JvmOverloads constructor( - val iss: String? = null, - val sub: String? = null, - val nbf: Long? = null, - val exp: Long? = null, - val vc: JsonElement -) diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/models/KeyCorrectnessProof.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/models/KeyCorrectnessProof.kt deleted file mode 100644 index 60b9616d1..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/models/KeyCorrectnessProof.kt +++ /dev/null @@ -1,20 +0,0 @@ -package io.iohk.atala.prism.walletsdk.pollux.models - -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable - -/** - * Represents the proof of correctness of a public key used for signing a credential. - * - * @property c The value `c` used in the proof. - * @property xzCap The value `xz_cap` used in the proof. - * @property xrCap The map of `xr_cap` values used in the proof. - */ -@Serializable -data class KeyCorrectnessProof( - val c: String, - @SerialName("xz_cap") - val xzCap: String, - @SerialName("xr_cap") - val xrCap: Map -) diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/models/W3CCredential.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/models/W3CCredential.kt deleted file mode 100644 index 1defab055..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/pollux/models/W3CCredential.kt +++ /dev/null @@ -1,256 +0,0 @@ -package io.iohk.atala.prism.walletsdk.pollux.models - -import io.iohk.atala.prism.walletsdk.domain.models.Claim -import io.iohk.atala.prism.walletsdk.domain.models.ClaimType -import io.iohk.atala.prism.walletsdk.domain.models.Credential -import io.iohk.atala.prism.walletsdk.domain.models.CredentialType -import io.iohk.atala.prism.walletsdk.domain.models.JsonString -import io.iohk.atala.prism.walletsdk.domain.models.StorableCredential -import io.iohk.atala.prism.walletsdk.domain.models.VerifiableCredentialTypeContainer -import kotlinx.serialization.Serializable -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json - -/** - * A data class representing a W3C Verifiable Credential. - * This data class conforms to the VerifiableCredential interface, which defines the properties and methods required for - * a verifiable credential. - * The W3CVerifiableCredential contains properties for the credential's context, type, ID, issuer, issuance date, - * expiration date, credential schema, credential subject, credential status, refresh service, evidence, terms of use, - * valid from date, valid until date, proof, and audience. - * - * Note: The W3CVerifiableCredential is designed to work with W3C-compliant verifiable credentials. - */ -@Serializable -data class W3CCredential @JvmOverloads constructor( - val credentialType: CredentialType = CredentialType.W3C, - val context: Array, - val type: Array, - val _id: String, - val _issuer: String, - val _subject: String?, - val issuanceDate: String, - val expirationDate: String? = null, - val credentialSchema: VerifiableCredentialTypeContainer? = null, - val credentialSubject: Map? = null, - val credentialStatus: VerifiableCredentialTypeContainer? = null, - val refreshService: VerifiableCredentialTypeContainer? = null, - val evidence: VerifiableCredentialTypeContainer? = null, - val termsOfUse: VerifiableCredentialTypeContainer? = null, - val validFrom: VerifiableCredentialTypeContainer? = null, - val validUntil: VerifiableCredentialTypeContainer? = null, - val proof: JsonString?, - val aud: Array = arrayOf() -) : Credential { - - override val id: String - get() = _id - - override val issuer: String - get() = _issuer - override val subject: String? - get() = _subject - - override val claims: Array - get() { - return credentialSubject?.let { - it.map { entry -> - Claim(key = entry.key, value = ClaimType.StringValue(entry.value)) - }.toTypedArray() - } ?: emptyArray() - } - override val properties: Map - get() { - val properties = mutableMapOf( - "issuanceDate" to issuanceDate, - "context" to context, - "type" to type, - "id" to this.id, - "aud" to aud - ) - - this.expirationDate?.let { properties["expirationDate"] = it } - this.credentialSchema?.let { properties["schema"] = it.type } - this.credentialStatus?.let { properties["credentialStatus"] = it.type } - this.refreshService?.let { properties["refreshService"] = it.type } - this.evidence?.let { properties["evidence"] = it.type } - this.termsOfUse?.let { properties["termsOfUse"] = it.type } - this.validFrom?.let { properties["validFrom"] = it.type } - this.validUntil?.let { properties["validUntil"] = it.type } - this.proof?.let { properties["proof"] = it } - - return properties.toMap() - } - - override var revoked: Boolean? = null - - /** - * Converts the current W3CCredential object to a StorableCredential object that can be stored and retrieved from a storage system. - * - * @return The converted StorableCredential object. - */ - fun toStorableCredential(): StorableCredential { - val c = this - return object : StorableCredential { - override val recoveryId: String - get() = "w3c+credential" - override val credentialData: ByteArray - get() = Json.encodeToString(c).toByteArray() - override val credentialCreated: String? - get() = null - override val credentialUpdated: String? - get() = null - override val credentialSchema: String? - get() = c.credentialSchema?.type - override val validUntil: String? - get() = null - override var revoked: Boolean? = c.revoked - override val availableClaims: Array - get() = claims.map { it.key }.toTypedArray() - - override val id: String - get() = c.id - override val issuer: String - get() = c.issuer - override val subject: String? - get() = c.subject - - override val claims: Array - get() { - return credentialSubject?.let { - it.map { entry -> - Claim(key = entry.key, value = ClaimType.StringValue(entry.value)) - }.toTypedArray() - } ?: emptyArray() - } - override val properties: Map - get() { - val properties = mutableMapOf( - "issuanceDate" to issuanceDate, - "context" to context, - "type" to type, - "id" to id, - "aud" to aud - ) - - c.expirationDate?.let { properties["expirationDate"] = it } - c.credentialSchema?.let { properties["schema"] = it.type } - c.credentialStatus?.let { properties["credentialStatus"] = it.type } - c.refreshService?.let { properties["refreshService"] = it.type } - c.evidence?.let { properties["evidence"] = it.type } - c.termsOfUse?.let { properties["termsOfUse"] = it.type } - c.validFrom?.let { properties["validFrom"] = it.type } - c.validUntil?.let { properties["validUntil"] = it.type } - c.proof?.let { properties["proof"] = it } - - return properties.toMap() - } - - /** - * Converts the current W3CCredential object to a StorableCredential object that can be stored and retrieved from a storage system. - * - * @return The converted StorableCredential object. - */ - override fun fromStorableCredential(): Credential { - return c - } - } - } - - /** - * Checks if the current W3CCredential object is equal to the specified object. - * - * Two W3CCredential objects are considered equal if they have the same values for the following properties: - * - id - * - credentialType - * - context - * - type - * - issuer - * - issuanceDate - * - expirationDate - * - credentialSchema - * - credentialSubject - * - credentialStatus - * - refreshService - * - evidence - * - termsOfUse - * - validFrom - * - validUntil - * - proof - * - aud - * - * @param other The object to compare with the current W3CCredential object. - * @return true if the objects are equal, false otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as W3CCredential - - if (id != other.id) return false - if (credentialType != other.credentialType) return false - if (!context.contentEquals(other.context)) return false - if (!type.contentEquals(other.type)) return false - if (issuer != other.issuer) return false - if (issuanceDate != other.issuanceDate) return false - if (expirationDate != other.expirationDate) return false - if (credentialSchema != other.credentialSchema) return false - if (credentialSubject != other.credentialSubject) return false - if (credentialStatus != other.credentialStatus) return false - if (refreshService != other.refreshService) return false - if (evidence != other.evidence) return false - if (termsOfUse != other.termsOfUse) return false - if (validFrom != other.validFrom) return false - if (validUntil != other.validUntil) return false - if (proof != other.proof) return false - if (!aud.contentEquals(other.aud)) return false - - return true - } - - /** - * Calculates a hash code value for the current `W3CCredential` object. - * - * The hash code is generated by combining the hash codes of the following properties: - * - `id` - * - `credentialType` - * - `context` - * - `type` - * - `issuer` - * - `issuanceDate` - * - `expirationDate` - * - `credentialSchema` - * - `credentialSubject` - * - `credentialStatus` - * - `refreshService` - * - `evidence` - * - `termsOfUse` - * - `validFrom` - * - `validUntil` - * - `proof` - * - `aud` - * - * @return The calculated hash code value. - */ - override fun hashCode(): Int { - var result = id.hashCode() - result = 31 * result + credentialType.hashCode() - result = 31 * result + context.contentHashCode() - result = 31 * result + type.contentHashCode() - result = 31 * result + issuer.hashCode() - result = 31 * result + issuanceDate.hashCode() - result = 31 * result + (expirationDate?.hashCode() ?: 0) - result = 31 * result + (credentialSchema?.hashCode() ?: 0) - result = 31 * result + credentialSubject.hashCode() - result = 31 * result + (credentialStatus?.hashCode() ?: 0) - result = 31 * result + (refreshService?.hashCode() ?: 0) - result = 31 * result + (evidence?.hashCode() ?: 0) - result = 31 * result + (termsOfUse?.hashCode() ?: 0) - result = 31 * result + (validFrom?.hashCode() ?: 0) - result = 31 * result + (validUntil?.hashCode() ?: 0) - result = 31 * result + proof.hashCode() - result = 31 * result + aud.contentHashCode() - return result - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/ConnectionManager.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/ConnectionManager.kt deleted file mode 100644 index 7deaee29c..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/ConnectionManager.kt +++ /dev/null @@ -1,249 +0,0 @@ -@file:Suppress("ktlint:standard:import-ordering") - -package io.iohk.atala.prism.walletsdk.prismagent - -import io.iohk.atala.prism.apollo.base64.base64UrlDecoded -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Castor -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Mercury -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Pluto -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Pollux -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentBase64 -import io.iohk.atala.prism.walletsdk.domain.models.CredentialType -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.DIDPair -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.prismagent.connectionsmanager.ConnectionsManager -import io.iohk.atala.prism.walletsdk.prismagent.connectionsmanager.DIDCommConnection -import io.iohk.atala.prism.walletsdk.prismagent.mediation.MediationHandler -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType -import io.iohk.atala.prism.walletsdk.prismagent.protocols.issueCredential.IssueCredential -import io.iohk.atala.prism.walletsdk.prismagent.protocols.revocation.RevocationNotification -import java.time.Duration -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.Job -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.first -import kotlinx.coroutines.launch -import kotlin.jvm.Throws - -/** - * ConnectionManager is responsible for managing connections and communication between entities. - * - * @property mercury The instance of the Mercury interface used for sending and receiving messages. - * @property castor The instance of the Castor interface used for working with DIDs. - * @property pluto The instance of the Pluto interface used for storing messages and connection information. - * @property mediationHandler The instance of the MediationHandler interface used for handling mediation. - * @property experimentLiveModeOptIn Flag to opt in or out of the experimental feature mediator live mode, using websockets. - * @property pairings The mutable list of DIDPair representing the connections managed by the ConnectionManager. - */ -class ConnectionManager @JvmOverloads constructor( - private val mercury: Mercury, - private val castor: Castor, - private val pluto: Pluto, - internal val mediationHandler: MediationHandler, - private var pairings: MutableList, - private val pollux: Pollux, - private val experimentLiveModeOptIn: Boolean = false, - private val scope: CoroutineScope = CoroutineScope(Dispatchers.IO) -) : ConnectionsManager, DIDCommConnection { - - var fetchingMessagesJob: Job? = null - - /** - * Starts the process of fetching messages at a regular interval. - * - * @param requestInterval The time interval (in seconds) between message fetch requests. - * Defaults to 5 seconds if not specified. - */ - @JvmOverloads - fun startFetchingMessages(requestInterval: Int = 5) { - // Check if the job for fetching messages is already running - if (fetchingMessagesJob == null) { - // Launch a coroutine in the provided scope - fetchingMessagesJob = scope.launch { - // Retrieve the current mediator DID - val currentMediatorDID = mediationHandler.mediatorDID - // Resolve the DID document for the mediator - val mediatorDidDoc = castor.resolveDID(currentMediatorDID.toString()) - var serviceEndpoint: String? = null - if (experimentLiveModeOptIn) { - // Loop through the services in the DID document to find a WebSocket endpoint - mediatorDidDoc.services.forEach { - if (it.serviceEndpoint.uri.contains("wss://") || it.serviceEndpoint.uri.contains("ws://")) { - serviceEndpoint = it.serviceEndpoint.uri - return@forEach // Exit loop once the WebSocket endpoint is found - } - } - - // If a WebSocket service endpoint is found - serviceEndpoint?.let { serviceEndpointUrl -> - // Listen for unread messages on the WebSocket endpoint - mediationHandler.listenUnreadMessages( - serviceEndpointUrl - ) { arrayMessages -> - processMessages(arrayMessages) - } - } - } - - // Fallback mechanism if no WebSocket service endpoint is available - if (serviceEndpoint == null) { - while (true) { - // Continuously await and process new messages - awaitMessages().collect { array -> - processMessages(array) - } - // Wait for the specified request interval before fetching new messages - delay(Duration.ofSeconds(requestInterval.toLong()).toMillis()) - } - } - } - - // Start the coroutine if it's not already active - fetchingMessagesJob?.let { - if (it.isActive) return - it.start() - } - } - } - - fun stopConnection() { - fetchingMessagesJob?.cancel() - } - - /** - * Suspends the current coroutine and boots the registered mediator associated with the mediator handler. - * If no mediator is available, a [PrismAgentError.NoMediatorAvailableError] is thrown. - * - * @throws PrismAgentError.NoMediatorAvailableError if no mediator is available. - */ - suspend fun startMediator() { - mediationHandler.bootRegisteredMediator() ?: throw PrismAgentError.NoMediatorAvailableError() - } - - /** - * Registers a mediator with the given host DID. - * - * @param host The DID of the entity to mediate with. - */ - suspend fun registerMediator(host: DID) { - mediationHandler.achieveMediation(host).collect { - println("Achieve mediation") - } - } - - /** - * Sends a message over the connection. - * - * @param message The message to send. - * @return The response message, if one is received. - */ - @Throws(PrismAgentError.NoMediatorAvailableError::class) - override suspend fun sendMessage(message: Message): Message? { - if (mediationHandler.mediator == null) { - throw PrismAgentError.NoMediatorAvailableError() - } - pluto.storeMessage(message) - return mercury.sendMessageParseResponse(message) - } - - /** - * Awaits messages from the connection. - * - * @return An array of messages received from the connection. - */ - override suspend fun awaitMessages(): Flow>> { - return mediationHandler.pickupUnreadMessages(NUMBER_OF_MESSAGES) - } - - /** - * Adds a connection to the manager. - * - * @param paired The [DIDPair] representing the connection to be added. - */ - override suspend fun addConnection(paired: DIDPair) { - if (pairings.contains(paired)) return - pluto.storeDIDPair(paired.host, paired.receiver, paired.name ?: "") - pairings.add(paired) - } - - /** - * Removes a connection from the manager. - * - * @param pair The [DIDPair] representing the connection to be removed. - * @return The [DIDPair] object that was removed from the manager, or null if the connection was not found. - */ - override suspend fun removeConnection(pair: DIDPair): DIDPair? { - val index = pairings.indexOf(pair) - if (index > -1) { - pairings.removeAt(index) - } - return null - } - - internal fun processMessages(arrayMessages: Array>) { - scope.launch { - val messagesIds = mutableListOf() - val messages = mutableListOf() - arrayMessages.map { pair -> - messagesIds.add(pair.first) - messages.add(pair.second) - } - - val allMessages = pluto.getAllMessages().first() - - val revokedMessages = messages.filter { it.piuri == ProtocolType.PrismRevocation.value } - revokedMessages.forEach { msg -> - val revokedMessage = RevocationNotification.fromMessage(msg) - val threadId = revokedMessage.body.threadId - val matchingMessages = - allMessages.filter { it.piuri == ProtocolType.DidcommIssueCredential.value && it.thid == threadId } - if (matchingMessages.isNotEmpty()) { - matchingMessages.forEach { message -> - val issueMessage = IssueCredential.fromMessage(message) - if (pollux.extractCredentialFormatFromMessage(issueMessage.attachments) == CredentialType.JWT) { - val attachment = - issueMessage.attachments.firstOrNull()?.data as? AttachmentBase64 - attachment?.let { - val credentialId = it.base64.base64UrlDecoded - pluto.revokeCredential(credentialId) - } - } - } - } - } - - // If there are any messages, mark them as read and store them - if (messagesIds.isNotEmpty()) { - mediationHandler.registerMessagesAsRead( - messagesIds.toTypedArray() - ) - pluto.storeMessages(messages) - } - } - } - - /** - * Awaits a response to a specified message ID from the connection. - * - * @param id The ID of the message for which to await a response. - * @return The response message, if one is received. - */ - override suspend fun awaitMessageResponse(id: String): Message? { - return try { - awaitMessages().first().map { - it.second - }.first { - it.thid == id - } - } catch (e: NoSuchElementException) { - null - } - } - - companion object { - const val NUMBER_OF_MESSAGES = 10 - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/PrismAgent.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/PrismAgent.kt deleted file mode 100644 index dab67092f..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/PrismAgent.kt +++ /dev/null @@ -1,1042 +0,0 @@ -@file:Suppress("ktlint:standard:import-ordering") - -package io.iohk.atala.prism.walletsdk.prismagent - -import anoncreds_wrapper.CredentialOffer -import anoncreds_wrapper.CredentialRequestMetadata -import anoncreds_wrapper.LinkSecret -import io.iohk.atala.prism.apollo.base64.base64UrlDecoded -import io.iohk.atala.prism.apollo.base64.base64UrlEncoded -import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519KeyPair -import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519PrivateKey -import io.iohk.atala.prism.walletsdk.apollo.utils.Secp256k1KeyPair -import io.iohk.atala.prism.walletsdk.apollo.utils.Secp256k1PrivateKey -import io.iohk.atala.prism.walletsdk.apollo.utils.X25519KeyPair -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Apollo -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Castor -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Mercury -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Pluto -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Pollux -import io.iohk.atala.prism.walletsdk.domain.models.Api -import io.iohk.atala.prism.walletsdk.domain.models.ApiImpl -import io.iohk.atala.prism.walletsdk.domain.models.ApolloError -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentBase64 -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentDescriptor -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentJsonData -import io.iohk.atala.prism.walletsdk.domain.models.Credential -import io.iohk.atala.prism.walletsdk.domain.models.CredentialType -import io.iohk.atala.prism.walletsdk.domain.models.Curve -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.DIDDocument -import io.iohk.atala.prism.walletsdk.domain.models.DIDPair -import io.iohk.atala.prism.walletsdk.domain.models.KeyCurve -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.domain.models.PeerDID -import io.iohk.atala.prism.walletsdk.domain.models.PolluxError -import io.iohk.atala.prism.walletsdk.domain.models.PrismDIDInfo -import io.iohk.atala.prism.walletsdk.domain.models.Seed -import io.iohk.atala.prism.walletsdk.domain.models.Signature -import io.iohk.atala.prism.walletsdk.domain.models.httpClient -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.KeyPair -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PrivateKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.StorableKey -import io.iohk.atala.prism.walletsdk.logger.LogComponent -import io.iohk.atala.prism.walletsdk.logger.Metadata -import io.iohk.atala.prism.walletsdk.logger.PrismLogger -import io.iohk.atala.prism.walletsdk.logger.PrismLoggerImpl -import io.iohk.atala.prism.walletsdk.pollux.models.AnonCredential -import io.iohk.atala.prism.walletsdk.pollux.models.CredentialRequestMeta -import io.iohk.atala.prism.walletsdk.pollux.models.JWTCredential -import io.iohk.atala.prism.walletsdk.prismagent.helpers.AgentOptions -import io.iohk.atala.prism.walletsdk.prismagent.mediation.BasicMediatorHandler -import io.iohk.atala.prism.walletsdk.prismagent.mediation.MediationHandler -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType -import io.iohk.atala.prism.walletsdk.prismagent.protocols.connection.DIDCommConnectionRunner -import io.iohk.atala.prism.walletsdk.prismagent.protocols.findProtocolTypeByValue -import io.iohk.atala.prism.walletsdk.prismagent.protocols.issueCredential.IssueCredential -import io.iohk.atala.prism.walletsdk.prismagent.protocols.issueCredential.OfferCredential -import io.iohk.atala.prism.walletsdk.prismagent.protocols.issueCredential.RequestCredential -import io.iohk.atala.prism.walletsdk.prismagent.protocols.outOfBand.DIDCommInvitationRunner -import io.iohk.atala.prism.walletsdk.prismagent.protocols.outOfBand.InvitationType -import io.iohk.atala.prism.walletsdk.prismagent.protocols.outOfBand.OutOfBandInvitation -import io.iohk.atala.prism.walletsdk.prismagent.protocols.outOfBand.PrismOnboardingInvitation -import io.iohk.atala.prism.walletsdk.prismagent.protocols.proofOfPresentation.Presentation -import io.iohk.atala.prism.walletsdk.prismagent.protocols.proofOfPresentation.RequestPresentation -import io.ktor.client.plugins.contentnegotiation.ContentNegotiation -import io.ktor.http.ContentType -import io.ktor.http.HttpMethod -import io.ktor.http.Url -import io.ktor.serialization.kotlinx.json.json -import java.net.UnknownHostException -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.MutableSharedFlow -import kotlinx.coroutines.flow.first -import kotlinx.coroutines.flow.firstOrNull -import kotlinx.coroutines.flow.map -import kotlinx.coroutines.flow.onSubscription -import kotlinx.coroutines.launch -import kotlinx.serialization.Serializable -import kotlinx.serialization.SerializationException -import kotlinx.serialization.json.Json -import kotlinx.serialization.json.JsonObject -import kotlinx.serialization.json.jsonObject - -/** - * Check if the passed URL is valid or not. - * @param str string to check its URL validity - * @return [Url] if valid, null if not valid - */ -private fun Url.Companion.parse(str: String): Url? { - try { - return Url(str) - } catch (e: Throwable) { - return null - } -} - -/** - * PrismAgent class is responsible for handling the connection to other agents in the network using a provided Mediator - * Service Endpoint and seed data. - */ -class PrismAgent { - var state: State = State.STOPPED - private set(value) { - field = value - prismAgentScope.launch { - flowState.emit(value) - } - } - val seed: Seed - val apollo: Apollo - val castor: Castor - val pluto: Pluto - val mercury: Mercury - val pollux: Pollux - val flowState = MutableSharedFlow() - - private val prismAgentScope: CoroutineScope = CoroutineScope(Dispatchers.Default) - private val api: Api - private var connectionManager: ConnectionManager - private var logger: PrismLogger - private val agentOptions: AgentOptions - - /** - * Initializes the PrismAgent with the given dependencies. - * - * @param apollo The Apollo instance used by the PrismAgent. - * @param castor The Castor instance used by the PrismAgent. - * @param pluto The Pluto instance used by the PrismAgent. - * @param mercury The Mercury instance used by the PrismAgent. - * @param pollux The Pollux instance used by the PrismAgent. - * @param connectionManager The ConnectionManager instance used by the PrismAgent. - * @param seed An optional Seed instance used by the Apollo if provided, otherwise a random seed will be used. - * @param api An optional Api instance used by the PrismAgent if provided, otherwise a default ApiImpl will be used. - * @param logger An optional PrismLogger instance used by the PrismAgent if provided, otherwise a PrismLoggerImpl with - * LogComponent.PRISM_AGENT will be used. - * @param agentOptions Options to configure certain features with in the prism agent. - */ - @JvmOverloads - constructor( - apollo: Apollo, - castor: Castor, - pluto: Pluto, - mercury: Mercury, - pollux: Pollux, - connectionManager: ConnectionManager, - seed: Seed?, - api: Api?, - logger: PrismLogger = PrismLoggerImpl(LogComponent.PRISM_AGENT), - agentOptions: AgentOptions = AgentOptions() - ) { - prismAgentScope.launch { - flowState.emit(State.STOPPED) - } - this.apollo = apollo - this.castor = castor - this.pluto = pluto - this.mercury = mercury - this.pollux = pollux - this.connectionManager = connectionManager - this.seed = seed ?: apollo.createRandomSeed().seed - this.api = api ?: ApiImpl( - httpClient { - install(ContentNegotiation) { - json( - Json { - ignoreUnknownKeys = true - prettyPrint = true - isLenient = true - } - ) - } - } - ) - this.logger = logger - this.agentOptions = agentOptions - } - - /** - * Initializes the PrismAgent constructor. - * - * @param apollo The instance of Apollo. - * @param castor The instance of Castor. - * @param pluto The instance of Pluto. - * @param mercury The instance of Mercury. - * @param pollux The instance of Pollux. - * @param seed The seed value for random generation. Default is null. - * @param api The instance of the API. Default is null. - * @param mediatorHandler The mediator handler. - * @param logger The logger for PrismAgent. Default is PrismLoggerImpl with LogComponent.PRISM_AGENT. - * @param agentOptions Options to configure certain features with in the prism agent. - */ - @JvmOverloads - constructor( - apollo: Apollo, - castor: Castor, - pluto: Pluto, - mercury: Mercury, - pollux: Pollux, - seed: Seed? = null, - api: Api? = null, - mediatorHandler: MediationHandler, - logger: PrismLogger = PrismLoggerImpl(LogComponent.PRISM_AGENT), - agentOptions: AgentOptions = AgentOptions() - ) { - prismAgentScope.launch { - flowState.emit(State.STOPPED) - } - this.apollo = apollo - this.castor = castor - this.pluto = pluto - this.mercury = mercury - this.pollux = pollux - this.seed = seed ?: apollo.createRandomSeed().seed - this.api = api ?: ApiImpl( - httpClient { - install(ContentNegotiation) { - json( - Json { - ignoreUnknownKeys = true - prettyPrint = true - isLenient = true - } - ) - } - } - ) - this.logger = logger - this.agentOptions = agentOptions - // Pairing will be removed in the future - this.connectionManager = - ConnectionManager(mercury, castor, pluto, mediatorHandler, mutableListOf(), pollux, agentOptions.experiments.liveMode) - } - - init { - flowState.onSubscription { - if (flowState.subscriptionCount.value <= 0) { - state = State.STOPPED - } else { - throw io.iohk.atala.prism.walletsdk.domain.models.UnknownError.SomethingWentWrongError( - "Agent state only accepts one subscription." - ) - // throw Exception("Agent state only accepts one subscription.") - } - } - } - - // Prism agent actions - /** - * Start the [PrismAgent] and Mediator services. - * - * @throws [PrismAgentError.MediationRequestFailedError] failed to connect to mediator. - * @throws [UnknownHostException] if unable to connect to the mediator. - */ - @Throws(PrismAgentError.MediationRequestFailedError::class, UnknownHostException::class) - suspend fun start() { - if (state != State.STOPPED) { - return - } - logger.info(message = "Starting agent") - state = State.STARTING - try { - connectionManager.startMediator() - } catch (error: PrismAgentError.NoMediatorAvailableError) { - logger.info(message = "Start accept DIDComm invitation") - try { - val hostDID = createNewPeerDID(updateMediator = false) - - logger.info(message = "Sending DIDComm connection message") - connectionManager.registerMediator(hostDID) - } catch (error: UnknownHostException) { - state = State.STOPPED - throw error - } - } - if (connectionManager.mediationHandler.mediator != null) { - state = State.RUNNING - logger.info( - message = "Mediation Achieved", - metadata = arrayOf( - Metadata.PublicMetadata( - key = "Routing DID", - value = connectionManager.mediationHandler.mediatorDID.toString() - ) - ) - ) - logger.info(message = "Agent running") - } else { - state = State.STOPPED - throw PrismAgentError.MediationRequestFailedError() - } - } - - /** - * Stops the [PrismAgent]. - * The function sets the state of [PrismAgent] to [State.STOPPING]. - * All ongoing events that was created by the [PrismAgent] are stopped. - * After all the events are stopped the state of the [PrismAgent] is set to [State.STOPPED]. - */ - fun stop() { - if (state != State.RUNNING) { - return - } - logger.info(message = "Stoping agent") - state = State.STOPPING - state = State.STOPPED - logger.info(message = "Agent not running") - } - - // DID Higher Functions - /** - * This method create a new Prism DID, that can be used to identify the agent and interact with other agents. - * - * @param keyPathIndex key path index used to identify the DID. - * @param alias An alias that can be used to identify the DID. - * @param services an array of services associated to the DID. - * @return The new created [DID] - */ - @JvmOverloads - suspend fun createNewPrismDID( - keyPathIndex: Int? = null, - alias: String? = null, - services: Array = emptyArray() - ): DID { - val index = keyPathIndex ?: (pluto.getPrismLastKeyPathIndex().first() + 1) - val keyPair = Secp256k1KeyPair.generateKeyPair(seed, KeyCurve(Curve.SECP256K1, index)) - val did = castor.createPrismDID(masterPublicKey = keyPair.publicKey, services = services) - registerPrismDID(did, index, alias, keyPair.privateKey) - return did - } - - /** - * This function receives a Prism DID and its information and stores it into the local database. - * - * @param did The DID to be stored - * @param keyPathIndex The index associated with the PrivateKey - * @param alias The alias associated with the DID if any - * @param privateKey The private key used to create the PrismDID - */ - private fun registerPrismDID( - did: DID, - keyPathIndex: Int, - alias: String? = null, - privateKey: PrivateKey - ) { - pluto.storePrismDIDAndPrivateKeys( - did = did, - keyPathIndex = keyPathIndex, - alias = alias, - listOf(privateKey as StorableKey) - ) - } - - /** - * This function creates a new Peer DID, stores it in pluto database and updates the mediator if requested. - * - * @param services The services associated to the new DID. - * @param updateMediator Indicates if the new DID should be added to the mediator's list. It will as well add the - * mediator service. - * @return A new [DID]. - */ - @JvmOverloads - suspend fun createNewPeerDID( - services: Array = emptyArray(), - updateMediator: Boolean - ): DID { - val keyAgreementKeyPair = X25519KeyPair.generateKeyPair() - val authenticationKeyPair = Ed25519KeyPair.generateKeyPair() - - var tmpServices = services - if (updateMediator) { - tmpServices = tmpServices.plus( - DIDDocument.Service( - id = DIDCOMM1, - type = arrayOf( - DIDCOMM_MESSAGING - ), - serviceEndpoint = DIDDocument.ServiceEndpoint( - uri = connectionManager.mediationHandler.mediator?.routingDID.toString() - ) - ) - ) - } - - val did = castor.createPeerDID( - arrayOf(keyAgreementKeyPair, authenticationKeyPair), - services = tmpServices - ) - registerPeerDID( - did, - keyAgreementKeyPair, - authenticationKeyPair, - updateMediator - ) - return did - } - - /** - * Registers a peer DID with the specified DID and private keys. - * - * @param did The DID (Decentralized Identifier) to register. - * @param keyAgreementKeyPair The key pair used for key agreement. - * @param authenticationKeyPair The key pair used for authentication. - * @param updateMediator Whether to update the mediator with the DID. - */ - suspend fun registerPeerDID( - did: DID, - keyAgreementKeyPair: KeyPair, - authenticationKeyPair: KeyPair, - updateMediator: Boolean - ) { - if (updateMediator) { - updateMediatorWithDID(did) - } - // The next logic is a bit tricky, so it's not forgotten this is a reminder. - // The next few lines are needed because of DIDComm library, the library will need - // to get the secret(private key) that is pair of the public key within the DIDPeer Document - // to this end the library will give you the id of the public key that is `did:{method}:{methodId}#ecnumbasis`. - // So the code below after the did is created, it will retrieve the document and - // store the private keys with the corresponding `id` of the one created on the document. - // So when the secret resolver asks for the secret we can identify it. - val document = castor.resolveDID(did.toString()) - - val listOfVerificationMethods: MutableList = - mutableListOf() - document.coreProperties.forEach { - if (it is DIDDocument.Authentication) { - listOfVerificationMethods.addAll(it.verificationMethods) - } - if (it is DIDDocument.KeyAgreement) { - listOfVerificationMethods.addAll(it.verificationMethods) - } - } - val verificationMethods = - DIDDocument.VerificationMethods(listOfVerificationMethods.toTypedArray()) - - verificationMethods.values.forEach { - if (it.type.contains("X25519")) { - pluto.storePrivateKeys( - keyAgreementKeyPair.privateKey as StorableKey, - did, - 0, - it.id.toString() - ) - } else if (it.type.contains("Ed25519")) { - pluto.storePrivateKeys( - authenticationKeyPair.privateKey as StorableKey, - did, - 0, - it.id.toString() - ) - } - } - - pluto.storePeerDID( - did = did - ) - } - - /** - * Updates the mediator with the specified DID by updating the key list with the given DID. - * - * @param did The DID to update the mediator with. - */ - suspend fun updateMediatorWithDID(did: DID) { - connectionManager.mediationHandler.updateKeyListWithDIDs(arrayOf(did)) - } - - fun setupMediatorHandler(mediatorHandler: MediationHandler) { - stop() - this.connectionManager = - ConnectionManager(mercury, castor, pluto, mediatorHandler, mutableListOf(), pollux, agentOptions.experiments.liveMode) - } - - /** - * Sets up a mediator DID for communication with the specified DID. - * - * @param did The DID of the mediator to set up. - */ - suspend fun setupMediatorDID(did: DID) { - val tmpMediatorHandler = BasicMediatorHandler( - mediatorDID = did, - mercury = mercury, - store = BasicMediatorHandler.PlutoMediatorRepositoryImpl(pluto) - ) - setupMediatorHandler(tmpMediatorHandler) - } - - /** - * This method fetches a DIDInfo from local storage. - * - * @param did The DID to fetch the info for - * @return A PrismDIDInfo if existent, null otherwise - */ - suspend fun getDIDInfo(did: DID): PrismDIDInfo? { - return pluto.getDIDInfoByDID(did) - .first() - } - - /** - * This method registers a DID pair into the local database. - * - * @param pair The DIDPair to be stored - */ - fun registerDIDPair(pair: DIDPair) { - pluto.storeDIDPair(pair.host, pair.receiver, pair.name ?: "") - } - - /** - * This method returns all DID pairs - * - * @return A list of the store DID pair - */ - suspend fun getAllDIDPairs(): List { - return pluto.getAllDidPairs().first() - } - - /** - * This method returns all registered PeerDIDs. - * - * @return A list of the stored PeerDIDs - */ - suspend fun getAllRegisteredPeerDIDs(): List { - return pluto.getAllPeerDIDs().first() - } - - // Messages related actions - - /** - * Sends a DIDComm message through HTTP using mercury and returns a message if this is returned immediately by the REST endpoint. - * - * @param message The message to be sent - * @return The message sent if successful, null otherwise - */ - suspend fun sendMessage(message: Message): Message? { - return connectionManager.sendMessage(message) - } - - // Credentials related actions - - /** - * This function will use the provided DID to sign a given message. - * - * @param did The DID which will be used to sign the message. - * @param message The message to be signed. - * @return The signature of the message. - */ - @Throws(PrismAgentError.CannotFindDIDPrivateKey::class) - suspend fun signWith(did: DID, message: ByteArray): Signature { - val privateKey = - pluto.getDIDPrivateKeysByDID(did).first().first() - ?: throw PrismAgentError.CannotFindDIDPrivateKey(did.toString()) - val returnByteArray: ByteArray = when (privateKey.getCurve()) { - Curve.ED25519.value -> { - val ed = privateKey as Ed25519PrivateKey - ed.sign(message) - } - - Curve.SECP256K1.value -> { - val secp = privateKey as Secp256k1PrivateKey - secp.sign(message) - } - - else -> { - throw ApolloError.InvalidSpecificKeyCurve( - privateKey.getCurve(), - arrayOf(Curve.SECP256K1.value, Curve.ED25519.value) - ) - } - } - return Signature(returnByteArray) - } - - /** - * This function prepares a request credential from an offer given the subject DID. - * @param did Subject DID. - * @param offer Received offer credential. - * @return Created request credential. - * @throws [PolluxError.InvalidPrismDID] if there is a problem creating the request credential. - * @throws [io.iohk.atala.prism.walletsdk.domain.models.UnknownError.SomethingWentWrongError] if credential type is not supported - **/ - @Throws( - PolluxError.InvalidPrismDID::class, - io.iohk.atala.prism.walletsdk.domain.models.UnknownError.SomethingWentWrongError::class - ) - suspend fun prepareRequestCredentialWithIssuer( - did: DID, - offer: OfferCredential - ): RequestCredential { - if (did.method != "prism") { - throw PolluxError.InvalidPrismDID("DID method is not \"prism\" ") - } - - return when (val type = pollux.extractCredentialFormatFromMessage(offer.attachments)) { - CredentialType.JWT -> { - val privateKeyKeyPath = pluto.getPrismDIDKeyPathIndex(did).first() - - val keyPair = Secp256k1KeyPair.generateKeyPair( - seed, - KeyCurve(Curve.SECP256K1, privateKeyKeyPath) - ) - val offerDataString = offer.attachments.firstNotNullOf { - when (it.data) { - is AttachmentJsonData -> it.data.data - else -> null - } - } - val offerJsonObject = Json.parseToJsonElement(offerDataString).jsonObject - val jwtString = - pollux.processCredentialRequestJWT(did, keyPair.privateKey, offerJsonObject) - val attachmentDescriptor = - AttachmentDescriptor( - mediaType = JWT_MEDIA_TYPE, - data = AttachmentBase64(jwtString.base64UrlEncoded) - ) - return RequestCredential( - from = offer.to, - to = offer.from, - thid = offer.thid, - body = RequestCredential.Body( - offer.body.goalCode, - offer.body.comment - ), - attachments = arrayOf(attachmentDescriptor) - ) - } - - CredentialType.ANONCREDS_OFFER -> { - val linkSecret = getLinkSecret() - val offerDataString = offer.attachments.firstNotNullOf { - when (it.data) { - is AttachmentBase64 -> it.data.base64 - else -> null - } - } - - val anonOffer = CredentialOffer(offerDataString.base64UrlDecoded) - val pair = pollux.processCredentialRequestAnoncreds( - did = did, - offer = anonOffer, - linkSecret = linkSecret, - linkSecretName = offer.thid ?: "" - ) - - val credentialRequest = pair.first - val credentialRequestMetadata = pair.second - - val json = credentialRequest.getJson() - - val metadata = - CredentialRequestMeta.fromCredentialRequestMetadata(credentialRequestMetadata) - pluto.storeCredentialMetadata(metadata) - - val attachmentDescriptor = - AttachmentDescriptor( - mediaType = ContentType.Application.Json.toString(), - format = CredentialType.ANONCREDS_REQUEST.type, - data = AttachmentBase64(json.base64UrlEncoded) - ) - - RequestCredential( - from = offer.to, - to = offer.from, - thid = offer.thid, - body = RequestCredential.Body( - offer.body.goalCode, - offer.body.comment - ), - attachments = arrayOf(attachmentDescriptor) - ) - } - - else -> { - // TODO: Create new prism agent error message - throw io.iohk.atala.prism.walletsdk.domain.models.UnknownError.SomethingWentWrongError( - "Not supported credential type: $type" - ) - // throw Error("Not supported credential type: $type") - } - } - } - - /** - * This function parses an issued credential message, stores, and returns the verifiable credential. - * @param message Issue credential Message. - * @return The parsed verifiable credential. - * @throws io.iohk.atala.prism.walletsdk.domain.models.UnknownError.SomethingWentWrongError if there is a problem parsing the credential. - */ - @Throws(io.iohk.atala.prism.walletsdk.domain.models.UnknownError.SomethingWentWrongError::class) - suspend fun processIssuedCredentialMessage(message: IssueCredential): Credential { - val credentialType = pollux.extractCredentialFormatFromMessage(message.attachments) - val attachment = message.attachments.firstOrNull()?.data as? AttachmentBase64 - - return attachment?.let { - val credentialData = it.base64.base64UrlDecoded - - // TODO: Clean this block of code - message.thid?.let { - val linkSecret = if (credentialType == CredentialType.ANONCREDS_ISSUE) { - getLinkSecret() - } else { - null - } - - val metadata = if (credentialType == CredentialType.ANONCREDS_ISSUE) { - val plutoMetadata = - pluto.getCredentialMetadata(message.thid).first() - ?: throw io.iohk.atala.prism.walletsdk.domain.models.UnknownError.SomethingWentWrongError( - "Invalid credential metadata" - ) - CredentialRequestMetadata( - plutoMetadata.json - ) - } else { - null - } - - val credential = - pollux.parseCredential( - jsonData = credentialData, - type = credentialType, - linkSecret = linkSecret, - credentialMetadata = metadata - ) - - val storableCredential = - pollux.credentialToStorableCredential( - type = credentialType, - credential = credential - ) - pluto.storeCredential(storableCredential) - return credential - } - ?: throw io.iohk.atala.prism.walletsdk.domain.models.UnknownError.SomethingWentWrongError( - "Thid should not be null" - ) - } ?: throw io.iohk.atala.prism.walletsdk.domain.models.UnknownError.SomethingWentWrongError( - "Cannot find attachment base64 in message" - ) - } - -// Message Events - /** - * Start fetching the messages from the mediator. - */ - @JvmOverloads - fun startFetchingMessages(requestInterval: Int = 5) { - connectionManager.startFetchingMessages(requestInterval) - } - - /** - * Stop fetching messages - */ - fun stopFetchingMessages() { - logger.info(message = "Stop streaming new unread messages") - connectionManager.stopConnection() - } - - /** - * Handles the messages events and return a publisher of the messages. - * - * @return [Flow] of [Message]. - */ - fun handleMessagesEvents(): Flow> { - return pluto.getAllMessages() - } - - /** - * Handles the received messages events and return a publisher of the messages. - * - * @return [Flow] of [Message]. - */ - fun handleReceivedMessagesEvents(): Flow> { - return pluto.getAllMessagesReceived() - } - -// Invitation functionalities - /** - * Parses the given string as an invitation - * @param str The string to parse - * @return The parsed invitation [InvitationType] - * @throws [PrismAgentError.UnknownInvitationTypeError] if the invitation is not a valid Prism or OOB type - * @throws [SerializationException] if Serialization failed - */ - @Throws(PrismAgentError.UnknownInvitationTypeError::class, SerializationException::class) - suspend fun parseInvitation(str: String): InvitationType { - Url.parse(str)?.let { - return parseOOBInvitation(it) - } ?: run { - try { - val json = Json.decodeFromString(str) - val typeString: String = if (json.containsKey("type")) { - json["type"].toString().trim('"') - } else { - "" - } - - val invite: InvitationType = when (val type = findProtocolTypeByValue(typeString)) { - ProtocolType.PrismOnboarding -> parsePrismInvitation(str) - ProtocolType.Didcomminvitation -> parseOOBInvitation(str) - else -> - throw PrismAgentError.UnknownInvitationTypeError(type.toString()) - } - - return invite - } catch (e: SerializationException) { - throw e - } - } - } - - /** - * Parses the given string as a Prism Onboarding invitation - * @param str The string to parse - * @return The parsed Prism Onboarding invitation - * @throws [io.iohk.atala.prism.walletsdk.domain.models.UnknownError.SomethingWentWrongError] if the string is not a valid Prism Onboarding invitation - */ - @Throws(io.iohk.atala.prism.walletsdk.domain.models.UnknownError.SomethingWentWrongError::class) - private suspend fun parsePrismInvitation(str: String): PrismOnboardingInvitation { - try { - val prismOnboarding = PrismOnboardingInvitation.fromJsonString(str) - val url = prismOnboarding.onboardEndpoint - val did = createNewPeerDID( - arrayOf( - DIDDocument.Service( - id = DIDCOMM1, - type = arrayOf(DIDCOMM_MESSAGING), - serviceEndpoint = DIDDocument.ServiceEndpoint( - uri = url, - accept = arrayOf(DIDCOMM_MESSAGING), - routingKeys = arrayOf() - ) - ) - ), - false - ) - prismOnboarding.from = did - return prismOnboarding - } catch (e: Exception) { - throw io.iohk.atala.prism.walletsdk.domain.models.UnknownError.SomethingWentWrongError( - e.message, - e.cause - ) - } - } - - /** - * Parses the given string as an Out-of-Band invitation - * @param str The string to parse - * @returns The parsed Out-of-Band invitation - * @throws [SerializationException] if Serialization failed - */ - @Throws(SerializationException::class) - private suspend fun parseOOBInvitation(str: String): OutOfBandInvitation { - return try { - Json.decodeFromString(str) - } catch (ex: SerializationException) { - throw ex - } - } - - /** - * Parses the given URL as an Out-of-Band invitation - * @param url The URL to parse - * @return The parsed Out-of-Band invitation - * @throws [PrismAgentError.UnknownInvitationTypeError] if the URL is not a valid Out-of-Band invitation - */ - private suspend fun parseOOBInvitation(url: Url): OutOfBandInvitation { - return DIDCommInvitationRunner(url).run() - } - - /** - * Accepts an Out-of-Band (DIDComm) invitation and establishes a new connection - * @param invitation The Out-of-Band invitation to accept - * @throws [PrismAgentError.NoMediatorAvailableError] if there is no mediator available or other errors occur during the acceptance process - */ - suspend fun acceptOutOfBandInvitation(invitation: OutOfBandInvitation) { - val ownDID = createNewPeerDID(updateMediator = true) - val pair = DIDCommConnectionRunner(invitation, pluto, ownDID, connectionManager).run() - connectionManager.addConnection(pair) - } - - /** - * Accepts a Prism Onboarding invitation and performs the onboarding process - * @param invitation The Prism Onboarding invitation to accept - * @throws [PrismAgentError.FailedToOnboardError] if failed to on board - */ - @Throws(PrismAgentError.FailedToOnboardError::class) - suspend fun acceptInvitation(invitation: PrismOnboardingInvitation) { - @Serializable - data class SendDID(val did: String) - - val response = api.request( - HttpMethod.Post.toString(), - invitation.onboardEndpoint, - arrayOf(), - arrayOf(), - SendDID(invitation.from.toString()) - ) - - if (response.status != 200) { - throw PrismAgentError.FailedToOnboardError(response.status, response.jsonString) - } - } - - /** - * This method returns a list of all the VerifiableCredentials stored locally. - */ - suspend fun getAllCredentials(): Flow> { - return pluto.getAllCredentials() - .map { list -> - list.map { - pollux.restoreCredential(it.restorationId, it.credentialData, it.revoked) - } - } - } - -// Proof related actions - - /** - * This function creates a Presentation from a request verification. - * @param request Request message received. - * @param credential Verifiable Credential to present. - * @return Presentation message prepared to send. - * @throws PrismAgentError if there is a problem creating the presentation. - **/ - @Throws(PolluxError.InvalidPrismDID::class) - suspend fun preparePresentationForRequestProof( - request: RequestPresentation, - credential: Credential - ): Presentation { - var mediaType: String? = null - var presentationString: String? - when (credential::class) { - JWTCredential::class -> { - val subjectDID = credential.subject?.let { - DID(it) - } ?: DID("") - if (subjectDID.method != PRISM) { - throw PolluxError.InvalidPrismDID() - } - - val privateKeyKeyPath = pluto.getPrismDIDKeyPathIndex(subjectDID).first() - val keyPair = - Secp256k1KeyPair.generateKeyPair( - seed, - KeyCurve(Curve.SECP256K1, privateKeyKeyPath) - ) - val requestData = request.attachments.mapNotNull { - when (it.data) { - is AttachmentJsonData -> it.data.data - else -> null - } - }.first() - val requestJsonObject = Json.parseToJsonElement(requestData).jsonObject - presentationString = pollux.createVerifiablePresentationJWT( - subjectDID, - keyPair.privateKey, - credential, - requestJsonObject - ) - mediaType = JWT_MEDIA_TYPE - } - - AnonCredential::class -> { - val format = pollux.extractCredentialFormatFromMessage(request.attachments) - if (format != CredentialType.ANONCREDS_PROOF_REQUEST) { - throw PrismAgentError.InvalidCredentialFormatError(CredentialType.ANONCREDS_PROOF_REQUEST) - } - val linkSecret = getLinkSecret() - val presentation = pollux.createVerifiablePresentationAnoncred( - request, - credential as AnonCredential, - linkSecret - ) - presentationString = presentation.getJson() - } - - else -> { - throw PrismAgentError.InvalidCredentialError(credential) - } - } - - val attachmentDescriptor = - AttachmentDescriptor( - mediaType = mediaType, - data = AttachmentBase64(presentationString.base64UrlEncoded) - ) - return Presentation( - from = request.to, - to = request.from, - thid = request.thid, - body = Presentation.Body(request.body.goalCode, request.body.comment), - attachments = arrayOf(attachmentDescriptor) - ) - } - - /** - * This method provides a channel to listen for credentials that are revoked. As long as there is an - * observer collecting from this flow the updates will keep happening. - */ - fun observeRevokedCredentials(): Flow> { - return pluto.observeRevokedCredentials() - .map { list -> - list.map { - pollux.restoreCredential(it.restorationId, it.credentialData, it.revoked) - } - } - } - - /** - * This method retrieves the link secret from Pluto. - * - * The method first retrieves the link secret using the `pluto.getLinkSecret()` function. If the link secret is not - * found, a new `LinkSecret` object is created and stored in Pluto using the `pluto.storeLinkSecret()` function. The - * newly created link secret object is then returned. If a link secret is found, a new `LinkSecret` object is created - * using the existing link secret value and returned. - * - * @return The retrieved or newly created link secret object. - */ - private suspend fun getLinkSecret(): LinkSecret { - val linkSecret = pluto.getLinkSecret().firstOrNull() - return if (linkSecret == null) { - val linkSecretObj = LinkSecret() - pluto.storeLinkSecret(linkSecretObj.getValue()) - linkSecretObj - } else { - LinkSecret.newFromValue(linkSecret) - } - } - - /** - * Enumeration representing the current state of the agent. - */ - enum class State { - STOPPED, - STARTING, - RUNNING, - STOPPING - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/PrismAgentError.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/PrismAgentError.kt deleted file mode 100644 index c6b241f28..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/PrismAgentError.kt +++ /dev/null @@ -1,104 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent - -import io.iohk.atala.prism.walletsdk.domain.models.Credential -import io.iohk.atala.prism.walletsdk.domain.models.CredentialType -import io.iohk.atala.prism.walletsdk.domain.models.Error -import io.iohk.atala.prism.walletsdk.domain.models.KnownPrismError - -sealed class PrismAgentError : KnownPrismError() { - - class CannotFindDIDKeyPairIndex : PrismAgentError() { - override val code: Int - get() = 111 - - override val message: String - get() = "To sign with a DID a key pair needs to be registered, please register the key pair first" - } - - class InvitationIsInvalidError : PrismAgentError() { - override val code: Int - get() = 112 - - override val message: String - get() = "The system could not parse the invitation, the message/json are invalid" - } - - class UnknownInvitationTypeError(private val type: String) : PrismAgentError() { - override val code: Int - get() = 113 - - override val message: String - get() = "The type of the invitation is not supported: $type" - } - - class InvalidMessageType(private val type: String, private val shouldBe: String) : PrismAgentError() { - override val code: Int - get() = 114 - - override val message: String - get() = "The following message $type, does not represent the protocol $shouldBe.\nAlso the message should have \"from\" and \"to\" fields\n" - } - - class NoMediatorAvailableError : PrismAgentError() { - override val code: Int - get() = 115 - - override val message: String - get() = "There is no mediator.\nYou need to provide a mediation handler and start the prism agent before doing some operations." - } - - class MediationRequestFailedError - @JvmOverloads constructor(private val underlyingError: Array? = null) : PrismAgentError() { - override val code: Int - get() = 116 - - override val message: String - get() { - val errorsMessages = underlyingError?.joinToString(separator = "\n") { errorDescription ?: "" } - val message = errorsMessages?.map { "Errors: $it" } - return "Something failed while trying to achieve mediation. $message" - } - } - - class OfferDoesNotProvideEnoughInformation : PrismAgentError() { - override val code: Int - get() = 117 - - override val message: String - get() = "Offer provided doesnt have challenge and domain in the attachments" - } - - class CannotFindDIDPrivateKey(private val did: String) : PrismAgentError() { - - override val code: Int - get() = 118 - override val message: String - get() = "Could not find private key for DID: $did" - } - - class FailedToOnboardError(private val statusCode: Int, private val response: String) : PrismAgentError() { - override val code: Int - get() = 119 - - override val message: String - get() = "Failed to onboard.\nStatus code: $statusCode\nResponse: $response" - } - - class InvalidCredentialError constructor(private val credential: Credential) : - PrismAgentError() { - override val code: Int - get() = 120 - - override val message: String - get() = "Invalid credential type, ${credential::class} is not supported" - } - - class InvalidCredentialFormatError constructor(private val expectedFormat: CredentialType) : - PrismAgentError() { - override val code: Int - get() = 121 - - override val message: String - get() = "Invalid credential format, it must be ${expectedFormat.type}" - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/connectionsmanager/ConnectionsManager.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/connectionsmanager/ConnectionsManager.kt deleted file mode 100644 index d1c179f96..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/connectionsmanager/ConnectionsManager.kt +++ /dev/null @@ -1,24 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.connectionsmanager - -import io.iohk.atala.prism.walletsdk.domain.models.DIDPair - -/** - * This interface represents a manager for managing connections between different entities. - * It provides methods for adding and removing connections. - */ -interface ConnectionsManager { - /** - * Adds a connection to the manager. - * - * @param paired The [DIDPair] representing the connection to be added. - */ - suspend fun addConnection(paired: DIDPair) - - /** - * Removes a connection from the manager. - * - * @param pair The [DIDPair] representing the connection to be removed. - * @return The [DIDPair] object that was removed from the manager, or null if the connection was not found. - */ - suspend fun removeConnection(pair: DIDPair): DIDPair? -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/connectionsmanager/DIDCommConnection.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/connectionsmanager/DIDCommConnection.kt deleted file mode 100644 index 06a8b96d6..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/connectionsmanager/DIDCommConnection.kt +++ /dev/null @@ -1,34 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.connectionsmanager - -import io.iohk.atala.prism.walletsdk.domain.models.Message -import kotlinx.coroutines.flow.Flow - -/** - * An interface representing a connection for exchanging messages using the DIDComm protocol. The DIDCommConnection - * protocol defines methods for awaiting and sending messages using the DIDComm protocol. - */ -interface DIDCommConnection { - - /** - * Awaits messages from the connection. - * - * @return An array of messages received from the connection. - */ - suspend fun awaitMessages(): Flow>> - - /** - * Awaits a response to a specified message ID from the connection. - * - * @param id The ID of the message for which to await a response. - * @return The response message, if one is received. - */ - suspend fun awaitMessageResponse(id: String): Message? - - /** - * Sends a message over the connection. - * - * @param message The message to send. - * @return The response message, if one is received. - */ - suspend fun sendMessage(message: Message): Message? -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/helpers/AttachmentDescriptorBuild.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/helpers/AttachmentDescriptorBuild.kt deleted file mode 100644 index 5079dd953..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/helpers/AttachmentDescriptorBuild.kt +++ /dev/null @@ -1,29 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.helpers - -import io.iohk.atala.prism.apollo.base64.base64UrlEncoded -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentBase64 -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentDescriptor -import io.ktor.http.ContentType -import kotlinx.serialization.Serializable -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json -import java.util.UUID - -/** - * Builds an AttachmentDescriptor object with the specified parameters. - * - * @param id The unique identifier for the attachment. If not provided, a random UUID will be generated. - * @param payload The payload data for the attachment. - * @param mediaType The media type of the attachment. If not provided, the default media type will be used. - * @return The built AttachmentDescriptor object. - */ -@JvmOverloads -inline fun AttachmentDescriptor.Companion.build( - id: String = UUID.randomUUID().toString(), - payload: T, - mediaType: String? = ContentType.Application.Json.toString() -): AttachmentDescriptor { - val encoded = Json.encodeToString(payload).base64UrlEncoded - val attachment = AttachmentBase64(base64 = encoded) - return AttachmentDescriptor(id, mediaType, attachment) -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/mediation/BasicMediatorHandler.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/mediation/BasicMediatorHandler.kt deleted file mode 100644 index 7c54d2df6..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/mediation/BasicMediatorHandler.kt +++ /dev/null @@ -1,252 +0,0 @@ -@file:Suppress("ktlint:standard:import-ordering") - -package io.iohk.atala.prism.walletsdk.prismagent.mediation - -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Mercury -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Pluto -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.Mediator -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.domain.models.UnknownError -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgentError -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType -import io.iohk.atala.prism.walletsdk.prismagent.protocols.mediation.MediationGrant -import io.iohk.atala.prism.walletsdk.prismagent.protocols.mediation.MediationKeysUpdateList -import io.iohk.atala.prism.walletsdk.prismagent.protocols.mediation.MediationRequest -import io.iohk.atala.prism.walletsdk.prismagent.protocols.pickup.PickupReceived -import io.iohk.atala.prism.walletsdk.prismagent.protocols.pickup.PickupRequest -import io.iohk.atala.prism.walletsdk.prismagent.protocols.pickup.PickupRunner -import io.ktor.client.HttpClient -import io.ktor.client.plugins.HttpTimeout -import io.ktor.client.plugins.websocket.WebSockets -import io.ktor.client.plugins.websocket.webSocket -import io.ktor.websocket.Frame -import io.ktor.websocket.readText -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.first -import kotlinx.coroutines.flow.flow -import java.util.UUID -import kotlinx.coroutines.isActive - -/** - * A class that provides an implementation of [MediationHandler] using a Pluto instance and a Mercury instance. It can - * be used to register, retrieve and update mediator information, achieve mediation, pick up unread messages, and - * register messages as read. - */ -class BasicMediatorHandler( - override val mediatorDID: DID, - private val mercury: Mercury, - private val store: MediatorRepository -) : MediationHandler { - - /** - * A class that provides an implementation of [MediatorRepository] using a [Pluto] instance. - */ - class PlutoMediatorRepositoryImpl(private val pluto: Pluto) : MediatorRepository { - - /** - * Fetches all the mediators from the [Pluto] store. - * - * @return An array of [Mediator] objects. - */ - override suspend fun getAllMediators(): List { - return pluto.getAllMediators().first() - } - - /** - * Stores a mediator in the [Pluto] store. - * - * @param mediator The [Mediator] object to store. - */ - override fun storeMediator(mediator: Mediator) { - pluto.storeMediator(mediator.mediatorDID, mediator.hostDID, mediator.routingDID) - } - } - - /** - * The active mediator associated with the mediator handler - */ - override var mediator: Mediator? = null - private set - - /** - * Boots the registered mediator associated with the mediator handler. - * - * @return The mediator that was booted. - */ - override suspend fun bootRegisteredMediator(): Mediator? { - if (mediator == null) { - mediator = store.getAllMediators().firstOrNull() - } - - return mediator - } - - /** - * Achieves mediation with the mediatorDID with the specified host DID as a user. - * - * @param host The DID of the entity to mediate with. - * @return The mediator associated with the achieved mediation. - */ - @Throws(PrismAgentError.MediationRequestFailedError::class) - override fun achieveMediation(host: DID): Flow { - return flow { - val registeredMediator = bootRegisteredMediator() - if (registeredMediator == null) { - try { - val requestMessage = - MediationRequest(from = host, to = mediatorDID).makeMessage() - val message = mercury.sendMessageParseResponse(message = requestMessage) - ?: throw UnknownError.SomethingWentWrongError( - message = "BasicMediatorHandler => mercury.sendMessageParseResponse returned null" - ) - - val grantedMessage = MediationGrant(message) - val routingDID = DID(grantedMessage.body.routingDid) - val tmpMediator = Mediator( - id = UUID.randomUUID().toString(), - mediatorDID = mediatorDID, - hostDID = host, - routingDID = routingDID - ) - store.storeMediator(tmpMediator) - mediator = tmpMediator - emit(tmpMediator) - } catch (e: UnknownError) { - throw PrismAgentError.MediationRequestFailedError(arrayOf(e)) - } - } else { - emit(registeredMediator) - } - } - } - - /** - * Updates the key list with the specified DIDs. - * - * @param dids An array of DIDs to add to the key list. - */ - @Throws(PrismAgentError.NoMediatorAvailableError::class) - override suspend fun updateKeyListWithDIDs(dids: Array) { - val keyListUpdateMessage = mediator?.let { - MediationKeysUpdateList( - from = it.hostDID, - to = it.mediatorDID, - recipientDids = dids - ).makeMessage() - } ?: throw PrismAgentError.NoMediatorAvailableError() - keyListUpdateMessage.let { message -> mercury.sendMessage(message) } - } - - /** - * Picks up the specified number of unread messages. - * - * @param limit The maximum number of messages to pick up. - * @return An array of pairs containing the message ID and the message itself. - */ - @Throws(PrismAgentError.NoMediatorAvailableError::class) - override fun pickupUnreadMessages(limit: Int): Flow>> { - val requestMessage = mediator?.let { - PickupRequest( - from = it.hostDID, - to = it.mediatorDID, - body = PickupRequest.Body(limit = limit) - ).makeMessage() - } ?: throw PrismAgentError.NoMediatorAvailableError() - - return flow { - val message = mercury.sendMessageParseResponse(requestMessage) - message?.let { - emit(PickupRunner(message, mercury).run()) - } - } - } - - /** - * Registers the specified message IDs as read. - * - * @param ids An array of message IDs to register as read. - */ - @Throws(PrismAgentError.NoMediatorAvailableError::class) - override suspend fun registerMessagesAsRead(ids: Array) { - val requestMessage = mediator?.let { - PickupReceived( - from = it.hostDID, - to = it.mediatorDID, - body = PickupReceived.Body(messageIdList = ids) - ).makeMessage() - } ?: throw PrismAgentError.NoMediatorAvailableError() - mercury.sendMessage(requestMessage) - } - - /** - * Listens for unread messages from a specified WebSocket service endpoint. - * - * This function creates a WebSocket connection to the provided service endpoint URI - * and listens for incoming messages. Upon receiving messages, it processes and - * dispatches them to the specified callback function. - * - * @param serviceEndpointUri The URI of the service endpoint. It should be a valid WebSocket URI. - * @param onMessageCallback A callback function that is invoked when a message is received. - * This function is responsible for handling the incoming message. - */ - override suspend fun listenUnreadMessages( - serviceEndpointUri: String, - onMessageCallback: OnMessageCallback - ) { - val client = HttpClient { - install(WebSockets) - install(HttpTimeout) { - requestTimeoutMillis = WEBSOCKET_TIMEOUT - connectTimeoutMillis = WEBSOCKET_TIMEOUT - socketTimeoutMillis = WEBSOCKET_TIMEOUT - } - } - if (serviceEndpointUri.contains("wss://") || serviceEndpointUri.contains("ws://")) { - client.webSocket(serviceEndpointUri) { - if (isActive) { - val liveDeliveryMessage = Message( - body = "{\"live_delivery\":true}", - piuri = ProtocolType.LiveDeliveryChange.value, - id = UUID.randomUUID().toString(), - from = mediator?.hostDID, - to = mediatorDID - ) - val packedMessage = mercury.packMessage(liveDeliveryMessage) - send(Frame.Text(packedMessage)) - } - while (isActive) { - try { - for (frame in incoming) { - if (frame is Frame.Text) { - val messages = - handleReceivedMessagesFromSockets(frame.readText()) - onMessageCallback.onMessage(messages) - } - } - } catch (e: Exception) { - e.printStackTrace() - continue - } - } - } - } - } - - private suspend fun handleReceivedMessagesFromSockets(text: String): Array> { - val decryptedMessage = mercury.unpackMessage(text) - if (decryptedMessage.piuri == ProtocolType.PickupStatus.value || - decryptedMessage.piuri == ProtocolType.PickupDelivery.value - ) { - return PickupRunner(decryptedMessage, mercury).run() - } else { - return emptyArray() - } - } -} - -fun interface OnMessageCallback { - fun onMessage(messages: Array>) -} - -const val WEBSOCKET_TIMEOUT: Long = 15_000 diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/mediation/MediationHandler.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/mediation/MediationHandler.kt deleted file mode 100644 index d5c613ca2..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/mediation/MediationHandler.kt +++ /dev/null @@ -1,72 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.mediation - -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.Mediator -import io.iohk.atala.prism.walletsdk.domain.models.Message -import kotlinx.coroutines.flow.Flow - -/** - * An interface representing a mediator handler for handling mediator routing in the DIDComm protocol. The - * MediatorHandler protocol defines methods and properties for booting registered mediators, achieving mediation, - * updating key lists, picking up unread messages, and registering messages as read. - */ -interface MediationHandler { - /** - * The active mediator associated with the mediator handler - */ - val mediator: Mediator? - - /** - * The DID of the mediator associated with the mediator handler - */ - val mediatorDID: DID - - /** - * Boots the registered mediator associated with the mediator handler. - * - * @return The mediator that was booted. - */ - suspend fun bootRegisteredMediator(): Mediator? - - /** - * Achieves mediation with the mediatorDID with the specified host DID as a user. - * - * @param host The DID of the entity to mediate with. - * @return The mediator associated with the achieved mediation. - */ - fun achieveMediation(host: DID): Flow - - /** - * Updates the key list with the specified DIDs. - * - * @param dids An array of DIDs to add to the key list. - */ - suspend fun updateKeyListWithDIDs(dids: Array) - - /** - * Picks up the specified number of unread messages. - * - * @param limit The maximum number of messages to pick up. - * @return An array of pairs containing the message ID and the message itself. - */ - fun pickupUnreadMessages(limit: Int): Flow>> - - /** - * Registers the specified message IDs as read. - * - * @param ids An array of message IDs to register as read. - */ - suspend fun registerMessagesAsRead(ids: Array) - - /** - * Listens for unread messages from a specified WebSocket service endpoint. - * - * @param serviceEndpointUri The URI of the service endpoint. It should be a valid WebSocket URI. - * @param onMessageCallback A callback function that is invoked when a message is received. - * This function is responsible for handling the incoming message. - */ - suspend fun listenUnreadMessages( - serviceEndpointUri: String, - onMessageCallback: OnMessageCallback - ) -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/mediation/MediatorRepository.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/mediation/MediatorRepository.kt deleted file mode 100644 index c5fe39be0..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/mediation/MediatorRepository.kt +++ /dev/null @@ -1,25 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.mediation - -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Pluto -import io.iohk.atala.prism.walletsdk.domain.models.Mediator - -/** - * An interface representing a store for storing and retrieving mediators. The MediatorStore protocol defines methods - * for storing and retrieving mediators. - */ -interface MediatorRepository { - - /** - * Stores a mediator in the [Pluto] store. - * - * @param mediator The [Mediator] object to store. - */ - fun storeMediator(mediator: Mediator) - - /** - * Fetches all the mediators from the [Pluto] store. - * - * @return An array of [Mediator] objects. - */ - suspend fun getAllMediators(): List -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/connection/ConnectionAccept.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/connection/ConnectionAccept.kt deleted file mode 100644 index 5e5109ebf..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/connection/ConnectionAccept.kt +++ /dev/null @@ -1,167 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.connection - -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.prismagent.GOAL_CODE -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgentError -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json -import java.util.UUID - -/** - * A class representing a connection acceptance message in the DIDComm protocol. The [ConnectionAccept] class defines - * properties and methods for encoding, decoding, and sending connection acceptance messages in the DIDComm protocol. - */ -class ConnectionAccept { - val type: String = ProtocolType.DidcommconnectionResponse.value - var id: String = UUID.randomUUID().toString() - lateinit var from: DID - lateinit var to: DID - var thid: String? = null - lateinit var body: Body - - /** - * Initializes a new instance of the ConnectionAccept struct with the specified parameters. - * - * @param from The DID of the sender of the connection acceptance message. - * @param to The DID of the recipient of the connection acceptance message. - * @param thid The thread ID of the connection acceptance message. - * @param body The body of the connection acceptance message. - */ - constructor( - from: DID, - to: DID, - thid: String? = null, - body: Body - ) { - this.from = from - this.to = to - this.thid = thid - this.body = body - } - - /** - * Initializes a new instance of the ConnectionAccept struct from the specified message. - * - * @param fromMessage The message to decode. - */ - @Throws(PrismAgentError.InvalidMessageType::class) - constructor(fromMessage: Message) { - if (fromMessage.piuri == ProtocolType.DidcommconnectionResponse.value && fromMessage.from != null && fromMessage.to != null) { - ConnectionAccept(from = fromMessage.from, to = fromMessage.to, body = Body(fromMessage.body)) - } else { - throw PrismAgentError.InvalidMessageType( - type = fromMessage.piuri, - shouldBe = ProtocolType.DidcommconnectionResponse.value - ) - } - } - - /** - * Initializes a new instance of the ConnectionAccept struct from the specified request. - * - * @param fromRequest The request to use for initialization. - */ - constructor(fromRequest: ConnectionRequest) { - ConnectionAccept( - from = fromRequest.from, - to = fromRequest.to, - thid = id, - body = Body(fromRequest.body.goalCode, fromRequest.body.goal, fromRequest.body.accept) - ) - } - - /** - * The `makeMessage` method creates a new `Message` object with the specified parameters. - * - * @return A new `Message` object. - */ - fun makeMessage(): Message { - return Message( - id = id, - piuri = type, - from = from, - to = to, - body = Json.encodeToString(body), - thid = thid - ) - } - - /** - * The body of the connection acceptance message, which is the same as the body of the invitation message - */ - @Serializable - data class Body( - /** - * The goal code of the connection acceptance message. - */ - @SerialName(GOAL_CODE) - val goalCode: String? = null, - /** - * The goal of the connection acceptance message - */ - val goal: String? = null, - /** - * An array of strings representing the accepted message types - */ - val accept: Array? = null - ) { - /** - * Checks if this [Body] object is equal to the specified [other] object. - * - * Two [Body] objects are considered equal if their [goalCode], [goal], and [accept] properties are equal. - * - * @param other The object to compare for equality. If the [other] object is not of type [Body], the method returns false. - * @return true if this [Body] object is equal to the specified [other] object, false otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - if (other == null || this::class != other::class) { - return false - } - - other as Body - - if (goalCode != other.goalCode) { - return false - } - if (goal != other.goal) { - return false - } - if (accept != null) { - if (other.accept == null) { - return false - } - if (!accept.contentEquals(other.accept)) { - return false - } - } else if (other.accept != null) { - return false - } - - return true - } - - /** - * Returns a hash code value for the object. - * - * The hash code is calculated based on the `goalCode`, `goal`, and `accept` properties. - * If the `goalCode` is not null, its hash code value is added to the result. - * If the `goal` is not null, its hash code value is multiplied by 31 and added to the result. - * If the `accept` array is not null, its content hash code value is multiplied by 31 and added to the result. - * - * @return The hash code value for the object. - */ - override fun hashCode(): Int { - var result = goalCode?.hashCode() ?: 0 - result = 31 * result + (goal?.hashCode() ?: 0) - result = 31 * result + (accept?.contentHashCode() ?: 0) - return result - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/connection/ConnectionRequest.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/connection/ConnectionRequest.kt deleted file mode 100644 index fc9d07637..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/connection/ConnectionRequest.kt +++ /dev/null @@ -1,187 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.connection - -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.prismagent.GOAL_CODE -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgentError -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType -import io.iohk.atala.prism.walletsdk.prismagent.protocols.outOfBand.OutOfBandInvitation -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json -import java.util.UUID - -/** - * A class representing a connection request message in the DIDComm protocol. The [ConnectionRequest] class defines - * properties and methods for encoding, decoding, and sending connection request messages in the DIDComm protocol. - */ -class ConnectionRequest { - val type: String = ProtocolType.DidcommconnectionRequest.value - var id: String = UUID.randomUUID().toString() - lateinit var from: DID - lateinit var to: DID - var thid: String? = null - lateinit var body: Body - - /** - * Represents a connection request message in the messaging protocol. - * - * @param from The sender's DID. - * @param to The recipient's DID. - * @param thid The thread ID. - * @param body The body of the connection request message. - */ - constructor( - from: DID, - to: DID, - thid: String? = null, - body: Body - ) { - this.from = from - this.to = to - this.thid = thid - this.body = body - } - - /** - * Initializes a new instance of the ConnectionRequest struct from the specified invitation message. - * - * @param inviteMessage The invitation message to use for initialization. - * @param from The DID of the sender of the connection request message. - */ - @Throws(PrismAgentError.InvitationIsInvalidError::class) - constructor(inviteMessage: Message, from: DID) { - inviteMessage.from?.let { toDID -> - val body = Json.decodeFromString(inviteMessage.body) - ConnectionRequest(from = from, to = toDID, thid = inviteMessage.id, body = body) - } ?: throw PrismAgentError.InvitationIsInvalidError() - } - - /** - * Initializes a new instance of the ConnectionRequest struct from the specified out-of-band invitation. - * - * @param inviteMessage The out-of-band invitation to use for initialization. - * @param from The DID of the sender of the connection request message. - */ - constructor(inviteMessage: OutOfBandInvitation, from: DID) : this( - from, - DID(inviteMessage.from), - inviteMessage.id, - Body( - goalCode = inviteMessage.body.goalCode, - goal = inviteMessage.body.goal, - accept = inviteMessage.body.accept?.toTypedArray() - ) - ) - - /** - * Initializes a new instance of the ConnectionRequest struct from the specified message. - * - * @param fromMessage The message to decode. - */ - @Throws(PrismAgentError.InvalidMessageType::class) - constructor(fromMessage: Message) { - if ( - fromMessage.piuri == ProtocolType.DidcommconnectionRequest.value && - fromMessage.from != null && - fromMessage.to != null - ) { - ConnectionRequest( - from = fromMessage.from, - to = fromMessage.to, - thid = fromMessage.id, - body = Json.decodeFromString(fromMessage.body) - ) - } else { - throw PrismAgentError.InvalidMessageType( - type = fromMessage.piuri, - shouldBe = ProtocolType.DidcommconnectionRequest.value - ) - } - } - - /** - * Creates a [Message] object based on the current state of the [ConnectionRequest] instance. - * - * @return The created [Message] object. - */ - fun makeMessage(): Message { - return Message( - id = this.id, - piuri = this.type, - from = this.from, - to = this.to, - body = Json.encodeToString(this.body), - thid = this.thid - ) - } - - /** - * The body of the connection acceptance message, which is the same as the body of the invitation message - */ - @Serializable - data class Body( - /** - * The goal code of the connection acceptance message. - */ - @SerialName(GOAL_CODE) - val goalCode: String? = null, - /** - * The goal of the connection acceptance message - */ - val goal: String? = null, - /** - * An array of strings representing the accepted message types - */ - val accept: Array? = null - ) { - /** - * Checks if the current object is equal to the specified object. - * - * @param other The other object to compare. - * @return true if the objects are equal, false otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - if (other == null || this::class != other::class) { - return false - } - - other as Body - - if (goalCode != other.goalCode) { - return false - } - if (goal != other.goal) { - return false - } - if (accept != null) { - if (other.accept == null) { - return false - } - if (!accept.contentEquals(other.accept)) { - return false - } - } else if (other.accept != null) { - return false - } - - return true - } - - /** - * Generates a hash code for the object based on its properties. - * - * @return The hash code value. - */ - override fun hashCode(): Int { - var result = goalCode?.hashCode() ?: 0 - result = 31 * result + (goal?.hashCode() ?: 0) - result = 31 * result + (accept?.contentHashCode() ?: 0) - return result - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/connection/DIDCommConnectionRunner.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/connection/DIDCommConnectionRunner.kt deleted file mode 100644 index e3731e2a5..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/connection/DIDCommConnectionRunner.kt +++ /dev/null @@ -1,46 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.connection - -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Pluto -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.DIDPair -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgentError -import io.iohk.atala.prism.walletsdk.prismagent.connectionsmanager.DIDCommConnection -import io.iohk.atala.prism.walletsdk.prismagent.protocols.outOfBand.OutOfBandInvitation - -/** - * Represents a runner for the DIDComm connection process. - * - * @property invitationMessage The out-of-band invitation message. - * @property pluto The Pluto instance. - * @property ownDID The own DID. - * @property connection The DIDComm connection. - */ -internal class DIDCommConnectionRunner( - private val invitationMessage: OutOfBandInvitation, - private val pluto: Pluto, - private val ownDID: DID, - private val connection: DIDCommConnection -) { - - /** - * Executes the DIDComm connection process and returns a pair of DIDs. - * - * @return A [DIDPair] representing the sender and receiver DIDs of the connection. - * @throws [PrismAgentError.InvitationIsInvalidError] if the invitation is invalid and cannot be parsed. - */ - @Throws(PrismAgentError.InvitationIsInvalidError::class) - internal suspend fun run(): DIDPair { - val request = ConnectionRequest(invitationMessage, ownDID) - connection.sendMessage(request.makeMessage()) - return DIDPair(ownDID, request.to, null) - // TODO: Check this with @Gonçalo -// val message = pluto.getAllMessagesReceived().first().first { -// it.id == request.id -// } -// if (message.piuri == ProtocolType.DidcommconnectionResponse.value) { -// return DIDPair(ownDID, request.to, null) -// } else { -// throw PrismAgentError.InvitationIsInvalidError() -// } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/IssueCredential.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/IssueCredential.kt deleted file mode 100644 index 7423f9817..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/IssueCredential.kt +++ /dev/null @@ -1,296 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.issueCredential - -import io.iohk.atala.prism.apollo.base64.base64UrlEncoded -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentBase64 -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentDescriptor -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.prismagent.GOAL_CODE -import io.iohk.atala.prism.walletsdk.prismagent.MORE_AVAILABLE -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgentError -import io.iohk.atala.prism.walletsdk.prismagent.REPLACEMENT_ID -import io.iohk.atala.prism.walletsdk.prismagent.helpers.build -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json -import java.util.UUID - -/** - * The IssueCredential class represents a credential issuance in the context of DIDComm messaging. - */ -@Serializable -data class IssueCredential( - val id: String = UUID.randomUUID().toString(), - val body: Body, - val attachments: Array, - val thid: String?, - val from: DID, - val to: DID -) { - val type: String = ProtocolType.DidcommIssueCredential.value - - /** - * Creates a [Message] object representing a DIDComm message. - * This function is used to generate a [Message] object based on the current state of an [IssueCredential] object. - * - * @return A [Message] object with the following properties: - * - id: A unique identifier generated using [UUID.randomUUID]. - * - piuri: The type of the message. - * - from: The sender's DID (Decentralized Identifier). - * - to: The recipient's DID. - * - body: The JSON-encoded body of the message. - * - attachments: An array of [AttachmentDescriptor] objects. - * - thid: The thread ID. - */ - fun makeMessage(): Message { - return Message( - id = id, - piuri = type, - from = from, - to = to, - body = Json.encodeToString(body), - attachments = attachments, - thid = thid - ) - } - - /** - * Retrieves an array of credential strings from the attachments. - * - * @return An array of credential strings. - */ - fun getCredentialStrings(): Array { - return attachments.mapNotNull { - when (it.data) { - is AttachmentBase64 -> { - it.data.base64.base64UrlEncoded - } - - else -> null - } - }.toTypedArray() - } - - companion object { - /** - * Converts a Message into an IssueCredential object. - * - * @param fromMessage The Message object to convert. - * @return The converted IssueCredential object. - * @throws PrismAgentError.InvalidMessageType if the fromMessage doesn't represent the DidcommIssueCredential protocol, - * or if it doesn't have "from" and "to" fields. - */ - @JvmStatic - @Throws(PrismAgentError.InvalidMessageType::class) - fun fromMessage(fromMessage: Message): IssueCredential { - require( - fromMessage.piuri == ProtocolType.DidcommIssueCredential.value && - fromMessage.from != null && - fromMessage.to != null - ) { - throw PrismAgentError.InvalidMessageType( - type = fromMessage.piuri, - shouldBe = ProtocolType.DidcommIssueCredential.value - ) - } - - val fromDID = fromMessage.from - val toDID = fromMessage.to - val body = Json.decodeFromString(fromMessage.body) - - return IssueCredential( - id = fromMessage.id, - body = body, - attachments = fromMessage.attachments, - thid = fromMessage.thid, - from = fromDID, - to = toDID - ) - } - - /** - * Creates an [IssueCredential] object from a [Message] object. - * - * @param msg The [Message] object containing the request credential information. - * @return The created [IssueCredential] object. - */ - @JvmStatic - fun makeIssueFromRequestCedential(msg: Message): IssueCredential { - val request = RequestCredential.fromMessage(msg) - return IssueCredential( - body = Body( - goalCode = request.body.goalCode, - comment = request.body.comment -// formats = request.body.formats - ), - attachments = request.attachments, - thid = msg.id, - from = request.to, - to = request.from - ) - } - } - - /** - * Represents the body of an issue credential message. - * - * @property goalCode The goal code associated with the credential (optional). - * @property comment Additional comment about the credential (optional). - * @property replacementId The ID of the credential being replaced (optional). - * @property moreAvailable Additional information about the availability of more credentials (optional). - */ - @Serializable - data class Body( - @SerialName(GOAL_CODE) - val goalCode: String? = null, - val comment: String? = null, - @SerialName(REPLACEMENT_ID) - val replacementId: String? = null, - @SerialName(MORE_AVAILABLE) - val moreAvailable: String? = null -// val formats: Array - ) { - /** - * Checks if the object is equal to the current `Body` object. - * - * Two `Body` objects are considered equal if they meet the following conditions: - * - They are the same instance (reference equality). - * - They belong to the same class. - * - Their `goalCode` fields have the same value. - * - Their `comment` fields have the same value. - * - Their `replacementId` fields have the same value. - * - * @param other The object to compare against the current `Body` object. - * @return `true` if the objects are equal, `false` otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as Body - - if (goalCode != other.goalCode) return false - if (comment != other.comment) return false - if (replacementId != other.replacementId) return false -// if (moreAvailable != other.moreAvailable) return false -// if (!formats.contentEquals(other.formats)) return false - - return true - } - - /** - * Calculates the hash code for the `hashCode()` method of the `Body` class. - * - * The hash code is calculated using the following formula: - * - The hash code of the `goalCode` field is calculated using its `hashCode()` method, or zero if it is null. - * - The hash code of the `comment` field is calculated using its `hashCode()` method, or zero if it is null. - * - The hash code of the `replacementId` field is calculated using its `hashCode()` method, or zero if it is null. - * - The final hash code is calculated by multiplying each field's hash code by 31 and summing them up. - * - * @return The calculated hash code value for the `Body` object. - */ - override fun hashCode(): Int { - var result = goalCode?.hashCode() ?: 0 - result = 31 * result + (comment?.hashCode() ?: 0) - result = 31 * result + (replacementId?.hashCode() ?: 0) -// result = 31 * result + (moreAvailable?.hashCode() ?: 0) -// result = 31 * result + formats.contentHashCode() - return result - } - } - - /** - * Checks if the object is equal to the current `IssueCredential` object. - * - * Two `IssueCredential` objects are considered equal if they meet the following conditions: - * - They are the same instance (reference equality). - * - They belong to the same class. - * - Their `id` fields have the same value. - * - Their `body` fields have the same value. - * - Their `attachments` arrays have the same content. - * - Their `thid` fields have the same value. - * - Their `from` fields have the same value. - * - Their `to` fields have the same value. - * - Their `type` fields have the same value. - * - * @param other The object to compare against the current `IssueCredential` object. - * @return `true` if the objects are equal, `false` otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as IssueCredential - - if (id != other.id) return false - if (body != other.body) return false - if (!attachments.contentEquals(other.attachments)) return false - if (thid != other.thid) return false - if (from != other.from) return false - if (to != other.to) return false - if (type != other.type) return false - - return true - } - - /** - * Calculates the hash code for the `IssueCredential` object. - * - * The hash code is calculated using the following formula: - * - The hash code of the `id` field is calculated using its `hashCode()` method. - * - The hash code of the `body` field is calculated using its `hashCode()` method. - * - The hash code of the `attachments` field is calculated using its `contentHashCode()` method. - * - The hash code of the `thid` field is calculated using its `hashCode()` method, or zero if it is null. - * - The hash code of the `from` field is calculated using its `hashCode()` method. - * - The hash code of the `to` field is calculated using its `hashCode()` method. - * - The hash code of the `type` field is calculated using its `hashCode()` method. - * - The final hash code is calculated by multiplying each field's hash code by 31 and summing them up. - * - * @return The calculated hash code value for the `IssueCredential` object. - */ - override fun hashCode(): Int { - var result = id.hashCode() - result = 31 * result + body.hashCode() - result = 31 * result + attachments.contentHashCode() - result = 31 * result + (thid?.hashCode() ?: 0) - result = 31 * result + from.hashCode() - result = 31 * result + to.hashCode() - result = 31 * result + type.hashCode() - return result - } -} - -/** - * Builds an instance of [IssueCredential] with the provided parameters. - * - * @param T The type of the credentials. - * @param fromDID The DID of the sender. - * @param toDID The DID of the recipient. - * @param thid The thread ID (optional). - * @param credentials The map of credential formats and their corresponding values (default is an empty map). - * @return An instance of [IssueCredential] with the specified parameters. - */ -@JvmOverloads -inline fun IssueCredential.Companion.build( - fromDID: DID, - toDID: DID, - thid: String?, - credentials: Map = mapOf() -): IssueCredential { - val aux = credentials.map { (key, value) -> - val attachment = AttachmentDescriptor.build(payload = value) - val format = CredentialFormat(attachId = attachment.id, format = key) - format to attachment - } - return IssueCredential( - body = IssueCredential.Body( -// formats = aux.map { it.first }.toTypedArray() - ), - attachments = aux.map { it.second }.toTypedArray(), - thid = thid, - from = fromDID, - to = toDID - ) -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/IssueCredentialProtocol.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/IssueCredentialProtocol.kt deleted file mode 100644 index 16fea5919..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/IssueCredentialProtocol.kt +++ /dev/null @@ -1,230 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.issueCredential - -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.domain.models.UnknownError -import io.iohk.atala.prism.walletsdk.prismagent.connectionsmanager.DIDCommConnection -import kotlinx.serialization.Serializable - -/** - * A class that represents the issue credential protocol in the DIDCommv2 format. - * - * @property stage The current stage of the protocol. - * @property propose The `ProposeCredential` object representing the propose message, or null if not applicable. - * @property offer The `OfferCredential` object representing the offer message, or null if not applicable. - * @property request The `RequestCredential` object representing the request message, or null if not applicable. - * @property connector The `DIDCommConnection` object representing the connection used to send and receive messages. - */ -@Serializable -class IssueCredentialProtocol { - - var stage: Stage - var propose: ProposeCredential? = null - var offer: OfferCredential? = null - var request: RequestCredential? = null - val connector: DIDCommConnection - - /** - * The IssueCredentialProtocol class represents a protocol for issuing credentials in the Atala PRISM architecture. - * It handles different stages of the protocol and communicates with a DIDComm connection to exchange messages. - * - * @param stage The current stage of the protocol. - * @param proposeMessage The propose message received in the protocol. - * @param offerMessage The offer message received in the protocol. - * @param requestMessage The request message received in the protocol. - * @param connector The DIDComm connection to communicate with. - */ - @JvmOverloads - constructor( - stage: Stage, - proposeMessage: Message? = null, - offerMessage: Message? = null, - requestMessage: Message? = null, - connector: DIDCommConnection - ) { - this.stage = stage - this.connector = connector - this.propose = proposeMessage?.let { - try { - ProposeCredential.fromMessage(it) - } catch (e: Throwable) { - null - } - } - this.offer = offerMessage?.let { - try { - OfferCredential.fromMessage(it) - } catch (e: Throwable) { - null - } - } - this.request = requestMessage?.let { - try { - RequestCredential.fromMessage(it) - } catch (e: Throwable) { - null - } - } - } - - /** - * Constructs an instance of [IssueCredentialProtocol] class. - * This constructor initializes the object with the provided [message] and [connector]. - * It determines the stage of the credential issuance process based on the message type in [message], - * and assigns the corresponding values to the [stage] and relevant property (propose, offer, or request). - * - * @param message The message object representing the received message. - * @param connector The DIDCommConnection instance used for message exchange. - * @throws [UnknownError.SomethingWentWrongError] if the message does not match any known message type. - */ - @Throws(UnknownError.SomethingWentWrongError::class) - constructor(message: Message, connector: DIDCommConnection) { - this.connector = connector - val proposed = try { - ProposeCredential.fromMessage(message) - } catch (e: Throwable) { - null - } - val offered = try { - OfferCredential.fromMessage(message) - } catch (e: Throwable) { - null - } - val requested = try { - RequestCredential.fromMessage(message) - } catch (e: Throwable) { - null - } - - when { - proposed != null -> { - this.stage = Stage.PROPOSE - this.propose = proposed - } - - offered != null -> { - this.stage = Stage.OFFER - this.offer = offered - } - - requested != null -> { - this.stage = Stage.REQUEST - this.request = requested - } - - else -> throw UnknownError.SomethingWentWrongError( - message = "Invalid step" - ) - } - } - - /** - * Proceeds to the next stage of the credential issuance process. - * - * If the current stage is PROPOSE: - * - If `propose` is null, sets the stage to REFUSED and returns. - * - * If the current stage is OFFER: - * - If `offer` is null, sets the stage to REFUSED and returns. - * - * Based on the current stage, performs the following actions: - * - PROPOSE: - * - Creates an OfferCredential from the proposed credential using the method `makeOfferFromProposedCredential()`. - * - Sends the offer message over the connector's connection using `sendMessage()`. - * - Sets the `messageId` to the ID of the sent message. - * - * - OFFER: - * - Creates a RequestCredential from the offer credential using the method `makeRequestFromOfferCredential()`. - * - Sends the request message over the connector's connection using `sendMessage()`. - * - Sets the `messageId` to the ID of the sent message. - * - * Based on the value of `messageId`, performs the following actions: - * - If `messageId` is null, returns. - * - * - Otherwise, awaits a response message with the specified `messageId` using `awaitMessageResponse()`. - * If no response message is received, returns. - * - * Based on the received response message, performs the following actions: - * - If the response is an IssueCredential message, sets the stage to COMPLETED. - * - If the response is an OfferCredential message, sets the stage to OFFER and assigns the received offer to `this.offer`. - * - If the response is a RequestCredential message, sets the stage to REQUEST and assigns the received request to `this.request`. - * - * @throws Throwable If there is an error in processing the messages. - */ - suspend fun nextStage() { - if (this.stage == Stage.PROPOSE) { - if (propose == null) { - stage = Stage.REFUSED - return - } - } else if (this.stage == Stage.OFFER) { - if (offer == null) { - stage = Stage.REFUSED - return - } - } - - val messageId: String = when (this.stage) { - Stage.PROPOSE -> { - val message = OfferCredential.makeOfferFromProposedCredential(proposed = propose!!) - connector.sendMessage(message.makeMessage()) - message.id - } - - Stage.OFFER -> { - val message = RequestCredential.makeRequestFromOfferCredential(offer = offer!!).makeMessage() - connector.sendMessage(message) - message.id - } - - Stage.REQUEST -> null - Stage.COMPLETED -> null - Stage.REFUSED -> null - } ?: return - - val response = connector.awaitMessageResponse(id = messageId) ?: return - - val issued = try { - IssueCredential.fromMessage(response) - } catch (e: Throwable) { - null - } - val offered = try { - OfferCredential.fromMessage(response) - } catch (e: Throwable) { - null - } - val requested = try { - RequestCredential.fromMessage(response) - } catch (e: Throwable) { - null - } - - when { - offered != null -> { - this.stage = Stage.OFFER - this.offer = offered - } - - issued != null -> { - this.stage = Stage.COMPLETED - } - - requested != null -> { - this.stage = Stage.REQUEST - this.request = requested - } - } - } - - /** - * Represents the different stages of the credential issuance process. - * The stages are PROPOSE, OFFER, REQUEST, COMPLETED, and REFUSED. - */ - enum class Stage { - PROPOSE, - OFFER, - REQUEST, - COMPLETED, - REFUSED - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/OfferCredential.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/OfferCredential.kt deleted file mode 100644 index e3097a221..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/OfferCredential.kt +++ /dev/null @@ -1,259 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.issueCredential - -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentDescriptor -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.prismagent.CREDENTIAL_PREVIEW -import io.iohk.atala.prism.walletsdk.prismagent.GOAL_CODE -import io.iohk.atala.prism.walletsdk.prismagent.MULTIPLE_AVAILABLE -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgentError -import io.iohk.atala.prism.walletsdk.prismagent.REPLACEMENT_ID -import io.iohk.atala.prism.walletsdk.prismagent.helpers.build -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json -import java.util.UUID - -/** - * ALL parameters are DIDCOMMV2 format and naming conventions and follows the protocol - * https://github.com/hyperledger/aries-rfcs/tree/main/features/0453-issue-credential-v2 - */ -@Serializable -data class OfferCredential @JvmOverloads constructor( - val id: String = UUID.randomUUID().toString(), - val body: Body, - val attachments: Array, - val thid: String?, - val from: DID, - val to: DID -) { - public val type: String = ProtocolType.DidcommOfferCredential.value - - /** - * Creates a [Message] object with the provided data and returns it. - * The [Message] object includes information about the sender, recipient, message body, - * and other metadata. The [Message] object is typically used for secure, decentralized communication - * in the Atala PRISM architecture. - * - * @return The [Message] object with the provided data. - */ - fun makeMessage(): Message { - return Message( - id = id, - piuri = type, - from = from, - to = to, - body = Json.encodeToString(body), - attachments = attachments, - thid = thid - ) - } - - companion object { - - /** - * Creates an [OfferCredential] object from the provided [ProposeCredential] data. - * - * @param proposed The [ProposeCredential] object containing the proposed credential data. - * @return The [OfferCredential] object created with the provided data. - */ - @JvmStatic - fun makeOfferFromProposedCredential(proposed: ProposeCredential): OfferCredential { - return OfferCredential( - body = Body( - goalCode = proposed.body.goalCode, - comment = proposed.body.comment, - credentialPreview = proposed.body.credentialPreview - ), - attachments = proposed.attachments, - thid = proposed.thid, - from = proposed.from, - to = proposed.to - ) - } - - /** - * Converts a Message object to an OfferCredential object. - * - * @param fromMessage The Message object to convert. - * @return The converted OfferCredential object. - * @throws PrismAgentError.InvalidMessageType if the message type is invalid or the "from" and "to" fields are not present. - */ - @JvmStatic - @Throws(PrismAgentError.InvalidMessageType::class) - fun fromMessage(fromMessage: Message): OfferCredential { - require( - fromMessage.piuri == ProtocolType.DidcommOfferCredential.value && - fromMessage.from != null && - fromMessage.to != null - ) { - throw PrismAgentError.InvalidMessageType( - type = fromMessage.piuri, - shouldBe = ProtocolType.DidcommOfferCredential.value - ) - } - - val fromDID = fromMessage.from - val toDID = fromMessage.to - val body = Json.decodeFromString(fromMessage.body) - return OfferCredential( - id = fromMessage.id, - body = body, - attachments = fromMessage.attachments, - thid = fromMessage.thid, - from = fromDID, - to = toDID - ) - } - } - - /** - * Checks if the current instance of `OfferCredential` is equal to the given object. - * - * @param other The object to compare with the current instance of `OfferCredential`. - * @return `true` if the objects are equal, `false` otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as OfferCredential - - if (id != other.id) return false - if (body != other.body) return false - if (!attachments.contentEquals(other.attachments)) return false - if (thid != other.thid) return false - if (from != other.from) return false - if (to != other.to) return false - if (type != other.type) return false - - return true - } - - /** - * Calculates the hash code for the current instance of the OfferCredential class. - * - * The hash code is computed by combining the hash codes of the following properties: - * - id - * - body - * - attachments - * - thid (if not null) - * - from - * - to - * - type - * - * @return The computed hash code for the current instance of the OfferCredential class. - */ - override fun hashCode(): Int { - var result = id.hashCode() - result = 31 * result + body.hashCode() - result = 31 * result + attachments.contentHashCode() - result = 31 * result + (thid?.hashCode() ?: 0) - result = 31 * result + from.hashCode() - result = 31 * result + to.hashCode() - result = 31 * result + type.hashCode() - return result - } - - /** - * Represents the body of an OfferCredential message. - * - * @property goalCode The goal code associated with the credential. - * @property comment Additional comments related to the credential. - * @property replacementId The ID of the credential being replaced, if applicable. - * @property multipleAvailable Indicates if multiple credentials of the same type are available for selection. - * @property credentialPreview The preview of the credential to be offered. - */ - @Serializable - data class Body @JvmOverloads constructor( - @SerialName(GOAL_CODE) - val goalCode: String? = null, - val comment: String? = null, - @SerialName(REPLACEMENT_ID) - val replacementId: String? = null, - @SerialName(MULTIPLE_AVAILABLE) - val multipleAvailable: String? = null, - @SerialName(CREDENTIAL_PREVIEW) - val credentialPreview: CredentialPreview - ) { - /** - * Compares this [Body] object to the specified [other] object for equality. - * - * @param other The object to compare for equality. - * @return `true` if the objects are equal, `false` otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as Body - - if (goalCode != other.goalCode) return false - if (comment != other.comment) return false - if (replacementId != other.replacementId) return false - if (multipleAvailable != other.multipleAvailable) return false - if (credentialPreview != other.credentialPreview) return false - - return true - } - - /** - * Computes the hash code value for this object. - * - * The hash code is computed by combining the hash codes of the following properties: - * - goalCode - * - comment - * - replacementId - * - multipleAvailable - * - credentialPreview - * - * @return The hash code value for this object. - */ - override fun hashCode(): Int { - var result = goalCode?.hashCode() ?: 0 - result = 31 * result + (comment?.hashCode() ?: 0) - result = 31 * result + (replacementId?.hashCode() ?: 0) - result = 31 * result + (multipleAvailable?.hashCode() ?: 0) - result = 31 * result + credentialPreview.hashCode() - return result - } - } -} - -/** - * Builds an OfferCredential object with the provided data. - * - * @param fromDID The DID of the sender. - * @param toDID The DID of the recipient. - * @param thid The thread ID. - * @param credentialPreview The preview of the credential. - * @param credentials The map of credentials. Default value is an empty map. - * @return The constructed OfferCredential object. - */ -@JvmOverloads -inline fun OfferCredential.Companion.build( - fromDID: DID, - toDID: DID, - thid: String?, - credentialPreview: CredentialPreview, - credentials: Map = mapOf() -): OfferCredential { - val aux = credentials.map { (key, value) -> - val attachment = AttachmentDescriptor.build( - payload = value - ) - val format = CredentialFormat(attachId = attachment.id, format = key) - format to attachment - } - return OfferCredential( - body = OfferCredential.Body( - credentialPreview = credentialPreview - ), - attachments = aux.map { it.second }.toTypedArray(), - thid = thid, - from = fromDID, - to = toDID - ) -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/ProposeCredential.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/ProposeCredential.kt deleted file mode 100644 index c90026d13..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/ProposeCredential.kt +++ /dev/null @@ -1,209 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.issueCredential - -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentDescriptor -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgentError -import io.iohk.atala.prism.walletsdk.prismagent.helpers.build -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType -import kotlinx.serialization.Serializable -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json -import java.util.UUID - -/** - * ALL parameters are DIDCOMMV2 format and naming conventions and follows the protocol - * https://github.com/hyperledger/aries-rfcs/tree/main/features/0453-issue-credential-v2 - */ -@Serializable -data class ProposeCredential @JvmOverloads constructor( - val id: String = UUID.randomUUID().toString(), - val body: Body, - val attachments: Array, - val thid: String?, - val from: DID, - val to: DID -) { - public val type: String = ProtocolType.DidcommProposeCredential.value - - /** - * This function creates a new [Message] object based on the provided data. The [Message] object represents a DIDComm message, - * which is used for secure, decentralized communication in the Atala PRISM architecture. The function sets the id, piuri, - * from, to, body, attachments, and thid properties of the [Message] object. The id property is generated using a random UUID, - * and the body property is encoded as a JSON string using the [Json.encodeToString] function. The other properties are set - * based on the values passed as arguments to the function. - * - * @return A new [Message] object. - */ - fun makeMessage(): Message { - return Message( - id = id, - piuri = type, - from = from, - to = to, - body = Json.encodeToString(body), - attachments = attachments, - thid = thid - ) - } - - companion object { - /** - * Converts a Message object to a ProposeCredential object. - * - * @param fromMessage The input Message object to convert. - * @return A ProposeCredential object created from the input Message. - * @throws PrismAgentError.InvalidMessageType If the input message does not represent the expected protocol type or if it does not have "from" and "to" fields. - */ - @JvmStatic - @Throws(PrismAgentError.InvalidMessageType::class) - fun fromMessage(fromMessage: Message): ProposeCredential { - require( - fromMessage.piuri == ProtocolType.DidcommProposeCredential.value && - fromMessage.from != null && - fromMessage.to != null - ) { - throw PrismAgentError.InvalidMessageType( - type = fromMessage.piuri, - shouldBe = ProtocolType.DidcommProposeCredential.value - ) - } - - val fromDID = fromMessage.from - val toDID = fromMessage.to - val body = Json.decodeFromString(fromMessage.body) - - return ProposeCredential( - id = fromMessage.id, - body = body, - attachments = fromMessage.attachments, - thid = fromMessage.thid, - from = fromDID, - to = toDID - ) - } - } - - /** - * Represents the body of a message for proposing a credential. - * - * @property goalCode The goal code. - * @property comment The comment. - * @property credentialPreview The credential preview. - */ - @Serializable - data class Body @JvmOverloads constructor( - val goalCode: String? = null, - val comment: String? = null, - val credentialPreview: CredentialPreview - ) { - /** - * Checks if this object is equal to the specified [other] object. - * - * @param other The object to compare for equality. - * @return `true` if the objects are equal, `false` otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as Body - - if (goalCode != other.goalCode) return false - if (comment != other.comment) return false - if (credentialPreview != other.credentialPreview) return false - - return true - } - - /** - * Computes the hash code value for this object. - * - * @return The hash code value for this object. - */ - override fun hashCode(): Int { - var result = goalCode?.hashCode() ?: 0 - result = 31 * result + (comment?.hashCode() ?: 0) - result = 31 * result + credentialPreview.hashCode() - return result - } - } - - /** - * Checks if this object is equal to the specified [other] object. - * - * @param other The object to compare for equality. - * @return `true` if the objects are equal, `false` otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as ProposeCredential - - if (id != other.id) return false - if (body != other.body) return false - if (!attachments.contentEquals(other.attachments)) return false - if (thid != other.thid) return false - if (from != other.from) return false - if (to != other.to) return false - if (type != other.type) return false - - return true - } - - /** - * Computes the hash code value for this object. - * - * @return The hash code value for this object. - */ - override fun hashCode(): Int { - var result = id.hashCode() - result = 31 * result + body.hashCode() - result = 31 * result + attachments.contentHashCode() - result = 31 * result + (thid?.hashCode() ?: 0) - result = 31 * result + from.hashCode() - result = 31 * result + to.hashCode() - result = 31 * result + type.hashCode() - return result - } -} - -/** - * This method builds a ProposeCredential object based on the provided parameters. The ProposeCredential represents a proposal to issue a credential in the Atala PRISM architecture - *. The method takes in the following parameters: - * - * @param fromDID The DID of the sender of the proposal. - * @param toDID The DID of the recipient of the proposal. - * @param thid The thread ID of the proposal. Optional. - * @param credentialPreview The credential preview object that describes the proposed credential. - * @param credentials A map of credential formats and their corresponding values. The values must be of type T, which must implement the Serializable interface. The default value - * is an empty map. - * - * @return A new ProposeCredential object. - */ -@JvmOverloads -inline fun ProposeCredential.Companion.build( - fromDID: DID, - toDID: DID, - thid: String?, - credentialPreview: CredentialPreview, - credentials: Map = mapOf() -): ProposeCredential { - val aux = credentials.map { (key, value) -> - val attachment = AttachmentDescriptor.build( - payload = value - ) - val format = CredentialFormat(attachId = attachment.id, format = key) - format to attachment - } - return ProposeCredential( - body = ProposeCredential.Body( - credentialPreview = credentialPreview - ), - attachments = aux.map { it.second }.toTypedArray(), - thid = thid, - from = fromDID, - to = toDID - ) -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/RequestCredential.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/RequestCredential.kt deleted file mode 100644 index 658f7d5c0..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/RequestCredential.kt +++ /dev/null @@ -1,240 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.issueCredential - -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentDescriptor -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgentError -import io.iohk.atala.prism.walletsdk.prismagent.helpers.build -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType -import kotlinx.serialization.Serializable -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json -import java.util.UUID - -/** - * ALL parameters are DIDCOMMV2 format and naming conventions and follows the protocol - * https://github.com/hyperledger/aries-rfcs/tree/main/features/0453-issue-credential-v2 - */ -@Serializable -data class RequestCredential @JvmOverloads constructor( - val id: String = UUID.randomUUID().toString(), - val body: Body, - val attachments: Array, - val thid: String?, - val from: DID, - val to: DID -) { - val type: String = ProtocolType.DidcommRequestCredential.value - - /** - * This method is used to create a [Message] object with the specified properties. - * - * @return The created [Message] object. - */ - fun makeMessage(): Message { - return Message( - id = id, - piuri = type, - from = from, - to = to, - body = Json.encodeToString(body), - attachments = attachments, - thid = thid - ) - } - - companion object { - /** - * Converts a Message object to a RequestCredential object. - * - * @param fromMessage The Message object to convert. - * @return The converted RequestCredential object. - * @throws PrismAgentError.InvalidMessageType If the Message object does not represent the expected protocol or is missing the "from" and "to" fields. - */ - @JvmStatic - @Throws(PrismAgentError.InvalidMessageType::class) - fun fromMessage(fromMessage: Message): RequestCredential { - require( - fromMessage.piuri == ProtocolType.DidcommRequestCredential.value && - fromMessage.from != null && - fromMessage.to != null - ) { - throw PrismAgentError.InvalidMessageType( - type = fromMessage.piuri, - shouldBe = ProtocolType.DidcommRequestCredential.value - ) - } - - val fromDID = fromMessage.from - val toDID = fromMessage.to - val body = Json.decodeFromString(fromMessage.body) - - return RequestCredential( - id = fromMessage.id, - body = body, - attachments = fromMessage.attachments, - thid = fromMessage.thid, - from = fromDID, - to = toDID - ) - } - - /** - * Creates a [RequestCredential] object based on the provided [OfferCredential]. - * - * @param offer The [OfferCredential] object containing the offer credential data. - * @return The [RequestCredential] object created with the data from the offer credential. - */ - @JvmStatic - fun makeRequestFromOfferCredential(offer: OfferCredential): RequestCredential { - return RequestCredential( - body = Body( - goalCode = offer.body.goalCode, - comment = offer.body.comment - ), - attachments = offer.attachments, - thid = offer.thid, - from = offer.to, - to = offer.from - ) - } - } - - /** - * Represents the body of a request credential. - * - * @property goalCode The goal code. - * @property comment The comment. - */ - @Serializable - data class Body @JvmOverloads constructor( - val goalCode: String? = null, - val comment: String? = null - ) { - /** - * Checks if this [Body] object is equal to the specified [other] object. - * - * Two [Body] objects are considered equal if they have the same values for the following properties: - * - [goalCode] (the goal code) - * - [comment] (the comment) - * - * @param other The object to compare with this [Body] object. - * @return true if the specified [other] object is equal to this [Body] object, false otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as Body - - if (goalCode != other.goalCode) return false - if (comment != other.comment) return false - - return true - } - - /** - * Calculates the hash code for the object. - * - * The hash code is calculated based on the values of the `goalCode` and `comment` properties. - * If `goalCode` is not null, its hash code is used as part of the calculation. - * If `comment` is not null, its hash code is used as part of the calculation. - * - * @return The hash code value for the object. - */ - override fun hashCode(): Int { - var result = goalCode?.hashCode() ?: 0 - result = 31 * result + (comment?.hashCode() ?: 0) - return result - } - } - - /** - * Checks if this [RequestCredential] object is equal to the specified [other] object. - * - * Two [RequestCredential] objects are considered equal if they have the same values for the following properties: - * - [id] (the ID) - * - [body] (the body) - * - [attachments] (the attachments) - * - [thid] (the THID) - * - [from] (the sender) - * - [to] (the receiver) - * - [type] (the type) - * - * @param other The object to compare with this [RequestCredential] object. - * @return true if the specified [other] object is equal to this [RequestCredential] object, false otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as RequestCredential - - if (id != other.id) return false - if (body != other.body) return false - if (!attachments.contentEquals(other.attachments)) return false - if (thid != other.thid) return false - if (from != other.from) return false - if (to != other.to) return false - if (type != other.type) return false - - return true - } - - /** - * Calculates the hash code for the [RequestCredential] object. - * - * The hash code is calculated based on the values of the following properties: - * - [id] (the ID) - * - [body] (the body) - * - [attachments] (the attachments) - * - [thid] (the THID) - * - [from] (the sender) - * - [to] (the receiver) - * - [type] (the type) - * - * @return The hash code value for the [RequestCredential] object. - */ - override fun hashCode(): Int { - var result = id.hashCode() - result = 31 * result + body.hashCode() - result = 31 * result + attachments.contentHashCode() - result = 31 * result + (thid?.hashCode() ?: 0) - result = 31 * result + from.hashCode() - result = 31 * result + to.hashCode() - result = 31 * result + type.hashCode() - return result - } -} - -/** - * Builds a [RequestCredential] object using the provided parameters. - * - * @param fromDID The DID of the sender. - * @param toDID The DID of the receiver. - * @param thid The THID (thread ID). - * @param credentials The map of credential formats and corresponding payloads. - * @return The created [RequestCredential] object. - */ -@JvmOverloads -inline fun RequestCredential.Companion.build( - fromDID: DID, - toDID: DID, - thid: String?, - credentials: Map = mapOf() -): RequestCredential { - val aux = credentials.map { (key, value) -> - val attachment = AttachmentDescriptor.build( - payload = value - ) - val format = CredentialFormat(attachId = attachment.id, format = key) - format to attachment - } - return RequestCredential( - body = RequestCredential.Body(), - attachments = aux.map { it.second }.toTypedArray(), - thid = thid, - from = fromDID, - to = toDID - ) -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/mediation/MediationGrant.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/mediation/MediationGrant.kt deleted file mode 100644 index 62fc6a1e9..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/mediation/MediationGrant.kt +++ /dev/null @@ -1,89 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.mediation - -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.prismagent.ROUTING_DID -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable -import kotlinx.serialization.json.Json -import java.util.UUID -import kotlin.jvm.Throws - -/** - * The `MediationProtocolError` class represents an error that can occur during mediation protocol processing. - * It is derived from the [Throwable] class and is sealed, meaning that it cannot be directly instantiated. - * - * @see Throwable - */ -sealed class MediationProtocolError : Throwable() { - /** - * The `InvalidMediationGrantError` class represents an error that can occur when a provided message is not a valid mediation grant. - * - * @throws MediationProtocolError.InvalidMediationGrantError if the provided message is not a valid mediation grant. - */ - class InvalidMediationGrantError : MediationProtocolError() -} - -/** - * The MediationGrant class represents a mediation grant in the Atala PRISM architecture. - * A mediation grant is used for granting permission to mediate a specific request. - * - * @property id The unique identifier of the mediation grant. - * @property type The type of the mediation grant. - * @property body The body of the mediation grant containing the routing DID. - * @constructor Creates a MediationGrant object with the specified ID and body. - * @throws MediationProtocolError.InvalidMediationGrantError if the provided message is not a valid mediation grant. - */ -class MediationGrant { - var id: String - var type = ProtocolType.DidcommMediationGrant.value - var body: Body - - /** - * Represents a mediation grant in the Atala PRISM architecture. - * A mediation grant is used for granting permission to mediate a specific request. - * - * @property id The unique identifier of the mediation grant. - * @property type The type of the mediation grant. - * @property body The body of the mediation grant containing the routing DID. - * - * @constructor Creates a MediationGrant object with the specified ID and body. - * - * @throws MediationProtocolError.InvalidMediationGrantError if the provided message is not a valid mediation grant. - */ - constructor( - id: String = UUID.randomUUID().toString(), - body: Body - ) { - this.id = id - this.body = body - } - - /** - * The `MediationGrant` class represents a mediation grant in the Atala PRISM architecture. - * A mediation grant is used for granting permission to mediate a specific request. - * - * @property id The unique identifier of the mediation grant. - * @property type The type of the mediation grant. - * @property body The body of the mediation grant containing the routing DID. - * @constructor Creates a MediationGrant object with the specified ID and body. - * @throws MediationProtocolError.InvalidMediationGrantError if the provided message is not a valid mediation grant. - */ - @Throws(MediationProtocolError.InvalidMediationGrantError::class) - constructor(fromMessage: Message) { - if (fromMessage.piuri != ProtocolType.DidcommMediationGrant.value) { - throw MediationProtocolError.InvalidMediationGrantError() - } - this.id = fromMessage.id - this.body = Json.decodeFromString(fromMessage.body) - } - - /** - * The [Body] class represents a body object that can be included in a [Message] object. - * It is used for secure, decentralized communication in the Atala PRISM architecture. - * - * @see Message - */ - @Serializable - data class Body(@SerialName(ROUTING_DID)var routingDid: String) -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/mediation/MediationKeysUpdateList.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/mediation/MediationKeysUpdateList.kt deleted file mode 100644 index acac975a4..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/mediation/MediationKeysUpdateList.kt +++ /dev/null @@ -1,146 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.mediation - -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.prismagent.ADD -import io.iohk.atala.prism.walletsdk.prismagent.RECEPIENT_DID -import io.iohk.atala.prism.walletsdk.prismagent.UPDATES -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType -import kotlinx.serialization.EncodeDefault -import kotlinx.serialization.ExperimentalSerializationApi -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json -import java.util.UUID - -/** - * MediationKeysUpdateList is a serializable class representing the list of keys updated in a mediation process. - * - * @property id The ID of the mediation keys update list. - * @property from The sender of the mediation keys update list. - * @property to The recipient of the mediation keys update list. - * @property type The type of the mediation keys update list. - * @property body The body of the mediation keys update list, containing the updates. - */ -@Serializable -final class MediationKeysUpdateList { - var id: String - var from: DID - var to: DID - var type = ProtocolType.DidcommMediationKeysUpdate.value - var body: Body - - /** - * The `MediationKeysUpdateList` class represents a list of updates for mediation keys. - * It is used to create a `Message` object with the specified parameters. - * - * @property id The ID of the `MediationKeysUpdateList` object. - * @property from The sender DID. - * @property to The recipient DID. - * @property recipientDids An array of recipient DIDs. - */ - @JvmOverloads - constructor( - id: String = UUID.randomUUID().toString(), - from: DID, - to: DID, - recipientDids: Array - ) { - this.id = id - this.from = from - this.to = to - this.body = Body( - updates = recipientDids.map { - Update(recipientDid = it.toString()) - }.toTypedArray() - ) - } - - /** - * This method creates a [Message] object with the specified parameters. - * The [Message] object represents a DIDComm message used for secure and decentralized communication in the Atala PRISM architecture. - * The [Message] object includes information about the sender, recipient, message body, and other metadata. - * The method sets default values for some properties and returns the created [Message] object. - * - * @return The created [Message] object. - */ - fun makeMessage(): Message { - return Message( - id = id, - piuri = type, - from = from, - to = to, - fromPrior = null, - body = Json.encodeToString(body), - extraHeaders = emptyMap(), - createdTime = "", - expiresTimePlus = "", - attachments = emptyArray(), - thid = null, - pthid = null, - ack = emptyArray(), - direction = Message.Direction.SENT - ) - } - - /** - * Represents an update object for mediation keys. - * - * @property recipientDid The recipient DID. - * @property action The action to be performed. - * @constructor Creates an instance of [Update]. - */ - @Serializable - data class Update - @OptIn(ExperimentalSerializationApi::class) - @JvmOverloads - constructor( - @SerialName(RECEPIENT_DID) - var recipientDid: String, - @EncodeDefault - var action: String = ADD - ) - - /** - * Represents a body object that contains `updates` for mediation keys. - * - * @property updates An array of [Update] objects representing the updates for mediation keys. - */ - @Serializable - data class Body @JvmOverloads constructor(var updates: Array = emptyArray()) { - /** - * Checks if this object is equal to another object. - * - * @param other The object to compare with. - * @return true if the objects are equal, false otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as Body - - return updates.contentEquals(other.updates) - } - - /** - * Calculates the hash code for the object. - * - * @return The hash code value for the object. - */ - override fun hashCode(): Int { - return updates.contentHashCode() - } - - /** - * Converts the updates in this [Body] object to a [Map] with keys of type [String] - * and values of type [Any?]. - * - * @return A [Map] containing the updates as key-value pairs. - */ - fun toMapStringAny(): Map { - return mapOf(Pair(UPDATES, updates)) - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/mediation/MediationRequest.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/mediation/MediationRequest.kt deleted file mode 100644 index 912e4f2ec..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/mediation/MediationRequest.kt +++ /dev/null @@ -1,104 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.mediation - -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.prismagent.EMPTY_BODY -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType -import java.util.UUID - -/** - * The `MediationRequest` class represents a mediation request in the application. - * - * @property id The unique identifier of the mediation request. - * @property type The type of the mediation request. Default value is [ProtocolType.DidcommMediationRequest]. - * @property from The source DID (Decentralized Identifier) of the mediation request. - * @property to The target DID (Decentralized Identifier) of the mediation request. - * @constructor Creates a `MediationRequest`. - * @param id The unique identifier of the mediation request. - * @param type The type of the mediation request. Default value is [ProtocolType.DidcommMediationRequest]. - * @param from The source DID (Decentralized Identifier) of the mediation request. - * @param to The target DID (Decentralized Identifier) of the mediation request. - */ -final class MediationRequest @JvmOverloads constructor( - val id: String, - val type: String = ProtocolType.DidcommMediationRequest.value, - val from: DID, - val to: DID -) { - /** - * The `MediationRequest` class represents a request for mediation between two entities. - * It contains information about the sender (`from`) and the recipient (`to`) of the mediation request. - * - * @property id The unique identifier of the mediation request. - * @property from The DID of the entity sending the request. - * @property to The DID of the entity receiving the request. - * - * @constructor Creates a new `MediationRequest` object with the specified `from` and `to` DIDs. - * The `id` is automatically generated using a random UUID. - */ - constructor( - from: DID, - to: DID - ) : this( - id = UUID.randomUUID().toString(), - from = from, - to = to - ) - - /** - * Creates a new [Message] object with default values for some properties and returns it. - * - * @return The newly created [Message] object. - */ - fun makeMessage(): Message { - return Message( - id = id, - piuri = type, - from = from, - to = to, - fromPrior = null, - body = EMPTY_BODY, - extraHeaders = mapOf(Pair("return_route", "all")), - attachments = emptyArray(), - thid = null, - pthid = null, - ack = emptyArray(), - direction = Message.Direction.SENT - ) - } - - /** - * Checks if this [MediationRequest] object is equal to another object. - * - * Two [MediationRequest] objects are considered equal if their properties match. - * - * @param other The object to compare equality with. - * @return true if this [MediationRequest] object is equal to the [other] object, false otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as MediationRequest - - if (id != other.id) return false - if (type != other.type) return false - if (from != other.from) return false - if (to != other.to) return false - - return true - } - - /** - * Generates the hash code for the `MediationRequest` object. - * - * @return The hash code value for the `MediationRequest` object. - */ - override fun hashCode(): Int { - var result = id.hashCode() - result = 31 * result + type.hashCode() - result = 31 * result + from.hashCode() - result = 31 * result + to.hashCode() - return result - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/outOfBand/InvitationRunner.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/outOfBand/InvitationRunner.kt deleted file mode 100644 index 2c54c1825..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/outOfBand/InvitationRunner.kt +++ /dev/null @@ -1,24 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.outOfBand - -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Mercury -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.ktor.http.Url - -/** - * The InvitationRunner class is responsible for running the invitation process by parsing the out-of-band URL, - * unpacking the message, and returning the unpacked message object. - * - * @param mercury The Mercury interface implementation used for packing and unpacking messages. - * @param url The URL object representing the out-of-band URL. - */ -class InvitationRunner(private val mercury: Mercury, private val url: Url) { - /** - * Runs the invitation process by parsing the out-of-band URL, unpacking the message, and returning the unpacked message object. - * - * @return The unpacked [Message] object. - */ - suspend fun run(): Message { - val messageString = OutOfBandParser().parseMessage(url) - return mercury.unpackMessage(messageString) - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/outOfBand/OutOfBandParser.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/outOfBand/OutOfBandParser.kt deleted file mode 100644 index 9ac6da753..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/outOfBand/OutOfBandParser.kt +++ /dev/null @@ -1,29 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.outOfBand - -import io.iohk.atala.prism.apollo.base64.base64UrlDecoded -import io.iohk.atala.prism.walletsdk.domain.models.CommonError -import io.iohk.atala.prism.walletsdk.prismagent.OOB -import io.ktor.http.URLBuilder -import io.ktor.http.Url - -/** - * The OutOfBandParser class is responsible for parsing out-of-band messages. - */ -class OutOfBandParser { - - /** - * Parses the message from the given URL. - * - * @param url The URL object representing the message. - * @return The parsed message. - * @throws CommonError.InvalidURLError If the URL is invalid. - */ - @Throws(CommonError.InvalidURLError::class) - fun parseMessage(url: Url): String { - val urlBuilder = URLBuilder(url) - - urlBuilder.parameters[OOB]?.let { message -> - return message.base64UrlDecoded - } ?: throw CommonError.InvalidURLError(url = url.toString()) - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/outOfBand/PrismOnboardingInvitation.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/outOfBand/PrismOnboardingInvitation.kt deleted file mode 100644 index bcd927fb1..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/outOfBand/PrismOnboardingInvitation.kt +++ /dev/null @@ -1,46 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.outOfBand - -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.prismagent.FROM -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable -import kotlinx.serialization.Transient -import kotlinx.serialization.decodeFromString -import kotlinx.serialization.json.Json - -/** - * Represents an onboarding invitation for PRISM. - * - * @param onboardEndpoint The endpoint for onboarding. - * @property fromString The string representation of the "from" field. - * @property from The DID object representing the "from" field. - * @property type The type of the invitation. - */ -@Serializable -data class PrismOnboardingInvitation @JvmOverloads constructor( - val onboardEndpoint: String, - @SerialName(FROM) - private val fromString: String, - @Transient - var from: DID? = null, - val type: String -) : InvitationType() { - - init { - // TODO: Should we check first if a DID instance was based or not? - from = DID(fromString) - } - - companion object { - /** - * Parses a JSON string into a PrismOnboardingInvitation object. - * - * @param string The JSON string to parse. - * @return A PrismOnboardingInvitation object parsed from the JSON string. - */ - @JvmStatic - fun fromJsonString(string: String): PrismOnboardingInvitation { - return Json.decodeFromString(string) - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/pickup/PickupDelivery.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/pickup/PickupDelivery.kt deleted file mode 100644 index 8e6fa9de5..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/pickup/PickupDelivery.kt +++ /dev/null @@ -1,35 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.pickup - -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentDescriptor -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgentError -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType - -/** - * The `PickupDelivery` class represents a pickup delivery protocol type in the Atala PRISM architecture. - * It is a final class, meaning it cannot be subclassed. - * - * @throws (PrismAgentError.InvalidMessageType):: if the protocol type of the given message is not `ProtocolType.PickupDelivery`. - * - * @property id: The id of the pickup delivery. - * @property type: The protocol type of the pickup delivery, always set to `ProtocolType.PickupDelivery.value`. - * @property attachments: An array of attachment descriptors associated with the pickup delivery. - */ -final class PickupDelivery -@Throws(PrismAgentError.InvalidMessageType::class) -constructor(fromMessage: Message) { - var id: String - var type = ProtocolType.PickupDelivery.value - val attachments: Array - - init { - if (fromMessage.piuri != ProtocolType.PickupDelivery.value) { - throw PrismAgentError.InvalidMessageType( - type = fromMessage.piuri, - shouldBe = ProtocolType.PickupDelivery.value - ) - } - this.id = fromMessage.id - this.attachments = fromMessage.attachments - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/pickup/PickupReceived.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/pickup/PickupReceived.kt deleted file mode 100644 index 376c45c2c..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/pickup/PickupReceived.kt +++ /dev/null @@ -1,87 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.pickup - -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.prismagent.MESSAGE_ID_LIST -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json -import java.util.UUID - -/** - * Represents a pickup received message. - * - * @property id The unique identifier of the pickup received message. If not provided, a random UUID will be generated. - * @property from The sender's DID (Decentralized Identifier) of the pickup received message. - * @property to The recipient's DID (Decentralized Identifier) of the pickup received message. - * @property body The body of the pickup received message. - */ -final class PickupReceived @JvmOverloads constructor( - var id: String = UUID.randomUUID().toString(), - val from: DID, - val to: DID, - var body: Body -) { - var type = ProtocolType.PickupReceived.value - - /** - * Creates a [Message] object for sending a message. - * - * @return A [Message] object representing the message to send. - */ - fun makeMessage(): Message { - return Message( - piuri = type, - from = from, - to = to, - body = Json.encodeToString(body), - extraHeaders = mapOf(Pair("return_route", "all")) - ) - } - - /** - * Represents a body of a message. - * - * @property messageIdList An array of message IDs. - */ - @Serializable - data class Body(@SerialName(MESSAGE_ID_LIST) var messageIdList: Array) { - /** - * Overrides the default implementation of `equals` defined in the `Any` class. - * This method checks if the current instance is equal to the specified [other] object. - * - * Two objects are considered equal if they meet the following conditions: - * - They refer to the same memory address (identity check) - * - They are of the same class - * - The [messageIdList] property of both objects is equal - * - * @param other The object to compare equality with - * @return `true` if the objects are equal, `false` otherwise - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (javaClass != other?.javaClass) return false - - other as Body - - return messageIdList.contentEquals(other.messageIdList) - } - - /** - * Returns the hash code value for this object. - * - * This method overrides the default implementation of `hashCode` defined in the `Any` class. - * The hash code of an object is an integer value that represents its unique identity. - * Two objects that are equal must also have the same hash code. - * - * This implementation calculates the hash code based on the content of the `messageIdList` array. - * - * @return the hash code value for this object - */ - override fun hashCode(): Int { - return messageIdList.contentHashCode() - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/pickup/PickupRequest.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/pickup/PickupRequest.kt deleted file mode 100644 index d704e5eb0..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/pickup/PickupRequest.kt +++ /dev/null @@ -1,62 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.pickup - -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType -import kotlinx.serialization.Serializable -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json -import java.util.UUID - -/** - * A class representing a pickup request. - * - * @property id The unique identifier of the pickup request. - * @property from The sender's DID (Decentralized Identifier). - * @property to The receiver's DID (Decentralized Identifier). - * @property body The body of the pickup request. - * @property type The type of the pickup request. - * @constructor Creates a pickup request with the specified parameters. - */ -final class PickupRequest @JvmOverloads constructor( - var id: String = UUID.randomUUID().toString(), - val from: DID, - val to: DID, - var body: Body -) { - var type = ProtocolType.PickupRequest.value - - /** - * Creates a [Message] object using the provided parameters. - * - * @return The created [Message] object. - */ - fun makeMessage(): Message { - return Message( - id = id, - piuri = type, - from = from, - to = to, - fromPrior = null, - body = Json.encodeToString(body), - extraHeaders = mapOf(Pair("return_route", "all")), - createdTime = "", - expiresTimePlus = "", - attachments = emptyArray(), - thid = null, - pthid = null, - ack = emptyArray(), - direction = Message.Direction.SENT - ) - } - - /** - * A class representing the body of a message. - * - * @property recipientKey The key of the message recipient. - * @property limit The maximum number of messages to pick up. - * @constructor Creates a Body object with the specified parameters. - */ - @Serializable - data class Body(var recipientKey: String? = null, var limit: Int) -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/pickup/PickupRunner.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/pickup/PickupRunner.kt deleted file mode 100644 index 2a4e117ca..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/pickup/PickupRunner.kt +++ /dev/null @@ -1,112 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.pickup - -import io.iohk.atala.prism.apollo.base64.base64UrlDecoded -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Mercury -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentBase64 -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentDescriptor -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentJsonData -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgentError -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType - -/** - * The `PickupRunner` class is responsible for processing `Message` objects related to pickup requests and delivering them - * using the `Mercury` service. It provides methods to run the pickup request and process the response. - * - * @property message The pickup request message to process. - * @property mercury The `Mercury` service to use for message delivery. - */ -class PickupRunner(message: Message, private val mercury: Mercury) { - - /** - * The [PickupResponseType] enum class represents the response types for the pickup functionality. - * The response types can be either "status" or "delivery". - * - * @property type The string representation of the pickup response type. - * @constructor Creates a [PickupResponseType] enum with the given type string. - */ - enum class PickupResponseType(val type: String) { - STATUS("status"), - DELIVERY("delivery") - } - - /** - * The `PickupResponse` data class represents the response from the pickup functionality. - * It includes the type of response (`PickupResponseType`) and a `Message` object. - * - * @property type The type of pickup response. - * @property message The message object. - */ - data class PickupResponse(val type: PickupResponseType, val message: Message) - - /** - * The [PickupAttachment] data class represents an attachment in the pickup functionality. - * It includes the attachment ID and the attachment data. - * - * @property attachmentId The ID of the attachment. - * @property data The data of the attachment. - */ - data class PickupAttachment( - val attachmentId: String, - val data: String - ) - - private val message: PickupResponse - - init { - when (message.piuri) { - ProtocolType.PickupStatus.value -> { - this.message = PickupResponse(PickupResponseType.STATUS, message) - } - - ProtocolType.PickupDelivery.value -> { - this.message = PickupResponse(PickupResponseType.DELIVERY, message) - } - - else -> { - throw PrismAgentError.InvalidMessageType( - type = message.piuri, - shouldBe = "${ProtocolType.PickupStatus.value} or ${ProtocolType.PickupDelivery.value}" - ) - } - } - } - - /** - * Runs the pickup functionality and returns an array of pairs containing attachment IDs and unpacked messages. - * If the type of the pickup response is DELIVERY, it processes the attachments, unpacks the messages, and returns them as an array. - * If the type is not DELIVERY, it returns an empty array. - * - * @return An array of pairs containing attachment IDs and unpacked messages. - */ - suspend fun run(): Array> { - return if (message.type == PickupResponseType.DELIVERY) { - message.message.attachments - .mapNotNull { processAttachment(it) } - .map { Pair(it.attachmentId, mercury.unpackMessage(it.data)) } - .toTypedArray() - } else { - arrayOf() - } - } - - /** - * Process the given attachment and convert it to a PickupAttachment object. - * - * @param attachment The AttachmentDescriptor to be processed. - * @return The PickupAttachment object if the attachment data is of type AttachmentBase64 or AttachmentJsonData, otherwise null. - * @TODO: Clean this method - */ - private fun processAttachment(attachment: AttachmentDescriptor): PickupAttachment? { - return if (Message.isBase64Attachment(attachment.data)) { - PickupAttachment(attachmentId = attachment.id, data = (attachment.data as AttachmentBase64).base64.base64UrlDecoded) - } else if (Message.isJsonAttachment(attachment.data)) { - PickupAttachment( - attachmentId = attachment.id, - data = (attachment.data as AttachmentJsonData).data - ) - } else { - null - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/proofOfPresentation/Presentation.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/proofOfPresentation/Presentation.kt deleted file mode 100644 index ae46ba9a8..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/proofOfPresentation/Presentation.kt +++ /dev/null @@ -1,255 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.proofOfPresentation - -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentDescriptor -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgentError -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType -import kotlinx.serialization.Serializable -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json -import java.util.UUID - -/** - * Data class representing proof types. - * - * @property schema The schema of the proof. - * @property requiredFields An optional array of required fields for the proof. - * @property trustIssuers An optional array of trusted issuers for the proof. - */ -@Serializable -data class ProofTypes( - val schema: String, - val requiredFields: Array?, - val trustIssuers: Array? -) { - /** - * Overrides the equals method from the Any class to compare two ProofTypes objects for equality. - * - * @param other The object to compare for equality. - * @return true if the objects are equal, false otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) { - return true - } - if (other == null || this::class != other::class) { - return false - } - - other as ProofTypes - - if (schema != other.schema) { - return false - } - if (requiredFields != null) { - if (other.requiredFields == null) { - return false - } - if (!requiredFields.contentEquals(other.requiredFields)) { - return false - } - } else if (other.requiredFields != null) { - return false - } - if (trustIssuers != null) { - if (other.trustIssuers == null) { - return false - } - if (!trustIssuers.contentEquals(other.trustIssuers)) { - return false - } - } else if (other.trustIssuers != null) { - return false - } - - return true - } - - /** - * Overrides the hashCode method from the Any class to generate a hash code for the ProofTypes object. - * - * @return The hash code value for the ProofTypes object. - */ - override fun hashCode(): Int { - var result = schema.hashCode() - result = 31 * result + (requiredFields?.contentHashCode() ?: 0) - result = 31 * result + (trustIssuers?.contentHashCode() ?: 0) - return result - } -} - -/** - * The Presentation class represents a presentation message in the PrismAgent software. - * It contains the necessary information for constructing a presentation message. - * - * @property type The type of the presentation message. - * @property id The unique identifier for the presentation message. - * @property body The body of the presentation message, including goal code and comment. - * @property attachments An array of AttachmentDescriptor objects representing the attachments in the message. - * @property thid The thread ID of the presentation message. - * @property from The sender's DID. - * @property to The recipient's DID. - */ -class Presentation { - val type = ProtocolType.DidcommPresentation.value - lateinit var id: String - lateinit var body: Body - lateinit var attachments: Array - var thid: String? = null - lateinit var from: DID - lateinit var to: DID - - /** - * The Presentation class represents a presentation message in the PrismAgent software. - * It contains the necessary information for constructing a presentation message. - * - * @param id The unique identifier for the presentation message. - * @param body The body of the presentation message, including goal code and comment. - * @param attachments An array of AttachmentDescriptor objects representing the attachments in the message. - * @param thid The thread ID of the presentation message. - * @param from The sender's DID. - * @param to The recipient's DID. - */ - @JvmOverloads - constructor( - id: String? = null, - body: Body, - attachments: Array, - thid: String? = null, - from: DID, - to: DID - ) { - this.id = id ?: UUID.randomUUID().toString() - this.body = body - this.attachments = attachments - this.thid = thid - this.from = from - this.to = to - } - - /** - * Constructor for creating a Presentation object from a Message object. - * - * @param fromMessage The Message object to create Presentation from. - * @throws PrismAgentError.InvalidMessageType if the message type does not represent the protocol "didcomm.presentation" or if the message does not have "from" and "to" fields. - */ - @Throws(PrismAgentError.InvalidMessageType::class) - constructor(fromMessage: Message) { - if ( - fromMessage.piuri == ProtocolType.DidcommPresentation.value && - fromMessage.from != null && - fromMessage.to != null - ) { - val body = Json.decodeFromString(fromMessage.body) - Presentation( - fromMessage.id, - body, - fromMessage.attachments, - fromMessage.thid, - fromMessage.from, - fromMessage.to - ) - } else { - throw PrismAgentError.InvalidMessageType( - type = fromMessage.piuri, - shouldBe = ProtocolType.DidcommPresentation.value - ) - } - } - - /** - * Creates a new [Message] object based on the provided parameters. - * - * @return The newly created [Message] object. - */ - fun makeMessage(): Message { - return Message( - id = id, - piuri = type, - from = from, - to = to, - body = Json.encodeToString(body), - attachments = attachments, - thid = thid - ) - } - - /** - * Converts a message into a Presentation object. - * - * @param msg The input message to convert. - * @return The converted Presentation object. - * @throws PrismAgentError.InvalidMessageType If the message type is invalid. - */ - @Throws(PrismAgentError.InvalidMessageType::class) - fun makePresentationFromRequest(msg: Message): Presentation { - val requestPresentation = RequestPresentation.fromMessage(msg) - return Presentation( - body = Body( - goalCode = requestPresentation.body.goalCode, - comment = requestPresentation.body.comment - ), - attachments = requestPresentation.attachments, - thid = requestPresentation.id, - from = requestPresentation.to, - to = requestPresentation.from - ) - } - - /** - * Compares this Presentation object with the specified object for equality. - * - * @param other The object to compare with this Presentation object. - * @return `true` if the specified object is equal to this Presentation object, `false` otherwise. - */ - override fun equals(other: Any?): Boolean { - if (other == null) return false - if (other::class != this::class) return false - val otherPresentation = other as Presentation - return otherPresentation.type == this.type && - otherPresentation.id == this.id && - otherPresentation.body == this.body && - otherPresentation.attachments.contentEquals(this.attachments) && - otherPresentation.thid == this.thid && - otherPresentation.from == this.from && - otherPresentation.to == this.to - } - - /** - * Calculates the hash code value for the Presentation object. - * - * The hash code is calculated based on the values of the following properties: - * - type - * - id - * - body - * - attachments - * - thid (nullable) - * - from - * - to - * - * @return The hash code value for the Presentation object. - */ - override fun hashCode(): Int { - var result = type.hashCode() - result = 31 * result + id.hashCode() - result = 31 * result + body.hashCode() - result = 31 * result + attachments.contentHashCode() - result = 31 * result + (thid?.hashCode() ?: 0) - result = 31 * result + from.hashCode() - result = 31 * result + to.hashCode() - return result - } - - /** - * Represents the body of a Presentation object. - * - * @param goalCode The goal code of the presentation body. - * @param comment The comment associated with the presentation body. - */ - @Serializable - data class Body @JvmOverloads constructor( - val goalCode: String? = null, - val comment: String? = null - ) -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/proofOfPresentation/ProposePresentation.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/proofOfPresentation/ProposePresentation.kt deleted file mode 100644 index d5c0ec4a2..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/proofOfPresentation/ProposePresentation.kt +++ /dev/null @@ -1,233 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.proofOfPresentation - -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentDescriptor -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.prismagent.GOAL_CODE -import io.iohk.atala.prism.walletsdk.prismagent.PROOF_TYPES -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgentError -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json -import java.util.UUID - -/** - * Class representing a proposal for a presentation. - * - * @property id The ID of the presentation. - * @property type The type of the presentation. - * @property body The body of the presentation. - * @property attachments The attachments of the presentation. - * @property thid The thread ID of the presentation. - * @property from The sender of the presentation. - * @property to The recipient of the presentation. - * @constructor Creates a ProposePresentation instance. - * @throws PrismAgentError.InvalidMessageType If the message type is invalid. - */ -class ProposePresentation { - - lateinit var id: String - val type = ProtocolType.DidcommProposePresentation.value - lateinit var body: Body - lateinit var attachments: Array - var thid: String? = null - lateinit var from: DID - lateinit var to: DID - - /** - * The `ProposePresentation` class represents a proposal for a presentation in the Prism agent. - * It is used to create a new `ProposePresentation` object with the given parameters. - * - * @param id The ID of the proposal. If not provided, a new random UUID will be generated. - * @param body The body of the proposal, including goal code, comment, and proof types. - * @param attachments An array of attachment descriptors for the proposal. - * @param thid The thread ID of the message. - * @param from The sender's DID. - * @param to The recipient's DID. - */ - @JvmOverloads - constructor( - id: String? = UUID.randomUUID().toString(), - body: Body, - attachments: Array, - thid: String?, - from: DID, - to: DID - ) { - this.id = id ?: UUID.randomUUID().toString() - this.body = body - this.attachments = attachments - this.thid = thid - this.from = from - this.to = to - } - - /** - * Constructs a ProposePresentation object by processing a Message. - * - * @throws PrismAgentError.InvalidMessageType if the fromMessage does not represent the expected protocol type - * - * @param fromMessage the input Message object - */ - @Throws(PrismAgentError.InvalidMessageType::class) - constructor(fromMessage: Message) { - if (fromMessage.piuri == ProtocolType.DidcommProposePresentation.value && - fromMessage.from != null && - fromMessage.to != null - ) { - ProposePresentation( - id = fromMessage.id, - body = Json.decodeFromString(fromMessage.body), - attachments = fromMessage.attachments, - thid = fromMessage.thid, - from = fromMessage.from, - to = fromMessage.to - ) - } else { - throw PrismAgentError.InvalidMessageType( - type = fromMessage.piuri, - shouldBe = ProtocolType.DidcommProposePresentation.value - ) - } - } - - /** - * Creates a [Message] object based on the current state of the [ProposePresentation] instance. - * The [Message] object includes information about the sender, recipient, message body, and other metadata. - * - * @return The created [Message] object. - */ - fun makeMessage(): Message { - return Message( - id = this.id, - piuri = this.type, - from = this.from, - to = this.to, - body = Json.encodeToString(this.body), - attachments = this.attachments, - thid = this.thid - ) - } - - /** - * Creates a proposal presentation from a request message. - * - * @param msg The request message. - * @return The created `ProposePresentation` object. - * @throws PrismAgentError.InvalidMessageType If the message type does not represent the expected protocol. - */ - @Throws(PrismAgentError.InvalidMessageType::class) - fun makeProposalFromRequest(msg: Message): ProposePresentation { - val request = RequestPresentation.fromMessage(msg) - - return ProposePresentation( - body = Body( - goalCode = request.body.goalCode, - comment = request.body.comment, - proofTypes = request.body.proofTypes - ), - attachments = request.attachments, - thid = msg.id, - from = request.to, - to = request.from - ) - } - - /** - * Compares this object with the specified object for equality. - * - * @param other the object to compare for equality. - * @return `true` if the objects are equal, `false` otherwise. - */ - override fun equals(other: Any?): Boolean { - if (other == null) return false - if (other::class != this::class) return false - val otherPresentation = other as ProposePresentation - return otherPresentation.type == this.type && - otherPresentation.id == this.id && - otherPresentation.body == this.body && - otherPresentation.attachments.contentEquals(this.attachments) && - otherPresentation.thid == this.thid && - otherPresentation.from == this.from && - otherPresentation.to == this.to - } - - /** - * Calculates the hash code of the [ProposePresentation] instance. - * - * The hash code is calculated based on the following fields of the instance: - * - id - * - type - * - body - * - attachments - * - thid (nullable) - * - from - * - to - * - * @return The hash code of the [ProposePresentation] instance. - */ - override fun hashCode(): Int { - var result = id.hashCode() - result = 31 * result + type.hashCode() - result = 31 * result + body.hashCode() - result = 31 * result + attachments.contentHashCode() - result = 31 * result + (thid?.hashCode() ?: 0) - result = 31 * result + from.hashCode() - result = 31 * result + to.hashCode() - return result - } - - /** - * Represents the body of a message in the ProposePresentation protocol. - * - * @property goalCode The goal code for the presentation. - * @property comment Additional comment about the presentation. - * @property proofTypes An array of proof types. - */ - @Serializable - data class Body @JvmOverloads constructor( - @SerialName(GOAL_CODE) - val goalCode: String? = null, - val comment: String? = null, - @SerialName(PROOF_TYPES) - val proofTypes: Array - ) { - /** - * Compares this [Body] object with the specified object for equality. - * - * @param other the object to compare for equality. - * @return `true` if the objects are equal, `false` otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as Body - - if (goalCode != other.goalCode) return false - if (comment != other.comment) return false - if (!proofTypes.contentEquals(other.proofTypes)) return false - - return true - } - - /** - * Calculates the hash code of the [Body] instance. - * - * The hash code is calculated based on the following fields of the instance: - * - goalCode - * - comment - * - proofTypes - * - * @return The hash code of the [Body] instance. - */ - override fun hashCode(): Int { - var result = goalCode?.hashCode() ?: 0 - result = 31 * result + (comment?.hashCode() ?: 0) - result = 31 * result + proofTypes.contentHashCode() - return result - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/proofOfPresentation/RequestPresentation.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/proofOfPresentation/RequestPresentation.kt deleted file mode 100644 index 62ae03f9e..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/proofOfPresentation/RequestPresentation.kt +++ /dev/null @@ -1,228 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.proofOfPresentation - -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentDescriptor -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.prismagent.GOAL_CODE -import io.iohk.atala.prism.walletsdk.prismagent.PROOF_TYPES -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgentError -import io.iohk.atala.prism.walletsdk.prismagent.WILL_CONFIRM -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json -import java.util.UUID - -@Serializable -/** - * The `RequestPresentation` class represents a request for presentation of credentials or proofs in a DIDComm protocol. - * - * @property id The unique identifier of the request. - * @property body The content of the request. - * @property attachments The array of attachment descriptors associated with the request. - * @property thid The thread ID of the request message. Default value is `null`. - * @property from The DID of the sender of the request. - * @property to The DID of the recipient of the request. - */ -data class RequestPresentation( - val id: String = UUID.randomUUID().toString(), - val body: Body, - val attachments: Array, - val thid: String? = null, - val from: DID, - val to: DID -) { - - val type = ProtocolType.DidcommRequestPresentation.value - - /** - * Creates a new [Message] object based on the current state of the [RequestPresentation] instance. - * The [Message] object contains information about the sender, recipient, message body, and other metadata. - * This method is typically used to convert a [RequestPresentation] instance into a [Message] object for communication purposes. - * - * @return The newly created [Message] object. - */ - fun makeMessage(): Message { - return Message( - id = this.id, - piuri = this.type, - from = this.from, - to = this.to, - body = Json.encodeToString(this.body), - attachments = this.attachments, - thid = this.thid - ) - } - - /** - * Checks if this [RequestPresentation] object is equal to the specified [other] object. - * - * Two [RequestPresentation] objects are considered equal if they meet the following conditions: - * - The two objects have the same class type. - * - The id, body, attachments, thid, from, to, and type properties of the two objects are also equal. - * - * @param other The object to compare with this [RequestPresentation] object. - * @return true if the specified [other] object is equal to this [RequestPresentation] object, false otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (javaClass != other?.javaClass) return false - - other as RequestPresentation - - if (id != other.id) return false - if (body != other.body) return false - if (!attachments.contentEquals(other.attachments)) return false - if (thid != other.thid) return false - if (from != other.from) return false - if (to != other.to) return false - return type == other.type - } - - /** - * Calculates the hash code for the [RequestPresentation] object. - * - * The hash code is calculated based on the following properties of the [RequestPresentation] object: - * - [id] - * - [body] - * - [attachments] - * - [thid] - * - [from] - * - [to] - * - [type] - * - * @return The hash code value for the [RequestPresentation] object. - */ - override fun hashCode(): Int { - var result = id.hashCode() - result = 31 * result + body.hashCode() - result = 31 * result + attachments.contentHashCode() - result = 31 * result + (thid?.hashCode() ?: 0) - result = 31 * result + from.hashCode() - result = 31 * result + to.hashCode() - result = 31 * result + type.hashCode() - return result - } - - companion object { - /** - * Converts a given [Message] object to a [RequestPresentation] object. - * - * @param fromMessage The [Message] object to convert. - * @return The converted [RequestPresentation] object. - * @throws PrismAgentError.InvalidMessageType if the [Message] object does not represent the correct protocol - * or if it is missing the "from" and "to" fields. - */ - @JvmStatic - @Throws(PrismAgentError.InvalidMessageType::class) - fun fromMessage(fromMessage: Message): RequestPresentation { - if (fromMessage.piuri == ProtocolType.DidcommRequestPresentation.value && - fromMessage.from != null && - fromMessage.to != null - ) { - return RequestPresentation( - id = fromMessage.id, - body = Json.decodeFromString(fromMessage.body), - attachments = fromMessage.attachments, - thid = fromMessage.thid, - from = fromMessage.from, - to = fromMessage.to - ) - } else { - throw PrismAgentError.InvalidMessageType( - type = fromMessage.piuri, - shouldBe = ProtocolType.DidcommRequestPresentation.value - ) - } - } - - /** - * Creates a [RequestPresentation] object based on the given [msg]. - * - * @param msg The [Message] object representing a proposal. - * @return The newly created [RequestPresentation] object. - * @throws PrismAgentError.InvalidMessageType if the message type is invalid. - */ - @JvmStatic - @Throws(PrismAgentError.InvalidMessageType::class) - fun makeRequestFromProposal(msg: Message): RequestPresentation { - val request = ProposePresentation(msg) - - return RequestPresentation( - body = Body( - goalCode = request.body.goalCode, - comment = request.body.comment, - willConfirm = false, - proofTypes = request.body.proofTypes - ), - attachments = request.attachments, - thid = msg.id, - from = request.to, - to = request.from - ) - } - } - - /** - * Represents a class that encapsulates the body of a message. - * - * @property goalCode The goal code associated with the body. - * @property comment The comment associated with the body. - * @property willConfirm A boolean indicating whether confirmation is required. - * @property proofTypes An array of proof types. - */ - @Serializable - data class Body @JvmOverloads constructor( - @SerialName(GOAL_CODE) - val goalCode: String? = null, - val comment: String? = null, - @SerialName(WILL_CONFIRM) - val willConfirm: Boolean? = false, - @SerialName(PROOF_TYPES) - val proofTypes: Array - ) { - /** - * Checks if this [Body] object is equal to the specified [other] object. - * - * Two [Body] objects are considered equal if they meet the following conditions: - * - The two objects have the same class type. - * - The goalCode, comment, willConfirm, and proofTypes properties of the two objects are also equal. - * - * @param other The object to compare with this [Body] object. - * @return true if the specified [other] object is equal to this [Body] object, false otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as Body - - if (goalCode != other.goalCode) return false - if (comment != other.comment) return false - if (willConfirm != other.willConfirm) return false - if (!proofTypes.contentEquals(other.proofTypes)) return false - - return true - } - - /** - * Calculates the hash code for the current object. - * - * The hash code is calculated based on the values of the following properties: - * - goalCode - * - comment - * - willConfirm - * - proofTypes - * - * @return The hash code value for the current object. - */ - override fun hashCode(): Int { - var result = goalCode?.hashCode() ?: 0 - result = 31 * result + (comment?.hashCode() ?: 0) - result = 31 * result + (willConfirm?.hashCode() ?: 0) - result = 31 * result + proofTypes.contentHashCode() - return result - } - } -} diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/revocation/RevocationNotification.kt b/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/revocation/RevocationNotification.kt deleted file mode 100644 index 6a7a0a402..000000000 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/revocation/RevocationNotification.kt +++ /dev/null @@ -1,59 +0,0 @@ -@file:Suppress("ktlint:standard:import-ordering") - -package io.iohk.atala.prism.walletsdk.prismagent.protocols.revocation - -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgentError -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType -import kotlinx.serialization.SerialName -import java.util.UUID -import kotlinx.serialization.Serializable -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json - -class RevocationNotification( - val id: String = UUID.randomUUID().toString(), - val body: Body, - val from: DID, - val to: DID -) { - val type = ProtocolType.PrismRevocation - - fun makeMessage(): Message { - return Message( - id = id, - piuri = type.value, - from = from, - to = to, - body = Json.encodeToString(body) - ) - } - - @Serializable - data class Body @JvmOverloads constructor( - @SerialName("issueCredentialProtocolThreadId") - val threadId: String, - val comment: String? - ) - - companion object { - fun fromMessage(message: Message): RevocationNotification { - require( - message.piuri == ProtocolType.PrismRevocation.value && - message.from != null && - message.to != null - ) { - throw PrismAgentError.InvalidMessageType( - type = message.piuri, - shouldBe = ProtocolType.PrismRevocation.value - ) - } - return RevocationNotification( - body = Json.decodeFromString(message.body), - from = message.from, - to = message.to - ) - } - } -} diff --git a/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/AvailableClaims.sq b/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/AvailableClaims.sq deleted file mode 100644 index e5b19e894..000000000 --- a/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/AvailableClaims.sq +++ /dev/null @@ -1,20 +0,0 @@ -CREATE TABLE AvailableClaims ( - id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, - credentialId TEXT NOT NULL, - claim TEXT NOT NULL, - FOREIGN KEY (credentialId) REFERENCES StorableCredential(id) -); - -insert: -INSERT INTO AvailableClaims(credentialId, claim) -VALUES (:credentialId, :claim); - -fetchAvailableClaimsByCredentialId: -SELECT * -FROM AvailableClaims -WHERE credentialId = ?; - -fetchAvailableClaimsByClaim: -SELECT * -FROM AvailableClaims -WHERE claim = :claim; diff --git a/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/CredentialMetadata.sq b/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/CredentialMetadata.sq deleted file mode 100644 index e5c92f83d..000000000 --- a/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/CredentialMetadata.sq +++ /dev/null @@ -1,14 +0,0 @@ -CREATE TABLE CredentialMetadata ( - id TEXT NOT NULL PRIMARY KEY, - linkSecretName TEXT NOT NULL, - json TEXT NOT NULL -); - -insert: -INSERT INTO CredentialMetadata(id, linkSecretName, json) -VALUES (:id, :linkSecretName, :json); - -fetchCredentialMetadata: -SELECT * -FROM CredentialMetadata -WHERE linkSecretName = ?; diff --git a/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/DID.sq b/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/DID.sq deleted file mode 100644 index cd98c5563..000000000 --- a/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/DID.sq +++ /dev/null @@ -1,41 +0,0 @@ -CREATE TABLE DID ( - did TEXT NOT NULL UNIQUE, - method TEXT NOT NULL , - methodId TEXT NOT NULL , - schema TEXT NOT NULL , - alias TEXT, - PRIMARY KEY (did) -); - -insert: -INSERT OR IGNORE INTO DID(did, method, methodId, schema, alias) -VALUES ?; - -fetchAllPrismDID: -SELECT DID.*, PrivateKey.keyPathIndex -FROM DID -JOIN PrivateKey ON DID.did = PrivateKey.didId -WHERE method = 'prism'; - -fetchDIDInfoByDID: -SELECT DID.*, PrivateKey.keyPathIndex -FROM DID -JOIN PrivateKey ON DID.did = PrivateKey.didId -WHERE DID.did = ?; - -fetchDIDInfoByAlias: -SELECT DID.*, PrivateKey.keyPathIndex -FROM DID -JOIN PrivateKey ON DID.did = PrivateKey.didId -WHERE alias = ?; - -fetchAllPeerDID: -SELECT DID.did, DID.alias, PrivateKey.* -FROM DID -JOIN PrivateKey ON DID.did = PrivateKey.didId -WHERE DID.method = 'peer'; - -fetchDIDByMethodId: -SELECT DID.did -FROM DID -WHERE methodId = ?; diff --git a/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/DIDPair.sq b/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/DIDPair.sq deleted file mode 100644 index 352d240cf..000000000 --- a/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/DIDPair.sq +++ /dev/null @@ -1,27 +0,0 @@ -CREATE TABLE DIDPair ( - id TEXT NOT NULL UNIQUE, -- ID will be hostDID and receiverDID concatenated - name TEXT, - hostDID TEXT NOT NULL, - receiverDID TEXT NOT NULL, - PRIMARY KEY (id), - FOREIGN KEY (hostDID) REFERENCES DID(did), - FOREIGN KEY (receiverDID) REFERENCES DID(did) -); - -insert: -INSERT INTO DIDPair(id, name, hostDID, receiverDID) -VALUES ?; - -fetchAllDIDPairs: -SELECT * -FROM DIDPair; - -fetchDIDPairByDID: -SELECT * -FROM DIDPair -WHERE DIDPair.hostDID = ?; - -fetchDIDPairByName: -SELECT * -FROM DIDPair -WHERE DIDPair.name = ?; diff --git a/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/LinkSecret.sq b/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/LinkSecret.sq deleted file mode 100644 index 8b81d796e..000000000 --- a/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/LinkSecret.sq +++ /dev/null @@ -1,12 +0,0 @@ -CREATE TABLE LinkSecret ( - id TEXT NOT NULL UNIQUE -); - -insert: -INSERT INTO LinkSecret(id) -VALUES ?; - -fetchLinkSecret: -SELECT * -FROM LinkSecret -LIMIT 1; diff --git a/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/Mediator.sq b/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/Mediator.sq deleted file mode 100644 index 0da123c2f..000000000 --- a/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/Mediator.sq +++ /dev/null @@ -1,24 +0,0 @@ -CREATE TABLE Mediator ( - id TEXT NOT NULL UNIQUE, -- VARCHAR(36) - mediatorDIDId TEXT NOT NULL, - hostDIDId TEXT, - routingDIDId TEXT, - PRIMARY KEY (id), - FOREIGN KEY (mediatorDIDId) REFERENCES DID(did), - FOREIGN KEY (hostDIDId) REFERENCES DID(did), - FOREIGN KEY (routingDIDId) REFERENCES DID(did) -); - -insert: -INSERT INTO Mediator(id, mediatorDIDId, hostDIDId, routingDIDId) -VALUES ?; - -fetchAllMediators: -SELECT Mediator.id, mediatorDID.did AS MediatorDID, hostDID.did AS HostDID, routingDID.did AS RoutingDID -FROM Mediator -JOIN DID AS mediatorDID -ON Mediator.mediatorDIDId = mediatorDID.methodId -JOIN DID AS hostDID -ON Mediator.hostDIDId = hostDID.methodId -JOIN DID AS routingDID -ON Mediator.routingDIDId = routingDID.methodId; diff --git a/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/Message.sq b/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/Message.sq deleted file mode 100644 index f413b5f9f..000000000 --- a/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/Message.sq +++ /dev/null @@ -1,58 +0,0 @@ -import kotlin.Int; - -CREATE TABLE Message ( - id TEXT NOT NULL UNIQUE, - createdTime TEXT NOT NULL , - dataJson TEXT NOT NULL, - `from` TEXT NOT NULL , - thid TEXT, - `to` TEXT NOT NULL , - type TEXT, - isReceived INTEGER AS Int DEFAULT 0, - PRIMARY KEY (id) -); - -insert: -INSERT OR REPLACE INTO Message(id, createdTime, dataJson, `from`, thid, `to`, type, isReceived) -VALUES ?; - -fetchAllMessages: -SELECT * -FROM Message; - -fetchAllMessagesFromTo: -SELECT * -FROM Message -WHERE `from` = :from -AND `to` = :to; - -fetchAllSentMessages: -SELECT * -FROM Message -WHERE isReceived = 0; - -fetchAllReceivedMessages: -SELECT * -FROM Message -WHERE isReceived = 1; - -fetchAllMessagesSentTo: -SELECT * -FROM Message -WHERE `to` = ?; - -fetchAllMessagesReceivedFrom: -SELECT * -FROM Message -WHERE `from` = ?; - -fetchAllMessagesOfType: -SELECT * -FROM Message -WHERE type = :type -AND (:relatedWithDID IS NULL OR `from` = :relatedWithDID OR `to` = :relatedWithDID); - -fetchMessageById: -SELECT * -FROM Message -WHERE id = ?; diff --git a/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/PrivateKey.sq b/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/PrivateKey.sq deleted file mode 100644 index d6c67ccd7..000000000 --- a/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/PrivateKey.sq +++ /dev/null @@ -1,32 +0,0 @@ -import kotlin.Int; - -CREATE TABLE PrivateKey ( - id TEXT NOT NULL UNIQUE, - restorationIdentifier TEXT NOT NULL, - data TEXT NOT NULL, - keyPathIndex INTEGER AS Int DEFAULT 0, - didId TEXT NOT NULL, - PRIMARY KEY (id), - FOREIGN KEY (didId) REFERENCES DID(did) -); - -insert: -INSERT INTO PrivateKey(id, restorationIdentifier, data, keyPathIndex, didId) -VALUES ?; - -fetchPrivateKeyByDID: -SELECT * FROM PrivateKey -WHERE didId = ?; - -fetchPrivateKeyByID: -SELECT * FROM PrivateKey -WHERE id = ?; - -fetchKeyPathIndexByDID: -SELECT keyPathIndex FROM PrivateKey -WHERE didId = ?; - -fetchLastkeyPathIndex: -SELECT keyPathIndex FROM PrivateKey -ORDER BY keyPathIndex DESC -LIMIT 1; diff --git a/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/StorableCredential.sq b/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/StorableCredential.sq deleted file mode 100644 index d3f5db0f2..000000000 --- a/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/StorableCredential.sq +++ /dev/null @@ -1,35 +0,0 @@ -import kotlin.Int; - -CREATE TABLE StorableCredential ( - id TEXT NOT NULL UNIQUE , - recoveryId TEXT NOT NULL, - credentialSchema TEXT NOT NULL, - credentialData BLOB NOT NULL, - issuer TEXT, - subject TEXT, - credentialCreated TEXT, - credentialUpdated TEXT, - validUntil TEXT, - revoked INTEGER AS Int DEFAULT 0, - PRIMARY KEY (id) -); - -insert: -INSERT OR IGNORE INTO StorableCredential(id, recoveryId, credentialSchema, credentialData, issuer, subject, credentialCreated, credentialUpdated, validUntil, revoked) -VALUES ?; - -fetchAllCredentials: -SELECT StorableCredential.*, AvailableClaims.claim AS claims -FROM StorableCredential -LEFT JOIN AvailableClaims ON StorableCredential.id = AvailableClaims.credentialId -GROUP BY StorableCredential.id; - -revokeCredentialById: -UPDATE StorableCredential -SET revoked = 1 -WHERE id = :id; - -observeRevokedCredential: -SELECT * -FROM StorableCredential -WHERE revoked = 1; \ No newline at end of file diff --git a/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/VerifiableCredential.sq b/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/VerifiableCredential.sq deleted file mode 100644 index 6822ea675..000000000 --- a/atala-prism-sdk/src/commonMain/sqldelight/io/iohk/atala/prism/walletsdk/pluto/data/VerifiableCredential.sq +++ /dev/null @@ -1,13 +0,0 @@ -CREATE TABLE VerifiableCredential ( - id TEXT NOT NULL UNIQUE, -- ID will be a hash of the values of a credential in a specific order - credentialType TEXT, - expirationDate TEXT, - issuanceDate TEXT, - verifiableCredentialJson TEXT NOT NULL, - issuerDIDId TEXT, - PRIMARY KEY (id) -); - -insert: -INSERT OR IGNORE INTO VerifiableCredential(id, credentialType, expirationDate, issuanceDate, verifiableCredentialJson, issuerDIDId) -VALUES ?; diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/apollo/ApolloTests.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/apollo/ApolloTests.kt deleted file mode 100644 index 712054168..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/apollo/ApolloTests.kt +++ /dev/null @@ -1,232 +0,0 @@ -package io.iohk.atala.prism.walletsdk.apollo - -import io.iohk.atala.prism.apollo.base64.base64UrlEncoded -import io.iohk.atala.prism.apollo.derivation.DerivationPath -import io.iohk.atala.prism.apollo.derivation.MnemonicHelper -import io.iohk.atala.prism.apollo.utils.ECConfig -import io.iohk.atala.prism.walletsdk.apollo.derivation.bip39Vectors -import io.iohk.atala.prism.walletsdk.apollo.helpers.BytesOps -import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519KeyPair -import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519PrivateKey -import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519PublicKey -import io.iohk.atala.prism.walletsdk.apollo.utils.Secp256k1KeyPair -import io.iohk.atala.prism.walletsdk.apollo.utils.Secp256k1PrivateKey -import io.iohk.atala.prism.walletsdk.apollo.utils.Secp256k1PublicKey -import io.iohk.atala.prism.walletsdk.apollo.utils.X25519KeyPair -import io.iohk.atala.prism.walletsdk.apollo.utils.X25519PrivateKey -import io.iohk.atala.prism.walletsdk.apollo.utils.X25519PublicKey -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Apollo -import io.iohk.atala.prism.walletsdk.domain.models.Curve -import io.iohk.atala.prism.walletsdk.domain.models.KeyCurve -import io.iohk.atala.prism.walletsdk.domain.models.Seed -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.CurveKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.KeyPair -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.KeyTypes -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.SeedKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.StorableKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.TypeKey -import kotlinx.serialization.json.Json -import org.junit.Assert.assertNotEquals -import org.junit.Before -import org.junit.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertFalse -import kotlin.test.assertTrue - -class ApolloTests { - lateinit var apollo: Apollo - lateinit var keyPair: KeyPair - - val testData = - byteArrayOf(-107, 101, 68, 118, 27, 74, 29, 50, -32, 72, 47, -127, -49, 3, -8, -55, -63, -66, 46, 125) - - @Before - fun before() { - apollo = ApolloImpl() - } - - @Test - fun testRandomMnemonicCode() { - for (i in 1..10) { - assertEquals(24, apollo.createRandomMnemonics().size) - } - } - - @Test - fun testGenerateRandomMnemonics() { - val seenWords = mutableSetOf() - for (i in 1..300) { - seenWords.addAll(apollo.createRandomMnemonics()) - } - // with great probability we'll see at least 75% of words after 3600 draws from 2048 possible - assertTrue(2048 - seenWords.size < 512) - } - - @Test - fun testComputeRightBinarySeed() { - val password = "mnemonicTREZOR" - val vectors = Json.decodeFromString>>(bip39Vectors) - for (v in vectors) { - val (_, mnemonicPhrase, binarySeedHex, _) = v - val mnemonicCode = mnemonicPhrase.split(" ").toTypedArray() - val binarySeed = apollo.createSeed(mnemonicCode, password) - - assertEquals(binarySeedHex, BytesOps.bytesToHex(binarySeed.value)) - } - } - - @Test - fun testFailWhenInvalidWordIsUsed() { - val mnemonicCode = arrayOf("hocus", "pocus", "mnemo", "codus") + Array(24) { "abandon" } - assertFailsWith { - apollo.createSeed(mnemonicCode, "") - } - } - - @Test - fun testKeyPairGeneration() { - keyPair = Secp256k1KeyPair.generateKeyPair(Seed(MnemonicHelper.createRandomSeed()), KeyCurve(Curve.SECP256K1)) - assertEquals(keyPair.publicKey.raw.size, ECConfig.PUBLIC_KEY_BYTE_SIZE) - assertEquals(keyPair.privateKey.raw.size, ECConfig.PRIVATE_KEY_BYTE_SIZE) - } - - @Test - fun testSignAndVerifyTest() { - val message = "The quick brown fox jumps over the lazy dog" - keyPair = Secp256k1KeyPair.generateKeyPair(Seed(MnemonicHelper.createRandomSeed()), KeyCurve(Curve.SECP256K1)) - val signature = (keyPair.privateKey as Secp256k1PrivateKey).sign(message.toByteArray()) - - assertEquals(signature.size <= ECConfig.SIGNATURE_MAX_BYTE_SIZE, true) - - assertTrue((keyPair.publicKey as Secp256k1PublicKey).verify(message.encodeToByteArray(), signature)) - assertTrue((keyPair.publicKey as Secp256k1PublicKey).isExportable()) - assertTrue((keyPair.privateKey as Secp256k1PrivateKey).isExportable()) - } - - @Test - fun testDerivePrivateKey_whenSecp256k1_thenWorksAsExpected() { - val path = "m/0'/0'/0'" - - val seed = Seed(MnemonicHelper.createRandomSeed()) - - val properties: MutableMap = mutableMapOf() - properties[TypeKey().property] = KeyTypes.EC - properties[SeedKey().property] = BytesOps.bytesToHex(seed.value) - properties[CurveKey().property] = Curve.SECP256K1.value - - val privateKey = apollo.createPrivateKey(properties) as Secp256k1PrivateKey - privateKey.derive(DerivationPath.fromPath(path)) - assertTrue(privateKey.isDerivable()) - - val ed25519KeyPair = Ed25519KeyPair.generateKeyPair() - val ed25519PrivateKey = ed25519KeyPair.privateKey as Ed25519PrivateKey - assertFalse(ed25519PrivateKey.isDerivable()) - } - - @Test - fun testCreateKeyPair_whenNoSeedAndKeyCurveEd25519_thenPrivateKeyLengthIsCorrect() { - val keyPair = Ed25519KeyPair.generateKeyPair() - val privateKey = keyPair.privateKey - val publicKey = keyPair.publicKey - assertEquals(32, privateKey.raw.size) - assertEquals(32, publicKey.raw.size) - assertTrue((keyPair.publicKey as Ed25519PublicKey).isExportable()) - assertTrue((keyPair.privateKey as Ed25519PrivateKey).isExportable()) - } - - @Test - fun testCreateKeyPair_whenNoSeedAndKeyCurveX25519_thenPrivateKeyLengthIsCorrect() { - val keyPair = X25519KeyPair.generateKeyPair() - val privateKey = keyPair.privateKey - val publicKey = keyPair.publicKey - assertEquals(32, privateKey.raw.size) - assertEquals(32, publicKey.raw.size) - assertTrue((keyPair.publicKey as X25519PublicKey).isExportable()) - assertTrue((keyPair.privateKey as X25519PrivateKey).isExportable()) - } - - @Test - fun testCreateKeyPair_whenUsingSeedAndMnemonics_thenKeyPairIsCorrect() { - val mnemonics = listOf( - "blade", - "multiply", - "coil", - "rare", - "fox", - "doll", - "tongue", - "please", - "icon", - "mind", - "gesture", - "moral", - "old", - "laugh", - "symptom", - "assume", - "burden", - "appear", - "always", - "oil", - "ticket", - "vault", - "return", - "height" - ) - val seed = Seed(MnemonicHelper.createSeed(mnemonics = mnemonics, passphrase = "mnemonic")) - - val expectedPrivateKeyBase64Url = "xURclKhT6as1Tb9vg4AJRRLPAMWb9dYTTthDvXEKjMc" - - assertEquals( - "7bcb8d37b2d11f998451cc5aec58710c081618b87c3fde1610e0f48d475a276992535a34daef8bcdaa39d1e955df65ef613d2ec7d8d6b815440a9140cf67242b", - BytesOps.bytesToHex(seed.value) - ) - val keyPair = Secp256k1KeyPair.generateKeyPair(seed, KeyCurve(Curve.SECP256K1)) - assertEquals(expectedPrivateKeyBase64Url, keyPair.privateKey.raw.base64UrlEncoded) - } - - @Test - fun testSignAndVerify_whenSignatureIsCorrect_thenVerifiedCorrectly() { - val keyPair = Ed25519KeyPair.generateKeyPair() - val message = "This is a test message" - val signature = (keyPair.privateKey as Ed25519PrivateKey).sign(message.toByteArray()) - - assertTrue((keyPair.publicKey as Ed25519PublicKey).verify(message.toByteArray(), signature)) - } - - @Test - fun testSignAndVerify_whenSignatureIsIncorrect_thenVerifyFails() { - val keyPair = Ed25519KeyPair.generateKeyPair() - val message = "This is a test message" - val signature = (keyPair.privateKey as Ed25519PrivateKey).sign(message.toByteArray()) - signature[0] = 1 - assertFalse((keyPair.publicKey as Ed25519PublicKey).verify(message.toByteArray(), signature)) - } - - @Test - fun testRestorePrivateKey_whenStorableSecp256k1_thenRestoredOk() { - val keyPairSecp256k1 = - Secp256k1KeyPair.generateKeyPair(Seed(MnemonicHelper.createRandomSeed()), KeyCurve(Curve.SECP256K1)) - val keyPairEd25519 = Ed25519KeyPair.generateKeyPair() - val privateKeySecp256k1 = keyPairSecp256k1.privateKey as Secp256k1PrivateKey - val privateKeyEd25519 = keyPairEd25519.privateKey as Ed25519PrivateKey - val storableKey = keyPairSecp256k1.privateKey as StorableKey - val restoredKey = apollo.restorePrivateKey(storableKey) - assertEquals(privateKeySecp256k1.raw, restoredKey.raw) - assertNotEquals(privateKeyEd25519.raw, restoredKey.raw) - } - - @Test - fun testRestorePublicKey_whenStorableSecp256k1_thenRestoredOk() { - val keyPairSecp256k1 = - Secp256k1KeyPair.generateKeyPair(Seed(MnemonicHelper.createRandomSeed()), KeyCurve(Curve.SECP256K1)) - val keyPairEd25519 = Ed25519KeyPair.generateKeyPair() - val publicKeySecp256k1 = keyPairSecp256k1.publicKey as Secp256k1PublicKey - val publicKeyEd25519 = keyPairEd25519.publicKey as Ed25519PublicKey - val storableKey = keyPairSecp256k1.publicKey as StorableKey - val restoredKey = apollo.restorePublicKey(storableKey) - assertEquals(publicKeySecp256k1.raw, restoredKey.raw) - assertNotEquals(publicKeyEd25519.raw, restoredKey.raw) - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/apollo/derivation/Bip32Vectors.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/apollo/derivation/Bip32Vectors.kt deleted file mode 100644 index acc492b11..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/apollo/derivation/Bip32Vectors.kt +++ /dev/null @@ -1,106 +0,0 @@ -package io.iohk.atala.prism.walletsdk.apollo.derivation - -import kotlinx.serialization.Serializable - -@Serializable -sealed class RawTestVectorBase { - abstract val seed: String - abstract val derivations: List> -} - -@Serializable -class RawTestVector( - override val seed: String, - override val derivations: List> -) : RawTestVectorBase() - -val bip32Vectors = - """ - [ - { - "seed" : "000102030405060708090a0b0c0d0e0f", - "derivations" : [ - [ - "m", - "0439a36013301597daef41fbe593a02cc513d0b55527ec2df1050e2e8ff49c85c23cbe7ded0e7ce6a594896b8f62888fdbc5c8821305e2ea42bf01e37300116281", - "e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35" - ], - [ - "m/0'", - "045a784662a4a20a65bf6aab9ae98a6c068a81c52e4b032c0fb5400c706cfccc567f717885be239daadce76b568958305183ad616ff74ed4dc219a74c26d35f839", - "edb2e14f9ee77d26dd93b4ecede8d16ed408ce149b6cd80b0715a2d911a0afea" - ], - [ - "m/0'/1", - "04501e454bf00751f24b1b489aa925215d66af2234e3891c3b21a52bedb3cd711c008794c1df8131b9ad1e1359965b3f3ee2feef0866be693729772be14be881ab", - "3c6cb8d0f6a264c91ea8b5030fadaa8e538b020f0a387421a12de9319dc93368" - ], - [ - "m/0'/1/2'", - "0457bfe1e341d01c69fe5654309956cbea516822fba8a601743a012a7896ee8dc24310ef3676384179e713be3115e93f34ac9a3933f6367aeb3081527ea74027b7", - "cbce0d719ecf7431d88e6a89fa1483e02e35092af60c042b1df2ff59fa424dca" - ], - [ - "m/0'/1/2'/2", - "04e8445082a72f29b75ca48748a914df60622a609cacfce8ed0e35804560741d292728ad8d58a140050c1016e21f285636a580f4d2711b7fac3957a594ddf416a0", - "0f479245fb19a38a1954c5c7c0ebab2f9bdfd96a17563ef28a6a4b1a2a764ef4" - ], - [ - "m/0'/1/2'/2/1000000000", - "042a471424da5e657499d1ff51cb43c47481a03b1e77f951fe64cec9f5a48f7011cf31cb47de7ccf6196d3a580d055837de7aa374e28c6c8a263e7b4512ceee362", - "471b76e389e528d6de6d816857e012c5455051cad6660850e58372a6c3e6e7c8" - ] - ] - }, - { - "seed" : "fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542", - "derivations" : [ - [ - "m", - "04cbcaa9c98c877a26977d00825c956a238e8dddfbd322cce4f74b0b5bd6ace4a77bd3305d363c26f82c1e41c667e4b3561c06c60a2104d2b548e6dd059056aa51", - "4b03d6fc340455b363f51020ad3ecca4f0850280cf436c70c727923f6db46c3e" - ], - [ - "m/0", - "04fc9e5af0ac8d9b3cecfe2a888e2117ba3d089d8585886c9c826b6b22a98d12ea67a50538b6f7d8b5f7a1cc657efd267cde8cc1d8c0451d1340a0fb3642777544", - "abe74a98f6c7eabee0428f53798f0ab8aa1bd37873999041703c742f15ac7e1e" - ], - [ - "m/0/2147483647'", - "04c01e7425647bdefa82b12d9bad5e3e6865bee0502694b94ca58b666abc0a5c3b6c8bf5e8fbfc053205b45776963d148187d0aebf9c08bf2b253dc1cf5860fc19", - "877c779ad9687164e9c2f4f0f4ff0340814392330693ce95a58fe18fd52e6e93" - ], - [ - "m/0/2147483647'/1", - "04a7d1d856deb74c508e05031f9895dab54626251b3806e16b4bd12e781a7df5b9105b3150817d235e80ea17914dc9d6f542b1c5f4b16d8d98fe3c94fc0a67de89", - "704addf544a06e5ee4bea37098463c23613da32020d604506da8c0518e1da4b7" - ], - [ - "m/0/2147483647'/1/2147483646'", - "04d2b36900396c9282fa14628566582f206a5dd0bcc8d5e892611806cafb0301f0ecb53a1b24eda1117d6864f1dbaf2f92345a1cb52c70036e2a424b37c3d829b0", - "f1c7c871a54a804afe328b4c83a1c33b8e5ff48f5087273f04efa83b247d6a2d" - ], - [ - "m/0/2147483647'/1/2147483646'/2", - "044d902e1a2fc7a8755ab5b694c575fce742c48d9ff192e63df5193e4c7afe1f9c4597bb130cb16893607c6e7418c46be47b8f4a3ddbe5e6e71051393b1d673abe", - "bb7d39bdb83ecf58f2fd82b6d918341cbef428661ef01ab97c28a4842125ac23" - ] - ] - }, - { - "seed" : "4b381541583be4423346c643850da4b320e46a87ae3d2a4e6da11eba819cd4acba45d239319ac14f863b8d5ab5a0d0c64d2e8a1e7d1457df2e5a3c51c73235be", - "derivations" : [ - [ - "m", - "04683af1ba5743bdfc798cf814efeeab2735ec52d95eced528e692b8e34c4e5669d2f2686ced96d375a75298f07ed30751e2a3f45e2d184b268d02c8d5dd6fbdb5", - "00ddb80b067e0d4993197fe10f2657a844a384589847602d56f0c629c81aae32" - ], - [ - "m/0'", - "046557fdda1d5d43d79611f784780471f086d58e8126b8c40acb82272a7712e7f259a34ffdc4c82e5cb68a96ccc6cb53e8765527148d1a85b52dfb8953d8d001fc", - "491f7a2eebc7b57028e0d3faa0acda02e75c33b03c48fb288c41e2ea44e1daef" - ] - ] - } - ] - """.trimIndent() diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/apollo/derivation/Bip39Vectors.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/apollo/derivation/Bip39Vectors.kt deleted file mode 100644 index a2778f0b8..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/apollo/derivation/Bip39Vectors.kt +++ /dev/null @@ -1,55 +0,0 @@ -package io.iohk.atala.prism.walletsdk.apollo.derivation - -val bip39Vectors = - """ - [ - [ - "0000000000000000000000000000000000000000000000000000000000000000", - "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art", - "bda85446c68413707090a52022edd26a1c9462295029f2e60cd7c4f2bbd3097170af7a4d73245cafa9c3cca8d561a7c3de6f5d4a10be8ed2a5e608d68f92fcc8", - "xprv9s21ZrQH143K32qBagUJAMU2LsHg3ka7jqMcV98Y7gVeVyNStwYS3U7yVVoDZ4btbRNf4h6ibWpY22iRmXq35qgLs79f312g2kj5539ebPM" - ], - [ - "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", - "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth title", - "bc09fca1804f7e69da93c2f2028eb238c227f2e9dda30cd63699232578480a4021b146ad717fbb7e451ce9eb835f43620bf5c514db0f8add49f5d121449d3e87", - "xprv9s21ZrQH143K3Y1sd2XVu9wtqxJRvybCfAetjUrMMco6r3v9qZTBeXiBZkS8JxWbcGJZyio8TrZtm6pkbzG8SYt1sxwNLh3Wx7to5pgiVFU" - ], - [ - "8080808080808080808080808080808080808080808080808080808080808080", - "letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic bless", - "c0c519bd0e91a2ed54357d9d1ebef6f5af218a153624cf4f2da911a0ed8f7a09e2ef61af0aca007096df430022f7a2b6fb91661a9589097069720d015e4e982f", - "xprv9s21ZrQH143K3CSnQNYC3MqAAqHwxeTLhDbhF43A4ss4ciWNmCY9zQGvAKUSqVUf2vPHBTSE1rB2pg4avopqSiLVzXEU8KziNnVPauTqLRo" - ], - [ - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo vote", - "dd48c104698c30cfe2b6142103248622fb7bb0ff692eebb00089b32d22484e1613912f0a5b694407be899ffd31ed3992c456cdf60f5d4564b8ba3f05a69890ad", - "xprv9s21ZrQH143K2WFF16X85T2QCpndrGwx6GueB72Zf3AHwHJaknRXNF37ZmDrtHrrLSHvbuRejXcnYxoZKvRquTPyp2JiNG3XcjQyzSEgqCB" - ], - [ - "68a79eaca2324873eacc50cb9c6eca8cc68ea5d936f98787c60c7ebc74e6ce7c", - "hamster diagram private dutch cause delay private meat slide toddler razor book happy fancy gospel tennis maple dilemma loan word shrug inflict delay length", - "64c87cde7e12ecf6704ab95bb1408bef047c22db4cc7491c4271d170a1b213d20b385bc1588d9c7b38f1b39d415665b8a9030c9ec653d75e65f847d8fc1fc440", - "xprv9s21ZrQH143K2XTAhys3pMNcGn261Fi5Ta2Pw8PwaVPhg3D8DWkzWQwjTJfskj8ofb81i9NP2cUNKxwjueJHHMQAnxtivTA75uUFqPFeWzk" - ], - [ - "9f6a2878b2520799a44ef18bc7df394e7061a224d2c33cd015b157d746869863", - "panda eyebrow bullet gorilla call smoke muffin taste mesh discover soft ostrich alcohol speed nation flash devote level hobby quick inner drive ghost inside", - "72be8e052fc4919d2adf28d5306b5474b0069df35b02303de8c1729c9538dbb6fc2d731d5f832193cd9fb6aeecbc469594a70e3dd50811b5067f3b88b28c3e8d", - "xprv9s21ZrQH143K2WNnKmssvZYM96VAr47iHUQUTUyUXH3sAGNjhJANddnhw3i3y3pBbRAVk5M5qUGFr4rHbEWwXgX4qrvrceifCYQJbbFDems" - ], - [ - "066dca1a2bb7e8a1db2832148ce9933eea0f3ac9548d793112d9a95c9407efad", - "all hour make first leader extend hole alien behind guard gospel lava path output census museum junior mass reopen famous sing advance salt reform", - "26e975ec644423f4a4c4f4215ef09b4bd7ef924e85d1d17c4cf3f136c2863cf6df0a475045652c57eb5fb41513ca2a2d67722b77e954b4b3fc11f7590449191d", - "xprv9s21ZrQH143K3rEfqSM4QZRVmiMuSWY9wugscmaCjYja3SbUD3KPEB1a7QXJoajyR2T1SiXU7rFVRXMV9XdYVSZe7JoUXdP4SRHTxsT1nzm" - ], - [ - "f585c11aec520db57dd353c69554b21a89b20fb0650966fa0a9d6f74fd989d8f", - "void come effort suffer camp survey warrior heavy shoot primary clutch crush open amazing screen patrol group space point ten exist slush involve unfold", - "01f5bced59dec48e362f2c45b5de68b9fd6c92c6634f44d6d40aab69056506f0e35524a518034ddc1192e1dacd32c1ed3eaa3c3b131c88ed8e7e54c49a5d0998", - "xprv9s21ZrQH143K39rnQJknpH1WEPFJrzmAqqasiDcVrNuk926oizzJDDQkdiTvNPr2FYDYzWgiMiC63YmfPAa2oPyNB23r2g7d1yiK6WpqaQS" - ] - ] - """.trimIndent() diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/castor/ApolloMock.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/castor/ApolloMock.kt deleted file mode 100644 index d2b068fc5..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/castor/ApolloMock.kt +++ /dev/null @@ -1,61 +0,0 @@ -package io.iohk.atala.prism.walletsdk.castor - -import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519KeyPair -import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519PrivateKey -import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519PublicKey -import io.iohk.atala.prism.walletsdk.apollo.utils.Secp256k1PublicKey -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Apollo -import io.iohk.atala.prism.walletsdk.domain.models.Seed -import io.iohk.atala.prism.walletsdk.domain.models.SeedWords -import io.iohk.atala.prism.walletsdk.domain.models.Signature -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.KeyPair -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PrivateKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PublicKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.StorableKey - -class ApolloMock : Apollo { - var createRandomMnemonicsReturn: Array = emptyArray() - var createSeedReturn: Seed = Seed(ByteArray(0)) - var createRandomSeedReturn: SeedWords = SeedWords(emptyArray(), Seed(ByteArray(0))) - var createKeyPairReturn: KeyPair = Ed25519KeyPair( - privateKey = Ed25519PrivateKey(ByteArray(0)), - publicKey = Ed25519PublicKey(ByteArray(0)) - ) - var compressedPublicKeyReturn: PublicKey = Secp256k1PublicKey(ByteArray(0)) - var publicKeyReturn: PublicKey = Ed25519PublicKey(ByteArray(0)) - var signMessageReturn: Signature = Signature(ByteArray(0)) - var verifySignatureReturn: Boolean = true - var compressedPublicKeyDataReturn: PublicKey = Secp256k1PublicKey(ByteArray(0)) - var signMessageByteArrayReturn: Signature = Signature(ByteArray(0)) - var signMessageStringReturn: Signature = Signature(ByteArray(0)) - - override fun createRandomMnemonics(): Array = createRandomMnemonicsReturn - - override fun createSeed(mnemonics: Array, passphrase: String): Seed { - return createSeedReturn - } - - override fun createRandomSeed(passphrase: String?): SeedWords { - return createRandomSeedReturn - } - - override fun createPrivateKey(properties: Map): PrivateKey { - TODO("Not yet implemented") - } - - override fun isPrivateKeyData(identifier: String, data: ByteArray): Boolean { - TODO("Not yet implemented") - } - - override fun isPublicKeyData(identifier: String, data: ByteArray): Boolean { - TODO("Not yet implemented") - } - - override fun restorePrivateKey(key: StorableKey): PrivateKey { - TODO("Not yet implemented") - } - - override fun restorePublicKey(key: StorableKey): PublicKey { - TODO("Not yet implemented") - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/castor/DIDCreateTest.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/castor/DIDCreateTest.kt deleted file mode 100644 index f3028d25d..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/castor/DIDCreateTest.kt +++ /dev/null @@ -1,266 +0,0 @@ -package io.iohk.atala.prism.walletsdk.castor - -import io.iohk.atala.prism.apollo.base64.base64UrlDecodedBytes -import io.iohk.atala.prism.walletsdk.apollo.ApolloImpl -import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519KeyPair -import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519PrivateKey -import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519PublicKey -import io.iohk.atala.prism.walletsdk.apollo.utils.X25519KeyPair -import io.iohk.atala.prism.walletsdk.apollo.utils.X25519PrivateKey -import io.iohk.atala.prism.walletsdk.apollo.utils.X25519PublicKey -import io.iohk.atala.prism.walletsdk.domain.models.CastorError -import io.iohk.atala.prism.walletsdk.domain.models.Curve -import io.iohk.atala.prism.walletsdk.domain.models.DIDDocument -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.CurveKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.KeyPair -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.KeyTypes -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.RawKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.TypeKey -import io.iohk.atala.prism.walletsdk.prismagent.DIDCOMM_MESSAGING -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.test.runTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith - -class DIDCreateTest { - - @OptIn(ExperimentalCoroutinesApi::class) - @Test - fun it_should_create_peerDID_correctly() = runTest { - val keyAgreementKeyPair = X25519KeyPair( - X25519PrivateKey( - byteArrayOf( - -24, - 18, - -94, - -98, - 106, - 49, - -55, - -55, - -6, - -66, - 75, - 73, - -120, - -96, - 33, - 28, - -55, - -109, - 105, - -67, - 9, - 28, - 88, - -98, - 43, - -4, - -6, - 75, - 65, - -68, - 112, - 92 - ) - ), - X25519PublicKey( - byteArrayOf( - -16, - 16, - 107, - -82, - -125, - 83, - 101, - -94, - -103, - -112, - 47, - 117, - -90, - -100, - 64, - 77, - 62, - -4, - 11, - 101, - -53, - -64, - -2, - -77, - -106, - -16, - -63, - -54, - -42, - -59, - 80, - 23 - ) - ) - ) - - val authenticationKeyPair = Ed25519KeyPair( - Ed25519PrivateKey( - byteArrayOf( - -68, - 7, - 65, - -41, - -60, - -42, - -9, - 55, - -113, - -80, - -86, - -106, - -40, - 97, - 81, - -13, - -22, - -124, - -58, - -39, - -64, - -126, - 75, - 88, - 126, - 39, - 51, - -52, - 121, - -64, - -5, - 35 - ) - ), - Ed25519PublicKey( - byteArrayOf( - -8, - 10, - 34, - 65, - -42, - -19, - -92, - 1, - -48, - -59, - -10, - -99, - -8, - -88, - -32, - 119, - 50, - -15, - -93, - 56, - -121, - -51, - 78, - -93, - 42, - -86, - -37, - 20, - 34, - -94, - 108, - -68 - ) - ) - ) - - val keyPairs: Array = arrayOf(keyAgreementKeyPair, authenticationKeyPair) - - val castor = CastorImpl(ApolloMock()) - val did = castor.createPeerDID(keyPairs, emptyArray()) - val validPeerDID = - "did:peer:2.Ez6LSsqHXypzFPGA7RdCu2NHUf2cK8dAW1AdHa5JDCRnXQ2yk.Vz6Mkw9W7jaqZ7hF5bSKeSpnqNxhFTiVMy3aBZjyEhrMxUQAF" - assertEquals(validPeerDID, did.toString()) - } - - @Test - fun testPeerDIDCreation_whenServicesProvided_thenCreatedCorrectly() = runTest { - val apollo = ApolloImpl() - - val properties: MutableMap = mutableMapOf() - properties[TypeKey().property] = KeyTypes.Curve25519 - properties[RawKey().property] = "COd9Xhr-amD7fuswWId2706JBUY_tmjp9eiNEieJeEE".base64UrlDecodedBytes - properties[CurveKey().property] = Curve.X25519.value - val keyAgreementPrivateKey = apollo.createPrivateKey(properties) - val keyAgreementKeyPair = X25519KeyPair( - privateKey = keyAgreementPrivateKey, - publicKey = keyAgreementPrivateKey.publicKey() - ) - - val properties2: MutableMap = mutableMapOf() - properties2[TypeKey().property] = KeyTypes.EC - properties2[RawKey().property] = "JLIJQ5jlkyqtGmtOth6yggJLLC0zuRhUPiBhd1-rGPs".base64UrlDecodedBytes - properties2[CurveKey().property] = Curve.ED25519.value - val authenticationPrivateKey = apollo.createPrivateKey(properties2) - val authenticationKeyPair = Ed25519KeyPair( - privateKey = authenticationPrivateKey, - publicKey = authenticationPrivateKey.publicKey() - ) - - val keyPairs: Array = arrayOf(keyAgreementKeyPair, authenticationKeyPair) - - val service = DIDDocument.Service( - id = "didcomm", - type = arrayOf(DIDCOMM_MESSAGING), - serviceEndpoint = DIDDocument.ServiceEndpoint( - uri = "https://example.com/endpoint", - accept = emptyArray(), - routingKeys = arrayOf("did:example:somemediator#somekey") - ) - ) - - val castor = CastorImpl(apollo) - val did = castor.createPeerDID(keyPairs, arrayOf(service)) - val expectedPeerDID = - "did:peer:2.Ez6LSoHkfN1Y4nK9RCjx7vopWsLrMGNFNgTNZgoCNQrTzmb1n.Vz6MknRZmapV7uYZQuZez9n9N3tQotjRN18UGS68Vcfo6gR4h.SeyJ0IjoiZG0iLCJzIjp7InVyaSI6Imh0dHBzOi8vZXhhbXBsZS5jb20vZW5kcG9pbnQiLCJyIjpbImRpZDpleGFtcGxlOnNvbWVtZWRpYXRvciNzb21la2V5Il0sImEiOltdfX0" - assertEquals(expectedPeerDID, did.toString()) - } - - @OptIn(ExperimentalCoroutinesApi::class) - @Test - fun it_should_throw_errors_if_wrong_keys_are_provided() = runTest { - val verKeyStr = "z6LSci5EK4Ezue5QA72ZX71QUbXY2xr5ygRw7wM1WJigTNnd" - val authKeyStr = "z6MkqgCXHEGr2wJZANPZGC8WFmeVuS3abAD9uvh7mTXygCFv" - - val fakeVerPrivateKey = Ed25519PrivateKey("".encodeToByteArray()) - val fakeAuthPrivateKey = X25519PrivateKey("".encodeToByteArray()) - - val verificationPubKey = Ed25519PublicKey(verKeyStr.encodeToByteArray()) - val authenticationPubKey = X25519PublicKey(authKeyStr.encodeToByteArray()) - - val verificationKeyPair = Ed25519KeyPair(fakeVerPrivateKey, verificationPubKey) - val authenticationKeyPair = Ed25519KeyPair(fakeAuthPrivateKey, authenticationPubKey) - - val keyPairs: Array = arrayOf(verificationKeyPair, authenticationKeyPair) - - val service = DIDDocument.Service( - id = "DIDCommV2", - type = arrayOf(DIDCOMM_MESSAGING), - serviceEndpoint = DIDDocument.ServiceEndpoint( - uri = "localhost:8082", - accept = arrayOf(DIDCOMM_MESSAGING), - routingKeys = arrayOf() - ) - ) - - val castor = CastorImpl(ApolloMock()) - - assertFailsWith { - castor.createPeerDID(keyPairs, arrayOf(service)) - } - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/castor/DIDParserTest.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/castor/DIDParserTest.kt deleted file mode 100644 index 238669ade..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/castor/DIDParserTest.kt +++ /dev/null @@ -1,93 +0,0 @@ -package io.iohk.atala.prism.walletsdk.castor - -import io.iohk.atala.prism.walletsdk.castor.did.DIDParser -import io.iohk.atala.prism.walletsdk.domain.models.CastorError -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith - -class DIDParserTest { - - @Test - fun it_should_test_valid_DIDs() { - val didExample1 = "did:aaaaaa:aa:aaa" - val didExample2 = "did:prism01:b2.-_%11:b4._-%11" - val didExample3 = - "did:prism:b6c0c33d701ac1b9a262a14454d1bbde3d127d697a76950963c5fd930605:Cj8KPRI7CgdtYXN0ZXIwEAFKLgoJc2VmsxEiECSTjyV7sUfCr_ArpN9rvCwR9fRMAhcsr_S7ZRiJk4p5k" - - val parsedDID1 = DIDParser.parse(didExample1) - val parsedDID2 = DIDParser.parse(didExample2) - val parsedDID3 = DIDParser.parse(didExample3) - - assertEquals(parsedDID1.schema, "did") - assertEquals(parsedDID1.method, "aaaaaa") - assertEquals(parsedDID1.methodId, "aa:aaa") - - assertEquals(parsedDID2.schema, "did") - assertEquals(parsedDID2.method, "prism01") - assertEquals(parsedDID2.methodId, "b2.-_%11:b4._-%11") - - assertEquals(parsedDID3.schema, "did") - assertEquals(parsedDID3.method, "prism") - assertEquals( - parsedDID3.methodId, - "b6c0c33d701ac1b9a262a14454d1bbde3d127d697a76950963c5fd930605:Cj8KPRI7CgdtYXN0ZXIwEAFKLgoJc2VmsxEiECSTjyV7sUfCr_ArpN9rvCwR9fRMAhcsr_S7ZRiJk4p5k" - ) - } - - @Test - fun it_should_test_invalid_DIDs() { - val didExample1 = "idi:aaaaaa:aa:aaa" - val didExample2 = "did:-prism-:aaaaa:aaaa" - val didExample3 = "did:prism:aaaaaaaaaaa::" - val didExample4 = "did::prism:aaaaaaaaaaa:aaaa" - val didExample5 = "did:prism::aaaaaaaaaaa:bbbb" - - assertFailsWith( - exceptionClass = CastorError.InvalidDIDString::class, - block = { - DIDParser.parse(didExample1) - } - ) - - assertFailsWith( - exceptionClass = CastorError.InvalidDIDString::class, - block = { - DIDParser.parse(didExample2) - } - ) - - assertFailsWith( - exceptionClass = CastorError.InvalidDIDString::class, - block = { - DIDParser.parse(didExample3) - } - ) - - assertFailsWith( - exceptionClass = CastorError.InvalidDIDString::class, - block = { - DIDParser.parse(didExample4) - } - ) - - assertFailsWith( - exceptionClass = CastorError.InvalidDIDString::class, - block = { - DIDParser.parse(didExample5) - } - ) - } - - @Test - fun test() { - val did = - "did:peer:2.Ez6LSmWXS6oahBFuVKi2HZ6bWe521uLdiDoPub9ExYM22ybj9.Vz6MkigNVs7sPs4i38uYqiBzbMJ5YKzfK3Re11e3mdL5YpqpV" - val parsedDID = DIDParser.parse(did) - assertEquals("peer", parsedDID.method) - assertEquals( - "2.Ez6LSmWXS6oahBFuVKi2HZ6bWe521uLdiDoPub9ExYM22ybj9.Vz6MkigNVs7sPs4i38uYqiBzbMJ5YKzfK3Re11e3mdL5YpqpV", - parsedDID.methodId - ) - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/castor/DIDUrlParserTest.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/castor/DIDUrlParserTest.kt deleted file mode 100644 index 4bc059fc8..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/castor/DIDUrlParserTest.kt +++ /dev/null @@ -1,42 +0,0 @@ -package io.iohk.atala.prism.walletsdk.castor - -import io.iohk.atala.prism.walletsdk.castor.did.DIDUrlParser -import kotlin.test.Test -import kotlin.test.assertContentEquals -import kotlin.test.assertEquals -import kotlin.test.assertNull - -class DIDUrlParserTest { - - @Test - fun it_should_test_valid_Urls() { - val didExample1 = "did:example:123456:adsd/path?query=something#fragment" - val didExample2 = "did:example:123456/path?query=something&query2=something#0" - val didExample3 = "did:example:123456/path/jpg.pp?query=something" - - val parsedDID1 = DIDUrlParser.parse(didExample1) - val parsedDID2 = DIDUrlParser.parse(didExample2) - val parsedDID3 = DIDUrlParser.parse(didExample3) - - assertEquals(parsedDID1.did.schema, "did") - assertEquals(parsedDID1.did.method, "example") - assertEquals(parsedDID1.did.methodId, "123456:adsd") - assertContentEquals(parsedDID1.path, arrayOf("path")) - assertEquals(parsedDID1.parameters, mapOf("query" to "something")) - assertEquals(parsedDID1.fragment, "fragment") - - assertEquals(parsedDID2.did.schema, "did") - assertEquals(parsedDID2.did.method, "example") - assertEquals(parsedDID2.did.methodId, "123456") - assertContentEquals(parsedDID2.path, arrayOf("path")) - assertEquals(parsedDID2.parameters, mapOf("query" to "something", "query2" to "something")) - assertEquals(parsedDID2.fragment, "0") - - assertEquals(parsedDID3.did.schema, "did") - assertEquals(parsedDID3.did.method, "example") - assertEquals(parsedDID3.did.methodId, "123456") - assertContentEquals(parsedDID3.path, arrayOf("path", "jpg.pp")) - assertEquals(parsedDID3.parameters, mapOf("query" to "something")) - assertNull(parsedDID3.fragment) - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/castor/PrismDIDMethodIdTests.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/castor/PrismDIDMethodIdTests.kt deleted file mode 100644 index 0fbc7ae06..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/castor/PrismDIDMethodIdTests.kt +++ /dev/null @@ -1,33 +0,0 @@ -package io.iohk.atala.prism.walletsdk.castor - -import io.iohk.atala.prism.walletsdk.castor.did.prismdid.PrismDIDMethodId -import io.iohk.atala.prism.walletsdk.domain.models.CastorError -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.test.runTest -import kotlin.test.Test -import kotlin.test.assertFailsWith - -class PrismDIDMethodIdTests { - - @OptIn(ExperimentalCoroutinesApi::class) - @Test - fun it_should_throwError_when_PrismDIDMethod_has_invalid_regex() = runTest { - val validation1 = listOf("aggh123dgasj_-ddadsd", "adbadhj21231_-:0wqebnma") - val validation2 = listOf("aggh12@3dgasj_-ddadsd", "adbadhj21231_-") - val validation3 = listOf("aggh1/23dgasj_-ddadsd", "adbadhj21231_-") - val validation4 = listOf("aggh1+23dgasj_-ddadsd", "adbadhj21231_-") - - assertFailsWith { - PrismDIDMethodId(validation1) - } - assertFailsWith { - PrismDIDMethodId(validation2) - } - assertFailsWith { - PrismDIDMethodId(validation3) - } - assertFailsWith { - PrismDIDMethodId(validation4) - } - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/castor/PrismDIDPublicKeyTests.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/castor/PrismDIDPublicKeyTests.kt deleted file mode 100644 index 165e74f85..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/castor/PrismDIDPublicKeyTests.kt +++ /dev/null @@ -1,49 +0,0 @@ -package io.iohk.atala.prism.walletsdk.castor - -import io.iohk.atala.prism.protos.PublicKey -import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519KeyPair -import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519PrivateKey -import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519PublicKey -import io.iohk.atala.prism.walletsdk.castor.did.prismdid.PrismDIDPublicKey -import io.iohk.atala.prism.walletsdk.castor.did.prismdid.id -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.test.runTest -import org.junit.Ignore -import org.junit.Test -import kotlin.test.assertContentEquals -import kotlin.test.assertEquals - -class PrismDIDPublicKeyTests { - - @OptIn(ExperimentalCoroutinesApi::class) - @Ignore("PrismDIDPublicKey requires Secp256k1Lib to be an interface in order to mock its result. Once that is done this test can be added back.") - @Test - fun it_should_parse_proto_toPrismDIDPublicKey() = runTest { - val apollo = ApolloMock() - val seed = apollo.createRandomSeed(passphrase = "mnemonics").seed - val keyPair = Ed25519KeyPair( - privateKey = Ed25519PrivateKey(ByteArray(0)), - publicKey = Ed25519PublicKey(ByteArray(0)) - ) - - val publicKey = PrismDIDPublicKey( - apollo = ApolloMock(), - id = PrismDIDPublicKey.Usage.MASTER_KEY.id(0), - usage = PrismDIDPublicKey.Usage.MASTER_KEY, - keyData = keyPair.publicKey - ) - val protoData = publicKey.toProto() - val proto = PublicKey( - id = protoData.id, - usage = protoData.usage, - keyData = protoData.keyData - ) - val parsedPublicKey = PrismDIDPublicKey( - apollo = apollo, - proto = proto - ) - assertEquals(parsedPublicKey.id, "master0") - assertContentEquals(parsedPublicKey.keyData.raw, publicKey.keyData.raw) - assertEquals(parsedPublicKey.usage, publicKey.usage) - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/ExportableImportableKeyTest.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/ExportableImportableKeyTest.kt deleted file mode 100644 index 86d79111d..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/ExportableImportableKeyTest.kt +++ /dev/null @@ -1,24 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models.keyManagement - -import junit.framework.TestCase.assertNull -import org.junit.Test -import kotlin.test.assertEquals -import kotlin.test.assertNotNull - -class ExportableImportableKeyTest { - - @Test - fun testPEMKeyTypeFromString_whenCorrectStringProvided_thenSuccess() { - val keyTypePrivate = PEMKeyType.fromString("-----BEGIN EC PRIVATE KEY-----") - assertNotNull(keyTypePrivate) - assertEquals(PEMKeyType.EC_PRIVATE_KEY, keyTypePrivate) - val keyTypePublic = PEMKeyType.fromString("-----BEGIN EC PUBLIC KEY-----") - assertNotNull(keyTypePublic) - assertEquals(PEMKeyType.EC_PUBLIC_KEY, keyTypePublic) - } - - @Test - fun testPEMKeyTypeFromString_whenWrongStringProvided_thenReturnNull() { - assertNull(PEMKeyType.fromString("-----BEGIN FAIL KEY-----")) - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/logger/PrismLoggerMock.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/logger/PrismLoggerMock.kt deleted file mode 100644 index f8f2d4759..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/logger/PrismLoggerMock.kt +++ /dev/null @@ -1,28 +0,0 @@ -package io.iohk.atala.prism.walletsdk.logger - -class PrismLoggerMock : PrismLogger { - override fun debug(message: String, metadata: Array) { - val metaString = metadata.joinToString { "${it.getValue(LogLevel.DEBUG)}\n" } - println("debug: [io.prism.kmm.sdk.Test] $message Metadata: $metaString") - } - - override fun info(message: String, metadata: Array) { - val metaString = metadata.joinToString { "${it.getValue(LogLevel.DEBUG)}\n" } - println("info: [io.prism.kmm.sdk.Test] $message Metadata: $metaString") - } - - override fun warning(message: String, metadata: Array) { - val metaString = metadata.joinToString { "${it.getValue(LogLevel.DEBUG)}\n" } - println("warning: [io.prism.kmm.sdk.Test] $message Metadata: $metaString") - } - - override fun error(message: String, metadata: Array) { - val metaString = metadata.joinToString { "${it.getValue(LogLevel.DEBUG)}\n" } - println("error: [io.prism.kmm.sdk.Test] $message Metadata: $metaString") - } - - override fun error(error: Error, metadata: Array) { - val metaString = metadata.joinToString { "${it.getValue(LogLevel.DEBUG)}\n" } - println("error: [io.prism.kmm.sdk.Test] ${error.message} Metadata: $metaString") - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/mercury/ApiMock.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/mercury/ApiMock.kt deleted file mode 100644 index ea8f108f9..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/mercury/ApiMock.kt +++ /dev/null @@ -1,50 +0,0 @@ -package io.iohk.atala.prism.walletsdk.mercury - -import io.iohk.atala.prism.walletsdk.domain.models.Api -import io.iohk.atala.prism.walletsdk.domain.models.HttpResponse -import io.iohk.atala.prism.walletsdk.prismagent.shared.KeyValue -import io.ktor.client.engine.mock.MockEngine -import io.ktor.client.engine.mock.respond -import io.ktor.client.plugins.contentnegotiation.ContentNegotiation -import io.ktor.http.ContentType -import io.ktor.http.HttpHeaders -import io.ktor.http.HttpStatusCode -import io.ktor.http.headersOf -import io.ktor.serialization.kotlinx.json.json -import kotlinx.serialization.json.Json -import io.ktor.client.HttpClient as KtorClient - -class ApiMock( - val statusCode: HttpStatusCode, - val response: String, - override var client: KtorClient = KtorClient( - engine = MockEngine { _ -> - respond( - content = response, - status = statusCode, - headers = headersOf(HttpHeaders.ContentType, ContentType.Application.Json.toString()) - ) - } - ) { - install(ContentNegotiation) { - json( - Json { - ignoreUnknownKeys = true - prettyPrint = true - isLenient = true - } - ) - } - } -) : Api { - - override suspend fun request( - httpMethod: String, - url: String, - urlParameters: Array, - httpHeaders: Array, - body: Any? - ): HttpResponse { - return HttpResponse(statusCode.value, response) - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/mercury/CastorMock.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/mercury/CastorMock.kt deleted file mode 100644 index 652521810..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/mercury/CastorMock.kt +++ /dev/null @@ -1,50 +0,0 @@ -package io.iohk.atala.prism.walletsdk.mercury - -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Castor -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.DIDDocument -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.KeyPair -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PublicKey -import kotlin.jvm.Throws - -class CastorMock : Castor { - var parseDIDReturn: DID? = null - var createPrismDIDReturn: DID? = null - var createPeerDIDReturn: DID? = DID( - "did", - "prism", - "b6c0c33d701ac1b9a262a14454d1bbde3d127d697a76950963c5fd930605:Cj8KPRI7CgdtYXN0ZXIwEAFKLgoJc2VmsxEiECSTjyV7sUfCr_ArpN9rvCwR9fRMAhcsr_S7ZRiJk4p5k" - ) - var resolveDIDReturn: DIDDocument? = null - var verifySignatureReturn: Boolean = false - - @Throws(Exception::class) - override fun parseDID(did: String): DID { - return parseDIDReturn ?: throw Exception("parseDID() not implemented in mock") - } - - @Throws(Exception::class) - override fun createPrismDID( - masterPublicKey: PublicKey, - services: Array? - ): DID { - return createPrismDIDReturn ?: throw Exception("createPrismDID() not implemented in mock") - } - - @Throws(Exception::class) - override fun createPeerDID( - keyPairs: Array, - services: Array - ): DID { - return createPeerDIDReturn ?: throw Exception("createPeerDID() not implemented in mock") - } - - @Throws(Exception::class) - override suspend fun resolveDID(did: String): DIDDocument { - return resolveDIDReturn ?: throw Exception("resolveDID() not implemented in mock") - } - - override suspend fun verifySignature(did: DID, challenge: ByteArray, signature: ByteArray): Boolean { - return verifySignatureReturn - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/mercury/DIDResolverTests.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/mercury/DIDResolverTests.kt deleted file mode 100644 index bd99343e3..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/mercury/DIDResolverTests.kt +++ /dev/null @@ -1,155 +0,0 @@ -package io.iohk.atala.prism.walletsdk.mercury - -import io.iohk.atala.prism.walletsdk.domain.models.Curve -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.DIDDocument -import io.iohk.atala.prism.walletsdk.domain.models.DIDUrl -import io.iohk.atala.prism.walletsdk.domain.models.OctetPublicKey -import io.iohk.atala.prism.walletsdk.mercury.resolvers.DIDCommDIDResolver -import io.iohk.atala.prism.walletsdk.prismagent.DIDCOMM_MESSAGING -import kotlinx.coroutines.test.runTest -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json -import org.didcommx.didcomm.common.VerificationMaterial -import org.didcommx.didcomm.common.VerificationMaterialFormat -import org.didcommx.didcomm.common.VerificationMethodType -import org.didcommx.didcomm.diddoc.DIDCommService -import org.didcommx.didcomm.diddoc.VerificationMethod -import kotlin.test.BeforeTest -import kotlin.test.Test -import kotlin.test.assertContains -import kotlin.test.assertEquals -import kotlin.test.assertNotNull - -@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) -class DIDResolverTests { - lateinit var castorMock: CastorMock - lateinit var sut: DIDCommDIDResolver - - @BeforeTest - fun setup() { - castorMock = CastorMock() - sut = DIDCommDIDResolver(castorMock) - } - - @Test - fun testResolve_shouldTransformDomainDIDDOcumentToDIDCommDIDDoc() = runTest { - val idDid = DID("did", "prism", "123") - val allAuthentication = DIDDocument.Authentication(arrayOf(), arrayOf()) - val resolveDIDReturn = DIDDocument(idDid, arrayOf(allAuthentication)) - castorMock.resolveDIDReturn = resolveDIDReturn - - val result = sut.resolve("didString") - val didDoc = result.get() - - assertNotNull(didDoc) - assertEquals(didDoc.did, resolveDIDReturn.id.toString()) - } - - @Test - fun testResolve_shouldTransformServices() = runTest { - val idDid = DID("did", "prism", "2") - val seAccept = arrayOf("someAccepts") - val seRoutingKeys = arrayOf("someRoutingKey") - val service = DIDDocument.Service( - id = "DIDCommV2", - type = arrayOf(DIDCOMM_MESSAGING), - serviceEndpoint = DIDDocument.ServiceEndpoint( - uri = "localhost:8082", - accept = seAccept, - routingKeys = seRoutingKeys - ) - ) - - val allAuthentication = DIDDocument.Authentication(arrayOf(), arrayOf()) - val resolveDIDReturn = DIDDocument(idDid, arrayOf(service, allAuthentication)) - castorMock.resolveDIDReturn = resolveDIDReturn - - val result = sut.resolve("didString") - val didDoc = result.get() - - assertContains( - didDoc.didCommServices, - DIDCommService( - id = service.id, - serviceEndpoint = service.serviceEndpoint.uri, - routingKeys = seRoutingKeys.toList(), - accept = seAccept.toList() - ) - ) - } - - @Test - fun testResolve_shouldTransformVerificationMethods() = runTest { - val idDid = DID("did", "prism", "123") - - val vmAuthentication = DIDDocument.VerificationMethod( - id = DIDUrl(DID("2", "1", "0")), - controller = DID("2", "2", "0"), - type = Curve.ED25519.value, - publicKeyJwk = mapOf("crv" to Curve.ED25519.value, "x" to "") - ) - - val vmKeyAgreement = DIDDocument.VerificationMethod( - id = DIDUrl(DID("3", "1", "0")), - controller = DID("3", "2", "0"), - type = Curve.X25519.value, - publicKeyJwk = mapOf("crv" to Curve.X25519.value, "x" to "") - ) - - val allAuthentication = DIDDocument.Authentication( - arrayOf(), - arrayOf(vmAuthentication, vmKeyAgreement) - ) - val resolveDIDReturn = DIDDocument(idDid, arrayOf(allAuthentication)) - castorMock.resolveDIDReturn = resolveDIDReturn - - val result = sut.resolve("didString") - val didDoc = result.get() - - assertContains(didDoc.authentications, vmAuthentication.id.string()) - var publicJwk = vmAuthentication.publicKeyJwk - assertNotNull(publicJwk) - var publicJwkCrv = publicJwk[CRV] - var publicJwkX = publicJwk[X] - assertNotNull(publicJwkCrv) - assertNotNull(publicJwkX) - assertContains( - didDoc.verificationMethods, - VerificationMethod( - id = vmAuthentication.id.string(), - controller = vmAuthentication.controller.toString(), - type = VerificationMethodType.JSON_WEB_KEY_2020, - verificationMaterial = VerificationMaterial( - VerificationMaterialFormat.JWK, - Json.encodeToString(OctetPublicKey(crv = publicJwkCrv, x = publicJwkX)) - ) - ) - ) - - assertContains(didDoc.keyAgreements, vmKeyAgreement.id.string()) - publicJwk = vmKeyAgreement.publicKeyJwk - assertNotNull(publicJwk) - publicJwkCrv = publicJwk[CRV] - publicJwkX = publicJwk[X] - assertNotNull(publicJwkCrv) - assertNotNull(publicJwkX) - assertContains( - didDoc.verificationMethods, - VerificationMethod( - id = vmKeyAgreement.id.string(), - controller = vmKeyAgreement.controller.toString(), - type = VerificationMethodType.JSON_WEB_KEY_2020, - verificationMaterial = VerificationMaterial( - VerificationMaterialFormat.JWK, - Json.encodeToString( - OctetPublicKey( - crv = publicJwkCrv, - x = publicJwkX - ) - ) - ) - ) - ) - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/mercury/MercuryTests.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/mercury/MercuryTests.kt deleted file mode 100644 index 5bb836eee..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/mercury/MercuryTests.kt +++ /dev/null @@ -1,68 +0,0 @@ -package io.iohk.atala.prism.walletsdk.mercury - -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.DIDDocument -import io.iohk.atala.prism.walletsdk.domain.models.MercuryError -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.logger.PrismLoggerMock -import io.ktor.http.HttpStatusCode -import kotlinx.coroutines.test.runTest -import kotlin.test.BeforeTest -import kotlin.test.Test -import kotlin.test.assertFailsWith -import kotlin.test.assertTrue - -@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) -class MercuryTests { - lateinit var apiMock: ApiMock - lateinit var castorMock: CastorMock - lateinit var protocolMock: ProtocolMock - lateinit var sut: MercuryImpl - - @BeforeTest - fun setup() { - apiMock = ApiMock(HttpStatusCode.OK, "") - castorMock = CastorMock() - protocolMock = ProtocolMock() - sut = MercuryImpl(castorMock, protocolMock, apiMock, PrismLoggerMock()) - } - - @Test - fun testPackMessage_shouldThrowError_whenToAbsent() = runTest { - val msg = Message(piuri = "", body = "") - assertFailsWith { sut.packMessage(msg) } - } - - @Test - fun testPackMessage_shouldCall_ProtocolPackEncrypted() = runTest { - val to = DID("test", "method", "id") - val from = DID("test", "method", "id") - val msg = Message(piuri = "", body = "", from = from, to = to) - sut.packMessage(msg) - assertTrue { protocolMock.packEncryptedWasCalledWith === msg } - } - - @Test - fun testUnpackMessage_shouldCall_ProtocolUnpack() = runTest { - val messageString = "testMessageString" - sut.unpackMessage(messageString) - assertTrue { protocolMock.unpackWasCalledWith === messageString } - } - - @Test - fun testSendMessage_shouldThrowError_whenToAbsent() = runTest { - val msg = Message(piuri = "", body = "") - assertFailsWith { sut.sendMessage(msg) } - } - - @Test - fun testSendMessage_shouldThrowError_whenServiceAbsent() = runTest { - val idDid = DID("did", "prism", "123") - val allAuthentication = DIDDocument.Authentication(arrayOf(), arrayOf()) - // val resolveDIDReturn = DIDDocument(idDid, arrayOf(/*service,*/ allAuthentication)) - val resolveDIDReturn = DIDDocument(idDid, arrayOf(allAuthentication)) - castorMock.resolveDIDReturn = resolveDIDReturn - val msg = Message(piuri = "", body = "", from = DID("test", "method", "id"), to = DID("test", "method", "id")) - assertFailsWith { sut.sendMessage(msg) } - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/mercury/PlutoMock.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/mercury/PlutoMock.kt deleted file mode 100644 index ca1a8a0e0..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/mercury/PlutoMock.kt +++ /dev/null @@ -1,191 +0,0 @@ -@file:Suppress("ktlint:standard:import-ordering") - -package io.iohk.atala.prism.walletsdk.mercury - -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Pluto -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.DIDPair -import io.iohk.atala.prism.walletsdk.domain.models.Mediator -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.domain.models.PeerDID -import io.iohk.atala.prism.walletsdk.domain.models.PrismDIDInfo -import io.iohk.atala.prism.walletsdk.domain.models.StorableCredential -import io.iohk.atala.prism.walletsdk.pollux.models.CredentialRequestMeta -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PrivateKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.StorableKey -import io.iohk.atala.prism.walletsdk.pluto.CredentialRecovery -import io.iohk.atala.prism.walletsdk.pluto.data.AvailableClaims -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.flow -class PlutoMock : Pluto { - var privateKeys = mutableListOf() - - override fun getDIDPrivateKeyByID(id: String): Flow { - val pk = privateKeys.find { - it.getCurve() == id - } - - return flow { emit(pk) } - } - - override fun storePrismDIDAndPrivateKeys( - did: DID, - keyPathIndex: Int, - alias: String?, - privateKeys: List - ) { - TODO("Not yet implemented") - } - - override fun storePeerDID(did: DID) { - TODO("Not yet implemented") - } - - override fun storeDIDPair(host: DID, receiver: DID, name: String) { - TODO("Not yet implemented") - } - - override fun storeMessage(message: Message) { - TODO("Not yet implemented") - } - - override fun storeMessages(messages: List) { - TODO("Not yet implemented") - } - - override fun storePrivateKeys(storableKey: StorableKey, did: DID, keyPathIndex: Int, metaId: String?) { - TODO("Not yet implemented") - } - - override fun storeMediator(mediator: DID, host: DID, routing: DID) { - TODO("Not yet implemented") - } - - override fun storeCredential(storableCredential: StorableCredential) { - TODO("Not yet implemented") - } - - override fun getAllPrismDIDs(): Flow> { - TODO("Not yet implemented") - } - - override fun getDIDInfoByDID(did: DID): Flow { - TODO("Not yet implemented") - } - - override fun getDIDInfoByAlias(alias: String): Flow> { - TODO("Not yet implemented") - } - - override fun getPrismDIDKeyPathIndex(did: DID): Flow { - TODO("Not yet implemented") - } - - override fun getPrismLastKeyPathIndex(): Flow { - TODO("Not yet implemented") - } - - override fun getAllPeerDIDs(): Flow> { - TODO("Not yet implemented") - } - - override fun getDIDPrivateKeysByDID(did: DID): Flow> { - TODO("Not yet implemented") - } - - override fun getAllDidPairs(): Flow> { - TODO("Not yet implemented") - } - - override fun getPairByDID(did: DID): Flow { - TODO("Not yet implemented") - } - - override fun getPairByName(name: String): Flow { - TODO("Not yet implemented") - } - - override fun getAllMessages(): Flow> { - TODO("Not yet implemented") - } - - override fun getAllMessages(did: DID): Flow> { - TODO("Not yet implemented") - } - - override fun getAllMessagesSent(): Flow> { - TODO("Not yet implemented") - } - - override fun getAllMessagesReceived(): Flow> { - TODO("Not yet implemented") - } - - override fun getAllMessagesSentTo(did: DID): Flow> { - TODO("Not yet implemented") - } - - override fun getAllMessagesReceivedFrom(did: DID): Flow> { - TODO("Not yet implemented") - } - - override fun getAllMessagesOfType(type: String, relatedWithDID: DID?): Flow> { - TODO("Not yet implemented") - } - - override fun getAllMessages(from: DID, to: DID): Flow> { - TODO("Not yet implemented") - } - - override fun getMessage(id: String): Flow { - TODO("Not yet implemented") - } - - override fun getAllMediators(): Flow> { - TODO("Not yet implemented") - } - - override fun getAllCredentials(): Flow> { - TODO("Not yet implemented") - } - - override fun insertAvailableClaim(credentialId: String, claim: String) { - TODO("Not yet implemented") - } - - override fun insertAvailableClaims(credentialId: String, claims: Array) { - TODO("Not yet implemented") - } - - override fun getAvailableClaimsByCredentialId(credentialId: String): Flow> { - TODO("Not yet implemented") - } - - override fun getAvailableClaimsByClaim(claim: String): Flow> { - TODO("Not yet implemented") - } - - override fun storeLinkSecret(linkSecret: String) { - TODO("Not yet implemented") - } - - override fun storeCredentialMetadata(metadata: CredentialRequestMeta) { - TODO("Not yet implemented") - } - - override fun getLinkSecret(): Flow { - TODO("Not yet implemented") - } - - override fun getCredentialMetadata(linkSecretName: String): Flow { - TODO("Not yet implemented") - } - - override fun revokeCredential(credentialId: String) { - TODO("Not yet implemented") - } - - override fun observeRevokedCredentials(): Flow> { - TODO("Not yet implemented") - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/mercury/ProtocolMock.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/mercury/ProtocolMock.kt deleted file mode 100644 index de28a45c6..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/mercury/ProtocolMock.kt +++ /dev/null @@ -1,19 +0,0 @@ -package io.iohk.atala.prism.walletsdk.mercury - -import io.iohk.atala.prism.walletsdk.domain.models.Message - -class ProtocolMock : DIDCommProtocol { - var packEncryptedWasCalledWith: Message? = null - - override fun packEncrypted(message: Message): String { - packEncryptedWasCalledWith = message - return "mock" - } - - var unpackWasCalledWith: String? = null - - override fun unpack(message: String): Message { - unpackWasCalledWith = message - return Message(piuri = "piuri", body = "tesstBody") - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/mercury/SecretsResolverTests.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/mercury/SecretsResolverTests.kt deleted file mode 100644 index 7bbcbe694..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/mercury/SecretsResolverTests.kt +++ /dev/null @@ -1,65 +0,0 @@ -package io.iohk.atala.prism.walletsdk.mercury - -import io.iohk.atala.prism.walletsdk.apollo.utils.X25519PrivateKey -import io.iohk.atala.prism.walletsdk.mercury.resolvers.DIDCommSecretsResolver -import io.iohk.atala.prism.walletsdk.prismagent.ApolloMock -import org.didcommx.didcomm.common.VerificationMaterialFormat -import org.didcommx.didcomm.common.VerificationMethodType -import org.junit.Before -import org.junit.Ignore -import org.junit.Test -import kotlin.test.assertContains -import kotlin.test.assertNotNull -import kotlin.test.assertTrue - -@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) -class SecretsResolverTests { - lateinit var plutoMock: PlutoMock - lateinit var apolloMock: ApolloMock - lateinit var sut: DIDCommSecretsResolver - - @Before - fun setup() { - plutoMock = PlutoMock() - apolloMock = ApolloMock() - sut = DIDCommSecretsResolver(plutoMock, apolloMock) - } - - @Ignore("Ignore this test for now until we can review with the team.") - @Test - fun testFindKey() { - val privateKey = X25519PrivateKey(ByteArray(4)) - val kid = privateKey.getCurve() - plutoMock.privateKeys.add(privateKey) - - val result = sut.findKey(kid) - val key = result.get() - - assertNotNull(key) - assertTrue { key.kid == kid } - assertTrue { key.type == VerificationMethodType.JSON_WEB_KEY_2020 } - assertTrue { key.verificationMaterial.format == VerificationMaterialFormat.MULTIBASE } - assertTrue { key.verificationMaterial.value == privateKey.raw.toString() } - } - - @Test - fun testFindKeys_kidMatches_isReturned() { - val privateKey = X25519PrivateKey(ByteArray(0)) - plutoMock.privateKeys.add(privateKey) - - val kids = listOf(privateKey.getCurve()) - val result = sut.findKeys(kids) - - assertTrue { result.size == 1 } - assertContains(result, privateKey.getCurve()) - } - - @Test - fun testFindKeys_kidNoMatch_emptySetReturned() { - val privateKey = X25519PrivateKey(ByteArray(0)) - val kids = listOf(privateKey.getCurve()) - val result = sut.findKeys(kids) - - assertTrue { result.isEmpty() } - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/pollux/PolluxImplTest.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/pollux/PolluxImplTest.kt deleted file mode 100644 index 88d11ab8f..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/pollux/PolluxImplTest.kt +++ /dev/null @@ -1,35 +0,0 @@ -package io.iohk.atala.prism.walletsdk.pollux - -import io.iohk.atala.prism.walletsdk.mercury.ApiMock -import io.iohk.atala.prism.walletsdk.prismagent.CastorMock -import io.ktor.http.HttpStatusCode -import kotlinx.coroutines.test.runTest -import kotlin.test.BeforeTest -import kotlin.test.Test -import kotlin.test.assertEquals - -class PolluxImplTest { - - lateinit var pollux: PolluxImpl - lateinit var castorMock: CastorMock - lateinit var apiMock: ApiMock - - @BeforeTest - fun setup() { - castorMock = CastorMock() - val json = - "{\"name\":\"Schema name\",\"version\":\"1.1\",\"attrNames\":[\"name\",\"surname\"],\"issuerId\":\"did:prism:604ba1764ab89993f9a74625cc4f3e04737919639293eb382cc7adc53767f550\"}" - apiMock = ApiMock(HttpStatusCode.OK, json) - pollux = PolluxImpl(castorMock, apiMock) - } - - @Test - fun testGetSchema_whenAnoncred_thenSchemaCorrect() = runTest { - val schema = pollux.getSchema("") - val attrNames = listOf("name", "surname") - assertEquals("Schema name", schema.name) - assertEquals("1.1", schema.version) - assertEquals(attrNames, schema.attrNames) - assertEquals("did:prism:604ba1764ab89993f9a74625cc4f3e04737919639293eb382cc7adc53767f550", schema.issuerId) - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/AndroidIgnore.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/AndroidIgnore.kt deleted file mode 100644 index e27b50e45..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/AndroidIgnore.kt +++ /dev/null @@ -1,3 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent - -expect annotation class AndroidIgnore() diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/ApolloMock.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/ApolloMock.kt deleted file mode 100644 index f49bc2101..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/ApolloMock.kt +++ /dev/null @@ -1,54 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent - -import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519KeyPair -import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519PrivateKey -import io.iohk.atala.prism.walletsdk.apollo.utils.Ed25519PublicKey -import io.iohk.atala.prism.walletsdk.apollo.utils.Secp256k1PrivateKey -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Apollo -import io.iohk.atala.prism.walletsdk.domain.models.Seed -import io.iohk.atala.prism.walletsdk.domain.models.SeedWords -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.KeyPair -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PrivateKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PublicKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.StorableKey - -class ApolloMock : Apollo { - var createRandomMnemonicsReturn: Array = emptyArray() - var createSeedReturn: Seed = Seed(ByteArray(0)) - var createRandomSeedReturn: SeedWords = SeedWords(emptyArray(), Seed(ByteArray(0))) - var createKeyPairReturn: KeyPair = Ed25519KeyPair( - privateKey = Ed25519PrivateKey(ByteArray(0)), - publicKey = Ed25519PublicKey(ByteArray(0)) - ) - var createPrivateKey: PrivateKey? = null - - override fun createRandomMnemonics(): Array = createRandomMnemonicsReturn - - override fun createSeed(mnemonics: Array, passphrase: String): Seed { - return createSeedReturn - } - - override fun createRandomSeed(passphrase: String?): SeedWords { - return createRandomSeedReturn - } - - override fun createPrivateKey(properties: Map): PrivateKey { - return createPrivateKey ?: Secp256k1PrivateKey(ByteArray(0)) - } - - override fun isPrivateKeyData(identifier: String, data: ByteArray): Boolean { - TODO("Not yet implemented") - } - - override fun isPublicKeyData(identifier: String, data: ByteArray): Boolean { - TODO("Not yet implemented") - } - - override fun restorePrivateKey(key: StorableKey): PrivateKey { - TODO("Not yet implemented") - } - - override fun restorePublicKey(key: StorableKey): PublicKey { - TODO("Not yet implemented") - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/CastorMock.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/CastorMock.kt deleted file mode 100644 index 878f29cf0..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/CastorMock.kt +++ /dev/null @@ -1,62 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent - -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Castor -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.DIDDocument -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.KeyPair -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PublicKey - -class CastorMock : Castor { - var parseDIDReturn: DID? = null - var createPrismDIDReturn: DID? = null - var createPeerDIDReturn: DID? = DID( - "did", - "prism", - "b6c0c33d701ac1b9a262a14454d1bbde3d127d697a76950963c5fd930605:Cj8KPRI7CgdtYXN0ZXIwEAFKLgoJc2VmsxEiECSTjyV7sUfCr_ArpN9rvCwR9fRMAhcsr_S7ZRiJk4p5k" - ) - var resolveDIDReturn: DIDDocument? = null - var verifySignatureReturn: Boolean = false - - override fun parseDID(did: String): DID { - return parseDIDReturn ?: throw Exception("parseDID() not implemented in mock") - } - - override fun createPrismDID( - masterPublicKey: PublicKey, - services: Array? - ): DID { - return createPrismDIDReturn ?: throw Exception("createPrismDID() not implemented in mock") - } - - override fun createPeerDID( - keyPairs: Array, - services: Array - ): DID { - return createPeerDIDReturn ?: throw Exception("createPeerDID() not implemented in mock") - } - - override suspend fun resolveDID(did: String): DIDDocument { - val coreProperty = DIDDocument.Service( - id = "DIDCommV2", - type = arrayOf(DIDCOMM_MESSAGING), - serviceEndpoint = DIDDocument.ServiceEndpoint( - uri = "localhost:8082", - accept = arrayOf(DIDCOMM_MESSAGING), - routingKeys = arrayOf() - ) - ) - resolveDIDReturn = DIDDocument( - DID( - "did", - "prism", - "b6c0c33d701ac1b9a262a14454d1bbde3d127d697a76950963c5fd930605:Cj8KPRI7CgdtYXN0ZXIwEAFKLgoJc2VmsxEiECSTjyV7sUfCr_ArpN9rvCwR9fRMAhcsr_S7ZRiJk4p5k" - ), - arrayOf(coreProperty) - ) - return resolveDIDReturn ?: throw Exception("resolveDID() not implemented in mock") - } - - override suspend fun verifySignature(did: DID, challenge: ByteArray, signature: ByteArray): Boolean { - return verifySignatureReturn - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/ConnectionManagerTest.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/ConnectionManagerTest.kt deleted file mode 100644 index 9a32042a5..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/ConnectionManagerTest.kt +++ /dev/null @@ -1,361 +0,0 @@ -@file:Suppress("ktlint:standard:import-ordering") - -package io.iohk.atala.prism.walletsdk.prismagent - -import io.iohk.atala.prism.apollo.base64.base64UrlEncoded -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Castor -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Mercury -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Pluto -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Pollux -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentBase64 -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentDescriptor -import io.iohk.atala.prism.walletsdk.domain.models.CredentialType -import io.iohk.atala.prism.walletsdk.domain.models.Curve -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.DIDDocument -import io.iohk.atala.prism.walletsdk.domain.models.DIDUrl -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.prismagent.mediation.MediationHandler -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.flow.flow -import kotlinx.coroutines.test.TestCoroutineDispatcher -import kotlinx.coroutines.test.runBlockingTest -import kotlinx.coroutines.test.runTest -import org.mockito.Mock -import org.mockito.Mockito.verify -import org.mockito.Mockito.`when` -import org.mockito.MockitoAnnotations -import org.mockito.kotlin.any -import java.util.UUID -import kotlinx.coroutines.flow.Flow -import org.mockito.Mockito.anyList -import org.mockito.kotlin.anyArray -import org.mockito.kotlin.argumentCaptor -import kotlin.test.assertNotNull -import kotlin.test.BeforeTest -import kotlin.test.Test -import kotlin.test.assertEquals - -class ConnectionManagerTest { - - @Mock - lateinit var mercuryMock: Mercury - - @Mock - lateinit var castorMock: Castor - - @Mock - lateinit var plutoMock: Pluto - - @Mock - lateinit var polluxMock: Pollux - - @Mock - lateinit var basicMediatorHandlerMock: MediationHandler - - lateinit var connectionManager: ConnectionManager - - val testDispatcher = TestCoroutineDispatcher() - - @BeforeTest - fun setup() { - MockitoAnnotations.openMocks(this) - connectionManager = ConnectionManager( - mercury = mercuryMock, - castor = castorMock, - pluto = plutoMock, - mediationHandler = basicMediatorHandlerMock, - pairings = mutableListOf(), - pollux = polluxMock, - experimentLiveModeOptIn = true, - scope = CoroutineScope(testDispatcher) - ) - } - - @Test - fun testStartFetchingMessages_whenServiceEndpointContainsWSS_thenUseWebsockets() = runTest { - `when`(basicMediatorHandlerMock.mediatorDID) - .thenReturn(DID("did:prism:b6c0c33d701ac1b9a262a14454d1bbde3d127d697a76950963c5fd930605:Cj8KPRI7CgdtYXN0ZXIwEAFKLgoJc2VmsxEiECSTjyV7sUfCr_ArpN9rvCwR9fRMAhcsr_S7ZRiJk4p5k")) - - val vmAuthentication = DIDDocument.VerificationMethod( - id = DIDUrl(DID("2", "1", "0")), - controller = DID("2", "2", "0"), - type = Curve.ED25519.value, - publicKeyJwk = mapOf("crv" to Curve.ED25519.value, "x" to "") - ) - - val vmKeyAgreement = DIDDocument.VerificationMethod( - id = DIDUrl(DID("3", "1", "0")), - controller = DID("3", "2", "0"), - type = Curve.X25519.value, - publicKeyJwk = mapOf("crv" to Curve.X25519.value, "x" to "") - ) - - val vmService = DIDDocument.Service( - id = UUID.randomUUID().toString(), - type = emptyArray(), - serviceEndpoint = DIDDocument.ServiceEndpoint( - uri = "wss://serviceEndpoint" - ) - ) - - val didDoc = DIDDocument( - id = DID("did:prism:asdfasdf"), - coreProperties = arrayOf( - DIDDocument.Authentication( - urls = emptyArray(), - verificationMethods = arrayOf(vmAuthentication) - ), - DIDDocument.KeyAgreement( - urls = emptyArray(), - verificationMethods = arrayOf(vmKeyAgreement) - ), - DIDDocument.Services( - values = arrayOf(vmService) - ) - ) - ) - - `when`(castorMock.resolveDID(any())).thenReturn(didDoc) - - connectionManager.startFetchingMessages() - assertNotNull(connectionManager.fetchingMessagesJob) - verify(basicMediatorHandlerMock).listenUnreadMessages(any(), any()) - } - - @Test - fun testStartFetchingMessages_whenServiceEndpointContainsWSSButOptInLiveModeFalse_thenRegunarlApi() = runTest { - connectionManager = ConnectionManager( - mercury = mercuryMock, - castor = castorMock, - pluto = plutoMock, - mediationHandler = basicMediatorHandlerMock, - pairings = mutableListOf(), - pollux = polluxMock, - experimentLiveModeOptIn = false, - scope = CoroutineScope(testDispatcher) - ) - - `when`(basicMediatorHandlerMock.mediatorDID) - .thenReturn(DID("did:prism:b6c0c33d701ac1b9a262a14454d1bbde3d127d697a76950963c5fd930605:Cj8KPRI7CgdtYXN0ZXIwEAFKLgoJc2VmsxEiECSTjyV7sUfCr_ArpN9rvCwR9fRMAhcsr_S7ZRiJk4p5k")) - - val vmAuthentication = DIDDocument.VerificationMethod( - id = DIDUrl(DID("2", "1", "0")), - controller = DID("2", "2", "0"), - type = Curve.ED25519.value, - publicKeyJwk = mapOf("crv" to Curve.ED25519.value, "x" to "") - ) - - val vmKeyAgreement = DIDDocument.VerificationMethod( - id = DIDUrl(DID("3", "1", "0")), - controller = DID("3", "2", "0"), - type = Curve.X25519.value, - publicKeyJwk = mapOf("crv" to Curve.X25519.value, "x" to "") - ) - - val vmService = DIDDocument.Service( - id = UUID.randomUUID().toString(), - type = emptyArray(), - serviceEndpoint = DIDDocument.ServiceEndpoint( - uri = "wss://serviceEndpoint" - ) - ) - - val didDoc = DIDDocument( - id = DID("did:prism:asdfasdf"), - coreProperties = arrayOf( - DIDDocument.Authentication( - urls = emptyArray(), - verificationMethods = arrayOf(vmAuthentication) - ), - DIDDocument.KeyAgreement( - urls = emptyArray(), - verificationMethods = arrayOf(vmKeyAgreement) - ), - DIDDocument.Services( - values = arrayOf(vmService) - ) - ) - ) - - `when`(castorMock.resolveDID(any())).thenReturn(didDoc) - val messages = arrayOf(Pair("1234", Message(piuri = "", body = ""))) - `when`(basicMediatorHandlerMock.pickupUnreadMessages(any())).thenReturn( - flow { - emit( - messages - ) - } - ) - val attachments: Array = - arrayOf( - AttachmentDescriptor( - mediaType = "application/json", - format = CredentialType.JWT.type, - data = AttachmentBase64(base64 = "asdfasdfasdfasdfasdfasdfasdfasdfasdf".base64UrlEncoded) - ) - ) - val listMessages = listOf( - Message( - piuri = ProtocolType.DidcommconnectionRequest.value, - body = "" - ), - Message( - piuri = ProtocolType.DidcommIssueCredential.value, - thid = UUID.randomUUID().toString(), - from = DID("did:peer:asdf897a6sdf"), - to = DID("did:peer:f706sg678ha"), - attachments = attachments, - body = """{}""" - ) - ) - val messageList: Flow> = flow { - emit(listMessages) - } - `when`(plutoMock.getAllMessages()).thenReturn(messageList) - - connectionManager.startFetchingMessages() - assertNotNull(connectionManager.fetchingMessagesJob) - verify(basicMediatorHandlerMock).pickupUnreadMessages(10) - verify(basicMediatorHandlerMock).registerMessagesAsRead(arrayOf("1234")) - } - - @Test - fun testStartFetchingMessages_whenServiceEndpointNotContainsWSS_thenUseAPIRequest() = - runBlockingTest { - `when`(basicMediatorHandlerMock.mediatorDID) - .thenReturn(DID("did:prism:b6c0c33d701ac1b9a262a14454d1bbde3d127d697a76950963c5fd930605:Cj8KPRI7CgdtYXN0ZXIwEAFKLgoJc2VmsxEiECSTjyV7sUfCr_ArpN9rvCwR9fRMAhcsr_S7ZRiJk4p5k")) - - val vmAuthentication = DIDDocument.VerificationMethod( - id = DIDUrl(DID("2", "1", "0")), - controller = DID("2", "2", "0"), - type = Curve.ED25519.value, - publicKeyJwk = mapOf("crv" to Curve.ED25519.value, "x" to "") - ) - - val vmKeyAgreement = DIDDocument.VerificationMethod( - id = DIDUrl(DID("3", "1", "0")), - controller = DID("3", "2", "0"), - type = Curve.X25519.value, - publicKeyJwk = mapOf("crv" to Curve.X25519.value, "x" to "") - ) - - val vmService = DIDDocument.Service( - id = UUID.randomUUID().toString(), - type = emptyArray(), - serviceEndpoint = DIDDocument.ServiceEndpoint( - uri = "https://serviceEndpoint" - ) - ) - - val didDoc = DIDDocument( - id = DID("did:prism:asdfasdf"), - coreProperties = arrayOf( - DIDDocument.Authentication( - urls = emptyArray(), - verificationMethods = arrayOf(vmAuthentication) - ), - DIDDocument.KeyAgreement( - urls = emptyArray(), - verificationMethods = arrayOf(vmKeyAgreement) - ), - DIDDocument.Services( - values = arrayOf(vmService) - ) - ) - ) - - `when`(castorMock.resolveDID(any())).thenReturn(didDoc) - val messages = arrayOf(Pair("1234", Message(piuri = "", body = ""))) - `when`(basicMediatorHandlerMock.pickupUnreadMessages(any())).thenReturn( - flow { - emit( - messages - ) - } - ) - val attachments: Array = - arrayOf( - AttachmentDescriptor( - mediaType = "application/json", - format = CredentialType.JWT.type, - data = AttachmentBase64(base64 = "asdfasdfasdfasdfasdfasdfasdfasdfasdf".base64UrlEncoded) - ) - ) - val listMessages = listOf( - Message( - piuri = ProtocolType.DidcommconnectionRequest.value, - body = "" - ), - Message( - piuri = ProtocolType.DidcommIssueCredential.value, - thid = UUID.randomUUID().toString(), - from = DID("did:peer:asdf897a6sdf"), - to = DID("did:peer:f706sg678ha"), - attachments = attachments, - body = """{}""" - ) - ) - val messageList: Flow> = flow { - emit(listMessages) - } - `when`(plutoMock.getAllMessages()).thenReturn(messageList) - - connectionManager.startFetchingMessages() - assertNotNull(connectionManager.fetchingMessagesJob) - verify(basicMediatorHandlerMock).pickupUnreadMessages(10) - verify(basicMediatorHandlerMock).registerMessagesAsRead(arrayOf("1234")) - } - - @Test - fun testConnectionManager_whenProcessMessageRevoke_thenAllCorrect() = runTest { - val threadId = UUID.randomUUID().toString() - val attachments: Array = - arrayOf( - AttachmentDescriptor( - mediaType = "application/json", - format = CredentialType.JWT.type, - data = AttachmentBase64(base64 = "asdfasdfasdfasdfasdfasdfasdfasdfasdf".base64UrlEncoded) - ) - ) - val listMessages = listOf( - Message( - piuri = ProtocolType.DidcommconnectionRequest.value, - body = "" - ), - Message( - piuri = ProtocolType.DidcommIssueCredential.value, - thid = threadId, - from = DID("did:peer:asdf897a6sdf"), - to = DID("did:peer:f706sg678ha"), - attachments = attachments, - body = """{}""" - ) - ) - val messageList: Flow> = flow { - emit(listMessages) - } - `when`(plutoMock.getAllMessages()).thenReturn(messageList) - `when`(polluxMock.extractCredentialFormatFromMessage(any())).thenReturn(CredentialType.JWT) - - val messages = arrayOf( - Pair( - threadId, - Message( - piuri = ProtocolType.PrismRevocation.value, - from = DID("did:peer:0978aszdf7890asg"), - to = DID("did:peer:asdf9068asdf"), - body = """{"issueCredentialProtocolThreadId":"$threadId","comment":null}""" - ) - ) - ) - - connectionManager.processMessages(messages) - val argumentCaptor = argumentCaptor() - verify(plutoMock).revokeCredential(argumentCaptor.capture()) - assertEquals("asdfasdfasdfasdfasdfasdfasdfasdfasdf", argumentCaptor.firstValue) - verify(basicMediatorHandlerMock).registerMessagesAsRead(anyArray()) - verify(plutoMock).storeMessages(anyList()) - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/DIDMock.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/DIDMock.kt deleted file mode 100644 index 9a1867eb7..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/DIDMock.kt +++ /dev/null @@ -1,11 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent - -import io.iohk.atala.prism.walletsdk.domain.models.DID - -fun DID.Companion.testable( - schema: String = "did", - method: String = "test1", - methodId: String = "test1Id" -): DID { - return DID(schema, method, methodId) -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/MediationHandlerMock.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/MediationHandlerMock.kt deleted file mode 100644 index c7e074bf2..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/MediationHandlerMock.kt +++ /dev/null @@ -1,55 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent - -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.Mediator -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.prismagent.mediation.MediationHandler -import io.iohk.atala.prism.walletsdk.prismagent.mediation.OnMessageCallback -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.flow -import java.util.UUID - -class MediationHandlerMock( - override var mediator: Mediator? = null, - override var mediatorDID: DID = DID.testable() -) : MediationHandler { - - var bootMediatorResponse: Mediator? = null - var achieveMediationResponse: Mediator? = null - var pickupUnreadMessagesResponse: Array> = emptyArray() - - @Throws() - override suspend fun bootRegisteredMediator(): Mediator? { - val hostDID = DID("did", "test", "123") - val routingDID = DID("did", "test", "123") - bootMediatorResponse = Mediator(UUID.randomUUID().toString(), mediatorDID, hostDID, routingDID) - mediator = bootMediatorResponse - return bootMediatorResponse - } - - @Throws() - override fun achieveMediation(host: DID): Flow { - mediator = achieveMediationResponse - return flow { achieveMediationResponse?.let { emit(it) } ?: throw PrismAgentError.NoMediatorAvailableError() } - } - - @Throws() - override suspend fun updateKeyListWithDIDs(dids: Array) { - } - - @Throws() - override fun pickupUnreadMessages(limit: Int): Flow>> { - return flow { emit(pickupUnreadMessagesResponse) } - } - - @Throws() - override suspend fun registerMessagesAsRead(ids: Array) { - } - - override suspend fun listenUnreadMessages( - serviceEndpointUri: String, - onMessageCallback: OnMessageCallback - ) { - TODO("Not yet implemented") - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/MercuryMock.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/MercuryMock.kt deleted file mode 100644 index 4db705320..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/MercuryMock.kt +++ /dev/null @@ -1,30 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent - -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Mercury -import io.iohk.atala.prism.walletsdk.domain.models.Message -import kotlin.jvm.Throws - -class MercuryMock : Mercury { - var packMessageResponse: String? = null - var unpackMessageResponse: Message? = null - var sendMessageResponse: ByteArray? = null - var sendMessageParseMessageResponse: Message? = null - - @Throws() - override fun packMessage(message: Message): String { - return packMessageResponse ?: "" - } - - @Throws() - override fun unpackMessage(message: String): Message { - return unpackMessageResponse ?: Message.testable() - } - - override suspend fun sendMessage(message: Message): ByteArray? { - return sendMessageResponse - } - - override suspend fun sendMessageParseResponse(message: Message): Message? { - return sendMessageParseMessageResponse - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/MessageMock.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/MessageMock.kt deleted file mode 100644 index f87f30b82..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/MessageMock.kt +++ /dev/null @@ -1,39 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent - -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentDescriptor -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.Message - -fun Message.Companion.testable( - id: String = "test1", - piuri: String = "test", - from: DID? = null, - to: DID? = null, - fromPrior: String? = null, - body: String = "", - extraHeaders: Map = emptyMap(), - createdTime: String = "", - expiresTimePlus: String = "", - attachments: Array = emptyArray(), - thid: String? = null, - pthid: String? = null, - ack: Array = emptyArray(), - direction: Message.Direction = Message.Direction.RECEIVED -): Message { - return Message( - id, - piuri, - from, - to, - fromPrior, - body, - extraHeaders, - createdTime, - expiresTimePlus, - attachments, - thid, - pthid, - ack, - direction - ) -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/PlutoMock.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/PlutoMock.kt deleted file mode 100644 index af68ac02a..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/PlutoMock.kt +++ /dev/null @@ -1,249 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent - -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Pluto -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.DIDPair -import io.iohk.atala.prism.walletsdk.domain.models.Mediator -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.domain.models.PeerDID -import io.iohk.atala.prism.walletsdk.domain.models.PrismDIDInfo -import io.iohk.atala.prism.walletsdk.domain.models.StorableCredential -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PrivateKey -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.StorableKey -import io.iohk.atala.prism.walletsdk.pluto.CredentialRecovery -import io.iohk.atala.prism.walletsdk.pluto.data.AvailableClaims -import io.iohk.atala.prism.walletsdk.pollux.models.CredentialRequestMeta -import kotlinx.coroutines.flow.Flow - -class PlutoMock : Pluto { - var wasStorePrismDIDAndPrivateKeysCalled: Boolean = false - var wasStorePeerDIDAndPrivateKeysCalled: Boolean = false - var wasStoreDIDPairCalled: Boolean = false - var wasStoreMessageCalled: Boolean = false - var wasStoreMessagesCalled: Boolean = false - var wasStorePrivateKeysCalled: Boolean = false - var wasStoreMediatorCalled: Boolean = false - var wasStoreCredentialCalled: Boolean = false - var wasGetAllPrismDIDsCalled: Boolean = false - var wasGetDIDInfoByDIDCalled: Boolean = false - var wasGetPrismLastKeyPathIndexCalled: Boolean = false - var wasGetAllPeerDIDsCalled: Boolean = false - var wasGetDIDPrivateKeysByDIDCalled: Boolean = false - var wasGetDIDPrivateKeysByIDCalled: Boolean = false - var wasGetAllDidPairsCalled: Boolean = false - var wasGetPairByDIDCalled: Boolean = false - var wasGetPairByNameCalled: Boolean = false - var wasGetAllMessagesCalled: Boolean = false - var wasGetAllMessagesSentCalled: Boolean = false - var wasGetAllMessagesSentToCalled: Boolean = false - var wasGetAllMessagesReceivedCalled: Boolean = false - var wasGetAllMessagesReceivedFromCalled: Boolean = false - var wasGetAllMessagesOfTypeCalled: Boolean = false - var wasGetMessageCalled: Boolean = false - var wasGetAllMediatorsCalled: Boolean = false - var wasGetAllCredentialsCalled: Boolean = false - - var storedPrismDID: List = listOf() - var storedPeerDID: List = listOf() - lateinit var getAllPrismDIDsReturn: Flow> - lateinit var getDIDInfoByDIDReturn: Flow - lateinit var getPrismDIDKeyPathIndexReturn: Flow - lateinit var getPrismLastKeyPathIndexReturn: Flow - lateinit var getAllPeerDIDsReturn: Flow> - lateinit var getDIDPrivateKeysReturn: Flow> - lateinit var getDIDPrivateKeysByIDReturn: Flow - lateinit var getAllDidPairsReturn: Flow> - lateinit var getPairByDIDReturn: Flow - lateinit var getPairByNameReturn: Flow - lateinit var getAllMessagesReturn: Flow> - lateinit var getAllMessagesSentReturn: Flow> - lateinit var getAllMessagesSentToReturn: Flow> - lateinit var getAllMessagesReceivedReturn: Flow> - lateinit var getAllMessagesReceivedFromReturn: Flow> - lateinit var getAllMessagesOfTypeReturn: Flow> - lateinit var getMessageReturn: Flow - lateinit var getAllMediatorsReturn: Flow> - lateinit var getAllCredentialsReturn: Flow> - lateinit var getLinkSecretReturn: Flow - lateinit var getCredentialMetadataReturn: Flow - - override fun storePrismDIDAndPrivateKeys( - did: DID, - keyPathIndex: Int, - alias: String?, - privateKeys: List - ) { - storedPrismDID += did - wasStorePrismDIDAndPrivateKeysCalled = true - } - - override fun storePeerDID(did: DID) { - storedPeerDID += did - wasStorePeerDIDAndPrivateKeysCalled = true - } - - override fun storeDIDPair(host: DID, receiver: DID, name: String) { - wasStoreDIDPairCalled = true - } - - override fun storeMessage(message: Message) { - wasStoreMessageCalled = true - } - - override fun storeMessages(messages: List) { - wasStoreMessagesCalled = true - } - - override fun storePrivateKeys(storableKey: StorableKey, did: DID, keyPathIndex: Int, metaId: String?) { - wasStorePrivateKeysCalled = true - } - - override fun storeMediator(mediator: DID, host: DID, routing: DID) { - wasStoreMediatorCalled = true - } - - override fun storeCredential(storableCredential: StorableCredential) { - wasStoreCredentialCalled = true - } - - override fun getAllPrismDIDs(): Flow> { - wasGetAllPrismDIDsCalled = true - return getAllPrismDIDsReturn - } - - override fun getDIDInfoByDID(did: DID): Flow { - wasGetDIDInfoByDIDCalled = true - return getDIDInfoByDIDReturn - } - - override fun getDIDInfoByAlias(alias: String): Flow> = getAllPrismDIDsReturn - - override fun getPrismDIDKeyPathIndex(did: DID): Flow = getPrismDIDKeyPathIndexReturn - - override fun getPrismLastKeyPathIndex(): Flow { - wasGetPrismLastKeyPathIndexCalled = true - return getPrismLastKeyPathIndexReturn - } - - override fun getAllPeerDIDs(): Flow> { - wasGetAllPeerDIDsCalled = true - return getAllPeerDIDsReturn - } - - override fun getDIDPrivateKeysByDID(did: DID): Flow> { - wasGetDIDPrivateKeysByDIDCalled = true - return getDIDPrivateKeysReturn - } - - override fun getDIDPrivateKeyByID(id: String): Flow { - wasGetDIDPrivateKeysByIDCalled = true - return getDIDPrivateKeysByIDReturn - } - - override fun getAllDidPairs(): Flow> { - wasGetAllDidPairsCalled = true - return getAllDidPairsReturn - } - - override fun getPairByDID(did: DID): Flow { - wasGetPairByDIDCalled = true - return getPairByDIDReturn - } - - override fun getPairByName(name: String): Flow { - wasGetPairByNameCalled = true - return getPairByNameReturn - } - - override fun getAllMessages(): Flow> { - wasGetAllMessagesCalled = true - return getAllMessagesReturn - } - - override fun getAllMessages(did: DID): Flow> { - wasGetAllMessagesCalled = true - return getAllMessagesReturn - } - - override fun getAllMessagesSent(): Flow> { - wasGetAllMessagesSentCalled = true - return getAllMessagesSentReturn - } - - override fun getAllMessagesReceived(): Flow> { - wasGetAllMessagesReceivedCalled = true - return getAllMessagesReceivedReturn - } - - override fun getAllMessagesSentTo(did: DID): Flow> { - wasGetAllMessagesSentToCalled = true - return getAllMessagesSentToReturn - } - - override fun getAllMessagesReceivedFrom(did: DID): Flow> { - wasGetAllMessagesReceivedFromCalled = true - return getAllMessagesReceivedFromReturn - } - - override fun getAllMessagesOfType(type: String, relatedWithDID: DID?): Flow> { - wasGetAllMessagesOfTypeCalled = true - return getAllMessagesOfTypeReturn - } - - override fun getAllMessages(from: DID, to: DID): Flow> { - wasGetAllMessagesCalled = true - return getAllMessagesReturn - } - - override fun getMessage(id: String): Flow { - wasGetMessageCalled = true - return getMessageReturn - } - - override fun getAllMediators(): Flow> { - wasGetAllMediatorsCalled = true - return getAllMediatorsReturn - } - - override fun getAllCredentials(): Flow> { - wasGetAllCredentialsCalled = true - return getAllCredentialsReturn - } - - override fun insertAvailableClaim(credentialId: String, claim: String) { - TODO("Not yet implemented") - } - - override fun insertAvailableClaims(credentialId: String, claims: Array) { - TODO("Not yet implemented") - } - - override fun getAvailableClaimsByCredentialId(credentialId: String): Flow> { - TODO("Not yet implemented") - } - - override fun getAvailableClaimsByClaim(claim: String): Flow> { - TODO("Not yet implemented") - } - - override fun storeLinkSecret(linkSecret: String) { - } - - override fun storeCredentialMetadata(metadata: CredentialRequestMeta) {} - - override fun getLinkSecret(): Flow { - return getLinkSecretReturn - } - - override fun getCredentialMetadata(linkSecretName: String): Flow { - return getCredentialMetadataReturn - } - - override fun revokeCredential(credentialId: String) { - TODO("Not yet implemented") - } - - override fun observeRevokedCredentials(): Flow> { - TODO("Not yet implemented") - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/PolluxMock.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/PolluxMock.kt deleted file mode 100644 index 95ab39ab1..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/PolluxMock.kt +++ /dev/null @@ -1,85 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent - -import anoncreds_wrapper.CredentialOffer -import anoncreds_wrapper.CredentialRequestMetadata -import anoncreds_wrapper.LinkSecret -import anoncreds_wrapper.Presentation -import anoncreds_wrapper.Schema -import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Pollux -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentDescriptor -import io.iohk.atala.prism.walletsdk.domain.models.Credential -import io.iohk.atala.prism.walletsdk.domain.models.CredentialType -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.StorableCredential -import io.iohk.atala.prism.walletsdk.domain.models.keyManagement.PrivateKey -import io.iohk.atala.prism.walletsdk.pollux.models.AnonCredential -import io.iohk.atala.prism.walletsdk.pollux.models.CredentialRequest -import io.iohk.atala.prism.walletsdk.pollux.models.CredentialRequestMeta -import io.iohk.atala.prism.walletsdk.prismagent.protocols.proofOfPresentation.RequestPresentation -import kotlinx.serialization.json.JsonObject - -class PolluxMock : Pollux { - - var extractedCredentialFormatFromMessageReturn: CredentialType? = null - var processCredentialRequestAnoncredsReturn: Pair? = null - - override suspend fun parseCredential( - jsonData: String, - type: CredentialType, - linkSecret: LinkSecret?, - credentialMetadata: CredentialRequestMetadata? - ): Credential { - TODO("Not yet implemented") - } - - override fun processCredentialRequestJWT(subjectDID: DID, privateKey: PrivateKey, offerJson: JsonObject): String { - TODO("Not yet implemented") - } - - override fun createVerifiablePresentationJWT( - subjectDID: DID, - privateKey: PrivateKey, - credential: Credential, - requestPresentationJson: JsonObject - ): String { - TODO("Not yet implemented") - } - - override suspend fun createVerifiablePresentationAnoncred( - request: RequestPresentation, - credential: AnonCredential, - linkSecret: LinkSecret - ): Presentation { - TODO("Not yet implemented") - } - - override fun restoreCredential(restorationIdentifier: String, credentialData: ByteArray, revoked: Boolean): Credential { - TODO("Not yet implemented") - } - - override suspend fun processCredentialRequestAnoncreds( - did: DID, - offer: CredentialOffer, - linkSecret: LinkSecret, - linkSecretName: String - ): Pair { - TODO("Not yet implemented") - // return processCredentialRequestAnoncredsReturn ?: throw Exception("Return not defined") - } - - override fun credentialToStorableCredential(type: CredentialType, credential: Credential): StorableCredential { - TODO("Not yet implemented") - } - - override fun extractCredentialFormatFromMessage(formats: Array): CredentialType { - return extractedCredentialFormatFromMessageReturn ?: throw Exception("Return not defined") - } - - override suspend fun getCredentialDefinition(id: String): anoncreds_wrapper.CredentialDefinition { - TODO("Not yet implemented") - } - - override suspend fun getSchema(schemaId: String): Schema { - TODO("Not yet implemented") - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/PrismAgentTests.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/PrismAgentTests.kt deleted file mode 100644 index def1787b6..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/PrismAgentTests.kt +++ /dev/null @@ -1,556 +0,0 @@ -@file:Suppress("ktlint:standard:import-ordering") - -package io.iohk.atala.prism.walletsdk.prismagent - -import anoncreds_wrapper.LinkSecret -import io.iohk.atala.prism.apollo.derivation.MnemonicHelper -import io.iohk.atala.prism.walletsdk.apollo.ApolloImpl -import io.iohk.atala.prism.walletsdk.apollo.utils.Secp256k1KeyPair -import io.iohk.atala.prism.walletsdk.castor.CastorImpl -import io.iohk.atala.prism.walletsdk.domain.models.Api -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentBase64 -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentDescriptor -import io.iohk.atala.prism.walletsdk.domain.models.ClaimType -import io.iohk.atala.prism.walletsdk.domain.models.CredentialType -import io.iohk.atala.prism.walletsdk.domain.models.Curve -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.DIDDocument -import io.iohk.atala.prism.walletsdk.domain.models.KeyCurve -import io.iohk.atala.prism.walletsdk.domain.models.Seed -import io.iohk.atala.prism.walletsdk.domain.models.Signature -import io.iohk.atala.prism.walletsdk.logger.PrismLoggerMock -import io.iohk.atala.prism.walletsdk.mercury.ApiMock -import io.iohk.atala.prism.walletsdk.pollux.PolluxImpl -import io.iohk.atala.prism.walletsdk.pollux.models.CredentialRequestMeta -import io.iohk.atala.prism.walletsdk.prismagent.helpers.AgentOptions -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType -import io.iohk.atala.prism.walletsdk.prismagent.protocols.issueCredential.CredentialPreview -import io.iohk.atala.prism.walletsdk.prismagent.protocols.issueCredential.IssueCredential -import io.iohk.atala.prism.walletsdk.prismagent.protocols.issueCredential.OfferCredential -import io.iohk.atala.prism.walletsdk.prismagent.protocols.outOfBand.OutOfBandInvitation -import io.iohk.atala.prism.walletsdk.prismagent.protocols.outOfBand.PrismOnboardingInvitation -import io.ktor.http.HttpStatusCode -import kotlinx.coroutines.flow.flow -import kotlinx.coroutines.test.runTest -import kotlinx.serialization.SerializationException -import kotlinx.serialization.json.Json -import kotlin.test.BeforeTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertFalse -import kotlin.test.assertTrue - -@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) -class PrismAgentTests { - - lateinit var apolloMock: ApolloMock - lateinit var castorMock: CastorMock - lateinit var plutoMock: PlutoMock - lateinit var mercuryMock: MercuryMock - lateinit var polluxMock: PolluxMock - lateinit var mediationHandlerMock: MediationHandlerMock - lateinit var connectionManager: ConnectionManager - lateinit var json: Json - - @BeforeTest - fun setup() { - apolloMock = ApolloMock() - castorMock = CastorMock() - plutoMock = PlutoMock() - mercuryMock = MercuryMock() - polluxMock = PolluxMock() - mediationHandlerMock = MediationHandlerMock() - // Pairing will be removed in the future - connectionManager = ConnectionManager(mercuryMock, castorMock, plutoMock, mediationHandlerMock, mutableListOf(), polluxMock, true) - json = Json { - ignoreUnknownKeys = true - prettyPrint = true - isLenient = true - } - } - - @Test - fun testCreateNewPrismDID_shouldCreateNewDID_whenCalled() = runTest { - val seed = Seed(MnemonicHelper.createRandomSeed()) - val validDID = DID("did", "test", "123") - castorMock.createPrismDIDReturn = validDID - val agent = PrismAgent( - apollo = apolloMock, - castor = castorMock, - pluto = plutoMock, - mercury = mercuryMock, - pollux = polluxMock, - connectionManager = connectionManager, - seed = seed, - api = null, - logger = PrismLoggerMock(), - agentOptions = AgentOptions() - ) - plutoMock.getPrismLastKeyPathIndexReturn = flow { emit(0) } - val newDID = agent.createNewPrismDID() - assertEquals(newDID, validDID) - assertEquals(newDID, plutoMock.storedPrismDID.first()) - assertTrue { plutoMock.wasGetPrismLastKeyPathIndexCalled } - assertTrue { plutoMock.wasStorePrismDIDAndPrivateKeysCalled } - } - - @Test - fun testCreateNewPeerDID_shouldCreateNewDID_whenCalled() = runTest { - val validDID = DID("did", "test", "123") - castorMock.createPeerDIDReturn = validDID - val agent = PrismAgent( - apolloMock, - castorMock, - plutoMock, - mercuryMock, - polluxMock, - connectionManager, - null, - null, - logger = PrismLoggerMock(), - agentOptions = AgentOptions() - ) - - val newDID = agent.createNewPeerDID(services = emptyArray(), updateMediator = false) - - assertEquals(newDID, validDID) - assertEquals(newDID, plutoMock.storedPeerDID.first()) - assertTrue { plutoMock.wasStorePeerDIDAndPrivateKeysCalled } - } - - @Test - fun testCreateNewPeerDID_whenUpdateMediatorFalse_thenShouldUseProvidedServices() = runTest { - val apollo = ApolloImpl() - val castor = CastorImpl(apollo = apollo, logger = PrismLoggerMock()) - val agent = PrismAgent( - apollo, - castor, - plutoMock, - mercuryMock, - polluxMock, - connectionManager, - null, - null, - logger = PrismLoggerMock(), - agentOptions = AgentOptions() - ) - - val seAccept = arrayOf("someAccepts") - val seRoutingKeys = arrayOf("someRoutingKey") - val service = DIDDocument.Service( - id = "DIDCommV2", - type = arrayOf(DIDCOMM_MESSAGING), - serviceEndpoint = DIDDocument.ServiceEndpoint( - uri = "localhost:8082", - accept = seAccept, - routingKeys = seRoutingKeys - ) - ) - val newDID = agent.createNewPeerDID(services = arrayOf(service), updateMediator = false) - - val document = castor.resolveDID(newDID.toString()) - val services = document.services - assertTrue(services.isNotEmpty()) - assertEquals(service.type.first(), services.first().type.first()) - assertEquals(service.serviceEndpoint, services.first().serviceEndpoint) - } - - @Test - fun testPrismAgentOnboardingInvitation_shouldAcceptOnboardingInvitation_whenStatusIs200() = runTest { - val agent = PrismAgent( - apollo = apolloMock, - castor = castorMock, - pluto = plutoMock, - mercury = mercuryMock, - pollux = polluxMock, - connectionManager = connectionManager, - seed = null, - api = ApiMock(HttpStatusCode.OK, "{\"success\":\"true\"}"), - logger = PrismLoggerMock(), - agentOptions = AgentOptions() - ) - val invitationString = """ - { - "type":"${ProtocolType.PrismOnboarding.value}", - "onboardEndpoint":"http://localhost/onboarding", - "from":"did:prism:b6c0c33d701ac1b9a262a14454d1bbde3d127d697a76950963c5fd930605:Cj8KPRI7CgdtYXN0ZXIwEAFKLgoJc2VmsxEiECSTjyV7sUfCr_ArpN9rvCwR9fRMAhcsr_S7ZRiJk4p5k" - } - """ - val invitation = agent.parseInvitation(invitationString) - assertEquals(PrismOnboardingInvitation::class, invitation::class) - agent.acceptInvitation(invitation as PrismOnboardingInvitation) - } - - @Test - fun testPrismAgentOnboardingInvitation_shouldRejectOnboardingInvitation_whenStatusIsNot200() = runTest { - val api = ApiMock(HttpStatusCode.BadRequest, "{\"success\":\"true\"}") - val agent = PrismAgent( - apollo = apolloMock, - castor = castorMock, - pluto = plutoMock, - mercury = mercuryMock, - pollux = polluxMock, - connectionManager = connectionManager, - seed = null, - api = api, - logger = PrismLoggerMock(), - agentOptions = AgentOptions() - ) - val invitationString = """ - { - "type":"${ProtocolType.PrismOnboarding.value}", - "onboardEndpoint":"http://localhost/onboarding", - "from":"did:prism:b6c0c33d701ac1b9a262a14454d1bbde3d127d697a76950963c5fd930605:Cj8KPRI7CgdtYXN0ZXIwEAFKLgoJc2VmsxEiECSTjyV7sUfCr_ArpN9rvCwR9fRMAhcsr_S7ZRiJk4p5k" - } - """ - val invitation = agent.parseInvitation(invitationString) - assertFailsWith { - agent.acceptInvitation(invitation as PrismOnboardingInvitation) - } - } - - @Test - fun testPrismAgentOnboardingInvitation_shouldRejectOnboardingInvitation_whenBodyIsWrong() = runTest { - val agent = PrismAgent( - apollo = apolloMock, - castor = castorMock, - pluto = plutoMock, - mercury = mercuryMock, - pollux = polluxMock, - connectionManager = connectionManager, - seed = null, - api = ApiMock(HttpStatusCode.OK, "{\"success\":\"true\"}"), - logger = PrismLoggerMock(), - agentOptions = AgentOptions() - ) - val invitationString = """ - { - "type":"${ProtocolType.PrismOnboarding.value}", - "errorField":"http://localhost/onboarding", - "from":"did:prism:b6c0c33d701ac1b9a262a14454d1bbde3d127d697a76950963c5fd930605:Cj8KPRI7CgdtYXN0ZXIwEAFKLgoJc2VmsxEiECSTjyV7sUfCr_ArpN9rvCwR9fRMAhcsr_S7ZRiJk4p5k" - } - """ - assertFailsWith { - agent.parseInvitation(invitationString) - } - } - - @Test - fun testPrismAgentSignWith_whenNoPrivateKeyAvailable_thenThrowCannotFindDIDPrivateKey() = runTest { - val agent = PrismAgent( - apollo = apolloMock, - castor = castorMock, - pluto = plutoMock, - mercury = mercuryMock, - pollux = polluxMock, - connectionManager = connectionManager, - seed = null, - api = null, - logger = PrismLoggerMock(), - agentOptions = AgentOptions() - ) - - plutoMock.getDIDPrivateKeysReturn = flow { emit(listOf(null)) } - - val did = DID("did", "peer", "asdf1234asdf1234") - val messageString = "This is a message" - assertFalse { plutoMock.wasGetDIDPrivateKeysByDIDCalled } - assertFailsWith(PrismAgentError.CannotFindDIDPrivateKey::class, null) { - agent.signWith(did, messageString.toByteArray()) - } - } - - @Test - fun testPrismAgentSignWith_whenPrivateKeyAvailable_thenSignatureReturned() = runTest { - val agent = PrismAgent( - apollo = apolloMock, - castor = castorMock, - pluto = plutoMock, - mercury = mercuryMock, - pollux = polluxMock, - connectionManager = connectionManager, - seed = null, - api = null, - logger = PrismLoggerMock(), - agentOptions = AgentOptions() - ) - - val privateKeys = listOf( - Secp256k1KeyPair.generateKeyPair( - seed = Seed(MnemonicHelper.createRandomSeed()), - curve = KeyCurve(Curve.SECP256K1) - ).privateKey - ) - plutoMock.getDIDPrivateKeysReturn = flow { emit(privateKeys) } - - val did = DID("did", "peer", "asdf1234asdf1234") - val messageString = "This is a message" - - assertEquals(Signature::class, agent.signWith(did, messageString.toByteArray())::class) - assertTrue { plutoMock.wasGetDIDPrivateKeysByDIDCalled } - } - - @Test - fun testParseInvitation_whenOutOfBand_thenReturnsOutOfBandInvitationObject() = runTest { - val agent = PrismAgent( - apollo = apolloMock, - castor = castorMock, - pluto = plutoMock, - mercury = mercuryMock, - pollux = polluxMock, - connectionManager = connectionManager, - seed = null, - api = null, - logger = PrismLoggerMock(), - agentOptions = AgentOptions() - ) - - val invitationString = """ - { - "type": "https://didcomm.org/out-of-band/2.0/invitation", - "id": "1234-1234-1234-1234", - "from": "did:peer:asdf42sf", - "body": { - "goal_code": "issue-vc", - "goal": "To issue a Faber College Graduate credential", - "accept": [ - "didcomm/v2", - "didcomm/aip2;env=rfc587" - ] - } - } - """ - - val invitation = agent.parseInvitation(invitationString.trim()) - assert(invitation is OutOfBandInvitation) - val oobInvitation: OutOfBandInvitation = invitation as OutOfBandInvitation - assertEquals("https://didcomm.org/out-of-band/2.0/invitation", oobInvitation.type.value) - assertEquals(DID("did:peer:asdf42sf").toString(), oobInvitation.from) - assertEquals( - OutOfBandInvitation.Body( - "issue-vc", - "To issue a Faber College Graduate credential", - listOf("didcomm/v2", "didcomm/aip2;env=rfc587") - ), - oobInvitation.body - ) - } - - @Test - fun testParseInvitation_whenOutOfBandWrongBody_thenThrowsUnknownInvitationTypeError() = runTest { - val agent = PrismAgent( - apollo = apolloMock, - castor = castorMock, - pluto = plutoMock, - mercury = mercuryMock, - pollux = polluxMock, - connectionManager = connectionManager, - seed = null, - api = null, - logger = PrismLoggerMock(), - agentOptions = AgentOptions() - ) - - val invitationString = """ - { - "type": "https://didcomm.org/out-of-band/2.0/invitation", - "id": "1234-1234-1234-1234", - "from": "did:peer:asdf42sf", - "wrongBody": {} - } - """ - - assertFailsWith { - agent.parseInvitation(invitationString.trim()) - } - } - - @Test - fun testStartPrismAgent_whenCalled_thenStatusIsRunning() = runTest { - val getLinkSecretReturn = flow { emit("linkSecret") } - plutoMock.getLinkSecretReturn = getLinkSecretReturn - val agent = PrismAgent( - apollo = apolloMock, - castor = castorMock, - pluto = plutoMock, - mercury = mercuryMock, - pollux = polluxMock, - connectionManager = connectionManager, - seed = null, - api = null, - logger = PrismLoggerMock(), - agentOptions = AgentOptions() - ) - assertEquals(PrismAgent.State.STOPPED, agent.state) - agent.start() - assertEquals(PrismAgent.State.RUNNING, agent.state) - } - - @Test - fun testStopPrismAgent_whenCalled_thenStatusIsStopped() = runTest { - val agent = PrismAgent( - apollo = apolloMock, - castor = castorMock, - pluto = plutoMock, - mercury = mercuryMock, - pollux = polluxMock, - connectionManager = connectionManager, - seed = null, - api = null, - logger = PrismLoggerMock(), - agentOptions = AgentOptions() - ) - agent.stop() - assertEquals(PrismAgent.State.STOPPED, agent.state) - } - - @Test - fun test_OOPInvitationInURLFormat() = runTest { - val oob = - "https://my.domain.com/path?_oob=eyJpZCI6ImQzNjM3NzlhLWYyMmItNGFiNC1hYjY0LTkxZjkxNjgzNzYwNyIsInR5cGUiOiJodHRwczovL2RpZGNvbW0ub3JnL291dC1vZi1iYW5kLzIuMC9pbnZpdGF0aW9uIiwiZnJvbSI6ImRpZDpwZWVyOjIuRXo2TFNjcGZReGJ2VEhLaGpvbzVvMzlmc254VEp1RTRobVp3ckROUE5BVzI0dmFORi5WejZNa3UzSkpVTDNkaHpYQXB0RWpuUDFpNkF0TDlTNGlwRTNYOHM3MWV4MW9WVGNHLlNleUowSWpvaVpHMGlMQ0p6SWpvaWFIUjBjSE02THk5ck9ITXRaR1YyTG1GMFlXeGhjSEpwYzIwdWFXOHZjSEpwYzIwdFlXZGxiblF2Wkdsa1kyOXRiU0lzSW5JaU9sdGRMQ0poSWpwYkltUnBaR052YlcwdmRqSWlYWDAiLCJib2R5Ijp7ImdvYWxfY29kZSI6ImlvLmF0YWxhcHJpc20uY29ubmVjdCIsImdvYWwiOiJFc3RhYmxpc2ggYSB0cnVzdCBjb25uZWN0aW9uIGJldHdlZW4gdHdvIHBlZXJzIHVzaW5nIHRoZSBwcm90b2NvbCAnaHR0cHM6Ly9hdGFsYXByaXNtLmlvL21lcmN1cnkvY29ubmVjdGlvbnMvMS4wL3JlcXVlc3QnIiwiYWNjZXB0IjpbXX19" - val agent = PrismAgent( - apollo = apolloMock, - castor = castorMock, - pluto = plutoMock, - mercury = mercuryMock, - pollux = polluxMock, - connectionManager = connectionManager, - seed = null, - api = null, - logger = PrismLoggerMock(), - agentOptions = AgentOptions() - ) - val x = agent.parseInvitation(oob) - assert(x is OutOfBandInvitation) - assert((x as OutOfBandInvitation).type == ProtocolType.Didcomminvitation) - } - - @AndroidIgnore - @Test - fun testAnoncreds_whenOfferReceived_thenProcessed() = runTest { - val fromDID = DID("did:prism:asdf42sf") - val toDID = DID("did:prism:asdf42sf") - - val apiMock: Api = ApiMock( - HttpStatusCode(200, "Ok"), - getCredentialDefinitionResponse - ) - val pollux = PolluxImpl(castorMock, apiMock) - plutoMock.getLinkSecretReturn = flow { emit(LinkSecret().getValue()) } - - val agent = PrismAgent( - apollo = apolloMock, - castor = castorMock, - pluto = plutoMock, - mercury = mercuryMock, - pollux = pollux, - connectionManager = connectionManager, - seed = null, - api = ApiMock(HttpStatusCode.OK, "{\"success\":\"true\"}"), - logger = PrismLoggerMock(), - agentOptions = AgentOptions() - ) - - val attachmentDescriptor = - AttachmentDescriptor( - mediaType = "application/json", - format = CredentialType.ANONCREDS_OFFER.type, - data = AttachmentBase64( - "eyJzY2hlbWFfaWQiOiJodHRwOi8vaG9zdC5kb2NrZXIuaW50ZXJuYWw6ODAwMC9wcmlzbS1hZ2VudC9zY2hlbWEtcmVnaXN0cnkvc2NoZW1hcy81ZTBkNWE5My00YmZkLTMxMTEtYTk1Ni01ZDViYzgyZjc2Y2MiLCJjcmVkX2RlZl9pZCI6Imh0dHA6Ly8xOTIuMTY4LjY4LjEwMjo4MDAwL3ByaXNtLWFnZW50L2NyZWRlbnRpYWwtZGVmaW5pdGlvbi1yZWdpc3RyeS9kZWZpbml0aW9ucy81ZTI5NWNmMi00MjI2LTNjN2QtYjI3Zi04N2JlMTYwNjQ3NmQvZGVmaW5pdGlvbiIsImtleV9jb3JyZWN0bmVzc19wcm9vZiI6eyJjIjoiMTAyNTI4NDk1NTgzODg5MzkwMDcxMzk2OTI1ODg2NzI1MDk2MDMwNjY4ODgwOTMzNzQ5NTUzODEyNTY3MzE0NjQ0ODE0ODU2Nzk2NjI4IiwieHpfY2FwIjoiMTA4NzM1NDQ3NTAzNTQwNDc2MDIyOTAzNTYxNDY1Nzk4NzExMDA5MTU3MDcwOTY1MjMzNzIyNTAzMzg1NDY2NjIyNjYxNDgyMDkzMjAyMjg2ODcxMDQ5MDM3MDA5NzA1ODg3OTUzMDY5NjczNjA4Mzg5MTQ4NzY5ODI1NjMyNTU3NTk0Mzg3NDI2MjkzODY5OTIxNTg4MTM0MzI1OTczODg5NDY1NjYzNzM4ODA4ODg5NTE3Njc4MzIwOTYxNTk0NDg5MjYxNzI3ODAxMTc1OTMxMTQ2MjcwNDk3MzE5NTc4MTc4NDg3Nzg3MTAxNzg1ODMwMjE2NjgzODk2ODE1ODUyNjgzNDc5NjUxMzQ5NDY3MzUzNzM4MjM0NjE4NTMyODIyMzU1MTQ3ODcxOTU5NTU5ODgzNTUxOTQ5OTkwODY0ODEzNTYyODU3NzU5NDU4MTg1MDI5MDI3NTI1NTMzMDQyMDQ5MjEwMDA4NTg3MTc2MzQwNTg4Nzc2Mjc0MzgxMDU2MzM5ODE0OTAzMTMyNjI2MzIyMzc3MjAwMjYwMjM4NDcwNjcyMzI4NDQ4NzIyOTk4NDc1MDIwMzA4MjY2NDIzODUyNzA3Njk2OTQyNjk3NDc3MzI0MDUzOTM0MjQ3NDU4MDcxNjkyMDM5OTQ4MDkxMDg5MjA0NDQ2MDkyODY0Njc1NTQyMDA0Nzk1MDUyNjMzNzczMTQyMDc4Mzg0MTA1MDQzMDY4NjQ3Nzg3NzY3MDE1MDc5MjE1OTEzNTIzODIxOTU4NDQ2NTAxODY2ODY1OTE1NzEwNjY1NDU1MzU4ODEwNTY0OTk3MDUwNjAzNDc4NDE0MzA4NDQzMzc3Njg3ODUyMzc4NDgwNzg3MTQ1MDY2MTQ5MzA5MTM0NzMyNDg4NzQzMTg1NDgxMzU5MzA1NTM3MiIsInhyX2NhcCI6W1siZGF0ZW9maXNzdWFuY2UiLCIxODg0NTYwNDI1ODExNzgxNjE2Njc5NjAyMzA5ODExOTI5NzEyNDA4MDA0MzkxMDEyNzk3ODAxODA0MzU0MzQ0MTI3NDI2MTk0ODg5NDI3MjU3NjQzMzg2MTkxNTY0NDM5ODUzOTQ2NTg4MzkyNjMwNzEwMzA1OTM2OTAxNDA3NjYwOTk2NDc5ODkxNTgzNDE2NDkxODYyNzA3MTczOTA2OTg4ODEzNDE5ODQyMDg1MDM1MTg1OTA0MzQ2MTU4OTM2NDIyOTY5OTMwODg4Njg3NTc0MDcyMzY5MDc2NjkxNTk4MjkyMDkwNDA3Mjg5ODM2NDc2ODQyNTc2MjI3MzAzNDAwOTI4MjkwMDM0NTYwNjk5NTg1NTMzMzkxNDg0OTMwMDQ3NTEwMzMxNDQxNjAyMzEwNjM3NDg2MjY2OTIyNTIyNTIxMzQ2ODM5ODkxMDg1ODM3NTczMzAzMjkyNzMyNTA5Mzc0MTI0ODgzMTA0MjEzNzYzMDA3NzMwOTY4Mzg4MDc0NzE3ODc5NDM5NjE5Njg1NzY4MjU1OTg4MjY0NjMxMTk1MTU3MjE3NjExMTE0NzE3Njc4NjUzMTc0NDc2MTc4MjA4NTIwNzk2MDkwNzI2MzE1MjIzMDU4MTk4NjM3NjU4NDU2NTA3NDcyNzA4MDI0OTgzMjUzNjQyMDAwNDI0MjQyNTUyMDcwNzUzMTg3MDI3MTE0MTI1NzQ0MzExNzMxOTM1NjgwNDE1MTk5NzI4OTE2NjgxNTY2MzY2NjkxNDQyMzE4OTE3NDAxMzA0MzMzNzI5ODU0MzQ2MTAwNDI2NDE1MzEwMzYwNjQ4NDg3NDYzNzgxNjI5NDQ2ODU3ODg2NjgzNTIzODk2ODcyMTExNDg3MjUwNjgwMDQzOTIxMzgyMDM1MDkxMTg4NzE1MDAwNTIzIl0sWyJlbWFpbGFkZHJlc3MiLCIxNTUwMTI2ODAwMjA1MzI5Mzg3NzcyNjA4OTY3NDk0NDIyOTc0MjU1MTI1NDU0NTEyOTc3NjExNTgyNDE2Nzc1MDg2OTA1NjIzNDUzMTIxNDg0NzM0MzkyNDQ4NzEyNTQyNTYwODUyMjUzNzcyODI2NTYyNjg5NzY1NjYwMzM3OTUyNTEyODQ4MDA1Mzk1NTQxMzcwMTI1Mzk4NDg4OTIxNDM4NDUwNzMxMzYwNTcwMzQ2MjMyNDEyODgzMzQ5NjU4MjMxOTQ5OTgwMTUwMTI2NTQ3Nzg0NTM2ODE2NzM0Njc2Mzg1NDA2OTM1MDQ4NDQ0NDM1ODY2MzYwNTk2MjE3NTM4Njg1NTg5MDE3NDY1NTg2MzI1MDQxNzc1OTcwMzQ1NjY1MjM3MzcyMDA3MjAxNTczNDAwODk3NDA3MDA0OTY1Nzk1MDE3MDQ2NDI5MzM5MzMwMTg2NjAwNzE1MjE3Mjg3ODk3Mjg1MDk1MTEwMzExMDYxODU1OTE1NjQ3Nzk3MTkyNTc4NDI1MDgzMjAwMTIwNDEyNTU4NDM2MjQyNTc0ODIzNjE4NTAxODY5NTQxNzAwMTU5NjMyNDkwNDgxMzY3ODU2NjA5MTAwNjA4MzI0MDcyODk3MjA3NDQxNzgwNDc1Njg4MTk4ODI3MDE1MjE2MDA5OTA4NjY0NTYwODk5MDMzODYxNjk1NTg2OTE1NzI4NjYwMDkzMjM3Njk4NzUzODMwOTAxODQ2MDE1OTU0NzEzNTc5MTc5NDgyMDMyNjIxMTEyNjA3NDcyOTM5NzYyNjM4OTgzMDkyNDE0NTgzMzMyODI2MjUzMTE3NDMwNTAwOTI2NTcwODcxNjI2MzYyMTQxNTM0NzUwMDQwMTkxNzEzMzE4OTQ1NTIwNDUzOTI5Mjk5Nzk3ODc2NDEyNzI3MzgiXSxbImZhbWlseW5hbWUiLCIyMDM1NjQzMjQ2ODM3MTA2MDc3MzEzNTkwOTY1Nzc2ODc1ODkwMjM0MTI0MDQ2MjcyOTc0OTQ0MDMxOTIxNzQ4NjQ1ODA0NDc2MjExODc4NTA1MTEzODE5NzYzMjM3MjczMTM4MjgzNDE1MTE2ODYyMzMwNTg0Mjc4NzcxNjg5NjMyNTIyNzE4NjYzMzkwOTg2MjI0NTA3NDg3OTc3MDk2MDMxMTAzMDY1MDQzNjI5Nzk3NjAzMjM2MTc1ODczOTA0MzUwMjMyNjU1Mjc2NzEzNjIxOTUwNzExNjExMzMzODM5OTE0OTU2MzEyNzM4NDkyNjI5NjQ3Nzk2NTk4NDUzOTM2MTY1NjIwNDI1MTc4OTU0NzE2MjE1OTUzNzQyNjM4NDk0NzA3NzMxNjM2NTc0OTI0Njc4MTk5NDQzMjY1MDU4NDM4MTc3NjE0NTM3NjE5NTI0NzY0MDkxNTY1NzUxODg0OTkzMTU4ODc3NjIxMjMxNzc5MDkzOTIyNzQ0NzM4Nzk5OTEwOTg0OTczOTMyMzYwNzM0OTA3NTQ1NTAxOTE2OTUyOTU3MTEwNTczMjQzODA5MDA1NzE5MjU5MTg1MzgwODI4NTU2MzgwMDA1NzU4MTkzNjIwMzc5MzA5NTk1NTgyMTAxMDEwOTg2MDkyNTE3NjM4Njc3NDYwMTQ5MzQ5ODc5NjYyMzc0MTQ0NzUwMDkyODAzNTE1OTUwMzc0MzkzMTAzMTY5MDYzNTE4ODczNTMzMjAxMjAxMjg4NzU3NjczNzk2OTAzOTAzMTEyNzYyMDgxNjE0MzY1NjgwNjEyNzQ1OTEyMTQ4Mjg0NTQ2MzgxOTA4NDAzNzExMDYwNzc0NDQzNDQyMjc3NTU5MjcyMjkzMDg2MzEzMzg5MDQ4ODA0MzA5OTg0NjgyMDA4MDgxMTYiXSxbImRyaXZpbmdsaWNlbnNlaWQiLCIyMzg0Nzk3NTUyNDQ2NTQ0Nzk3NjQyNTc0NjMyMDU3MjgwODIyODkwODgxNjY4NDQyMTczNDY5OTQ4MDYwOTU0ODU2MjY4MDU2MzQ4MTEyMjQ3MzA4NzYwMDQwNTAxODY4NzE3NDQ4MTI1MDI0NDc2MTcwOTU5Njg0Njc1NzY0MjAwMjc5MTcyMzAwOTgzMTQ1MjgzMDAwMzQzNjIxOTEzNTYwNjA5MzQzNTQyNDM2ODQzNDI0NzkwMzUxNjgwMjg3MDAwNzc4ODM5ODQwMDI0NjA4NDg4NTA5MDQ3MjU3MDI0ODU1Njc5ODk3ODc3NTk5NjU2MTc2NDAwMzk1MTQ0MzY5NjkyNzU4MzIxOTc0MzQyODk2MzY4NzEwMTA3ODIyMTQ4NTM2MzIwMDI0NjYwMzUzNTk1MzA5MDgxMTIwNDQyMTgzNDQ3NzE5NzA5Nzc4MjQxNTI2NDQ4MjU5NTY1NTYyNDUxODYyMDk2OTQzMTUwMzk4ODQ1OTM0ODA3OTM4NjE0MTE4Mzk2MjA5NTc5NDM0OTU2MDk2NzY3OTAzMTE4MDc4MTk1NjE1NzI4MDgwNjA3NzMyOTczMTg2NzU0MTA3Mjc2MTM4OTk1NDQzMzQxNzAxMDQ5OTY3NTc0ODA1MjM2MjEyNTIyNDc0MDI5NTcyOTc0OTk4MjA2NDExMDM5MzQxODY4MzIwMTgwMDU5MzQ4ODE4MDQ5NTgyNjU4ODg0OTI2Nzk2OTAzMzc1OTY4NjMwNjA0MDgwOTE2MTc1ODIzMDIyNjc3ODc5MzE4MDgyODUwNzgwMzQyNDU0ODI4OTEzMTA4Nzk1MDg4NjA1Mzk1NjUxMzM0NTMyNDU3NzUxNjQxNTUwOTE5NDQ4NDAzODM1OTI0NDg5NzYzMjE4NDUyNzUzMzY0NjAzMzE3NzgxMDA0Il0sWyJkcml2aW5nY2xhc3MiLCI3MTMwODIxMTg0NjAwNjAwNjE1Nzk1NDU5NjkyNDYwMzE1NzM4ODA5NTU0MjA0NTQ4OTI1NjA2MzkyNzQ2MjE3MDQyMDI1OTExNjE2NTM4ODQ0ODgyMDgwNjM5MTQ0MjAwMDA2NzIwMzY4MjUzNzMzMzM0ODk1NTQ0NjU5ODU1ODk3MzQzNjc1MzMxNjUwMDI2NjgwNzc1MjgxMzgxMzY0MzcyNTE3ODgzMDI5NTE1MDM2MjQ1ODIyOTUwNzU3MDYwNTk2Nzc5MDE0ODUzODIzMTczNTU0NjczMTk0NjAxODU0MTk2NDQ1NDI3MzIxNTk1Mjk4NTg0OTI5MDM3NTMyMzk3NDMxODE1MDk0Mzk3MjQyODUwMTQ3NjY3NTc0NDM1OTY5ODMzMzE2NDc1MTY0MDM4NjIxMzk1Mzk0ODAxOTg3MzIyOTc0NDY0MjYxNTQyODMxNzI0OTQwNDQ5NjQyMjI5OTA3MzIwNzY2Njg0Nzk0NTgwMDExNzc4NzM0NzI5OTk0MjkxMjAxMDA3NTY5NTE5ODg0ODU3MzU2OTY5NzIwMDUwMTk5OTE3MDk3MjIzOTU3Mjc0MzI2MjkxNjc2Mjc1OTIzOTI1NTQ2MTMxODIxNDE2NDc3MDE3OTk2NzE1OTU3MzAxOTM4MzMyNzU0MzE5OTA0ODkxNDExNDU0MjkzNjMwMDU1NTg4MTUwNjA3ODQ4MTM1MDU1Njk5OTM2OTAxNzAzNTAwNjM2MzgxNDQ5ODAzMTM2NzAyODQwNDcyMjY1MDAzNTczNzk4MDM1NzYyNjIzMzAwOTQzNTQ3Mjk1NDA4OTkxODgyNDMxODEwNzIwNzE3NDE3NjIxNjYxNzUyNzEzNzM2ODQ2MDY4NzExNDk4OTkxMjc2NDcyMDgxNDAzMjEyMzUwNDEzNDA0MjQyNDQiXSxbIm1hc3Rlcl9zZWNyZXQiLCIxNDQ0ODk0NjYyMjg1MjAwNjE4ODEwMjI2MTUxMTk3NjIwMjc0OTgwNTk0NzkzMzU3ODY0MDg1NDA0MzcxNzY2MTA0NzI5OTg0ODI3MjgyNzA4NTkzODUyMDU1NDUwNTUzOTc3MzA3MDQwMTY5NDA1ODgwMTEwMzMxMDU3MDMxNjc4OTM2NDQ2MDQ3NDE4NzE0NDc5OTA3Mjg5MTExMTkxMzA5MDQ2MTMzMzAxMTIzNTk4MTAyMzg0NjQ5ODA3NTQwOTY4NjQ5NzU2MjY4NDAwNDc2NDk5ODY2NDg1MjMxNjkzMDEyMjUxNzA5ODE3OTE3MTMyNjUxNjExNDM0NzkzMTI4NDM5MjQ1NjY3ODE1NjQ2NDUxOTg1ODAyNTg3NDYwMDk4ODk2MDc3OTA3ODUwNTE4NzI4MzMxNzAyMTQ2OTk0NzQzMDUxMDM5ODkwNjA3MzE5NzYyNjkyNTY4NjcwOTY5NDA1OTU2NDU5ODMxMTU5Njg2MTk1OTM3ODM0OTUyNzM2NjY4MDU5NDUxNDM5MTQ3NDI0Njg0ODY2OTg1ODE0Nzg5MzY5NTE0NDczOTExNTA1NjM1OTUwMjg1OTU0NzI3ODE4OTk2MjI4NDI4NTU5NjY3MjM5MDcxNTkwMTI2NzYxOTQ4MDQ5NTE2OTY1MTg4OTE1MTkzMTYxMjk4MDU4NDAwMjk3MDQ2MzQ0NTg2ODk5OTQ2MTA0MDM0ODc2MjkxMjU1NDMxNzYyMTcyMTc3MTEwODk5OTgxOTU1MjM0MDE0NzM2ODgzNTczMjQ1OTA3MTUxNzAzMjM1MDY2MjU0NDU2NzU5NDUxNDIzODcxNTA5NzgwMzA5NDAxODYzNDc4OTgxMjU0MDMwNjE2NDYxNTg4NjU0NjgxMDg5OTk4OTE4NjA2NTc4MjM0ODc5OTg1NjcxIl1dfSwibm9uY2UiOiIxMTE2NzA0MDg4NDcyOTA3NTIzNjkwNDkwIn0=" - ) - ) - - val offerCredential = OfferCredential( - body = OfferCredential.Body( - credentialPreview = CredentialPreview( - attributes = arrayOf( - CredentialPreview.Attribute(name = "Name", value = "Value", mediaType = "application/json") - ) - ) - ), - attachments = arrayOf(attachmentDescriptor), - thid = "1", - from = fromDID, - to = toDID - ) - val requestCredential = agent.prepareRequestCredentialWithIssuer(did = toDID, offer = offerCredential) - assertEquals(offerCredential.from, requestCredential.to) - assertEquals(offerCredential.to, requestCredential.from) - assertTrue(requestCredential.attachments.size == 1) - assertEquals(requestCredential.attachments[0].format, CredentialType.ANONCREDS_REQUEST.type) - assertEquals(offerCredential.thid, requestCredential.thid) - } - - @AndroidIgnore - @Test - fun testAnoncreds_whenCredentialIssued_thenProcessed() = runTest { - val fromDID = DID("did:prism:asdf42sf") - val toDID = DID("did:prism:asdf42sf") - - val apiMock: Api = ApiMock( - HttpStatusCode(200, "Ok"), - getCredentialDefinitionResponse - ) - val pollux = PolluxImpl(castorMock, apiMock) - plutoMock.getLinkSecretReturn = flow { emit(LinkSecret().getValue()) } - val meta = CredentialRequestMeta( - linkSecretName = "1", - json = "{\"link_secret_blinding_data\":{\"v_prime\":\"1234\",\"vr_prime\":\"1234\"},\"nonce\":\"411729288962137159046778\",\"link_secret_name\":\"link:secret:id\"}" - ) - plutoMock.getCredentialMetadataReturn = flow { emit(meta) } - - val agent = PrismAgent( - apollo = apolloMock, - castor = castorMock, - pluto = plutoMock, - mercury = mercuryMock, - pollux = pollux, - connectionManager = connectionManager, - seed = null, - api = ApiMock(HttpStatusCode.OK, "{\"success\":\"true\"}"), - logger = PrismLoggerMock(), - agentOptions = AgentOptions() - ) - - val attachmentDescriptor = - AttachmentDescriptor( - mediaType = "application/json", - format = CredentialType.ANONCREDS_ISSUE.type, - data = AttachmentBase64( - "eyJzY2hlbWFfaWQiOiJodHRwOi8vaG9zdC5kb2NrZXIuaW50ZXJuYWw6ODAwMC9wcmlzbS1hZ2VudC9zY2hlbWEtcmVnaXN0cnkvc2NoZW1hcy81ZTBkNWE5My00YmZkLTMxMTEtYTk1Ni01ZDViYzgyZjc2Y2MiLCJjcmVkX2RlZl9pZCI6Imh0dHA6Ly8xOTIuMTY4LjY4LjEwMjo4MDAwL3ByaXNtLWFnZW50L2NyZWRlbnRpYWwtZGVmaW5pdGlvbi1yZWdpc3RyeS9kZWZpbml0aW9ucy81ZTI5NWNmMi00MjI2LTNjN2QtYjI3Zi04N2JlMTYwNjQ3NmQvZGVmaW5pdGlvbiIsInJldl9yZWdfaWQiOm51bGwsInZhbHVlcyI6eyJkcml2aW5nTGljZW5zZUlEIjp7InJhdyI6IjEyMzQ1IiwiZW5jb2RlZCI6IjEyMzQ1In0sImVtYWlsQWRkcmVzcyI6eyJyYXciOiJhbGljZUB3b25kZXJsYW5kLmNvbSIsImVuY29kZWQiOiI3NTEwNzA0NjM0MDE2NTY3NzAxMTk0MjA3NTY0NDAwOTA2NjU0MTY2MTE0ODgyMjU4OTAzMzY3OTg2MTIwOTE4NjQ5Mjc2ODY2OTkyNCJ9LCJkYXRlT2ZJc3N1YW5jZSI6eyJyYXciOiIyMDIwLTExLTEzVDIwOjIwOjM5KzAwOjAwIiwiZW5jb2RlZCI6IjUzODY4NTU5NTMxNzQ4NDY3MDk3NTIwODU5MDUzMDgxODM1NzQ3NDM1NjExNjA2ODQyMDQxMTQ3NTgyMDA0ODc0MzQ4MDQ2MTY0Njg1In0sImZhbWlseU5hbWUiOnsicmF3IjoiV29uZGVybGFuZCIsImVuY29kZWQiOiIxNjc5MDg0OTMxMjM3NDc5NDczNjgxMzM3NzU2NzI1Mzg1MTM3MzYwNzk3MDQ3MzM3NzcwMTQ3NzI2OTE5NDAxOTU1NzY1NDU2MjAzNSJ9LCJkcml2aW5nQ2xhc3MiOnsicmF3IjoiMyIsImVuY29kZWQiOiIzIn19LCJzaWduYXR1cmUiOnsicF9jcmVkZW50aWFsIjp7Im1fMiI6IjExMTI0OTQwODk5NTQ2MzQ0NTY2MjA3NjExNTQyODEwMzAyNDE1ODY5Njg4MDE3NTMyNDYwMzM3MDY0NTk2Mjk1NjIxNzkwMDk2MTUxNSIsImEiOiIxNjk5NjYwOTQ5MDE3NjQ2MzAzOTIxMTc4MjgyNDkxODM5MjE4MzUwNjk5MjM4Nzk2NDQxOTg4OTI0NzA1MzI0NjMzNTQ0MzM0Mzc1ODQwNjgyODY3Nzc3MDQ5NDY2ODM3NjcyMjQxMzgxMjgwMjE0OTIxMDI1NDcyNTAwNDAwMjYyMjA1NTE1MzQxOTQxOTEyMjc2ODIxMTcwNzYwNDAwNzkzMzA3NDY3MDQzOTAzMTAzMDI3MTI2NjU4MDM3MDg1MTExMDU1NDczOTI2MTc2ODU2ODY1MTg3Njc3OTAzMTQzODkzNzg2NTU0NjA2MDQ1MDYyMDQxMzAxMzM3MDQ0NTQzMTk2NTM0NzMwNjczODc4Njg3MjUxMjc3NzEyMzEwODUzNDU4MTYxMjg1NzE1MDIxNTk4OTkxODgxNjE5OTI0NTU5NzY0NTU3NDQzMjUxMDcwNzg5NDAzMTQ2MzMxODE4Njk4NTU1MzIzMDU0NTUzNDI0NzkyNjk5OTE2MzIzODg2NzA0MjE0NDY0ODcwMTI5NTkwODcwODIxOTc1MDkwNjQ4MTkzNjExNjY5MjMxMTk2NzY2Nzg5ODU5NDQ3MTMwOTMwNDIxMjI0NTE0MTI1ODYyMzI5OTU5NTIyNjkxMTE0Mzc3MzA4MzYyNjY2OTY2NzQ3NTQxNjU2NzkzOTc4ODc4Mzc0NTQ4MzcwODgyMDMzMTk2MDQxMjE5NDQ1MjAxOTIxNDYzNzEwMjM4OTUyMjkzNDkyODg0OTU5MDgxMDU3MDc2NzAwOTI1OTI2NTYyODg4MTcwODk5NzIzNDA2MjMzMzc0OSIsImUiOiIyNTkzNDQ3MjMwNTUwNjIwNTk5MDcwMjU0OTE0ODA2OTc1NzE5MzgyNzc4ODk1MTUxNTIzMDYyNDk3Mjg1ODMxMDU2NjU4MDA3MTMzMDY3NTkxNDk5ODE2OTA1NTkxOTM5ODcxNDMwMTIzNjc5MTMyMDYyOTkzMjM4OTk2OTY5NDIyMTMyMzU5NTY3NDI5MzAxMzgxMDE1NDA1MjExMzIyOTAyMjgyNzk3NjM0NDM3NTAxNDkiLCJ2IjoiOTI3MjIxODI0NzE5ODYxNzc0Nzk0ODU4NTgzNDAwNjY1MDM4NDQ2MjE4ODE4MDU2MDY3NjYwNzA5MTE5NDg1NTg4OTY3MDY0OTU1NTM0MjA2MDkyOTQ1MjU3NzgwMzMzMzQwMTAyNTA0MzI3OTMzNjYwNzA5NTUzMzk5MzE4OTE4NTQxNjUxMTgxMDM2NjgwOTMzNzM0MjUyNDA2NDYzMTg2OTQxODk3MDQ1NTA1OTUyMDYwNzI5NTExODM3NzA1OTM3MjQxMzYwMzcyNjM4NTEwODk1MDMxNzc5NjMxODUyNjQyOTIyNTQwNzkxOTc2NzgzMDc2OTk3MTI5MzIyNjA1NjAzNzIyMjA4ODMwOTAyNzcwNTM5Njk2ODA3MTI0MzQ0MzY0NDk1ODAzNDgxNTg4MzczMTk5Mjg3OTgyMjM2MTE5MjIwODU3OTk2NzQwNzI3MjA2OTc4NjMyMjU1NDY0NTk5NDE2NTMwOTYwOTc0ODg0NjczMDgzMzk5NjY1NDI2Mjg1NzY0NDI0NjMwMDMxODA1ODEwNjE5MDI3Njc3MjY4NDAzNzA3NzIzOTAzNDMzOTAxMzg3NDkyMzEyNzA3Nzk4MTcxMzk5ODI0NjM5NDQ1MjI4ODAxNDQ0OTIwMzk5OTkwMzAzMDYzNzg1NDg1NDU3NDIyODQwNjI1NjYyMDg5MzM3NzYxNTIzODUyMTUzMTMwMTIzMzA2NzExNjkzMTkxNTI4MTUzNzk4MjQ0ODE5OTAzMTQ4NjM0MTYzMDg2NDQ4ODkyOTc0ODgzMzQyMzUzMDI0MTA4MjM3MzY1MjI0NTI5MTA5NzEyNjE4ODc4MzY3OTc4Njg3NTY3NTM1MTEzODg1NzU4MTg0ODU2NTU1NzI3MTY0MTk0MTAyODg3MDQ1OTg4NDc2NTI0OTE2NTA0NzM5NDY1Mzk1MjQzMDc0NTY4OTU2MzExODY3OTA5ODc4NDE2MDMwODY1MjY4NDQzNTg2NzI5NjQ3NzA2NjUzNzcwNDU1NjcwOTc4NzkyNDE0Mjc5MzM1NDk0NTE1OTUxMTQ4ODg3MjAzMDg2NjYyMTEwODc1NjA5NjM4NjMxNCJ9LCJyX2NyZWRlbnRpYWwiOm51bGx9LCJzaWduYXR1cmVfY29ycmVjdG5lc3NfcHJvb2YiOnsic2UiOiIyMzQ0OTA4OTM4ODc3NDk2OTAwMTU1NzIzNTE5NzU1OTc2NDEzMzYzMDI4NzE1NTY4Nzc3MzgwNDM4NTA5NDQ0MDE0MjIzMTk5OTg4NDA1NDM0OTU3NzkzMzY5NzE0ODg3OTA4MDI1MDgwNjc0NDQ2MDQ2ODIyNDM2NTQ5Mzg1OTk3NzA5OTc3MTYwMDE1MTM0MTAzMjQ4OTkyNTI3OTYyNTk2OTIwMTA3ODUyNzYzMDUxNDUyMjM5MzEwOTQyODU1OTk3OTEwNzA0ODgxMTQ1OTE4NjI4MTU2NjA4NDUzNzc5MzcyMDIyMzI5ODM3MzYzOTQ2MDgzNTQ2OTE5NjY1OTA4MzY5NzAxMTc2NTk2Njk5MzQ1MDU2NzQ1MjI3MjY0MzczMTYyMTM4NTE0MDQxMTU3NjY5ODAzNjQ5ODgzNjg0NTA4NjQyNTc4OTM2MDc2Mjg2NDk1NzgzMTY2MTM4NjAyNjIzMDU4Nzk2OTk4NzA5NzYyODAzNzYxNzkyODI2NDUzNjIzODg4MjQ3ODkzMzc1MDQxODY0NTU0MDIwMzY5OTY0MzQwMDQ4Njg2NzAzMDM5NzkyODkzMzA1NzQ2MDE4NDkyMTIxMjk5ODI4MTYwNTU1Njg5MDQ4MzgyNTQ4OTU4NjY2OTI2MzMwMzU3OTczMDc0OTY2MzA5OTUwMDczMTMwMjA0NjgxNjI2MjQ5ODIxNTA0MjY0MTU3ODkwMzg3MTQ4OTk4MjU5NTc1MTE3NDI2MTM1MjU5MjMwMTE5MTY3NDE2MTAxNTIzMTA0NTQ1NjU4MTkyMjE2NzY5NTA5MTkxMzMxOSIsImMiOiIzNjU3Nzg5MjU2Mjk4NTIzNDUxNDYzODU4ODIxODcwNDgzOTI5MDAyNTI5NTUxMTI5ODc1NTI3NzY5NDQ2NjE5MDUyODMxMzE3ODkifSwicmV2X3JlZyI6bnVsbCwid2l0bmVzcyI6bnVsbH0" - ) - ) - - val issuedCredential = IssueCredential( - body = IssueCredential.Body(), - attachments = arrayOf(attachmentDescriptor), - thid = "1", - from = fromDID, - to = toDID - ) - - val credential = agent.processIssuedCredentialMessage(issuedCredential) - - credential.claims.map { - if (it.key == "emailAddress") { - assertEquals("alice@wonderland.com", (it.value as ClaimType.StringValue).value) - } - if (it.key == "familyName") { - assertEquals("Wonderland", (it.value as ClaimType.StringValue).value) - } - if (it.key == "dateOfIssuance") { - assertEquals("2020-11-13T20:20:39+00:00", (it.value as ClaimType.StringValue).value) - } - if (it.key == "drivingLicenseID") { - assertEquals("12345", (it.value as ClaimType.StringValue).value) - } - if (it.key == "drivingClass") { - assertEquals("3", (it.value as ClaimType.StringValue).value) - } - } - } - - val getCredentialDefinitionResponse = - "{\"schemaId\":\"http://host.docker.internal:8000/prism-agent/schema-registry/schemas/5e0d5a93-4bfd-3111-a956-5d5bc82f76cc\",\"type\":\"CL\",\"tag\":\"licence\",\"value\":{\"primary\":{\"n\":\"105195159277979097653318357586659371305119697478469834190626350283715795188687389523188659352120689851168860621983864738336838773213022505168653440146374011050277159372491059901432822905781969400722059341786498751125483895348734607382548396665339315322605154516776326303787844694026898270194867398625429469096229269732265502538641116512214652017416624138065704599041020588805936844771273861390913500753293895219370960892829297672575154196820931047049021760519166121287056337193413235473255257349024671869248216238831094979209384406168241010010012567685965827447177652200129684927663161550376084422586141212281146491949\",\"s\":\"85376740935726732134199731472843597191822272986425414914465211197069650618238336366149699822721009443794877925725075553195071288777117865451699414058058985000654277974066307286552934230286237253977472401290858765904161191229985245519871949378628131263513153683765553672655918133136828182050729012388157183851720391379381006921499997765191873729408614024320763554099291141052786589157823043612948619201525441997065264492145372001259366749278235381762443117203343617927241093647322654346302447381494008414208398219626199373278313446814209403507903682881070548386699522575055488393512785511441688197244526708647113340516\",\"r\":{\"dateofissuance\":\"16159515692057558658031632775257139859912833740243870833808276956469677196577164655991169139545328065546186056342530531355718904597216453319851305621683589202769847381737819412615902541110462703838858425423753481085962114120185123089078513531045426316918036549403698066078445947881055316312848598741184161901260446303171175343050250045452903485086185722998336149005743485268486377824763449026501058416292877646187105446333888525480394665310217044483841168928926515929150167890936706159800372381200383816724043496032886366767166850459338411710056171379538841845247931898550165532492578625954615979453881721709564750235\",\"drivingclass\":\"83649701835078373520097916558245060224505938113940626586910000950978790663411517512280043632278010831292224659523658613504637416710001103641231226266903556936380105758523760424939825687213460920436570466066231912959327201876189240504388424799892400351592593406285436824571943165913587899115814843543998396726679289422080229750418336051741708013580146373647528674381958028243228435161765957312248113519708734663989428761879029086059388435772829434952754093999424834120341657211221855300108096057633128467059590470639772605075954658131680801785637700237403873940041665483384938586320674338994185073499523485570537331062\",\"emailaddress\":\"96995643129591814391344614133120459563648002327749700279517548454036811217735867585059116635583558148259032071807493674533230465312311981127622542797279917256478867847832932893748528200469349058284133058865149153179959849308383505167342565738382180666525211256221655129861213392455759272915565057394420728271409215556596974900718332893753172173500744392522771654048192448229319313386967045678744665093451560743782910263014930200762027209565313884859542996067229707388839912195826334964819133016500346618083969320902775088800287566711941842968839787149808739739233388585677095545116231323172342995837636586249573194609\",\"drivinglicenseid\":\"102840929811153624977554462471309185033977661854754815794111114507549576719389525167082631547450413573293352276930065480432301200611396989595571202142654033217842162456070556560693402484110499573693863745648118310258284468114751958738878996458420605301017450868522680454545537837403398645500541915771765220093329728663621098538954397330411649083351383375839056527007892276284168437065687748085384178113959961057476582871100422859953560730152958588610850909069434658487744782540788968302663076149478487413357533660817020800754493642858564081116318655661240523146995256712471572605700346459123074377380656921337264554594\",\"familyname\":\"2428690037146701497427424649573806616639612325136606164619283916796880313617677563507218774958436668407050506838114136163250163675016510113975582318007560622124292458766639319715064358235569650961433812439763343736699708535945693241909905707497180931492818502593885932421170612418693515054756633264933222189766691632082890045477718331705366111669009551578289182848340651375008362238266590844461708981816856194045325523248527964502118319210042254240848590574645476930113881493472578612352948284862674703949781070309344526122291448990325949065193279599181502524961004046979227803224474342778516917124487012958845744311\",\"master_secret\":\"96236339155824229583363924057798366491998077727991424922911165403434522806469328114407334094535810942859512352089785125683335350062474092708044674085769524387654467267128528564551803293661877480971961092735622606052503557881856409855812611523475975566606131897917979412576797874632169829901968854843162299366867885636535326810998541141840561418097240137120398317445832694001031827068485975315937269024666370665530455146256019590700349556357390218401217383173228376078058967743472704019765210324846681867991543267171763037513180046865961560351035005185946817643006206395175857900512245900162751815626427008481585714891\"},\"rctxt\":\"54359809198312125478916383106913469635175253891208897419510030559787479974126666313900084654632259260010008369569778456071591398552341004538623276997178295939490854663263886825856426285604332554317424030793691008221895556474599466123873279022389276698551452690414982831059651505731449763128921782866843113361548859434294057249048041670761184683271568216202174527891374770703485794299697663353847310928998125365841476766767508733046891626759537001358973715760759776149482147060701775948253839125589216812475133616408444838011643485797584321993661048373877626880635937563283836661934456534313802815974883441215836680800\",\"z\":\"99592262675748359673042256590146366586480829950402370244401571195191609039150608482506917768910598228167758026656953725016982562881531475875469671976107506976812319765644401707559997823702387678953647104105378063905395973550729717937712350758544336716556268064226491839700352305793370980462034813589488455836259737325502578253339820590260554457468082536249525493340350556649403477875367398139579018197084796440810685458274393317299082017275568964540311198115802021902455672385575542594821996060452628805634468222196284384514736044680778624637228114693554834388824212714580770066729185685978935409859595244639193538156\"}},\"issuerId\":\"did:prism:604ba1764ab89993f9a74625cc4f3e04737919639293eb382cc7adc53767f550\"}" -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/helpers/DID.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/helpers/DID.kt deleted file mode 100644 index ab6632365..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/helpers/DID.kt +++ /dev/null @@ -1,20 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.helpers - -import io.iohk.atala.prism.walletsdk.domain.models.DID - -fun DID.Companion.fromMethodAndMethodId( - method: String?, - methodId: String? -): DID { - return DID( - method = method ?: "test", - methodId = methodId ?: "testableId" - ) -} - -fun DID.Companion.fromIndex(index: Int): DID { - return DID.fromMethodAndMethodId( - method = "test$index", - methodId = "testableId$index" - ) -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/MediationKeysUpdateListTest.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/MediationKeysUpdateListTest.kt deleted file mode 100644 index bbbc991ec..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/MediationKeysUpdateListTest.kt +++ /dev/null @@ -1,35 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols - -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.prismagent.protocols.mediation.MediationKeysUpdateList -import kotlinx.serialization.decodeFromString -import kotlinx.serialization.json.Json -import kotlin.test.Test -import kotlin.test.assertEquals - -class MediationKeysUpdateListTest { - @Test - fun makeMessageShouldReturnValidMessage() { - // given - val id = "test_id" - val from = DID("did:example:123") - val to = DID("did:example:456") - val recipientDid = DID("did:example:789") - val mediationKeysUpdateList = MediationKeysUpdateList(id, from, to, arrayOf(recipientDid)) - - // when - val message = mediationKeysUpdateList.makeMessage() - - // then - assertEquals(id, message.id) - assertEquals(ProtocolType.DidcommMediationKeysUpdate.value, message.piuri) - assertEquals(from, message.from) - assertEquals(to, message.to) - - val expectedBody = MediationKeysUpdateList.Body( - updates = arrayOf(MediationKeysUpdateList.Update(recipientDid = recipientDid.toString())) - ) - val actualBody: MediationKeysUpdateList.Body = Json.decodeFromString(message.body) - assertEquals(expectedBody, actualBody) - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/IssueCredentialTest.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/IssueCredentialTest.kt deleted file mode 100644 index 7045db1fb..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/IssueCredentialTest.kt +++ /dev/null @@ -1,79 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.issueCredential - -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgentError -import io.iohk.atala.prism.walletsdk.prismagent.helpers.fromIndex -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith - -class IssueCredentialTest { - - @Test - fun testCredentialFromMessage_whenValidIssueMessage_thenInitIssueCredential() { - val fromDID = DID.fromIndex(index = 0) - val toDID = DID.fromIndex(index = 1) - val validIssueCredential = IssueCredential( - body = IssueCredential.Body( -// formats = arrayOf( -// CredentialFormat( -// attachId = "test1", -// format = "test" -// ) -// ) - ), - attachments = arrayOf(), - thid = "1", - from = fromDID, - to = toDID - ) - val issueMessage = validIssueCredential.makeMessage() - val testIssueCredentialFormat = IssueCredential.fromMessage(issueMessage) - assertEquals(testIssueCredentialFormat, validIssueCredential) - } - - @Test - fun testWhenInvalidIssueMessageThenInitIssueCredential() { - val invalidIssueCredential = Message( - piuri = "InvalidType", - from = null, - to = null, - body = "" - ) - assertFailsWith { - IssueCredential.fromMessage(invalidIssueCredential) - } - } - - @Test - fun testWhenValidRequestMessageThenInitIssueCredential() { - val fromDID = DID.fromIndex(index = 0) - val toDID = DID.fromIndex(index = 1) - val validRequestCredential = RequestCredential( - body = RequestCredential.Body( -// formats = arrayOf( -// CredentialFormat( -// attachId = "test1", -// format = "test" -// ) -// ) - ), - attachments = arrayOf(), - thid = "1", - from = fromDID, - to = toDID - ) - val requestMessage = validRequestCredential.makeMessage() - val testIssueCredential = IssueCredential.makeIssueFromRequestCedential(requestMessage) - - assertEquals(validRequestCredential.from, testIssueCredential.to) - assertEquals(validRequestCredential.to, testIssueCredential.from) - assertEquals(validRequestCredential.attachments, testIssueCredential.attachments) - assertEquals(validRequestCredential.id, testIssueCredential.thid) - assertEquals(testIssueCredential.thid, requestMessage.id) - assertEquals(validRequestCredential.body.goalCode, testIssueCredential.body.goalCode) - assertEquals(validRequestCredential.body.comment, testIssueCredential.body.comment) -// assertContentEquals(validRequestCredential.body.formats, testIssueCredential.body.formats) - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/OfferCredentialTest.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/OfferCredentialTest.kt deleted file mode 100644 index ebc84e555..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/OfferCredentialTest.kt +++ /dev/null @@ -1,57 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.issueCredential - -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgentError -import io.iohk.atala.prism.walletsdk.prismagent.helpers.fromIndex -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith - -class OfferCredentialTest { - - @Test - fun testWhenValidOfferMessageThenInitOfferCredential() { - val fromDID = DID.fromIndex(index = 0) - val toDID = DID.fromIndex(index = 1) - val validOfferCredential = OfferCredential( - body = OfferCredential.Body( - credentialPreview = CredentialPreview( - attributes = arrayOf( - CredentialPreview.Attribute( - name = "test1", - value = "test", - mediaType = "test.x" - ) - ) - ) -// formats = arrayOf( -// CredentialFormat( -// attachId = "test1", -// format = "test" -// ) -// ) - ), - attachments = arrayOf(), - thid = "1", - from = fromDID, - to = toDID - ) - val offerMessage = validOfferCredential.makeMessage() - val testOfferCredentialFormat = OfferCredential.fromMessage(offerMessage) - assertEquals(testOfferCredentialFormat, validOfferCredential) - } - - @Test - fun testWhenInvalidOfferMessageThenInitOfferCredential() { - val invalidOfferCredential = Message( - piuri = "InvalidType", - from = null, - to = null, - body = "" - ) - assertFailsWith { - OfferCredential.fromMessage(invalidOfferCredential) - } - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/ProposeCredentialTest.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/ProposeCredentialTest.kt deleted file mode 100644 index 8129cc72e..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/ProposeCredentialTest.kt +++ /dev/null @@ -1,57 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.issueCredential - -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgentError -import io.iohk.atala.prism.walletsdk.prismagent.helpers.fromIndex -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith - -class ProposeCredentialTest { - - @Test - fun testWhenValidProposeMessageThenInitProposeCredential() { - val fromDID = DID.fromIndex(index = 0) - val toDID = DID.fromIndex(index = 1) - val validProposeCredential = ProposeCredential( - body = ProposeCredential.Body( - credentialPreview = CredentialPreview( - attributes = arrayOf( - CredentialPreview.Attribute( - name = "test1", - value = "test", - mediaType = "test.x" - ) - ) - ) -// formats = arrayOf( -// CredentialFormat( -// attachId = "test1", -// format = "test" -// ) -// ) - ), - attachments = arrayOf(), - thid = "1", - from = fromDID, - to = toDID - ) - val proposeMessage = validProposeCredential.makeMessage() - val testOfferCredentialFormat = ProposeCredential.fromMessage(proposeMessage) - assertEquals(testOfferCredentialFormat, validProposeCredential) - } - - @Test - fun testWhenInvalidProposeMessageThenInitProposeCredential() { - val invalidProposeCredential = Message( - piuri = "InvalidType", - from = null, - to = null, - body = "" - ) - assertFailsWith { - ProposeCredential.fromMessage(invalidProposeCredential) - } - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/RequestCredentialTest.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/RequestCredentialTest.kt deleted file mode 100644 index 2bf0cf0e3..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/RequestCredentialTest.kt +++ /dev/null @@ -1,50 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.issueCredential - -import io.iohk.atala.prism.walletsdk.domain.models.DID -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgentError -import io.iohk.atala.prism.walletsdk.prismagent.helpers.fromIndex -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith - -class RequestCredentialTest { - - @Test - fun testWhenValidRequestMessageThenInitRequestCredential() { - val fromDID = DID.fromIndex(index = 0) - val toDID = DID.fromIndex(index = 1) - val validRequestCredential = RequestCredential( - body = RequestCredential.Body( - goalCode = "test1", - comment = "test1" -// formats = arrayOf( -// CredentialFormat( -// attachId = "test1", -// format = "test" -// ) -// ) - ), - attachments = arrayOf(), - thid = "1", - from = fromDID, - to = toDID - ) - val requestMessage = validRequestCredential.makeMessage() - val testRequestCredentialFormat = RequestCredential.fromMessage(requestMessage) - assertEquals(testRequestCredentialFormat, validRequestCredential) - } - - @Test - fun testWhenInvalidRequestMessageThenInitRequestCredential() { - val invalidRequestCredential = Message( - piuri = "InvalidType", - from = null, - to = null, - body = "" - ) - assertFailsWith { - RequestCredential.fromMessage(invalidRequestCredential) - } - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/outOfBand/OutOfBandInvitationTest.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/outOfBand/OutOfBandInvitationTest.kt deleted file mode 100644 index f09378fc7..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/outOfBand/OutOfBandInvitationTest.kt +++ /dev/null @@ -1,36 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.outOfBand - -import kotlinx.serialization.decodeFromString -import kotlinx.serialization.json.Json -import kotlin.test.Test -import kotlin.test.assertEquals - -class OutOfBandInvitationTest { - - @Test - fun testOutOfBandInvitation_whenJsonProvided_thenOutOfBandInvitationCorrect() { - val invitationString = """ - { - "type": "https://didcomm.org/out-of-band/2.0/invitation", - "id": "1234-1234-1234-1234", - "from": "did:peer:asdf42sf", - "body": { - "goal_code": "issue-vc", - "goal": "To issue a Faber College Graduate credential", - "accept": [ - "didcomm/v2", - "didcomm/aip2;env=rfc587" - ] - } - } - """ - val oob = Json.decodeFromString(invitationString) - assertEquals("https://didcomm.org/out-of-band/2.0/invitation", oob.type.value) - assertEquals("1234-1234-1234-1234", oob.id) - assertEquals("did:peer:asdf42sf", oob.from) - assertEquals("issue-vc", oob.body.goalCode) - assertEquals("To issue a Faber College Graduate credential", oob.body.goal) - assertEquals("didcomm/v2", oob.body.accept?.get(0)) - assertEquals("didcomm/aip2;env=rfc587", oob.body.accept?.get(1)) - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/outOfBand/OutOfBandParserTest.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/outOfBand/OutOfBandParserTest.kt deleted file mode 100644 index 8c0500e91..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/outOfBand/OutOfBandParserTest.kt +++ /dev/null @@ -1,26 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.outOfBand - -import io.iohk.atala.prism.walletsdk.domain.models.CommonError -import io.ktor.http.Url -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith - -class OutOfBandParserTest { - - @Test - fun testParseMessage_whenCorrectUrlPassed_thenResultJsonCorrect() { - val expectedJson = - "{\"body\":\"{}\",\"id\":\"a38abd0d-de3e-4d3f-a4ac-a41ef58ac3fc\",\"piuri\":\"Something wrong\",\"attachments\":[],\"extraHeaders\":[],\"createdTime\":\"1678471374846\",\"expiresTimePlus\":\"167847137484686400000\",\"ack\":[],\"direction\":1}" - val resultJson = - OutOfBandParser().parseMessage(Url("localhost:8080?_oob=eyJib2R5Ijoie30iLCJpZCI6ImEzOGFiZDBkLWRlM2UtNGQzZi1hNGFjLWE0MWVmNThhYzNmYyIsInBpdXJpIjoiU29tZXRoaW5nIHdyb25nIiwiYXR0YWNobWVudHMiOltdLCJleHRyYUhlYWRlcnMiOltdLCJjcmVhdGVkVGltZSI6IjE2Nzg0NzEzNzQ4NDYiLCJleHBpcmVzVGltZVBsdXMiOiIxNjc4NDcxMzc0ODQ2ODY0MDAwMDAiLCJhY2siOltdLCJkaXJlY3Rpb24iOjF9")) - assertEquals(expectedJson, resultJson) - } - - @Test - fun testParseMessage_whenWrongUrlPassed_thenThrowsInvalidURLError() { - assertFailsWith(CommonError.InvalidURLError::class) { - OutOfBandParser().parseMessage(Url("localhost:8080?_oobb=eyJib2R5Ijoie3")) - } - } -} diff --git a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/pickup/PickupRunnerTest.kt b/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/pickup/PickupRunnerTest.kt deleted file mode 100644 index 2f38cf5d8..000000000 --- a/atala-prism-sdk/src/commonTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/pickup/PickupRunnerTest.kt +++ /dev/null @@ -1,65 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.pickup - -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentDescriptor -import io.iohk.atala.prism.walletsdk.domain.models.AttachmentJsonData -import io.iohk.atala.prism.walletsdk.domain.models.Message -import io.iohk.atala.prism.walletsdk.prismagent.MercuryMock -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgentError -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.test.runTest -import org.junit.Before -import org.junit.Test -import java.util.UUID -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertTrue - -class PickupRunnerTest { - - lateinit var message: Message - lateinit var mercury: MercuryMock - - @Before - fun setup() { - mercury = MercuryMock() - } - - @Test - fun testPickupRun_whenPiuriNotValid_thenInvalidPickupDeliveryMessageError() { - val message = Message(piuri = ProtocolType.DidcommRequestPresentation.value, body = "") - assertFailsWith(PrismAgentError.InvalidMessageType::class) { - PickupRunner(message, mercury) - } - } - - @OptIn(ExperimentalCoroutinesApi::class) - @Test - fun testPickupRun_whenMessageIsStatus_thenEmptyArrayMessages() = runTest { - val message = Message(piuri = ProtocolType.PickupStatus.value, body = "") - val messages = PickupRunner(message, mercury).run() - assertTrue(messages.isEmpty()) - } - - @OptIn(ExperimentalCoroutinesApi::class) - @Test - fun testPickupRun_whenMessageIsDelivery_thenArrayOfMessages() = runTest { - val attachmentData = AttachmentJsonData("{\"key\":\"value\"") - val attachmentId = UUID.randomUUID().toString() - val message = Message( - piuri = ProtocolType.PickupDelivery.value, - body = "", - attachments = arrayOf( - AttachmentDescriptor( - id = attachmentId, - data = attachmentData - ) - ) - ) - mercury.unpackMessageResponse = message - val messages = PickupRunner(message, mercury).run() - assertTrue(messages.isNotEmpty()) - assertEquals(attachmentId, messages[0].first) - assertEquals(message, messages[0].second) - } -} diff --git a/atala-prism-sdk/src/jvmMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/HttpClient.kt b/atala-prism-sdk/src/jvmMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/HttpClient.kt deleted file mode 100644 index c6ff00ce2..000000000 --- a/atala-prism-sdk/src/jvmMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/HttpClient.kt +++ /dev/null @@ -1,8 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -import io.ktor.client.HttpClientConfig -import io.ktor.client.engine.okhttp.OkHttp - -actual fun httpClient(config: HttpClientConfig<*>.() -> Unit) = io.ktor.client.HttpClient(OkHttp) { - config(this) -} diff --git a/atala-prism-sdk/src/jvmMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Platform.kt b/atala-prism-sdk/src/jvmMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Platform.kt deleted file mode 100644 index b5adbbc89..000000000 --- a/atala-prism-sdk/src/jvmMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/Platform.kt +++ /dev/null @@ -1,8 +0,0 @@ -package io.iohk.atala.prism.walletsdk.domain.models - -actual object Platform { - actual val OS: String - get() = "JVM - ${System.getProperty("java.runtime.name")} - ${System.getProperty("java.runtime.version")}" - actual val type: PlatformType - get() = PlatformType.JVM -} diff --git a/atala-prism-sdk/src/jvmMain/kotlin/io/iohk/atala/prism/walletsdk/pluto/data/DbConnection.kt b/atala-prism-sdk/src/jvmMain/kotlin/io/iohk/atala/prism/walletsdk/pluto/data/DbConnection.kt deleted file mode 100644 index 968b65374..000000000 --- a/atala-prism-sdk/src/jvmMain/kotlin/io/iohk/atala/prism/walletsdk/pluto/data/DbConnection.kt +++ /dev/null @@ -1,18 +0,0 @@ -package io.iohk.atala.prism.walletsdk.pluto.data - -import app.cash.sqldelight.db.SqlDriver -import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver -import io.iohk.atala.prism.walletsdk.PrismPlutoDb - -actual class DbConnection actual constructor() { - actual var driver: SqlDriver? = null - actual suspend fun connectDb(context: Any?): SqlDriver { - val driver = JdbcSqliteDriver(JdbcSqliteDriver.IN_MEMORY) - PrismPlutoDb.Schema.create(driver) - this.driver = driver - return driver - } -} - -actual val SqlDriver.isConnected: Boolean - get() = (this as? JdbcSqliteDriver)?.getConnection()?.isValid(1) ?: false diff --git a/atala-prism-sdk/src/jvmTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/AndroidIgnore.jvm.kt b/atala-prism-sdk/src/jvmTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/AndroidIgnore.jvm.kt deleted file mode 100644 index 66be643dc..000000000 --- a/atala-prism-sdk/src/jvmTest/kotlin/io/iohk/atala/prism/walletsdk/prismagent/AndroidIgnore.jvm.kt +++ /dev/null @@ -1,5 +0,0 @@ -package io.iohk.atala.prism.walletsdk.prismagent - -import org.junit.Ignore - -actual typealias AndroidIgnore = Ignore diff --git a/atala-prism-sdk/webpack.config.d/polyfill.js b/atala-prism-sdk/webpack.config.d/polyfill.js deleted file mode 100644 index f5b3bf1c8..000000000 --- a/atala-prism-sdk/webpack.config.d/polyfill.js +++ /dev/null @@ -1,10 +0,0 @@ -config.resolve = { - fallback: { - stream: require.resolve("stream-browserify") - } -}; -var webpack = require('webpack'); - -config.plugins.push(new webpack.ProvidePlugin({ - Buffer: ['buffer', 'Buffer'], -})); diff --git a/edge-agent-sdk/build.gradle.kts b/edge-agent-sdk/build.gradle.kts index c6839afbe..d25740d03 100644 --- a/edge-agent-sdk/build.gradle.kts +++ b/edge-agent-sdk/build.gradle.kts @@ -31,7 +31,7 @@ koverReport { filters { excludes { packages( - "io.iohk.atala.prism.protos", + "org.hyperledger.identus.protos", "org.hyperledger.identus.walletsdk.domain", "org.hyperledger.identus.walletsdk.pluto.data" ) @@ -237,7 +237,7 @@ tasks.withType().configureEach { "docs/Mercury.md", "docs/Pluto.md", "docs/Pollux.md", - "docs/PrismAgent.md" + "docs/EdgeAgent.md" ) sourceLink { localDirectory.set(projectDir.resolve("src")) diff --git a/edge-agent-sdk/docs/PrismAgent.md b/edge-agent-sdk/docs/EdgeAgent.md similarity index 51% rename from edge-agent-sdk/docs/PrismAgent.md rename to edge-agent-sdk/docs/EdgeAgent.md index 002c21398..8eed15b70 100644 --- a/edge-agent-sdk/docs/PrismAgent.md +++ b/edge-agent-sdk/docs/EdgeAgent.md @@ -1,23 +1,23 @@ -# Package org.hyperledger.identus.walletsdk.prismagent +# Package org.hyperledger.identus.walletsdk.edgeagent -Prism Agent is a powerful and flexible library for working with decentralized identifiers on the Prism platform. Whether +Identus is a powerful and flexible library for working with decentralized identifiers on the Identus platform. Whether you are building a decentralized application that requires secure and private identity management or working with a more -traditional system that requires reliable and resilient communication between DIDs, Prism Agent provides the tools and +traditional system that requires reliable and resilient communication between DIDs, Edge Agent provides the tools and features you need to do the job with ease. ## Overview -Prism Agent is a comprehensive library that combines all the Prism platform's building blocks - Apollo, Castor, Pluto, +Identus is a comprehensive library that combines all the Identus platform's building blocks - Apollo, Castor, Pluto, Mercury, and Pollux - to provide a seamless experience for developers working with decentralized identifiers (DIDs) on -the Prism platform. +the Identus platform. -Prism Agent is designed to provide high-level functionality for DID management and DID communication. This includes DID +Identus is designed to provide high-level functionality for DID management and DID communication. This includes DID management, DIDComm mediation management, and support for various DIDComm protocols, including mediation, proof presentation, issue credentials, and out-of-band messages. -With Prism Agent, developers can easily manage and communicate with DIDs seamlessly and efficiently. Prism Agent +With Edge Agent, developers can easily manage and communicate with DIDs seamlessly and efficiently. Edge 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 supports receiving messages through the mediator, allowing developers to easily manage and respond to +Edge Agent also supports receiving messages through the mediator, allowing developers to easily manage and respond to incoming messages securely and efficiently. diff --git a/edge-agent-sdk/docs/EdgeAgentSDK.md b/edge-agent-sdk/docs/EdgeAgentSDK.md index 60afca2f1..73e3a132a 100644 --- a/edge-agent-sdk/docs/EdgeAgentSDK.md +++ b/edge-agent-sdk/docs/EdgeAgentSDK.md @@ -1,6 +1,6 @@ # Module EdgeAgentSDK -Atala PRISM KMP SDK is a library and documentation that helps developers build KMM/JVM/Android SSI (self-sovereign +Identus KMP SDK is a library and documentation that helps developers build KMM/JVM/Android SSI (self-sovereign identity) applications with Identus. 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 fundamental considerations around the project. @@ -84,11 +84,11 @@ Together, these building blocks provide a solid foundation for building decentra secure, privacy-preserving, and interoperable. Using Identus, developers can focus on creating innovative identity solutions without worrying about the underlying infrastructure. -### Prism Agent +### Edge Agent -Prism Agent is a comprehensive library that combines all the Prism platform's building blocks - Apollo, Castor, Pluto, +Edge Agent is a comprehensive library that combines all the Identus platform's building blocks - Apollo, Castor, Pluto, Mercury, and Pollux - to provide a seamless experience for developers working with decentralized identifiers (DIDs) on -the Prism platform. +the Identus platform. ## Documentation @@ -97,4 +97,4 @@ the Prism platform. - [Getting Started](https://docs.atalaprism.io/docs/getting-started) - [What is identity?](https://docs.atalaprism.io/docs/concepts/what-is-identity) - [Digital wallets](https://docs.atalaprism.io/docs/concepts/digital-wallets) -- [Atala PRISM Overview](https://docs.atalaprism.io/docs/atala-prism/overview) +- [Identus Overview](https://docs.atalaprism.io/docs/atala-prism/overview) diff --git a/edge-agent-sdk/src/androidInstrumentedTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/AnoncredsTests.kt b/edge-agent-sdk/src/androidInstrumentedTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/AnoncredsTests.kt index ef02553d6..d5661b25d 100644 --- a/edge-agent-sdk/src/androidInstrumentedTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/AnoncredsTests.kt +++ b/edge-agent-sdk/src/androidInstrumentedTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/AnoncredsTests.kt @@ -1,6 +1,6 @@ @file:Suppress("ktlint:standard:import-ordering") -package org.hyperledger.identus.walletsdk.prismagent +package org.hyperledger.identus.walletsdk.edgeagent import androidx.test.ext.junit.runners.AndroidJUnit4 import anoncreds_wrapper.LinkSecret @@ -10,14 +10,14 @@ import org.hyperledger.identus.walletsdk.domain.models.AttachmentDescriptor import org.hyperledger.identus.walletsdk.domain.models.ClaimType import org.hyperledger.identus.walletsdk.domain.models.CredentialType import org.hyperledger.identus.walletsdk.domain.models.DID -import org.hyperledger.identus.walletsdk.logger.PrismLoggerMock +import org.hyperledger.identus.walletsdk.logger.EdgeLoggerMock import org.hyperledger.identus.walletsdk.mercury.ApiMock import org.hyperledger.identus.walletsdk.pollux.PolluxImpl import org.hyperledger.identus.walletsdk.pollux.models.CredentialRequestMeta import org.hyperledger.identus.walletsdk.pollux.models.LinkSecretBlindingData -import org.hyperledger.identus.walletsdk.prismagent.protocols.issueCredential.CredentialPreview -import org.hyperledger.identus.walletsdk.prismagent.protocols.issueCredential.IssueCredential -import org.hyperledger.identus.walletsdk.prismagent.protocols.issueCredential.OfferCredential +import org.hyperledger.identus.walletsdk.edgeagent.protocols.issueCredential.CredentialPreview +import org.hyperledger.identus.walletsdk.edgeagent.protocols.issueCredential.IssueCredential +import org.hyperledger.identus.walletsdk.edgeagent.protocols.issueCredential.OfferCredential import io.ktor.http.HttpStatusCode import junit.framework.TestCase.assertEquals import junit.framework.TestCase.assertTrue @@ -73,7 +73,7 @@ class AnoncredsTests { val pollux = PolluxImpl(castorMock, apiMock) plutoMock.getLinkSecretReturn = flow { emit(LinkSecret().getValue()) } - val agent = PrismAgent( + val agent = EdgeAgent( apollo = apolloMock, castor = castorMock, pluto = plutoMock, @@ -82,7 +82,7 @@ class AnoncredsTests { connectionManager = connectionManager, seed = null, api = ApiMock(statusCode = HttpStatusCode.OK, response = "{\"success\":\"true\"}"), - logger = PrismLoggerMock() + logger = EdgeLoggerMock() ) val attachmentDescriptor = @@ -137,7 +137,7 @@ class AnoncredsTests { ) plutoMock.getCredentialMetadataReturn = flow { emit(meta) } - val agent = PrismAgent( + val agent = EdgeAgent( apollo = apolloMock, castor = castorMock, pluto = plutoMock, @@ -146,7 +146,7 @@ class AnoncredsTests { connectionManager = connectionManager, seed = null, api = ApiMock(HttpStatusCode.OK, "{\"success\":\"true\"}"), - logger = PrismLoggerMock() + logger = EdgeLoggerMock() ) val attachmentDescriptor = diff --git a/edge-agent-sdk/src/androidUnitTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/AndroidIgnore.android.kt b/edge-agent-sdk/src/androidUnitTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/AndroidIgnore.android.kt index c4db54223..56a0049db 100644 --- a/edge-agent-sdk/src/androidUnitTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/AndroidIgnore.android.kt +++ b/edge-agent-sdk/src/androidUnitTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/AndroidIgnore.android.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent +package org.hyperledger.identus.walletsdk.edgeagent import org.junit.Ignore diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/apollo/ApolloImpl.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/apollo/ApolloImpl.kt index cb50d4147..56a6dd114 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/apollo/ApolloImpl.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/apollo/ApolloImpl.kt @@ -29,7 +29,7 @@ import org.hyperledger.identus.walletsdk.domain.models.keyManagement.StorableKey import org.hyperledger.identus.walletsdk.domain.models.keyManagement.TypeKey /** - * Apollo defines the set of cryptographic operations that are used in the Atala PRISM. + * Apollo defines the set of cryptographic operations that are used in the Identus. */ class ApolloImpl : Apollo { diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/castor/CastorImpl.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/castor/CastorImpl.kt index 3e5173117..71a5ccf41 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/castor/CastorImpl.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/castor/CastorImpl.kt @@ -17,8 +17,8 @@ import org.hyperledger.identus.walletsdk.domain.models.keyManagement.PublicKey import org.hyperledger.identus.walletsdk.logger.LogComponent import org.hyperledger.identus.walletsdk.logger.LogLevel import org.hyperledger.identus.walletsdk.logger.Metadata -import org.hyperledger.identus.walletsdk.logger.PrismLogger -import org.hyperledger.identus.walletsdk.logger.PrismLoggerImpl +import org.hyperledger.identus.walletsdk.logger.EdgeLogger +import org.hyperledger.identus.walletsdk.logger.EdgeLoggerImpl import kotlin.jvm.Throws /** @@ -30,7 +30,7 @@ class CastorImpl @JvmOverloads constructor( val apollo: Apollo, - private val logger: PrismLogger = PrismLoggerImpl(LogComponent.CASTOR) + private val logger: EdgeLogger = EdgeLoggerImpl(LogComponent.CASTOR) ) : Castor { var resolvers: Array = arrayOf( PeerDIDResolver(), diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/castor/did/prismdid/PrismDIDPublicKey.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/castor/did/prismdid/PrismDIDPublicKey.kt index 35165eea5..f28e69170 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/castor/did/prismdid/PrismDIDPublicKey.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/castor/did/prismdid/PrismDIDPublicKey.kt @@ -12,7 +12,7 @@ import pbandk.ByteArr import kotlin.jvm.Throws /** - * Represents a public key for the Atala PRISM system. + * Represents a public key for the Identus system. * * @property apollo The instance of [Apollo] used for cryptographic operations. * @property id The ID of the public key. diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/castor/shared/CastorShared.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/castor/shared/CastorShared.kt index 932c67c95..2b41d2d77 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/castor/shared/CastorShared.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/castor/shared/CastorShared.kt @@ -48,7 +48,7 @@ import org.hyperledger.identus.walletsdk.domain.models.keyManagement.PublicKey import org.hyperledger.identus.walletsdk.logger.LogComponent import org.hyperledger.identus.walletsdk.logger.LogLevel import org.hyperledger.identus.walletsdk.logger.Metadata -import org.hyperledger.identus.walletsdk.logger.PrismLoggerImpl +import org.hyperledger.identus.walletsdk.logger.EdgeLoggerImpl import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json @@ -65,12 +65,12 @@ internal class CastorShared { companion object { /** - * The logger property is a PrismLoggerImpl instance for logging purposes. + * The logger property is a EdgeLoggerImpl instance for logging purposes. * It is used to log debug, info, warning, and error messages, along with the associated metadata. * * @property logger The logger instance. */ - private val logger = PrismLoggerImpl(LogComponent.CASTOR) + private val logger = EdgeLoggerImpl(LogComponent.CASTOR) /** * parseDID parses a string representation of a Decentralized Identifier (DID) into a DID object. diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/buildingblocks/Apollo.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/buildingblocks/Apollo.kt index e01a0b494..aaf65dac2 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/buildingblocks/Apollo.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/buildingblocks/Apollo.kt @@ -8,7 +8,7 @@ import org.hyperledger.identus.walletsdk.domain.models.keyManagement.PrivateKey import kotlin.jvm.Throws /** - * Apollo defines the set of cryptographic operations that are used in the Atala PRISM. + * Apollo defines the set of cryptographic operations that are used in the Identus. */ interface Apollo : KeyRestoration { diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/buildingblocks/Pluto.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/buildingblocks/Pluto.kt index 452333296..76a5628bc 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/buildingblocks/Pluto.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/buildingblocks/Pluto.kt @@ -17,7 +17,7 @@ import org.hyperledger.identus.walletsdk.pollux.models.CredentialRequestMeta import kotlinx.coroutines.flow.Flow /** - * The `Pluto` interface defines the contract for storing and retrieving various data related to Atala PRISM architecture. + * The `Pluto` interface defines the contract for storing and retrieving various data related to Identus architecture. */ interface Pluto { diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/buildingblocks/Pollux.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/buildingblocks/Pollux.kt index 081176b5a..46deae936 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/buildingblocks/Pollux.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/buildingblocks/Pollux.kt @@ -15,7 +15,7 @@ import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.StorableCredential import org.hyperledger.identus.walletsdk.domain.models.keyManagement.PrivateKey import org.hyperledger.identus.walletsdk.pollux.models.AnonCredential -import org.hyperledger.identus.walletsdk.prismagent.protocols.proofOfPresentation.RequestPresentation +import org.hyperledger.identus.walletsdk.edgeagent.protocols.proofOfPresentation.RequestPresentation /** * The `Pollux` interface represents a set of operations for working with verifiable credentials. diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/models/Api.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/models/Api.kt index 3b93d33f9..4b8de4c57 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/models/Api.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/models/Api.kt @@ -1,6 +1,6 @@ package org.hyperledger.identus.walletsdk.domain.models -import org.hyperledger.identus.walletsdk.prismagent.shared.KeyValue +import org.hyperledger.identus.walletsdk.edgeagent.shared.KeyValue import io.ktor.client.HttpClient as KtorClient /** diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/models/ApiImpl.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/models/ApiImpl.kt index c2afa316f..fd6eca95c 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/models/ApiImpl.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/models/ApiImpl.kt @@ -5,8 +5,8 @@ import io.ktor.client.request.request import io.ktor.client.statement.bodyAsText import io.ktor.http.HttpMethod import io.ktor.http.Url -import org.hyperledger.identus.walletsdk.prismagent.shared.KeyValue -import org.hyperledger.identus.walletsdk.prismagent.shared.PrismShared +import org.hyperledger.identus.walletsdk.edgeagent.shared.KeyValue +import org.hyperledger.identus.walletsdk.edgeagent.shared.PrismShared /** * Implementation of API interface for http requests. diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/models/Errors.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/models/Errors.kt index 70b9ea346..a11232a03 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/models/Errors.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/models/Errors.kt @@ -3,7 +3,7 @@ package org.hyperledger.identus.walletsdk.domain.models import org.hyperledger.identus.walletsdk.domain.models.keyManagement.KeyTypes /** - * An interface that represents a base error in the Prism SDK. + * An interface that represents a base error in the Identus SDK. */ abstract interface Error { val code: Int? @@ -144,7 +144,7 @@ constructor( /** * An implementation of the [ApolloError] class that represents an error caused by invalid mnemonic words. - * This error occurs when one or more mnemonic words are invalid in a PRISM API response. + * This error occurs when one or more mnemonic words are invalid in a Identus API response. * * @param invalidWords The array of invalid mnemonic words. * @property message The error message for this error, which is determined based on the presence of invalid words. diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/models/Message.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/models/Message.kt index 9ee2c856f..3133fb736 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/models/Message.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/domain/models/Message.kt @@ -13,7 +13,7 @@ import kotlin.time.Duration.Companion.days /** * The [Message] data class represents a DIDComm message, which is used for secure, decentralized communication in the - * Atala PRISM architecture. A [Message] object includes information about the sender, recipient, message body, and other metadata. + * Identus architecture. A [Message] object includes information about the sender, recipient, message body, and other metadata. * [Message] objects are typically exchanged between DID controllers using the [Mercury] building block. */ @Serializable diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/AgentConstants.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/AgentConstants.kt similarity index 93% rename from atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/AgentConstants.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/AgentConstants.kt index fdca80aba..03282e47c 100644 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/AgentConstants.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/AgentConstants.kt @@ -1,4 +1,4 @@ -package io.iohk.atala.prism.walletsdk.prismagent +package org.hyperledger.identus.walletsdk.edgeagent const val DIDCOMM1 = "#didcomm-1" const val DIDCOMM_MESSAGING = "DIDCommMessaging" diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/ConnectionManager.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/ConnectionManager.kt similarity index 90% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/ConnectionManager.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/ConnectionManager.kt index 195a31485..786d10f94 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/ConnectionManager.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/ConnectionManager.kt @@ -1,6 +1,4 @@ -@file:Suppress("ktlint:standard:import-ordering") - -package org.hyperledger.identus.walletsdk.prismagent +package org.hyperledger.identus.walletsdk.edgeagent import io.iohk.atala.prism.apollo.base64.base64UrlDecoded import org.hyperledger.identus.walletsdk.domain.buildingblocks.Castor @@ -12,12 +10,12 @@ import org.hyperledger.identus.walletsdk.domain.models.CredentialType import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.DIDPair import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.connectionsmanager.ConnectionsManager -import org.hyperledger.identus.walletsdk.prismagent.connectionsmanager.DIDCommConnection -import org.hyperledger.identus.walletsdk.prismagent.mediation.MediationHandler -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType -import org.hyperledger.identus.walletsdk.prismagent.protocols.issueCredential.IssueCredential -import org.hyperledger.identus.walletsdk.prismagent.protocols.revocation.RevocationNotification +import org.hyperledger.identus.walletsdk.edgeagent.connectionsmanager.ConnectionsManager +import org.hyperledger.identus.walletsdk.edgeagent.connectionsmanager.DIDCommConnection +import org.hyperledger.identus.walletsdk.edgeagent.mediation.MediationHandler +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType +import org.hyperledger.identus.walletsdk.edgeagent.protocols.issueCredential.IssueCredential +import org.hyperledger.identus.walletsdk.edgeagent.protocols.revocation.RevocationNotification import java.time.Duration import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -115,12 +113,12 @@ class ConnectionManager @JvmOverloads constructor( /** * Suspends the current coroutine and boots the registered mediator associated with the mediator handler. - * If no mediator is available, a [PrismAgentError.NoMediatorAvailableError] is thrown. + * If no mediator is available, a [EdgeAgentError.NoMediatorAvailableError] is thrown. * - * @throws PrismAgentError.NoMediatorAvailableError if no mediator is available. + * @throws EdgeAgentError.NoMediatorAvailableError if no mediator is available. */ suspend fun startMediator() { - mediationHandler.bootRegisteredMediator() ?: throw PrismAgentError.NoMediatorAvailableError() + mediationHandler.bootRegisteredMediator() ?: throw EdgeAgentError.NoMediatorAvailableError() } /** @@ -140,10 +138,10 @@ class ConnectionManager @JvmOverloads constructor( * @param message The message to send. * @return The response message, if one is received. */ - @Throws(PrismAgentError.NoMediatorAvailableError::class) + @Throws(EdgeAgentError.NoMediatorAvailableError::class) override suspend fun sendMessage(message: Message): Message? { if (mediationHandler.mediator == null) { - throw PrismAgentError.NoMediatorAvailableError() + throw EdgeAgentError.NoMediatorAvailableError() } pluto.storeMessage(message) return mercury.sendMessageParseResponse(message) diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/PrismAgent.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/EdgeAgent.kt similarity index 88% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/PrismAgent.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/EdgeAgent.kt index ca8997100..881f4c739 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/PrismAgent.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/EdgeAgent.kt @@ -1,6 +1,6 @@ @file:Suppress("ktlint:standard:import-ordering") -package org.hyperledger.identus.walletsdk.prismagent +package org.hyperledger.identus.walletsdk.edgeagent import anoncreds_wrapper.CredentialOffer import anoncreds_wrapper.CredentialRequestMetadata @@ -42,26 +42,26 @@ import org.hyperledger.identus.walletsdk.domain.models.keyManagement.PrivateKey import org.hyperledger.identus.walletsdk.domain.models.keyManagement.StorableKey import org.hyperledger.identus.walletsdk.logger.LogComponent import org.hyperledger.identus.walletsdk.logger.Metadata -import org.hyperledger.identus.walletsdk.logger.PrismLogger -import org.hyperledger.identus.walletsdk.logger.PrismLoggerImpl +import org.hyperledger.identus.walletsdk.logger.EdgeLogger +import org.hyperledger.identus.walletsdk.logger.EdgeLoggerImpl import org.hyperledger.identus.walletsdk.pollux.models.AnonCredential import org.hyperledger.identus.walletsdk.pollux.models.CredentialRequestMeta import org.hyperledger.identus.walletsdk.pollux.models.JWTCredential -import org.hyperledger.identus.walletsdk.prismagent.helpers.AgentOptions -import org.hyperledger.identus.walletsdk.prismagent.mediation.BasicMediatorHandler -import org.hyperledger.identus.walletsdk.prismagent.mediation.MediationHandler -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType -import org.hyperledger.identus.walletsdk.prismagent.protocols.connection.DIDCommConnectionRunner -import org.hyperledger.identus.walletsdk.prismagent.protocols.findProtocolTypeByValue -import org.hyperledger.identus.walletsdk.prismagent.protocols.issueCredential.IssueCredential -import org.hyperledger.identus.walletsdk.prismagent.protocols.issueCredential.OfferCredential -import org.hyperledger.identus.walletsdk.prismagent.protocols.issueCredential.RequestCredential -import org.hyperledger.identus.walletsdk.prismagent.protocols.outOfBand.DIDCommInvitationRunner -import org.hyperledger.identus.walletsdk.prismagent.protocols.outOfBand.InvitationType -import org.hyperledger.identus.walletsdk.prismagent.protocols.outOfBand.OutOfBandInvitation -import org.hyperledger.identus.walletsdk.prismagent.protocols.outOfBand.PrismOnboardingInvitation -import org.hyperledger.identus.walletsdk.prismagent.protocols.proofOfPresentation.Presentation -import org.hyperledger.identus.walletsdk.prismagent.protocols.proofOfPresentation.RequestPresentation +import org.hyperledger.identus.walletsdk.edgeagent.helpers.AgentOptions +import org.hyperledger.identus.walletsdk.edgeagent.mediation.BasicMediatorHandler +import org.hyperledger.identus.walletsdk.edgeagent.mediation.MediationHandler +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType +import org.hyperledger.identus.walletsdk.edgeagent.protocols.connection.DIDCommConnectionRunner +import org.hyperledger.identus.walletsdk.edgeagent.protocols.findProtocolTypeByValue +import org.hyperledger.identus.walletsdk.edgeagent.protocols.issueCredential.IssueCredential +import org.hyperledger.identus.walletsdk.edgeagent.protocols.issueCredential.OfferCredential +import org.hyperledger.identus.walletsdk.edgeagent.protocols.issueCredential.RequestCredential +import org.hyperledger.identus.walletsdk.edgeagent.protocols.outOfBand.DIDCommInvitationRunner +import org.hyperledger.identus.walletsdk.edgeagent.protocols.outOfBand.InvitationType +import org.hyperledger.identus.walletsdk.edgeagent.protocols.outOfBand.OutOfBandInvitation +import org.hyperledger.identus.walletsdk.edgeagent.protocols.outOfBand.PrismOnboardingInvitation +import org.hyperledger.identus.walletsdk.edgeagent.protocols.proofOfPresentation.Presentation +import org.hyperledger.identus.walletsdk.edgeagent.protocols.proofOfPresentation.RequestPresentation import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.http.ContentType import io.ktor.http.HttpMethod @@ -97,10 +97,10 @@ private fun Url.Companion.parse(str: String): Url? { } /** - * PrismAgent class is responsible for handling the connection to other agents in the network using a provided Mediator + * EdgeAgent class is responsible for handling the connection to other agents in the network using a provided Mediator * Service Endpoint and seed data. */ -class PrismAgent { +class EdgeAgent { var state: State = State.STOPPED private set(value) { field = value @@ -119,23 +119,23 @@ class PrismAgent { private val prismAgentScope: CoroutineScope = CoroutineScope(Dispatchers.Default) private val api: Api private var connectionManager: ConnectionManager - private var logger: PrismLogger + private var logger: EdgeLogger private val agentOptions: AgentOptions /** - * Initializes the PrismAgent with the given dependencies. + * Initializes the EdgeAgent with the given dependencies. * - * @param apollo The Apollo instance used by the PrismAgent. - * @param castor The Castor instance used by the PrismAgent. - * @param pluto The Pluto instance used by the PrismAgent. - * @param mercury The Mercury instance used by the PrismAgent. - * @param pollux The Pollux instance used by the PrismAgent. - * @param connectionManager The ConnectionManager instance used by the PrismAgent. + * @param apollo The Apollo instance used by the EdgeAgent. + * @param castor The Castor instance used by the EdgeAgent. + * @param pluto The Pluto instance used by the EdgeAgent. + * @param mercury The Mercury instance used by the EdgeAgent. + * @param pollux The Pollux instance used by the EdgeAgent. + * @param connectionManager The ConnectionManager instance used by the EdgeAgent. * @param seed An optional Seed instance used by the Apollo if provided, otherwise a random seed will be used. - * @param api An optional Api instance used by the PrismAgent if provided, otherwise a default ApiImpl will be used. - * @param logger An optional PrismLogger instance used by the PrismAgent if provided, otherwise a PrismLoggerImpl with + * @param api An optional Api instance used by the EdgeAgent if provided, otherwise a default ApiImpl will be used. + * @param logger An optional EdgeLogger instance used by the EdgeAgent if provided, otherwise a EdgeLoggerImpl with * LogComponent.PRISM_AGENT will be used. - * @param agentOptions Options to configure certain features with in the prism agent. + * @param agentOptions Options to configure certain features with in the edge agent. */ @JvmOverloads constructor( @@ -147,7 +147,7 @@ class PrismAgent { connectionManager: ConnectionManager, seed: Seed?, api: Api?, - logger: PrismLogger = PrismLoggerImpl(LogComponent.PRISM_AGENT), + logger: EdgeLogger = EdgeLoggerImpl(LogComponent.PRISM_AGENT), agentOptions: AgentOptions = AgentOptions() ) { prismAgentScope.launch { @@ -178,7 +178,7 @@ class PrismAgent { } /** - * Initializes the PrismAgent constructor. + * Initializes the EdgeAgent constructor. * * @param apollo The instance of Apollo. * @param castor The instance of Castor. @@ -188,8 +188,8 @@ class PrismAgent { * @param seed The seed value for random generation. Default is null. * @param api The instance of the API. Default is null. * @param mediatorHandler The mediator handler. - * @param logger The logger for PrismAgent. Default is PrismLoggerImpl with LogComponent.PRISM_AGENT. - * @param agentOptions Options to configure certain features with in the prism agent. + * @param logger The logger for EdgemAgent. Default is EdgeLoggerImpl with LogComponent.PRISM_AGENT. + * @param agentOptions Options to configure certain features with in the Edge Agent. */ @JvmOverloads constructor( @@ -201,7 +201,7 @@ class PrismAgent { seed: Seed? = null, api: Api? = null, mediatorHandler: MediationHandler, - logger: PrismLogger = PrismLoggerImpl(LogComponent.PRISM_AGENT), + logger: PrismLogger = EdgeLoggerImpl(LogComponent.PRISM_AGENT), agentOptions: AgentOptions = AgentOptions() ) { prismAgentScope.launch { @@ -246,14 +246,14 @@ class PrismAgent { } } - // Prism agent actions + // Edge agent actions /** - * Start the [PrismAgent] and Mediator services. + * Start the [EdgeAgent] and Mediator services. * - * @throws [PrismAgentError.MediationRequestFailedError] failed to connect to mediator. + * @throws [EdgeAgentError.MediationRequestFailedError] failed to connect to mediator. * @throws [UnknownHostException] if unable to connect to the mediator. */ - @Throws(PrismAgentError.MediationRequestFailedError::class, UnknownHostException::class) + @Throws(EdgeAgentError.MediationRequestFailedError::class, UnknownHostException::class) suspend fun start() { if (state != State.STOPPED) { return @@ -262,7 +262,7 @@ class PrismAgent { state = State.STARTING try { connectionManager.startMediator() - } catch (error: PrismAgentError.NoMediatorAvailableError) { + } catch (error: EdgeAgentError.NoMediatorAvailableError) { logger.info(message = "Start accept DIDComm invitation") try { val hostDID = createNewPeerDID(updateMediator = false) @@ -288,15 +288,15 @@ class PrismAgent { logger.info(message = "Agent running") } else { state = State.STOPPED - throw PrismAgentError.MediationRequestFailedError() + throw EdgeAgentError.MediationRequestFailedError() } } /** - * Stops the [PrismAgent]. - * The function sets the state of [PrismAgent] to [State.STOPPING]. - * All ongoing events that was created by the [PrismAgent] are stopped. - * After all the events are stopped the state of the [PrismAgent] is set to [State.STOPPED]. + * Stops the [EdgeAgent]. + * The function sets the state of [EdgeAgent] to [State.STOPPING]. + * All ongoing events that was created by the [EdgeAgent] are stopped. + * After all the events are stopped the state of the [EdgeAgent] is set to [State.STOPPED]. */ fun stop() { if (state != State.RUNNING) { @@ -546,11 +546,11 @@ class PrismAgent { * @param message The message to be signed. * @return The signature of the message. */ - @Throws(PrismAgentError.CannotFindDIDPrivateKey::class) + @Throws(EdgeAgentError.CannotFindDIDPrivateKey::class) suspend fun signWith(did: DID, message: ByteArray): Signature { val privateKey = pluto.getDIDPrivateKeysByDID(did).first().first() - ?: throw PrismAgentError.CannotFindDIDPrivateKey(did.toString()) + ?: throw EdgeAgentError.CannotFindDIDPrivateKey(did.toString()) val returnByteArray: ByteArray = when (privateKey.getCurve()) { Curve.ED25519.value -> { val ed = privateKey as Ed25519PrivateKey @@ -672,7 +672,7 @@ class PrismAgent { } else -> { - // TODO: Create new prism agent error message + // TODO: Create new edge agent error message throw org.hyperledger.identus.walletsdk.domain.models.UnknownError.SomethingWentWrongError( "Not supported credential type: $type" ) @@ -780,10 +780,10 @@ class PrismAgent { * Parses the given string as an invitation * @param str The string to parse * @return The parsed invitation [InvitationType] - * @throws [PrismAgentError.UnknownInvitationTypeError] if the invitation is not a valid Prism or OOB type + * @throws [EdgeAgentError.UnknownInvitationTypeError] if the invitation is not a valid Prism or OOB type * @throws [SerializationException] if Serialization failed */ - @Throws(PrismAgentError.UnknownInvitationTypeError::class, SerializationException::class) + @Throws(EdgeAgentError.UnknownInvitationTypeError::class, SerializationException::class) suspend fun parseInvitation(str: String): InvitationType { Url.parse(str)?.let { return parseOOBInvitation(it) @@ -800,7 +800,7 @@ class PrismAgent { ProtocolType.PrismOnboarding -> parsePrismInvitation(str) ProtocolType.Didcomminvitation -> parseOOBInvitation(str) else -> - throw PrismAgentError.UnknownInvitationTypeError(type.toString()) + throw EdgeAgentError.UnknownInvitationTypeError(type.toString()) } return invite @@ -864,7 +864,7 @@ class PrismAgent { * Parses the given URL as an Out-of-Band invitation * @param url The URL to parse * @return The parsed Out-of-Band invitation - * @throws [PrismAgentError.UnknownInvitationTypeError] if the URL is not a valid Out-of-Band invitation + * @throws [EdgeAgentError.UnknownInvitationTypeError] if the URL is not a valid Out-of-Band invitation */ private suspend fun parseOOBInvitation(url: Url): OutOfBandInvitation { return DIDCommInvitationRunner(url).run() @@ -873,7 +873,7 @@ class PrismAgent { /** * Accepts an Out-of-Band (DIDComm) invitation and establishes a new connection * @param invitation The Out-of-Band invitation to accept - * @throws [PrismAgentError.NoMediatorAvailableError] if there is no mediator available or other errors occur during the acceptance process + * @throws [EdgeAgentError.NoMediatorAvailableError] if there is no mediator available or other errors occur during the acceptance process */ suspend fun acceptOutOfBandInvitation(invitation: OutOfBandInvitation) { val ownDID = createNewPeerDID(updateMediator = true) @@ -884,9 +884,9 @@ class PrismAgent { /** * Accepts a Prism Onboarding invitation and performs the onboarding process * @param invitation The Prism Onboarding invitation to accept - * @throws [PrismAgentError.FailedToOnboardError] if failed to on board + * @throws [EdgeAgentError.FailedToOnboardError] if failed to on board */ - @Throws(PrismAgentError.FailedToOnboardError::class) + @Throws(EdgeAgentError.FailedToOnboardError::class) suspend fun acceptInvitation(invitation: PrismOnboardingInvitation) { @Serializable data class SendDID(val did: String) @@ -900,7 +900,7 @@ class PrismAgent { ) if (response.status != 200) { - throw PrismAgentError.FailedToOnboardError(response.status, response.jsonString) + throw EdgeAgentError.FailedToOnboardError(response.status, response.jsonString) } } @@ -923,7 +923,7 @@ class PrismAgent { * @param request Request message received. * @param credential Verifiable Credential to present. * @return Presentation message prepared to send. - * @throws PrismAgentError if there is a problem creating the presentation. + * @throws EdgeAgentError if there is a problem creating the presentation. **/ @Throws(PolluxError.InvalidPrismDID::class) suspend fun preparePresentationForRequestProof( @@ -966,7 +966,7 @@ class PrismAgent { AnonCredential::class -> { val format = pollux.extractCredentialFormatFromMessage(request.attachments) if (format != CredentialType.ANONCREDS_PROOF_REQUEST) { - throw PrismAgentError.InvalidCredentialFormatError(CredentialType.ANONCREDS_PROOF_REQUEST) + throw EdgeAgentError.InvalidCredentialFormatError(CredentialType.ANONCREDS_PROOF_REQUEST) } val linkSecret = getLinkSecret() val presentation = pollux.createVerifiablePresentationAnoncred( @@ -978,7 +978,7 @@ class PrismAgent { } else -> { - throw PrismAgentError.InvalidCredentialError(credential) + throw EdgeAgentError.InvalidCredentialError(credential) } } diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/PrismAgentError.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/EdgeAgentError.kt similarity index 81% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/PrismAgentError.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/EdgeAgentError.kt index 286cae580..cc4b4ad13 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/PrismAgentError.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/EdgeAgentError.kt @@ -1,13 +1,13 @@ -package org.hyperledger.identus.walletsdk.prismagent +package org.hyperledger.identus.walletsdk.edgeagent import org.hyperledger.identus.walletsdk.domain.models.Credential import org.hyperledger.identus.walletsdk.domain.models.CredentialType import org.hyperledger.identus.walletsdk.domain.models.Error import org.hyperledger.identus.walletsdk.domain.models.KnownPrismError -sealed class PrismAgentError : KnownPrismError() { +sealed class EdgeAgentError : KnownPrismError() { - class CannotFindDIDKeyPairIndex : PrismAgentError() { + class CannotFindDIDKeyPairIndex : EdgeAgentError() { override val code: Int get() = 111 @@ -15,7 +15,7 @@ sealed class PrismAgentError : KnownPrismError() { get() = "To sign with a DID a key pair needs to be registered, please register the key pair first" } - class InvitationIsInvalidError : PrismAgentError() { + class InvitationIsInvalidError : EdgeAgentError() { override val code: Int get() = 112 @@ -23,7 +23,7 @@ sealed class PrismAgentError : KnownPrismError() { get() = "The system could not parse the invitation, the message/json are invalid" } - class UnknownInvitationTypeError(private val type: String) : PrismAgentError() { + class UnknownInvitationTypeError(private val type: String) : EdgeAgentError() { override val code: Int get() = 113 @@ -31,7 +31,7 @@ sealed class PrismAgentError : KnownPrismError() { get() = "The type of the invitation is not supported: $type" } - class InvalidMessageType(private val type: String, private val shouldBe: String) : PrismAgentError() { + class InvalidMessageType(private val type: String, private val shouldBe: String) : EdgeAgentError() { override val code: Int get() = 114 @@ -39,16 +39,16 @@ sealed class PrismAgentError : KnownPrismError() { get() = "The following message $type, does not represent the protocol $shouldBe.\nAlso the message should have \"from\" and \"to\" fields\n" } - class NoMediatorAvailableError : PrismAgentError() { + class NoMediatorAvailableError : EdgeAgentError() { override val code: Int get() = 115 override val message: String - get() = "There is no mediator.\nYou need to provide a mediation handler and start the prism agent before doing some operations." + get() = "There is no mediator.\nYou need to provide a mediation handler and start the edge agent before doing some operations." } class MediationRequestFailedError - @JvmOverloads constructor(private val underlyingError: Array? = null) : PrismAgentError() { + @JvmOverloads constructor(private val underlyingError: Array? = null) : EdgeAgentError() { override val code: Int get() = 116 @@ -60,7 +60,7 @@ sealed class PrismAgentError : KnownPrismError() { } } - class OfferDoesNotProvideEnoughInformation : PrismAgentError() { + class OfferDoesNotProvideEnoughInformation : EdgeAgentError() { override val code: Int get() = 117 @@ -68,7 +68,7 @@ sealed class PrismAgentError : KnownPrismError() { get() = "Offer provided doesnt have challenge and domain in the attachments" } - class CannotFindDIDPrivateKey(private val did: String) : PrismAgentError() { + class CannotFindDIDPrivateKey(private val did: String) : EdgeAgentError() { override val code: Int get() = 118 @@ -76,7 +76,7 @@ sealed class PrismAgentError : KnownPrismError() { get() = "Could not find private key for DID: $did" } - class FailedToOnboardError(private val statusCode: Int, private val response: String) : PrismAgentError() { + class FailedToOnboardError(private val statusCode: Int, private val response: String) : EdgeAgentError() { override val code: Int get() = 119 @@ -85,7 +85,7 @@ sealed class PrismAgentError : KnownPrismError() { } class InvalidCredentialError constructor(private val credential: Credential) : - PrismAgentError() { + EdgeAgentError() { override val code: Int get() = 120 @@ -94,7 +94,7 @@ sealed class PrismAgentError : KnownPrismError() { } class InvalidCredentialFormatError constructor(private val expectedFormat: CredentialType) : - PrismAgentError() { + EdgeAgentError() { override val code: Int get() = 121 diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/connectionsmanager/ConnectionsManager.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/connectionsmanager/ConnectionsManager.kt similarity index 91% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/connectionsmanager/ConnectionsManager.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/connectionsmanager/ConnectionsManager.kt index 7f6941119..9b62916f8 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/connectionsmanager/ConnectionsManager.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/connectionsmanager/ConnectionsManager.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent.connectionsmanager +package org.hyperledger.identus.walletsdk.edgeagent.connectionsmanager import org.hyperledger.identus.walletsdk.domain.models.DIDPair diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/connectionsmanager/DIDCommConnection.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/connectionsmanager/DIDCommConnection.kt similarity index 93% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/connectionsmanager/DIDCommConnection.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/connectionsmanager/DIDCommConnection.kt index 8e27fa450..2fcc4f1be 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/connectionsmanager/DIDCommConnection.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/connectionsmanager/DIDCommConnection.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent.connectionsmanager +package org.hyperledger.identus.walletsdk.edgeagent.connectionsmanager import kotlinx.coroutines.flow.Flow import org.hyperledger.identus.walletsdk.domain.models.Message diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/helpers/AgentOptions.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/helpers/AgentOptions.kt similarity index 88% rename from atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/helpers/AgentOptions.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/helpers/AgentOptions.kt index 95408a082..e9f98a5de 100644 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/helpers/AgentOptions.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/helpers/AgentOptions.kt @@ -1,4 +1,4 @@ -package io.iohk.atala.prism.walletsdk.prismagent.helpers +package org.hyperledger.identus.walletsdk.edgeagent.helpers /** * Class that represent agent options that the SDK user can define to modify some behaviors of the SDK. diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/helpers/AttachmentDescriptorBuild.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/helpers/AttachmentDescriptorBuild.kt similarity index 95% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/helpers/AttachmentDescriptorBuild.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/helpers/AttachmentDescriptorBuild.kt index aad7ed562..894a22c07 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/helpers/AttachmentDescriptorBuild.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/helpers/AttachmentDescriptorBuild.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent.helpers +package org.hyperledger.identus.walletsdk.edgeagent.helpers import io.iohk.atala.prism.apollo.base64.base64UrlEncoded import io.ktor.http.ContentType diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/mediation/BasicMediatorHandler.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/mediation/BasicMediatorHandler.kt similarity index 87% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/mediation/BasicMediatorHandler.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/mediation/BasicMediatorHandler.kt index 90c7a47b7..6cbda25fa 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/mediation/BasicMediatorHandler.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/mediation/BasicMediatorHandler.kt @@ -1,6 +1,6 @@ @file:Suppress("ktlint:standard:import-ordering") -package org.hyperledger.identus.walletsdk.prismagent.mediation +package org.hyperledger.identus.walletsdk.edgeagent.mediation import org.hyperledger.identus.walletsdk.domain.buildingblocks.Mercury import org.hyperledger.identus.walletsdk.domain.buildingblocks.Pluto @@ -8,14 +8,14 @@ import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.Mediator import org.hyperledger.identus.walletsdk.domain.models.Message import org.hyperledger.identus.walletsdk.domain.models.UnknownError -import org.hyperledger.identus.walletsdk.prismagent.PrismAgentError -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType -import org.hyperledger.identus.walletsdk.prismagent.protocols.mediation.MediationGrant -import org.hyperledger.identus.walletsdk.prismagent.protocols.mediation.MediationKeysUpdateList -import org.hyperledger.identus.walletsdk.prismagent.protocols.mediation.MediationRequest -import org.hyperledger.identus.walletsdk.prismagent.protocols.pickup.PickupReceived -import org.hyperledger.identus.walletsdk.prismagent.protocols.pickup.PickupRequest -import org.hyperledger.identus.walletsdk.prismagent.protocols.pickup.PickupRunner +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgentError +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType +import org.hyperledger.identus.walletsdk.edgeagent.protocols.mediation.MediationGrant +import org.hyperledger.identus.walletsdk.edgeagent.protocols.mediation.MediationKeysUpdateList +import org.hyperledger.identus.walletsdk.edgeagent.protocols.mediation.MediationRequest +import org.hyperledger.identus.walletsdk.edgeagent.protocols.pickup.PickupReceived +import org.hyperledger.identus.walletsdk.edgeagent.protocols.pickup.PickupRequest +import org.hyperledger.identus.walletsdk.edgeagent.protocols.pickup.PickupRunner import io.ktor.client.HttpClient import io.ktor.client.plugins.HttpTimeout import io.ktor.client.plugins.websocket.WebSockets @@ -88,7 +88,7 @@ class BasicMediatorHandler( * @param host The DID of the entity to mediate with. * @return The mediator associated with the achieved mediation. */ - @Throws(PrismAgentError.MediationRequestFailedError::class) + @Throws(EdgeAgentError.MediationRequestFailedError::class) override fun achieveMediation(host: DID): Flow { return flow { val registeredMediator = bootRegisteredMediator() @@ -113,7 +113,7 @@ class BasicMediatorHandler( mediator = tmpMediator emit(tmpMediator) } catch (e: UnknownError) { - throw PrismAgentError.MediationRequestFailedError(arrayOf(e)) + throw EdgeAgentError.MediationRequestFailedError(arrayOf(e)) } } else { emit(registeredMediator) @@ -126,7 +126,7 @@ class BasicMediatorHandler( * * @param dids An array of DIDs to add to the key list. */ - @Throws(PrismAgentError.NoMediatorAvailableError::class) + @Throws(EdgeAgentError.NoMediatorAvailableError::class) override suspend fun updateKeyListWithDIDs(dids: Array) { val keyListUpdateMessage = mediator?.let { MediationKeysUpdateList( @@ -134,7 +134,7 @@ class BasicMediatorHandler( to = it.mediatorDID, recipientDids = dids ).makeMessage() - } ?: throw PrismAgentError.NoMediatorAvailableError() + } ?: throw EdgeAgentError.NoMediatorAvailableError() keyListUpdateMessage.let { message -> mercury.sendMessage(message) } } @@ -144,7 +144,7 @@ class BasicMediatorHandler( * @param limit The maximum number of messages to pick up. * @return An array of pairs containing the message ID and the message itself. */ - @Throws(PrismAgentError.NoMediatorAvailableError::class) + @Throws(EdgeAgentError.NoMediatorAvailableError::class) override fun pickupUnreadMessages(limit: Int): Flow>> { val requestMessage = mediator?.let { PickupRequest( @@ -152,7 +152,7 @@ class BasicMediatorHandler( to = it.mediatorDID, body = PickupRequest.Body(limit = limit) ).makeMessage() - } ?: throw PrismAgentError.NoMediatorAvailableError() + } ?: throw EdgeAgentError.NoMediatorAvailableError() return flow { val message = mercury.sendMessageParseResponse(requestMessage) @@ -167,7 +167,7 @@ class BasicMediatorHandler( * * @param ids An array of message IDs to register as read. */ - @Throws(PrismAgentError.NoMediatorAvailableError::class) + @Throws(EdgeAgentError.NoMediatorAvailableError::class) override suspend fun registerMessagesAsRead(ids: Array) { val requestMessage = mediator?.let { PickupReceived( @@ -175,7 +175,7 @@ class BasicMediatorHandler( to = it.mediatorDID, body = PickupReceived.Body(messageIdList = ids) ).makeMessage() - } ?: throw PrismAgentError.NoMediatorAvailableError() + } ?: throw EdgeAgentError.NoMediatorAvailableError() mercury.sendMessage(requestMessage) } diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/mediation/MediationHandler.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/mediation/MediationHandler.kt similarity index 97% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/mediation/MediationHandler.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/mediation/MediationHandler.kt index 61d26aba1..58facb995 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/mediation/MediationHandler.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/mediation/MediationHandler.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent.mediation +package org.hyperledger.identus.walletsdk.edgeagent.mediation import kotlinx.coroutines.flow.Flow import org.hyperledger.identus.walletsdk.domain.models.DID diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/mediation/MediatorRepository.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/mediation/MediatorRepository.kt similarity index 91% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/mediation/MediatorRepository.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/mediation/MediatorRepository.kt index f34da1405..f7d599ec1 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/mediation/MediatorRepository.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/mediation/MediatorRepository.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent.mediation +package org.hyperledger.identus.walletsdk.edgeagent.mediation import org.hyperledger.identus.walletsdk.domain.buildingblocks.Pluto import org.hyperledger.identus.walletsdk.domain.models.Mediator diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/ProtocolType.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/ProtocolType.kt similarity index 90% rename from atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/ProtocolType.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/ProtocolType.kt index 52f03aa11..a76b78496 100644 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/ProtocolType.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/ProtocolType.kt @@ -1,7 +1,5 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols +package org.hyperledger.identus.walletsdk.edgeagent.protocols -import io.iohk.atala.prism.walletsdk.prismagent.PROTOCOL_TYPE -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgentError import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializable @@ -11,6 +9,8 @@ import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder +import org.hyperledger.identus.walletsdk.edgeagent.PROTOCOL_TYPE +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgentError @Serializable(with = ProtocolTypeSerializer::class) enum class ProtocolType(val value: String) { @@ -67,9 +67,9 @@ object ProtocolTypeSerializer : KSerializer { * * @param string The string value to match with the ProtocolType's value. * @return The matched ProtocolType. - * @throws PrismAgentError.UnknownInvitationTypeError If the type of the invitation is not supported. + * @throws EdgeAgentError.UnknownInvitationTypeError If the type of the invitation is not supported. */ -@Throws(PrismAgentError.UnknownInvitationTypeError::class) +@Throws(EdgeAgentError.UnknownInvitationTypeError::class) fun findProtocolTypeByValue(string: String): ProtocolType { val it = ProtocolType.values().iterator() while (it.hasNext()) { @@ -78,5 +78,5 @@ fun findProtocolTypeByValue(string: String): ProtocolType { return internalType } } - throw PrismAgentError.UnknownInvitationTypeError(string) + throw EdgeAgentError.UnknownInvitationTypeError(string) } diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/connection/ConnectionAccept.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/connection/ConnectionAccept.kt similarity index 93% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/connection/ConnectionAccept.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/connection/ConnectionAccept.kt index bad7237e8..c77d8e9df 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/connection/ConnectionAccept.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/connection/ConnectionAccept.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.connection +package org.hyperledger.identus.walletsdk.edgeagent.protocols.connection import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @@ -6,9 +6,9 @@ import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.GOAL_CODE -import org.hyperledger.identus.walletsdk.prismagent.PrismAgentError -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType +import org.hyperledger.identus.walletsdk.edgeagent.GOAL_CODE +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgentError +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType import java.util.UUID /** @@ -48,12 +48,12 @@ class ConnectionAccept { * * @param fromMessage The message to decode. */ - @Throws(PrismAgentError.InvalidMessageType::class) + @Throws(EdgeAgentError.InvalidMessageType::class) constructor(fromMessage: Message) { if (fromMessage.piuri == ProtocolType.DidcommconnectionResponse.value && fromMessage.from != null && fromMessage.to != null) { ConnectionAccept(from = fromMessage.from, to = fromMessage.to, body = Body(fromMessage.body)) } else { - throw PrismAgentError.InvalidMessageType( + throw EdgeAgentError.InvalidMessageType( type = fromMessage.piuri, shouldBe = ProtocolType.DidcommconnectionResponse.value ) diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/connection/ConnectionRequest.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/connection/ConnectionRequest.kt similarity index 90% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/connection/ConnectionRequest.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/connection/ConnectionRequest.kt index 58306748e..52b842195 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/connection/ConnectionRequest.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/connection/ConnectionRequest.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.connection +package org.hyperledger.identus.walletsdk.edgeagent.protocols.connection import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @@ -6,10 +6,10 @@ import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.GOAL_CODE -import org.hyperledger.identus.walletsdk.prismagent.PrismAgentError -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType -import org.hyperledger.identus.walletsdk.prismagent.protocols.outOfBand.OutOfBandInvitation +import org.hyperledger.identus.walletsdk.edgeagent.GOAL_CODE +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgentError +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType +import org.hyperledger.identus.walletsdk.edgeagent.protocols.outOfBand.OutOfBandInvitation import java.util.UUID /** @@ -50,12 +50,12 @@ class ConnectionRequest { * @param inviteMessage The invitation message to use for initialization. * @param from The DID of the sender of the connection request message. */ - @Throws(PrismAgentError.InvitationIsInvalidError::class) + @Throws(EdgeAgentError.InvitationIsInvalidError::class) constructor(inviteMessage: Message, from: DID) { inviteMessage.from?.let { toDID -> val body = Json.decodeFromString(inviteMessage.body) ConnectionRequest(from = from, to = toDID, thid = inviteMessage.id, body = body) - } ?: throw PrismAgentError.InvitationIsInvalidError() + } ?: throw EdgeAgentError.InvitationIsInvalidError() } /** @@ -80,7 +80,7 @@ class ConnectionRequest { * * @param fromMessage The message to decode. */ - @Throws(PrismAgentError.InvalidMessageType::class) + @Throws(EdgeAgentError.InvalidMessageType::class) constructor(fromMessage: Message) { if ( fromMessage.piuri == ProtocolType.DidcommconnectionRequest.value && @@ -94,7 +94,7 @@ class ConnectionRequest { body = Json.decodeFromString(fromMessage.body) ) } else { - throw PrismAgentError.InvalidMessageType( + throw EdgeAgentError.InvalidMessageType( type = fromMessage.piuri, shouldBe = ProtocolType.DidcommconnectionRequest.value ) diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/connection/DIDCommConnectionRunner.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/connection/DIDCommConnectionRunner.kt similarity index 71% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/connection/DIDCommConnectionRunner.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/connection/DIDCommConnectionRunner.kt index e6afcd8f5..f608d9f5a 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/connection/DIDCommConnectionRunner.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/connection/DIDCommConnectionRunner.kt @@ -1,11 +1,11 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.connection +package org.hyperledger.identus.walletsdk.edgeagent.protocols.connection import org.hyperledger.identus.walletsdk.domain.buildingblocks.Pluto import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.DIDPair -import org.hyperledger.identus.walletsdk.prismagent.PrismAgentError -import org.hyperledger.identus.walletsdk.prismagent.connectionsmanager.DIDCommConnection -import org.hyperledger.identus.walletsdk.prismagent.protocols.outOfBand.OutOfBandInvitation +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgentError +import org.hyperledger.identus.walletsdk.edgeagent.connectionsmanager.DIDCommConnection +import org.hyperledger.identus.walletsdk.edgeagent.protocols.outOfBand.OutOfBandInvitation /** * Represents a runner for the DIDComm connection process. @@ -26,9 +26,9 @@ internal class DIDCommConnectionRunner( * Executes the DIDComm connection process and returns a pair of DIDs. * * @return A [DIDPair] representing the sender and receiver DIDs of the connection. - * @throws [PrismAgentError.InvitationIsInvalidError] if the invitation is invalid and cannot be parsed. + * @throws [EdgeAgentError.InvitationIsInvalidError] if the invitation is invalid and cannot be parsed. */ - @Throws(PrismAgentError.InvitationIsInvalidError::class) + @Throws(EdgeAgentError.InvitationIsInvalidError::class) internal suspend fun run(): DIDPair { val request = ConnectionRequest(invitationMessage, ownDID) connection.sendMessage(request.makeMessage()) @@ -40,7 +40,7 @@ internal class DIDCommConnectionRunner( // if (message.piuri == ProtocolType.DidcommconnectionResponse.value) { // return DIDPair(ownDID, request.to, null) // } else { -// throw PrismAgentError.InvitationIsInvalidError() +// throw EdgeAgentError.InvitationIsInvalidError() // } } } diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/CredentialFormat.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/issueCredential/CredentialFormat.kt similarity index 76% rename from atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/CredentialFormat.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/issueCredential/CredentialFormat.kt index 29b5ef2df..0ee35c8ea 100644 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/CredentialFormat.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/issueCredential/CredentialFormat.kt @@ -1,8 +1,8 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.issueCredential +package org.hyperledger.identus.walletsdk.edgeagent.protocols.issueCredential -import io.iohk.atala.prism.walletsdk.prismagent.ATTACH_ID import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable +import org.hyperledger.identus.walletsdk.edgeagent.ATTACH_ID /** * know Format: diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/CredentialPreview.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/issueCredential/CredentialPreview.kt similarity index 95% rename from atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/CredentialPreview.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/issueCredential/CredentialPreview.kt index 63daf2ff0..86b841d95 100644 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/issueCredential/CredentialPreview.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/issueCredential/CredentialPreview.kt @@ -1,10 +1,10 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.issueCredential +package org.hyperledger.identus.walletsdk.edgeagent.protocols.issueCredential -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType import kotlinx.serialization.EncodeDefault import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType /** * https://github.com/hyperledger/aries-rfcs/tree/main/features/0453-issue-credential-v2#preview-credential diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/IssueCredential.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/issueCredential/IssueCredential.kt similarity index 93% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/IssueCredential.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/issueCredential/IssueCredential.kt index 8c3604df6..6ef992494 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/IssueCredential.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/issueCredential/IssueCredential.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.issueCredential +package org.hyperledger.identus.walletsdk.edgeagent.protocols.issueCredential import io.iohk.atala.prism.apollo.base64.base64UrlEncoded import kotlinx.serialization.SerialName @@ -9,12 +9,12 @@ import org.hyperledger.identus.walletsdk.domain.models.AttachmentBase64 import org.hyperledger.identus.walletsdk.domain.models.AttachmentDescriptor import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.GOAL_CODE -import org.hyperledger.identus.walletsdk.prismagent.MORE_AVAILABLE -import org.hyperledger.identus.walletsdk.prismagent.PrismAgentError -import org.hyperledger.identus.walletsdk.prismagent.REPLACEMENT_ID -import org.hyperledger.identus.walletsdk.prismagent.helpers.build -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType +import org.hyperledger.identus.walletsdk.edgeagent.GOAL_CODE +import org.hyperledger.identus.walletsdk.edgeagent.MORE_AVAILABLE +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgentError +import org.hyperledger.identus.walletsdk.edgeagent.REPLACEMENT_ID +import org.hyperledger.identus.walletsdk.edgeagent.helpers.build +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType import java.util.UUID /** @@ -79,18 +79,18 @@ data class IssueCredential( * * @param fromMessage The Message object to convert. * @return The converted IssueCredential object. - * @throws PrismAgentError.InvalidMessageType if the fromMessage doesn't represent the DidcommIssueCredential protocol, + * @throws EdgeAgentError.InvalidMessageType if the fromMessage doesn't represent the DidcommIssueCredential protocol, * or if it doesn't have "from" and "to" fields. */ @JvmStatic - @Throws(PrismAgentError.InvalidMessageType::class) + @Throws(EdgeAgentError.InvalidMessageType::class) fun fromMessage(fromMessage: Message): IssueCredential { require( fromMessage.piuri == ProtocolType.DidcommIssueCredential.value && fromMessage.from != null && fromMessage.to != null ) { - throw PrismAgentError.InvalidMessageType( + throw EdgeAgentError.InvalidMessageType( type = fromMessage.piuri, shouldBe = ProtocolType.DidcommIssueCredential.value ) diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/IssueCredentialProtocol.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/issueCredential/IssueCredentialProtocol.kt similarity index 97% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/IssueCredentialProtocol.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/issueCredential/IssueCredentialProtocol.kt index 361992e8b..8c4b555bb 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/IssueCredentialProtocol.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/issueCredential/IssueCredentialProtocol.kt @@ -1,9 +1,9 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.issueCredential +package org.hyperledger.identus.walletsdk.edgeagent.protocols.issueCredential import kotlinx.serialization.Serializable import org.hyperledger.identus.walletsdk.domain.models.Message import org.hyperledger.identus.walletsdk.domain.models.UnknownError -import org.hyperledger.identus.walletsdk.prismagent.connectionsmanager.DIDCommConnection +import org.hyperledger.identus.walletsdk.edgeagent.connectionsmanager.DIDCommConnection /** * A class that represents the issue credential protocol in the DIDCommv2 format. @@ -24,7 +24,7 @@ class IssueCredentialProtocol { val connector: DIDCommConnection /** - * The IssueCredentialProtocol class represents a protocol for issuing credentials in the Atala PRISM architecture. + * The IssueCredentialProtocol class represents a protocol for issuing credentials in the Identus architecture. * It handles different stages of the protocol and communicates with a DIDComm connection to exchange messages. * * @param stage The current stage of the protocol. diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/OfferCredential.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/issueCredential/OfferCredential.kt similarity index 91% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/OfferCredential.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/issueCredential/OfferCredential.kt index 7764313c4..ef6e705db 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/OfferCredential.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/issueCredential/OfferCredential.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.issueCredential +package org.hyperledger.identus.walletsdk.edgeagent.protocols.issueCredential import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @@ -7,13 +7,13 @@ import kotlinx.serialization.json.Json import org.hyperledger.identus.walletsdk.domain.models.AttachmentDescriptor import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.CREDENTIAL_PREVIEW -import org.hyperledger.identus.walletsdk.prismagent.GOAL_CODE -import org.hyperledger.identus.walletsdk.prismagent.MULTIPLE_AVAILABLE -import org.hyperledger.identus.walletsdk.prismagent.PrismAgentError -import org.hyperledger.identus.walletsdk.prismagent.REPLACEMENT_ID -import org.hyperledger.identus.walletsdk.prismagent.helpers.build -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType +import org.hyperledger.identus.walletsdk.edgeagent.CREDENTIAL_PREVIEW +import org.hyperledger.identus.walletsdk.edgeagent.GOAL_CODE +import org.hyperledger.identus.walletsdk.edgeagent.MULTIPLE_AVAILABLE +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgentError +import org.hyperledger.identus.walletsdk.edgeagent.REPLACEMENT_ID +import org.hyperledger.identus.walletsdk.edgeagent.helpers.build +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType import java.util.UUID /** @@ -35,7 +35,7 @@ data class OfferCredential @JvmOverloads constructor( * Creates a [Message] object with the provided data and returns it. * The [Message] object includes information about the sender, recipient, message body, * and other metadata. The [Message] object is typically used for secure, decentralized communication - * in the Atala PRISM architecture. + * in the Identus architecture. * * @return The [Message] object with the provided data. */ @@ -79,17 +79,17 @@ data class OfferCredential @JvmOverloads constructor( * * @param fromMessage The Message object to convert. * @return The converted OfferCredential object. - * @throws PrismAgentError.InvalidMessageType if the message type is invalid or the "from" and "to" fields are not present. + * @throws EdgeAgentError.InvalidMessageType if the message type is invalid or the "from" and "to" fields are not present. */ @JvmStatic - @Throws(PrismAgentError.InvalidMessageType::class) + @Throws(EdgeAgentError.InvalidMessageType::class) fun fromMessage(fromMessage: Message): OfferCredential { require( fromMessage.piuri == ProtocolType.DidcommOfferCredential.value && fromMessage.from != null && fromMessage.to != null ) { - throw PrismAgentError.InvalidMessageType( + throw EdgeAgentError.InvalidMessageType( type = fromMessage.piuri, shouldBe = ProtocolType.DidcommOfferCredential.value ) diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/ProposeCredential.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/issueCredential/ProposeCredential.kt similarity index 91% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/ProposeCredential.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/issueCredential/ProposeCredential.kt index 1430aad94..169c485dc 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/ProposeCredential.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/issueCredential/ProposeCredential.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.issueCredential +package org.hyperledger.identus.walletsdk.edgeagent.protocols.issueCredential import kotlinx.serialization.Serializable import kotlinx.serialization.encodeToString @@ -6,9 +6,9 @@ import kotlinx.serialization.json.Json import org.hyperledger.identus.walletsdk.domain.models.AttachmentDescriptor import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.PrismAgentError -import org.hyperledger.identus.walletsdk.prismagent.helpers.build -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgentError +import org.hyperledger.identus.walletsdk.edgeagent.helpers.build +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType import java.util.UUID /** @@ -28,7 +28,7 @@ data class ProposeCredential @JvmOverloads constructor( /** * This function creates a new [Message] object based on the provided data. The [Message] object represents a DIDComm message, - * which is used for secure, decentralized communication in the Atala PRISM architecture. The function sets the id, piuri, + * which is used for secure, decentralized communication in the Identus architecture. The function sets the id, piuri, * from, to, body, attachments, and thid properties of the [Message] object. The id property is generated using a random UUID, * and the body property is encoded as a JSON string using the [Json.encodeToString] function. The other properties are set * based on the values passed as arguments to the function. @@ -53,17 +53,17 @@ data class ProposeCredential @JvmOverloads constructor( * * @param fromMessage The input Message object to convert. * @return A ProposeCredential object created from the input Message. - * @throws PrismAgentError.InvalidMessageType If the input message does not represent the expected protocol type or if it does not have "from" and "to" fields. + * @throws EdgeAgentError.InvalidMessageType If the input message does not represent the expected protocol type or if it does not have "from" and "to" fields. */ @JvmStatic - @Throws(PrismAgentError.InvalidMessageType::class) + @Throws(EdgeAgentError.InvalidMessageType::class) fun fromMessage(fromMessage: Message): ProposeCredential { require( fromMessage.piuri == ProtocolType.DidcommProposeCredential.value && fromMessage.from != null && fromMessage.to != null ) { - throw PrismAgentError.InvalidMessageType( + throw EdgeAgentError.InvalidMessageType( type = fromMessage.piuri, shouldBe = ProtocolType.DidcommProposeCredential.value ) @@ -170,7 +170,7 @@ data class ProposeCredential @JvmOverloads constructor( } /** - * This method builds a ProposeCredential object based on the provided parameters. The ProposeCredential represents a proposal to issue a credential in the Atala PRISM architecture + * This method builds a ProposeCredential object based on the provided parameters. The ProposeCredential represents a proposal to issue a credential in the Identus architecture *. The method takes in the following parameters: * * @param fromDID The DID of the sender of the proposal. diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/RequestCredential.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/issueCredential/RequestCredential.kt similarity index 93% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/RequestCredential.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/issueCredential/RequestCredential.kt index f83818703..8e70723d0 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/RequestCredential.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/issueCredential/RequestCredential.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.issueCredential +package org.hyperledger.identus.walletsdk.edgeagent.protocols.issueCredential import kotlinx.serialization.Serializable import kotlinx.serialization.encodeToString @@ -6,9 +6,9 @@ import kotlinx.serialization.json.Json import org.hyperledger.identus.walletsdk.domain.models.AttachmentDescriptor import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.PrismAgentError -import org.hyperledger.identus.walletsdk.prismagent.helpers.build -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgentError +import org.hyperledger.identus.walletsdk.edgeagent.helpers.build +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType import java.util.UUID /** @@ -49,17 +49,17 @@ data class RequestCredential @JvmOverloads constructor( * * @param fromMessage The Message object to convert. * @return The converted RequestCredential object. - * @throws PrismAgentError.InvalidMessageType If the Message object does not represent the expected protocol or is missing the "from" and "to" fields. + * @throws EdgeAgentError.InvalidMessageType If the Message object does not represent the expected protocol or is missing the "from" and "to" fields. */ @JvmStatic - @Throws(PrismAgentError.InvalidMessageType::class) + @Throws(EdgeAgentError.InvalidMessageType::class) fun fromMessage(fromMessage: Message): RequestCredential { require( fromMessage.piuri == ProtocolType.DidcommRequestCredential.value && fromMessage.from != null && fromMessage.to != null ) { - throw PrismAgentError.InvalidMessageType( + throw EdgeAgentError.InvalidMessageType( type = fromMessage.piuri, shouldBe = ProtocolType.DidcommRequestCredential.value ) diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/mediation/MediationGrant.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/mediation/MediationGrant.kt similarity index 90% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/mediation/MediationGrant.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/mediation/MediationGrant.kt index 82ea2d886..9fba8dc68 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/mediation/MediationGrant.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/mediation/MediationGrant.kt @@ -1,11 +1,11 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.mediation +package org.hyperledger.identus.walletsdk.edgeagent.protocols.mediation import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.ROUTING_DID -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType +import org.hyperledger.identus.walletsdk.edgeagent.ROUTING_DID +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType import java.util.UUID import kotlin.jvm.Throws @@ -25,7 +25,7 @@ sealed class MediationProtocolError : Throwable() { } /** - * The MediationGrant class represents a mediation grant in the Atala PRISM architecture. + * The MediationGrant class represents a mediation grant in the Identus architecture. * A mediation grant is used for granting permission to mediate a specific request. * * @property id The unique identifier of the mediation grant. @@ -40,7 +40,7 @@ class MediationGrant { var body: Body /** - * Represents a mediation grant in the Atala PRISM architecture. + * Represents a mediation grant in the Identus architecture. * A mediation grant is used for granting permission to mediate a specific request. * * @property id The unique identifier of the mediation grant. @@ -60,7 +60,7 @@ class MediationGrant { } /** - * The `MediationGrant` class represents a mediation grant in the Atala PRISM architecture. + * The `MediationGrant` class represents a mediation grant in the Identus architecture. * A mediation grant is used for granting permission to mediate a specific request. * * @property id The unique identifier of the mediation grant. @@ -80,7 +80,7 @@ class MediationGrant { /** * The [Body] class represents a body object that can be included in a [Message] object. - * It is used for secure, decentralized communication in the Atala PRISM architecture. + * It is used for secure, decentralized communication in the Identus architecture. * * @see Message */ diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/mediation/MediationKeysUpdateList.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/mediation/MediationKeysUpdateList.kt similarity index 92% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/mediation/MediationKeysUpdateList.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/mediation/MediationKeysUpdateList.kt index 7390fccd9..0f84bc398 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/mediation/MediationKeysUpdateList.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/mediation/MediationKeysUpdateList.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.mediation +package org.hyperledger.identus.walletsdk.edgeagent.protocols.mediation import kotlinx.serialization.EncodeDefault import kotlinx.serialization.ExperimentalSerializationApi @@ -8,10 +8,10 @@ import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.ADD -import org.hyperledger.identus.walletsdk.prismagent.RECEPIENT_DID -import org.hyperledger.identus.walletsdk.prismagent.UPDATES -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType +import org.hyperledger.identus.walletsdk.edgeagent.ADD +import org.hyperledger.identus.walletsdk.edgeagent.RECEPIENT_DID +import org.hyperledger.identus.walletsdk.edgeagent.UPDATES +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType import java.util.UUID /** @@ -59,7 +59,7 @@ final class MediationKeysUpdateList { /** * This method creates a [Message] object with the specified parameters. - * The [Message] object represents a DIDComm message used for secure and decentralized communication in the Atala PRISM architecture. + * The [Message] object represents a DIDComm message used for secure and decentralized communication in the Identus architecture. * The [Message] object includes information about the sender, recipient, message body, and other metadata. * The method sets default values for some properties and returns the created [Message] object. * diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/mediation/MediationRequest.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/mediation/MediationRequest.kt similarity index 94% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/mediation/MediationRequest.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/mediation/MediationRequest.kt index 57e2f472e..f25b91dcb 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/mediation/MediationRequest.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/mediation/MediationRequest.kt @@ -1,9 +1,9 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.mediation +package org.hyperledger.identus.walletsdk.edgeagent.protocols.mediation import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.EMPTY_BODY -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType +import org.hyperledger.identus.walletsdk.edgeagent.EMPTY_BODY +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType import java.util.UUID /** diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/outOfBand/DIDCommInvitationRunner.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/outOfBand/DIDCommInvitationRunner.kt similarity index 63% rename from atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/outOfBand/DIDCommInvitationRunner.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/outOfBand/DIDCommInvitationRunner.kt index 536dab3f6..404d8f504 100644 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/outOfBand/DIDCommInvitationRunner.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/outOfBand/DIDCommInvitationRunner.kt @@ -1,10 +1,10 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.outOfBand +package org.hyperledger.identus.walletsdk.edgeagent.protocols.outOfBand -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgentError -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType import io.ktor.http.Url import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgentError +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType /** * This class represents a runner for the DIDComm Invitation protocol. It is responsible for running the invitation @@ -18,14 +18,14 @@ internal class DIDCommInvitationRunner(private val url: Url) { * Runs the DIDComm Invitation protocol. * * @return The parsed OutOfBandInvitation message. - * @throws PrismAgentError.UnknownInvitationTypeError If the type of the invitation is unknown or unsupported. + * @throws EdgeAgentError.UnknownInvitationTypeError If the type of the invitation is unknown or unsupported. */ - @Throws(PrismAgentError.UnknownInvitationTypeError::class) + @Throws(EdgeAgentError.UnknownInvitationTypeError::class) internal suspend fun run(): OutOfBandInvitation { val messageString = OutOfBandParser().parseMessage(url) val message: OutOfBandInvitation = Json.decodeFromString(messageString) if (message.type != ProtocolType.Didcomminvitation) { - throw PrismAgentError.UnknownInvitationTypeError(message.type.toString()) + throw EdgeAgentError.UnknownInvitationTypeError(message.type.toString()) } return message } diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/InvitationRunner.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/outOfBand/InvitationRunner.kt similarity index 92% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/InvitationRunner.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/outOfBand/InvitationRunner.kt index 4d789c0db..4862105ae 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/InvitationRunner.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/outOfBand/InvitationRunner.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.outOfBand +package org.hyperledger.identus.walletsdk.edgeagent.protocols.outOfBand import io.ktor.http.Url import org.hyperledger.identus.walletsdk.domain.buildingblocks.Mercury diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/outOfBand/InvitationType.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/outOfBand/InvitationType.kt similarity index 68% rename from atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/outOfBand/InvitationType.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/outOfBand/InvitationType.kt index 22aab2a7a..c344cf1b8 100644 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/outOfBand/InvitationType.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/outOfBand/InvitationType.kt @@ -1,4 +1,4 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.outOfBand +package org.hyperledger.identus.walletsdk.edgeagent.protocols.outOfBand import kotlinx.serialization.Serializable diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/outOfBand/OutOfBandInvitation.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/outOfBand/OutOfBandInvitation.kt similarity index 84% rename from atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/outOfBand/OutOfBandInvitation.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/outOfBand/OutOfBandInvitation.kt index 7fc8ff1ce..4bfc686ef 100644 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/outOfBand/OutOfBandInvitation.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/outOfBand/OutOfBandInvitation.kt @@ -1,11 +1,11 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.outOfBand +package org.hyperledger.identus.walletsdk.edgeagent.protocols.outOfBand -import io.iohk.atala.prism.walletsdk.prismagent.GOAL_CODE -import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType import kotlinx.serialization.EncodeDefault import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable +import org.hyperledger.identus.walletsdk.edgeagent.GOAL_CODE +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType import java.util.UUID /** diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/OutOfBandParser.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/outOfBand/OutOfBandParser.kt similarity index 86% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/OutOfBandParser.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/outOfBand/OutOfBandParser.kt index 74bd78b41..6d9e75c1a 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/OutOfBandParser.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/outOfBand/OutOfBandParser.kt @@ -1,10 +1,10 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.outOfBand +package org.hyperledger.identus.walletsdk.edgeagent.protocols.outOfBand import io.iohk.atala.prism.apollo.base64.base64UrlDecoded import io.ktor.http.URLBuilder import io.ktor.http.Url import org.hyperledger.identus.walletsdk.domain.models.CommonError -import org.hyperledger.identus.walletsdk.prismagent.OOB +import org.hyperledger.identus.walletsdk.edgeagent.OOB /** * The OutOfBandParser class is responsible for parsing out-of-band messages. diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/PrismOnboardingInvitation.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/outOfBand/PrismOnboardingInvitation.kt similarity index 91% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/PrismOnboardingInvitation.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/outOfBand/PrismOnboardingInvitation.kt index fd9bc7a4e..b20630277 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/PrismOnboardingInvitation.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/outOfBand/PrismOnboardingInvitation.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.outOfBand +package org.hyperledger.identus.walletsdk.edgeagent.protocols.outOfBand import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @@ -6,7 +6,7 @@ import kotlinx.serialization.Transient import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import org.hyperledger.identus.walletsdk.domain.models.DID -import org.hyperledger.identus.walletsdk.prismagent.FROM +import org.hyperledger.identus.walletsdk.edgeagent.FROM /** * Represents an onboarding invitation for PRISM. diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/pickup/PickupDelivery.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/pickup/PickupDelivery.kt similarity index 67% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/pickup/PickupDelivery.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/pickup/PickupDelivery.kt index 673a52708..a9dce9d4b 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/pickup/PickupDelivery.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/pickup/PickupDelivery.kt @@ -1,22 +1,22 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.pickup +package org.hyperledger.identus.walletsdk.edgeagent.protocols.pickup import org.hyperledger.identus.walletsdk.domain.models.AttachmentDescriptor import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.PrismAgentError -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgentError +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType /** - * The `PickupDelivery` class represents a pickup delivery protocol type in the Atala PRISM architecture. + * The `PickupDelivery` class represents a pickup delivery protocol type in the Identus architecture. * It is a final class, meaning it cannot be subclassed. * - * @throws (PrismAgentError.InvalidMessageType):: if the protocol type of the given message is not `ProtocolType.PickupDelivery`. + * @throws (EdgeAgentError.InvalidMessageType):: if the protocol type of the given message is not `ProtocolType.PickupDelivery`. * * @property id: The id of the pickup delivery. * @property type: The protocol type of the pickup delivery, always set to `ProtocolType.PickupDelivery.value`. * @property attachments: An array of attachment descriptors associated with the pickup delivery. */ final class PickupDelivery -@Throws(PrismAgentError.InvalidMessageType::class) +@Throws(EdgeAgentError.InvalidMessageType::class) constructor(fromMessage: Message) { var id: String var type = ProtocolType.PickupDelivery.value @@ -24,7 +24,7 @@ constructor(fromMessage: Message) { init { if (fromMessage.piuri != ProtocolType.PickupDelivery.value) { - throw PrismAgentError.InvalidMessageType( + throw EdgeAgentError.InvalidMessageType( type = fromMessage.piuri, shouldBe = ProtocolType.PickupDelivery.value ) diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/pickup/PickupReceived.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/pickup/PickupReceived.kt similarity index 93% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/pickup/PickupReceived.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/pickup/PickupReceived.kt index d7ccf97f5..b3adf1cfd 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/pickup/PickupReceived.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/pickup/PickupReceived.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.pickup +package org.hyperledger.identus.walletsdk.edgeagent.protocols.pickup import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @@ -6,8 +6,8 @@ import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.MESSAGE_ID_LIST -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType +import org.hyperledger.identus.walletsdk.edgeagent.MESSAGE_ID_LIST +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType import java.util.UUID /** diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/pickup/PickupRequest.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/pickup/PickupRequest.kt similarity index 93% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/pickup/PickupRequest.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/pickup/PickupRequest.kt index a64d67dd0..0fa538e67 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/pickup/PickupRequest.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/pickup/PickupRequest.kt @@ -1,11 +1,11 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.pickup +package org.hyperledger.identus.walletsdk.edgeagent.protocols.pickup import kotlinx.serialization.Serializable import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType import java.util.UUID /** diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/pickup/PickupRunner.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/pickup/PickupRunner.kt similarity index 94% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/pickup/PickupRunner.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/pickup/PickupRunner.kt index 0cead400c..4f4775400 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/pickup/PickupRunner.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/pickup/PickupRunner.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.pickup +package org.hyperledger.identus.walletsdk.edgeagent.protocols.pickup import io.iohk.atala.prism.apollo.base64.base64UrlDecoded import org.hyperledger.identus.walletsdk.domain.buildingblocks.Mercury @@ -6,8 +6,8 @@ import org.hyperledger.identus.walletsdk.domain.models.AttachmentBase64 import org.hyperledger.identus.walletsdk.domain.models.AttachmentDescriptor import org.hyperledger.identus.walletsdk.domain.models.AttachmentJsonData import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.PrismAgentError -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgentError +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType /** * The `PickupRunner` class is responsible for processing `Message` objects related to pickup requests and delivering them @@ -64,7 +64,7 @@ class PickupRunner(message: Message, private val mercury: Mercury) { } else -> { - throw PrismAgentError.InvalidMessageType( + throw EdgeAgentError.InvalidMessageType( type = message.piuri, shouldBe = "${ProtocolType.PickupStatus.value} or ${ProtocolType.PickupDelivery.value}" ) diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/prismOnboarding/PrismOnboardingInvitation.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/prismOnboarding/PrismOnboardingInvitation.kt similarity index 77% rename from atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/prismOnboarding/PrismOnboardingInvitation.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/prismOnboarding/PrismOnboardingInvitation.kt index b2fe94683..cd285f74f 100644 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/protocols/prismOnboarding/PrismOnboardingInvitation.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/prismOnboarding/PrismOnboardingInvitation.kt @@ -1,9 +1,9 @@ -package io.iohk.atala.prism.walletsdk.prismagent.protocols.prismOnboarding +package org.hyperledger.identus.walletsdk.edgeagent.protocols.prismOnboarding -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgentError import kotlinx.serialization.Serializable import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgentError /** * Represents an onboarding invitation in PRISM. @@ -12,10 +12,10 @@ import kotlinx.serialization.json.Json * * @constructor Creates a PrismOnboardingInvitation object from a JSON string representation of the invitation. * @param jsonString The JSON string representation of the invitation. - * @throws PrismAgentError.InvitationIsInvalidError If the JSON string is invalid and cannot be parsed. + * @throws EdgeAgentError.InvitationIsInvalidError If the JSON string is invalid and cannot be parsed. */ class PrismOnboardingInvitation -@Throws(PrismAgentError.InvitationIsInvalidError::class) +@Throws(EdgeAgentError.InvitationIsInvalidError::class) constructor(jsonString: String) { var body: Body @@ -28,7 +28,7 @@ constructor(jsonString: String) { body = try { json.decodeFromString(jsonString) } catch (e: Throwable) { - throw PrismAgentError.InvitationIsInvalidError() + throw EdgeAgentError.InvitationIsInvalidError() } } diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/proofOfPresentation/Presentation.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/proofOfPresentation/Presentation.kt similarity index 92% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/proofOfPresentation/Presentation.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/proofOfPresentation/Presentation.kt index d01c4d729..7542863f1 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/proofOfPresentation/Presentation.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/proofOfPresentation/Presentation.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.proofOfPresentation +package org.hyperledger.identus.walletsdk.edgeagent.protocols.proofOfPresentation import kotlinx.serialization.Serializable import kotlinx.serialization.encodeToString @@ -6,8 +6,8 @@ import kotlinx.serialization.json.Json import org.hyperledger.identus.walletsdk.domain.models.AttachmentDescriptor import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.PrismAgentError -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgentError +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType import java.util.UUID /** @@ -80,7 +80,7 @@ data class ProofTypes( } /** - * The Presentation class represents a presentation message in the PrismAgent software. + * The Presentation class represents a presentation message in the [EdgemAgent] software. * It contains the necessary information for constructing a presentation message. * * @property type The type of the presentation message. @@ -101,7 +101,7 @@ class Presentation { lateinit var to: DID /** - * The Presentation class represents a presentation message in the PrismAgent software. + * The Presentation class represents a presentation message in the [EdgeAgent] software. * It contains the necessary information for constructing a presentation message. * * @param id The unique identifier for the presentation message. @@ -132,9 +132,9 @@ class Presentation { * Constructor for creating a Presentation object from a Message object. * * @param fromMessage The Message object to create Presentation from. - * @throws PrismAgentError.InvalidMessageType if the message type does not represent the protocol "didcomm.presentation" or if the message does not have "from" and "to" fields. + * @throws EdgeAgentError.InvalidMessageType if the message type does not represent the protocol "didcomm.presentation" or if the message does not have "from" and "to" fields. */ - @Throws(PrismAgentError.InvalidMessageType::class) + @Throws(EdgeAgentError.InvalidMessageType::class) constructor(fromMessage: Message) { if ( fromMessage.piuri == ProtocolType.DidcommPresentation.value && @@ -151,7 +151,7 @@ class Presentation { fromMessage.to ) } else { - throw PrismAgentError.InvalidMessageType( + throw EdgeAgentError.InvalidMessageType( type = fromMessage.piuri, shouldBe = ProtocolType.DidcommPresentation.value ) @@ -180,9 +180,9 @@ class Presentation { * * @param msg The input message to convert. * @return The converted Presentation object. - * @throws PrismAgentError.InvalidMessageType If the message type is invalid. + * @throws EdgeAgentError.InvalidMessageType If the message type is invalid. */ - @Throws(PrismAgentError.InvalidMessageType::class) + @Throws(EdgeAgentError.InvalidMessageType::class) fun makePresentationFromRequest(msg: Message): Presentation { val requestPresentation = RequestPresentation.fromMessage(msg) return Presentation( diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/proofOfPresentation/ProposePresentation.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/proofOfPresentation/ProposePresentation.kt similarity index 89% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/proofOfPresentation/ProposePresentation.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/proofOfPresentation/ProposePresentation.kt index 4f3c4677a..480cf8850 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/proofOfPresentation/ProposePresentation.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/proofOfPresentation/ProposePresentation.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.proofOfPresentation +package org.hyperledger.identus.walletsdk.edgeagent.protocols.proofOfPresentation import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @@ -7,10 +7,10 @@ import kotlinx.serialization.json.Json import org.hyperledger.identus.walletsdk.domain.models.AttachmentDescriptor import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.GOAL_CODE -import org.hyperledger.identus.walletsdk.prismagent.PROOF_TYPES -import org.hyperledger.identus.walletsdk.prismagent.PrismAgentError -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType +import org.hyperledger.identus.walletsdk.edgeagent.GOAL_CODE +import org.hyperledger.identus.walletsdk.edgeagent.PROOF_TYPES +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgentError +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType import java.util.UUID /** @@ -24,7 +24,7 @@ import java.util.UUID * @property from The sender of the presentation. * @property to The recipient of the presentation. * @constructor Creates a ProposePresentation instance. - * @throws PrismAgentError.InvalidMessageType If the message type is invalid. + * @throws EdgeAgentError.InvalidMessageType If the message type is invalid. */ class ProposePresentation { @@ -37,7 +37,7 @@ class ProposePresentation { lateinit var to: DID /** - * The `ProposePresentation` class represents a proposal for a presentation in the Prism agent. + * The `ProposePresentation` class represents a proposal for a presentation in the Edge agent. * It is used to create a new `ProposePresentation` object with the given parameters. * * @param id The ID of the proposal. If not provided, a new random UUID will be generated. @@ -67,11 +67,11 @@ class ProposePresentation { /** * Constructs a ProposePresentation object by processing a Message. * - * @throws PrismAgentError.InvalidMessageType if the fromMessage does not represent the expected protocol type + * @throws EdgeAgentError.InvalidMessageType if the fromMessage does not represent the expected protocol type * * @param fromMessage the input Message object */ - @Throws(PrismAgentError.InvalidMessageType::class) + @Throws(EdgeAgentError.InvalidMessageType::class) constructor(fromMessage: Message) { if (fromMessage.piuri == ProtocolType.DidcommProposePresentation.value && fromMessage.from != null && @@ -86,7 +86,7 @@ class ProposePresentation { to = fromMessage.to ) } else { - throw PrismAgentError.InvalidMessageType( + throw EdgeAgentError.InvalidMessageType( type = fromMessage.piuri, shouldBe = ProtocolType.DidcommProposePresentation.value ) @@ -116,9 +116,9 @@ class ProposePresentation { * * @param msg The request message. * @return The created `ProposePresentation` object. - * @throws PrismAgentError.InvalidMessageType If the message type does not represent the expected protocol. + * @throws EdgeAgentError.InvalidMessageType If the message type does not represent the expected protocol. */ - @Throws(PrismAgentError.InvalidMessageType::class) + @Throws(EdgeAgentError.InvalidMessageType::class) fun makeProposalFromRequest(msg: Message): ProposePresentation { val request = RequestPresentation.fromMessage(msg) diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/proofOfPresentation/RequestPresentation.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/proofOfPresentation/RequestPresentation.kt similarity index 91% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/proofOfPresentation/RequestPresentation.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/proofOfPresentation/RequestPresentation.kt index ce5e2a91f..2909150d1 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/proofOfPresentation/RequestPresentation.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/proofOfPresentation/RequestPresentation.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.proofOfPresentation +package org.hyperledger.identus.walletsdk.edgeagent.protocols.proofOfPresentation import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @@ -7,11 +7,11 @@ import kotlinx.serialization.json.Json import org.hyperledger.identus.walletsdk.domain.models.AttachmentDescriptor import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.GOAL_CODE -import org.hyperledger.identus.walletsdk.prismagent.PROOF_TYPES -import org.hyperledger.identus.walletsdk.prismagent.PrismAgentError -import org.hyperledger.identus.walletsdk.prismagent.WILL_CONFIRM -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType +import org.hyperledger.identus.walletsdk.edgeagent.GOAL_CODE +import org.hyperledger.identus.walletsdk.edgeagent.PROOF_TYPES +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgentError +import org.hyperledger.identus.walletsdk.edgeagent.WILL_CONFIRM +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType import java.util.UUID @Serializable @@ -111,11 +111,11 @@ data class RequestPresentation( * * @param fromMessage The [Message] object to convert. * @return The converted [RequestPresentation] object. - * @throws PrismAgentError.InvalidMessageType if the [Message] object does not represent the correct protocol + * @throws EdgeAgentError.InvalidMessageType if the [Message] object does not represent the correct protocol * or if it is missing the "from" and "to" fields. */ @JvmStatic - @Throws(PrismAgentError.InvalidMessageType::class) + @Throws(EdgeAgentError.InvalidMessageType::class) fun fromMessage(fromMessage: Message): RequestPresentation { if (fromMessage.piuri == ProtocolType.DidcommRequestPresentation.value && fromMessage.from != null && @@ -130,7 +130,7 @@ data class RequestPresentation( to = fromMessage.to ) } else { - throw PrismAgentError.InvalidMessageType( + throw EdgeAgentError.InvalidMessageType( type = fromMessage.piuri, shouldBe = ProtocolType.DidcommRequestPresentation.value ) @@ -142,10 +142,10 @@ data class RequestPresentation( * * @param msg The [Message] object representing a proposal. * @return The newly created [RequestPresentation] object. - * @throws PrismAgentError.InvalidMessageType if the message type is invalid. + * @throws EdgeAgentError.InvalidMessageType if the message type is invalid. */ @JvmStatic - @Throws(PrismAgentError.InvalidMessageType::class) + @Throws(EdgeAgentError.InvalidMessageType::class) fun makeRequestFromProposal(msg: Message): RequestPresentation { val request = ProposePresentation(msg) diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/revocation/RevocationNotification.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/revocation/RevocationNotification.kt similarity index 82% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/revocation/RevocationNotification.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/revocation/RevocationNotification.kt index 5fc90c1e9..2d6fa0b94 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/revocation/RevocationNotification.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/revocation/RevocationNotification.kt @@ -1,11 +1,9 @@ -@file:Suppress("ktlint:standard:import-ordering") - -package org.hyperledger.identus.walletsdk.prismagent.protocols.revocation +package org.hyperledger.identus.walletsdk.edgeagent.protocols.revocation import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.PrismAgentError -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgentError +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType import kotlinx.serialization.SerialName import java.util.UUID import kotlinx.serialization.Serializable @@ -44,7 +42,7 @@ class RevocationNotification( message.from != null && message.to != null ) { - throw PrismAgentError.InvalidMessageType( + throw EdgeAgentError.InvalidMessageType( type = message.piuri, shouldBe = ProtocolType.PrismRevocation.value ) diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/shared/KeyValue.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/shared/KeyValue.kt similarity index 78% rename from atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/shared/KeyValue.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/shared/KeyValue.kt index 6df3c68e9..fabb967ec 100644 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/shared/KeyValue.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/shared/KeyValue.kt @@ -1,4 +1,4 @@ -package io.iohk.atala.prism.walletsdk.prismagent.shared +package org.hyperledger.identus.walletsdk.edgeagent.shared import kotlinx.serialization.Serializable diff --git a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/shared/PrismShared.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/shared/PrismShared.kt similarity index 97% rename from atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/shared/PrismShared.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/shared/PrismShared.kt index 65f626ce3..29aef906c 100644 --- a/atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/prismagent/shared/PrismShared.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/shared/PrismShared.kt @@ -1,4 +1,4 @@ -package io.iohk.atala.prism.walletsdk.prismagent.shared +package org.hyperledger.identus.walletsdk.edgeagent.shared import io.ktor.client.request.HttpRequestBuilder import io.ktor.client.request.setBody diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/logger/PrismLogger.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/logger/EdgeLogger.kt similarity index 97% rename from edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/logger/PrismLogger.kt rename to edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/logger/EdgeLogger.kt index e62bf099a..8dc1915c8 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/logger/PrismLogger.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/logger/EdgeLogger.kt @@ -24,10 +24,10 @@ private const val METADATA_PRIVACY_STR = "------" private val hashingLog = UUID.randomUUID().toString() /** - * PrismLogger is an interface that defines methods for logging messages + * EdgeLogger is an interface that defines methods for logging messages * with different log levels and metadata. */ -interface PrismLogger { +interface EdgeLogger { /** * Logs a debug message with optional metadata. * @@ -66,20 +66,20 @@ interface PrismLogger { * @param error The error to be logged. * @param metadata An array of metadata objects to be included in the log message. Defaults to an empty array if not provided. * - * @see PrismLogger.error + * @see EdgeLogger.error * @see Metadata */ fun error(error: Error, metadata: Array = arrayOf()) } /** - * Implementation of the PrismLogger interface. + * Implementation of the EdgeLogger interface. * * @property category the LogComponent category for this logger */ -class PrismLoggerImpl(category: LogComponent) : PrismLogger { - - private val log = logging("[io.prism.kmm.sdk.$category]") +class EdgeLoggerImpl(category: LogComponent) : EdgeLogger { + edgeagent + private val log = logging("[org.hyperledger.identus.walletsdk.$category]") private var logLevel: LogLevel = LogLevel.INFO diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/mercury/MercuryImpl.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/mercury/MercuryImpl.kt index 20916d5a2..9dffa48b3 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/mercury/MercuryImpl.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/mercury/MercuryImpl.kt @@ -14,11 +14,11 @@ import org.hyperledger.identus.walletsdk.domain.models.Message import org.hyperledger.identus.walletsdk.logger.LogComponent import org.hyperledger.identus.walletsdk.logger.LogLevel import org.hyperledger.identus.walletsdk.logger.Metadata -import org.hyperledger.identus.walletsdk.logger.PrismLogger -import org.hyperledger.identus.walletsdk.logger.PrismLoggerImpl +import org.hyperledger.identus.walletsdk.logger.EdgeLogger +import org.hyperledger.identus.walletsdk.logger.EdgeLoggerImpl import org.hyperledger.identus.walletsdk.mercury.forward.ForwardMessage -import org.hyperledger.identus.walletsdk.prismagent.DIDCOMM_MESSAGING -import org.hyperledger.identus.walletsdk.prismagent.shared.KeyValue +import org.hyperledger.identus.walletsdk.edgeagent.DIDCOMM_MESSAGING +import org.hyperledger.identus.walletsdk.edgeagent.shared.KeyValue /** * The DIDCommProtocol interface provides methods for packing and unpacking DIDComm messages. @@ -55,7 +55,7 @@ constructor( private val castor: Castor, private val protocol: DIDCommProtocol, private val api: Api, - private val logger: PrismLogger = PrismLoggerImpl(LogComponent.MERCURY) + private val logger: EdgeLogger = EdgeLoggerImpl(LogComponent.MERCURY) ) : Mercury { /** diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/mercury/resolvers/DIDCommDIDResolver.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/mercury/resolvers/DIDCommDIDResolver.kt index 9e1638e18..d0c933f44 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/mercury/resolvers/DIDCommDIDResolver.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/mercury/resolvers/DIDCommDIDResolver.kt @@ -21,7 +21,7 @@ import org.hyperledger.identus.walletsdk.domain.models.OctetPublicKey import org.hyperledger.identus.walletsdk.mercury.CRV import org.hyperledger.identus.walletsdk.mercury.MULTIBASE_BYTES_SIZE import org.hyperledger.identus.walletsdk.mercury.X -import org.hyperledger.identus.walletsdk.prismagent.DIDCOMM_MESSAGING +import org.hyperledger.identus.walletsdk.edgeagent.DIDCOMM_MESSAGING import java.util.Optional /** diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/mercury/resolvers/DIDCommWrapper.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/mercury/resolvers/DIDCommWrapper.kt index 3d6aff319..5dd98e8b6 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/mercury/resolvers/DIDCommWrapper.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/mercury/resolvers/DIDCommWrapper.kt @@ -36,7 +36,7 @@ import org.hyperledger.identus.walletsdk.domain.models.Message import org.hyperledger.identus.walletsdk.logger.LogComponent import org.hyperledger.identus.walletsdk.logger.LogLevel import org.hyperledger.identus.walletsdk.logger.Metadata -import org.hyperledger.identus.walletsdk.logger.PrismLoggerImpl +import org.hyperledger.identus.walletsdk.logger.EdgeLoggerImpl import org.hyperledger.identus.walletsdk.mercury.ATTACHMENT_SEPARATOR import org.hyperledger.identus.walletsdk.mercury.BASE64 import org.hyperledger.identus.walletsdk.mercury.DIDCommProtocol @@ -57,7 +57,7 @@ class DIDCommWrapper(castor: Castor, pluto: Pluto, apollo: Apollo) : DIDCommProt private val didDocResolver = DIDCommDIDResolver(castor) private val secretsResolver = DIDCommSecretsResolver(pluto, apollo) private val didComm = DIDComm(didDocResolver, secretsResolver) - private val logger = PrismLoggerImpl(LogComponent.MERCURY) + private val logger = EdgeLoggerImpl(LogComponent.MERCURY) /** * Converts a JSON element to a map. diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/mercury/resolvers/DefaultSecretsResolverImpl.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/mercury/resolvers/DefaultSecretsResolverImpl.kt index 5789a147d..414aff3e3 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/mercury/resolvers/DefaultSecretsResolverImpl.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/mercury/resolvers/DefaultSecretsResolverImpl.kt @@ -1,6 +1,6 @@ package org.hyperledger.identus.walletsdk.mercury.resolvers -import io.iohk.atala.prism.apollo.base64.base64UrlEncoded +import io.iohk.atala..apollo.base64.base64UrlEncoded import kotlinx.coroutines.flow.firstOrNull import kotlinx.serialization.Serializable import org.hyperledger.identus.walletsdk.domain.buildingblocks.Pluto diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/pollux/PolluxImpl.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/pollux/PolluxImpl.kt index 2d3fa0695..f6751b36c 100644 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/pollux/PolluxImpl.kt +++ b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/pollux/PolluxImpl.kt @@ -49,8 +49,8 @@ import org.hyperledger.identus.walletsdk.domain.models.keyManagement.PrivateKey import org.hyperledger.identus.walletsdk.pollux.models.AnonCredential import org.hyperledger.identus.walletsdk.pollux.models.JWTCredential import org.hyperledger.identus.walletsdk.pollux.models.W3CCredential -import org.hyperledger.identus.walletsdk.prismagent.protocols.proofOfPresentation.RequestPresentation -import org.hyperledger.identus.walletsdk.prismagent.shared.KeyValue +import org.hyperledger.identus.walletsdk.edgeagent.protocols.proofOfPresentation.RequestPresentation +import org.hyperledger.identus.walletsdk.edgeagent.shared.KeyValue import java.math.BigInteger import java.security.KeyFactory import java.security.interfaces.ECPrivateKey diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/AgentConstants.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/AgentConstants.kt deleted file mode 100644 index 6116114c9..000000000 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/AgentConstants.kt +++ /dev/null @@ -1,23 +0,0 @@ -package org.hyperledger.identus.walletsdk.prismagent - -const val DIDCOMM1 = "#didcomm-1" -const val DIDCOMM_MESSAGING = "DIDCommMessaging" -const val PRISM = "prism" -const val JWT_MEDIA_TYPE = "prism/jwt" -const val PROTOCOL_TYPE = "ProtocolType" -const val GOAL_CODE = "goal_code" -const val WILL_CONFIRM = "will_confirm" -const val PROOF_TYPES = "proof_types" -const val MESSAGE_ID_LIST = "message_id_list" -const val OOB = "_oob" -const val FROM = "from" -const val ROUTING_DID = "routing_did" -const val RECEPIENT_DID = "recipient_did" -const val ADD = "add" -const val UPDATES = "updates" -const val EMPTY_BODY = "{}" -const val ATTACH_ID = "attach_id" -const val REPLACEMENT_ID = "replacement_id" -const val MORE_AVAILABLE = "more_available" -const val MULTIPLE_AVAILABLE = "multiple_available" -const val CREDENTIAL_PREVIEW = "credential_preview" diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/helpers/AgentOptions.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/helpers/AgentOptions.kt deleted file mode 100644 index ea3f95cdf..000000000 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/helpers/AgentOptions.kt +++ /dev/null @@ -1,13 +0,0 @@ -package org.hyperledger.identus.walletsdk.prismagent.helpers - -/** - * Class that represent agent options that the SDK user can define to modify some behaviors of the SDK. - * @param experiments Represents the experimental features available - */ -data class AgentOptions(val experiments: Experiments = Experiments()) - -/** - * Class to define experimental features available within the SDK. - * @param liveMode Flag to enable or disable the live mode to listen for messages from the mediator. - */ -data class Experiments(val liveMode: Boolean = false) diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/ProtocolType.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/ProtocolType.kt deleted file mode 100644 index 8446eeae2..000000000 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/ProtocolType.kt +++ /dev/null @@ -1,82 +0,0 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols - -import kotlinx.serialization.ExperimentalSerializationApi -import kotlinx.serialization.KSerializer -import kotlinx.serialization.Serializable -import kotlinx.serialization.Serializer -import kotlinx.serialization.descriptors.PrimitiveKind -import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor -import kotlinx.serialization.descriptors.SerialDescriptor -import kotlinx.serialization.encoding.Decoder -import kotlinx.serialization.encoding.Encoder -import org.hyperledger.identus.walletsdk.prismagent.PROTOCOL_TYPE -import org.hyperledger.identus.walletsdk.prismagent.PrismAgentError - -@Serializable(with = ProtocolTypeSerializer::class) -enum class ProtocolType(val value: String) { - DidcommMediationRequest("https://didcomm.org/coordinate-mediation/2.0/mediate-request"), - DidcommMediationGrant("https://didcomm.org/coordinate-mediation/2.0/mediate-grant"), - DidcommMediationDeny("https://didcomm.org/coordinate-mediation/2.0/mediate-deny"), - DidcommMediationKeysUpdate("https://didcomm.org/coordinate-mediation/2.0/keylist-update"), - DidcommPresentation("https://didcomm.atalaprism.io/present-proof/3.0/presentation"), - DidcommRequestPresentation("https://didcomm.atalaprism.io/present-proof/3.0/request-presentation"), - DidcommProposePresentation("https://didcomm.atalaprism.io/present-proof/3.0/propose-presentation"), - DidcommCredentialPreview("https://didcomm.org/issue-credential/3.0/credential-preview"), - DidcommIssueCredential("https://didcomm.org/issue-credential/3.0/issue-credential"), - DidcommOfferCredential("https://didcomm.org/issue-credential/3.0/offer-credential"), - DidcommProposeCredential("https://didcomm.org/issue-credential/3.0/propose-credential"), - DidcommRequestCredential("https://didcomm.org/issue-credential/3.0/request-credential"), - DidcommconnectionRequest("https://atalaprism.io/mercury/connections/1.0/request"), - DidcommconnectionResponse("https://atalaprism.io/mercury/connections/1.0/response"), - Didcomminvitation("https://didcomm.org/out-of-band/2.0/invitation"), - PrismOnboarding("https://atalaprism.io/did-request"), - PickupRequest("https://didcomm.org/messagepickup/3.0/delivery-request"), - PickupDelivery("https://didcomm.org/messagepickup/3.0/delivery"), - PickupStatus("https://didcomm.org/messagepickup/3.0/status"), - PickupReceived("https://didcomm.org/messagepickup/3.0/messages-received"), - LiveDeliveryChange("https://didcomm.org/messagepickup/3.0/live-delivery-change"), - PrismRevocation("https://atalaprism.io/revocation_notification/1.0/revoke"), - None(""); - - companion object { - @JvmStatic - fun findProtocolType(type: String, default: ProtocolType): ProtocolType { - return ProtocolType.values().find { it.value == type } ?: default - } - } -} - -@OptIn(ExperimentalSerializationApi::class) -@Serializer(forClass = ProtocolType::class) -object ProtocolTypeSerializer : KSerializer { - override val descriptor: SerialDescriptor - get() = PrimitiveSerialDescriptor(PROTOCOL_TYPE, PrimitiveKind.STRING) - - override fun serialize(encoder: Encoder, value: ProtocolType) { - encoder.encodeString(value.value) - } - - override fun deserialize(decoder: Decoder): ProtocolType { - val protocolType = decoder.decodeString() - return ProtocolType.findProtocolType(protocolType, ProtocolType.None) - } -} - -/** - * Finds the ProtocolType based on the given string value. - * - * @param string The string value to match with the ProtocolType's value. - * @return The matched ProtocolType. - * @throws PrismAgentError.UnknownInvitationTypeError If the type of the invitation is not supported. - */ -@Throws(PrismAgentError.UnknownInvitationTypeError::class) -fun findProtocolTypeByValue(string: String): ProtocolType { - val it = ProtocolType.values().iterator() - while (it.hasNext()) { - val internalType = it.next() - if (internalType.value == string) { - return internalType - } - } - throw PrismAgentError.UnknownInvitationTypeError(string) -} diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/CredentialFormat.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/CredentialFormat.kt deleted file mode 100644 index 6181fc5ef..000000000 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/CredentialFormat.kt +++ /dev/null @@ -1,19 +0,0 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.issueCredential - -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable -import org.hyperledger.identus.walletsdk.prismagent.ATTACH_ID - -/** - * know Format: - * https://github.com/hyperledger/aries-rfcs/tree/main/features/0453-issue-credential-v2#propose-attachment-registry - * - dif/credential-manifest@v1.0 - * - aries/ld-proof-vc-detail@v1.0 - * - hlindy/cred-filter@v2.0 - */ -@Serializable -data class CredentialFormat( - @SerialName(ATTACH_ID) - val attachId: String, - val format: String -) diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/CredentialPreview.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/CredentialPreview.kt deleted file mode 100644 index ac01234b1..000000000 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/CredentialPreview.kt +++ /dev/null @@ -1,111 +0,0 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.issueCredential - -import kotlinx.serialization.EncodeDefault -import kotlinx.serialization.ExperimentalSerializationApi -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType - -/** - * https://github.com/hyperledger/aries-rfcs/tree/main/features/0453-issue-credential-v2#preview-credential - */ -@Serializable -data class CredentialPreview -@OptIn(ExperimentalSerializationApi::class) -@JvmOverloads -constructor( - @SerialName("schema_id") - @EncodeDefault - val schemaId: String? = null, - val body: Body -) { - val type: String = ProtocolType.DidcommCredentialPreview.value - - /** - * Initializes a new instance of [CredentialPreview]. - * - * @param schemaId The ID of the schema associated with the credential. Defaults to `null` if not provided. - * @param attributes An array of attributes to include in the credential preview. - */ - constructor(schemaId: String? = null, attributes: Array) : this(schemaId, Body(attributes)) - - /** - * Compares this [CredentialPreview] object to the specified [other] object for equality. - * - * @param other The object to compare for equality. - * @return `true` if the objects are equal, `false` otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as CredentialPreview - - return type == other.type - } - - /** - * Computes the hash code value for this object. - * - * @return The hash code value for this object. - */ - override fun hashCode(): Int { - return type.hashCode() - } - - /** - * Represents a body object. - * - * @property attributes The array of attributes. - * - * @see Attribute - */ - @Serializable - data class Body( - val attributes: Array - ) { - /** - * Checks if this `Body` object is equal to another object. - * - * @param other The object to compare to this `Body` object. - * @return `true` if the objects are equal, `false` otherwise. - */ - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other == null || this::class != other::class) return false - - other as Body - - return attributes.contentEquals(other.attributes) - } - - /** - * Calculates the hash code for this `Body` object. - * - * The hash code is calculated based on the `attributes` property of the `Body` object. - * - * @return The hash code value for this object. - * - * @see Body - * @see Attribute - */ - override fun hashCode(): Int { - return attributes.contentHashCode() - } - } - - /** - * Represents an attribute in a credential preview. - * - * @property name The name of the attribute. - * @property value The value of the attribute. - * @property mediaType The media type of the attribute, if applicable. - */ - @Serializable - data class Attribute( - val name: String, - val value: String, - @SerialName("media_type") - val mediaType: String? - ) -} diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/DIDCommInvitationRunner.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/DIDCommInvitationRunner.kt deleted file mode 100644 index 24f417d4d..000000000 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/DIDCommInvitationRunner.kt +++ /dev/null @@ -1,32 +0,0 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.outOfBand - -import io.ktor.http.Url -import kotlinx.serialization.decodeFromString -import kotlinx.serialization.json.Json -import org.hyperledger.identus.walletsdk.prismagent.PrismAgentError -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType - -/** - * This class represents a runner for the DIDComm Invitation protocol. It is responsible for running the invitation - * process and parsing the invitation message. - * - * @property url The URL of the invitation message. - */ -internal class DIDCommInvitationRunner(private val url: Url) { - - /** - * Runs the DIDComm Invitation protocol. - * - * @return The parsed OutOfBandInvitation message. - * @throws PrismAgentError.UnknownInvitationTypeError If the type of the invitation is unknown or unsupported. - */ - @Throws(PrismAgentError.UnknownInvitationTypeError::class) - internal suspend fun run(): OutOfBandInvitation { - val messageString = OutOfBandParser().parseMessage(url) - val message: OutOfBandInvitation = Json.decodeFromString(messageString) - if (message.type != ProtocolType.Didcomminvitation) { - throw PrismAgentError.UnknownInvitationTypeError(message.type.toString()) - } - return message - } -} diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/InvitationType.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/InvitationType.kt deleted file mode 100644 index 95246c203..000000000 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/InvitationType.kt +++ /dev/null @@ -1,9 +0,0 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.outOfBand - -import kotlinx.serialization.Serializable - -/** - * Represents a sealed class for different types of invitations. - */ -@Serializable -sealed class InvitationType diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/OutOfBandInvitation.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/OutOfBandInvitation.kt deleted file mode 100644 index ad504153a..000000000 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/OutOfBandInvitation.kt +++ /dev/null @@ -1,42 +0,0 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.outOfBand - -import kotlinx.serialization.EncodeDefault -import kotlinx.serialization.ExperimentalSerializationApi -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable -import org.hyperledger.identus.walletsdk.prismagent.GOAL_CODE -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType -import java.util.UUID - -/** - * Represents an out-of-band invitation message in the DIDComm protocol. The [OutOfBandInvitation] class represents an - * out-of-band invitation message in the DIDComm protocol. - */ -@Serializable -class OutOfBandInvitation -@OptIn(ExperimentalSerializationApi::class) -@JvmOverloads -constructor( - val id: String = UUID.randomUUID().toString(), - val body: Body, - val from: String, - @EncodeDefault - val type: ProtocolType = ProtocolType.Didcomminvitation, - @EncodeDefault - val typ: String? = null -) : InvitationType() { - - /** - * Represents the body of the out-of-band invitation message. - */ - @OptIn(ExperimentalSerializationApi::class) - @Serializable - data class Body constructor( - @SerialName(GOAL_CODE) - @EncodeDefault - val goalCode: String? = null, - @EncodeDefault - val goal: String? = null, - val accept: List? - ) -} diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/prismOnboarding/PrismOnboardingInvitation.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/prismOnboarding/PrismOnboardingInvitation.kt deleted file mode 100644 index 445b94ae0..000000000 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/prismOnboarding/PrismOnboardingInvitation.kt +++ /dev/null @@ -1,48 +0,0 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.prismOnboarding - -import kotlinx.serialization.Serializable -import kotlinx.serialization.decodeFromString -import kotlinx.serialization.json.Json -import org.hyperledger.identus.walletsdk.prismagent.PrismAgentError - -/** - * Represents an onboarding invitation in PRISM. - * - * This class is responsible for parsing and storing the information from a PRISM onboarding invitation. - * - * @constructor Creates a PrismOnboardingInvitation object from a JSON string representation of the invitation. - * @param jsonString The JSON string representation of the invitation. - * @throws PrismAgentError.InvitationIsInvalidError If the JSON string is invalid and cannot be parsed. - */ -class PrismOnboardingInvitation -@Throws(PrismAgentError.InvitationIsInvalidError::class) -constructor(jsonString: String) { - var body: Body - - init { - val json = Json { - ignoreUnknownKeys = true - prettyPrint = true - isLenient = true - } - body = try { - json.decodeFromString(jsonString) - } catch (e: Throwable) { - throw PrismAgentError.InvitationIsInvalidError() - } - } - - /** - * Represents the body of an invitation in the PrismOnboardingInvitation class. - * - * @property type The type of the invitation. - * @property onboardEndpoint The onboard endpoint of the invitation. - * @property from The sender of the invitation. - */ - @Serializable - data class Body( - val type: String, - val onboardEndpoint: String, - val from: String - ) -} diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/shared/KeyValue.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/shared/KeyValue.kt deleted file mode 100644 index a7964053d..000000000 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/shared/KeyValue.kt +++ /dev/null @@ -1,15 +0,0 @@ -package org.hyperledger.identus.walletsdk.prismagent.shared - -import kotlinx.serialization.Serializable - -/** - * Represents a key-value pair. - * - * @param key The key. - * @param value The value. - */ -@Serializable -data class KeyValue( - val key: String, - val value: String -) diff --git a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/shared/PrismShared.kt b/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/shared/PrismShared.kt deleted file mode 100644 index e61ac0d61..000000000 --- a/edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/prismagent/shared/PrismShared.kt +++ /dev/null @@ -1,78 +0,0 @@ -package org.hyperledger.identus.walletsdk.prismagent.shared - -import io.ktor.client.request.HttpRequestBuilder -import io.ktor.client.request.setBody -import io.ktor.http.ContentType -import io.ktor.http.HttpHeaders -import io.ktor.http.HttpMethod -import io.ktor.http.Url -import io.ktor.http.contentType -import io.ktor.http.path - -/** - * Utility class for shared functionality used by Prism API. - */ -internal object PrismShared { - /** - * Maps an array of [KeyValue] objects to a [Map] with key-value pairs. - * - * @param array The array of [KeyValue] objects to be mapped. - * @return A [Map] containing the key-value pairs from the array. - */ - @JvmStatic - fun mapFromKeyValueArray(array: Array): Map { - val response = mutableMapOf() - array.forEach { - response[it.key] = it.value - } - return response - } - - /** - * Constructs an HTTP request builder with the specified parameters. - * - * @param httpMethod the HTTP method to be used for the request (e.g., "GET", "POST", "PUT", "DELETE", etc.) - * @param url the URL to send the request to - * @param urlParametersArray the array of URL parameters to be included in the request (default is an empty array) - * @param httpHeadersArray the array of HTTP headers to be included in the request (default is an empty array) - * @param body the request body to be sent with the request (default is null) - * @return the constructed HttpRequestBuilder object - */ - @JvmStatic - fun getRequestBuilder( - httpMethod: HttpMethod, - url: Url, - urlParametersArray: Array, - httpHeadersArray: Array, - body: Any? - ): HttpRequestBuilder { - val urlParameters: Map = mapFromKeyValueArray(urlParametersArray) - val httpHeaders: Map = mapFromKeyValueArray(httpHeadersArray) - - val builder = HttpRequestBuilder() - for (header in httpHeaders) { - builder.headers.append(header.key, header.value) - } - if (!builder.headers.contains(HttpHeaders.ContentType)) { - builder.contentType(ContentType.Application.Json) - } - - body?.let { - builder.setBody(body) - } - - builder.url { - builder.method = httpMethod - protocol = url.protocol - host = url.host - port = url.specifiedPort - - path(url.encodedPath) - - for (parameter in urlParameters) { - parameters.append(parameter.key, parameter.value) - } - } - return builder - } -} diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/castor/DIDCreateTest.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/castor/DIDCreateTest.kt index b8afdf8bc..bf9174eb9 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/castor/DIDCreateTest.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/castor/DIDCreateTest.kt @@ -18,7 +18,7 @@ import org.hyperledger.identus.walletsdk.domain.models.keyManagement.KeyPair import org.hyperledger.identus.walletsdk.domain.models.keyManagement.KeyTypes import org.hyperledger.identus.walletsdk.domain.models.keyManagement.RawKey import org.hyperledger.identus.walletsdk.domain.models.keyManagement.TypeKey -import org.hyperledger.identus.walletsdk.prismagent.DIDCOMM_MESSAGING +import org.hyperledger.identus.walletsdk.edgeagent.DIDCOMM_MESSAGING import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/logger/PrismLoggerMock.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/logger/PrismLoggerMock.kt index 9870d372e..7ab1d9012 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/logger/PrismLoggerMock.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/logger/PrismLoggerMock.kt @@ -1,28 +1,28 @@ package org.hyperledger.identus.walletsdk.logger -class PrismLoggerMock : PrismLogger { +class PrismLoggerMock : EdgeLogger { override fun debug(message: String, metadata: Array) { val metaString = metadata.joinToString { "${it.getValue(LogLevel.DEBUG)}\n" } - println("debug: [io.prism.kmm.sdk.Test] $message Metadata: $metaString") + println("debug: [org.hyperledger.identus.walletsdk.Test] $message Metadata: $metaString") } override fun info(message: String, metadata: Array) { val metaString = metadata.joinToString { "${it.getValue(LogLevel.DEBUG)}\n" } - println("info: [io.prism.kmm.sdk.Test] $message Metadata: $metaString") + println("info: [org.hyperledger.identus.walletsdk.Test] $message Metadata: $metaString") } override fun warning(message: String, metadata: Array) { val metaString = metadata.joinToString { "${it.getValue(LogLevel.DEBUG)}\n" } - println("warning: [io.prism.kmm.sdk.Test] $message Metadata: $metaString") + println("warning: [org.hyperledger.identus.walletsdk.Test] $message Metadata: $metaString") } override fun error(message: String, metadata: Array) { val metaString = metadata.joinToString { "${it.getValue(LogLevel.DEBUG)}\n" } - println("error: [io.prism.kmm.sdk.Test] $message Metadata: $metaString") + println("error: [org.hyperledger.identus.walletsdk.Test] $message Metadata: $metaString") } override fun error(error: Error, metadata: Array) { val metaString = metadata.joinToString { "${it.getValue(LogLevel.DEBUG)}\n" } - println("error: [io.prism.kmm.sdk.Test] ${error.message} Metadata: $metaString") + println("error: [org.hyperledger.identus.walletsdk.Test] ${error.message} Metadata: $metaString") } } diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/mercury/ApiMock.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/mercury/ApiMock.kt index 0a2c73260..4bc021e1f 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/mercury/ApiMock.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/mercury/ApiMock.kt @@ -11,7 +11,7 @@ import io.ktor.serialization.kotlinx.json.json import kotlinx.serialization.json.Json import org.hyperledger.identus.walletsdk.domain.models.Api import org.hyperledger.identus.walletsdk.domain.models.HttpResponse -import org.hyperledger.identus.walletsdk.prismagent.shared.KeyValue +import org.hyperledger.identus.walletsdk.edgeagent.shared.KeyValue import io.ktor.client.HttpClient as KtorClient class ApiMock( diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/mercury/DIDResolverTests.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/mercury/DIDResolverTests.kt index f8506d662..d33ac74cc 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/mercury/DIDResolverTests.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/mercury/DIDResolverTests.kt @@ -14,7 +14,7 @@ import org.hyperledger.identus.walletsdk.domain.models.DIDDocument import org.hyperledger.identus.walletsdk.domain.models.DIDUrl import org.hyperledger.identus.walletsdk.domain.models.OctetPublicKey import org.hyperledger.identus.walletsdk.mercury.resolvers.DIDCommDIDResolver -import org.hyperledger.identus.walletsdk.prismagent.DIDCOMM_MESSAGING +import org.hyperledger.identus.walletsdk.edgeagent.DIDCOMM_MESSAGING import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertContains diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/mercury/MercuryTests.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/mercury/MercuryTests.kt index 5d8f5e535..78f2def4b 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/mercury/MercuryTests.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/mercury/MercuryTests.kt @@ -6,7 +6,7 @@ import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.DIDDocument import org.hyperledger.identus.walletsdk.domain.models.MercuryError import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.logger.PrismLoggerMock +import org.hyperledger.identus.walletsdk.logger.EdgeLoggerMock import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertFailsWith @@ -24,7 +24,7 @@ class MercuryTests { apiMock = ApiMock(HttpStatusCode.OK, "") castorMock = CastorMock() protocolMock = ProtocolMock() - sut = MercuryImpl(castorMock, protocolMock, apiMock, PrismLoggerMock()) + sut = MercuryImpl(castorMock, protocolMock, apiMock, EdgeLoggerMock()) } @Test diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/mercury/SecretsResolverTests.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/mercury/SecretsResolverTests.kt index 702aade73..6284eac6d 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/mercury/SecretsResolverTests.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/mercury/SecretsResolverTests.kt @@ -4,7 +4,7 @@ import org.didcommx.didcomm.common.VerificationMaterialFormat import org.didcommx.didcomm.common.VerificationMethodType import org.hyperledger.identus.walletsdk.apollo.utils.X25519PrivateKey import org.hyperledger.identus.walletsdk.mercury.resolvers.DIDCommSecretsResolver -import org.hyperledger.identus.walletsdk.prismagent.ApolloMock +import org.hyperledger.identus.walletsdk.edgeagent.ApolloMock import org.junit.Before import org.junit.Ignore import org.junit.Test diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/pollux/PolluxImplTest.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/pollux/PolluxImplTest.kt index 0d51a0f73..ae261656b 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/pollux/PolluxImplTest.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/pollux/PolluxImplTest.kt @@ -3,7 +3,7 @@ package org.hyperledger.identus.walletsdk.pollux import io.ktor.http.HttpStatusCode import kotlinx.coroutines.test.runTest import org.hyperledger.identus.walletsdk.mercury.ApiMock -import org.hyperledger.identus.walletsdk.prismagent.CastorMock +import org.hyperledger.identus.walletsdk.edgeagent.CastorMock import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/AndroidIgnore.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/AndroidIgnore.kt index 35652183c..916b4f9ad 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/AndroidIgnore.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/AndroidIgnore.kt @@ -1,3 +1,3 @@ -package org.hyperledger.identus.walletsdk.prismagent +package org.hyperledger.identus.walletsdk.edgeagent expect annotation class AndroidIgnore() diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/ApolloMock.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/ApolloMock.kt index 3be28e1e4..43406ff23 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/ApolloMock.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/ApolloMock.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent +package org.hyperledger.identus.walletsdk.edgeagent import org.hyperledger.identus.walletsdk.apollo.utils.Ed25519KeyPair import org.hyperledger.identus.walletsdk.apollo.utils.Ed25519PrivateKey diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/CastorMock.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/CastorMock.kt index 51ecde2f3..9671d56d3 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/CastorMock.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/CastorMock.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent +package org.hyperledger.identus.walletsdk.edgeagent import org.hyperledger.identus.walletsdk.domain.buildingblocks.Castor import org.hyperledger.identus.walletsdk.domain.models.DID diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/ConnectionManagerTest.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/ConnectionManagerTest.kt index 31e6e568d..8ec78a043 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/ConnectionManagerTest.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/ConnectionManagerTest.kt @@ -1,6 +1,6 @@ @file:Suppress("ktlint:standard:import-ordering") -package org.hyperledger.identus.walletsdk.prismagent +package org.hyperledger.identus.walletsdk.edgeagent import io.iohk.atala.prism.apollo.base64.base64UrlEncoded import org.hyperledger.identus.walletsdk.domain.buildingblocks.Castor @@ -15,8 +15,8 @@ import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.DIDDocument import org.hyperledger.identus.walletsdk.domain.models.DIDUrl import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.mediation.MediationHandler -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType +import org.hyperledger.identus.walletsdk.edgeagent.mediation.MediationHandler +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.flow import kotlinx.coroutines.test.TestCoroutineDispatcher diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/DIDMock.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/DIDMock.kt index 4dbcc3b22..42039bd68 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/DIDMock.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/DIDMock.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent +package org.hyperledger.identus.walletsdk.edgeagent import org.hyperledger.identus.walletsdk.domain.models.DID diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/MediationHandlerMock.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/MediationHandlerMock.kt index ebd6edf9a..252797edd 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/MediationHandlerMock.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/MediationHandlerMock.kt @@ -1,12 +1,12 @@ -package org.hyperledger.identus.walletsdk.prismagent +package org.hyperledger.identus.walletsdk.edgeagent import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.Mediator import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.mediation.MediationHandler -import org.hyperledger.identus.walletsdk.prismagent.mediation.OnMessageCallback +import org.hyperledger.identus.walletsdk.edgeagent.mediation.MediationHandler +import org.hyperledger.identus.walletsdk.edgeagent.mediation.OnMessageCallback import java.util.UUID class MediationHandlerMock( @@ -30,7 +30,7 @@ class MediationHandlerMock( @Throws() override fun achieveMediation(host: DID): Flow { mediator = achieveMediationResponse - return flow { achieveMediationResponse?.let { emit(it) } ?: throw PrismAgentError.NoMediatorAvailableError() } + return flow { achieveMediationResponse?.let { emit(it) } ?: throw EdgeAgentError.NoMediatorAvailableError() } } @Throws() diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/MercuryMock.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/MercuryMock.kt index 40b9c52e2..b7c1a7aa9 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/MercuryMock.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/MercuryMock.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent +package org.hyperledger.identus.walletsdk.edgeagent import org.hyperledger.identus.walletsdk.domain.buildingblocks.Mercury import org.hyperledger.identus.walletsdk.domain.models.Message diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/MessageMock.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/MessageMock.kt index 1d67369e8..234ffc974 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/MessageMock.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/MessageMock.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent +package org.hyperledger.identus.walletsdk.edgeagent import org.hyperledger.identus.walletsdk.domain.models.AttachmentDescriptor import org.hyperledger.identus.walletsdk.domain.models.DID diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/PlutoMock.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/PlutoMock.kt index bb7777bfa..004667231 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/PlutoMock.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/PlutoMock.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent +package org.hyperledger.identus.walletsdk.edgeagent import kotlinx.coroutines.flow.Flow import org.hyperledger.identus.walletsdk.domain.buildingblocks.Pluto diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/PolluxMock.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/PolluxMock.kt index 11dc3310e..a9feef25c 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/PolluxMock.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/PolluxMock.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent +package org.hyperledger.identus.walletsdk.edgeagent import anoncreds_wrapper.CredentialOffer import anoncreds_wrapper.CredentialRequestMetadata @@ -16,7 +16,7 @@ import org.hyperledger.identus.walletsdk.domain.models.keyManagement.PrivateKey import org.hyperledger.identus.walletsdk.pollux.models.AnonCredential import org.hyperledger.identus.walletsdk.pollux.models.CredentialRequest import org.hyperledger.identus.walletsdk.pollux.models.CredentialRequestMeta -import org.hyperledger.identus.walletsdk.prismagent.protocols.proofOfPresentation.RequestPresentation +import org.hyperledger.identus.walletsdk.edgeagent.protocols.proofOfPresentation.RequestPresentation class PolluxMock : Pollux { diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/PrismAgentTests.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/PrismAgentTests.kt index b62bba8aa..8b997bae2 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/PrismAgentTests.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/PrismAgentTests.kt @@ -1,6 +1,6 @@ @file:Suppress("ktlint:standard:import-ordering") -package org.hyperledger.identus.walletsdk.prismagent +package org.hyperledger.identus.walletsdk.edgeagent import anoncreds_wrapper.LinkSecret import io.iohk.atala.prism.apollo.derivation.MnemonicHelper @@ -22,13 +22,13 @@ import org.hyperledger.identus.walletsdk.logger.PrismLoggerMock import org.hyperledger.identus.walletsdk.mercury.ApiMock import org.hyperledger.identus.walletsdk.pollux.PolluxImpl import org.hyperledger.identus.walletsdk.pollux.models.CredentialRequestMeta -import org.hyperledger.identus.walletsdk.prismagent.helpers.AgentOptions -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType -import org.hyperledger.identus.walletsdk.prismagent.protocols.issueCredential.CredentialPreview -import org.hyperledger.identus.walletsdk.prismagent.protocols.issueCredential.IssueCredential -import org.hyperledger.identus.walletsdk.prismagent.protocols.issueCredential.OfferCredential -import org.hyperledger.identus.walletsdk.prismagent.protocols.outOfBand.OutOfBandInvitation -import org.hyperledger.identus.walletsdk.prismagent.protocols.outOfBand.PrismOnboardingInvitation +import org.hyperledger.identus.walletsdk.edgeagent.helpers.AgentOptions +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType +import org.hyperledger.identus.walletsdk.edgeagent.protocols.issueCredential.CredentialPreview +import org.hyperledger.identus.walletsdk.edgeagent.protocols.issueCredential.IssueCredential +import org.hyperledger.identus.walletsdk.edgeagent.protocols.issueCredential.OfferCredential +import org.hyperledger.identus.walletsdk.edgeagent.protocols.outOfBand.OutOfBandInvitation +import org.hyperledger.identus.walletsdk.edgeagent.protocols.outOfBand.PrismOnboardingInvitation import io.ktor.http.HttpStatusCode import kotlinx.coroutines.flow.flow import kotlinx.coroutines.test.runTest @@ -42,7 +42,7 @@ import kotlin.test.assertFalse import kotlin.test.assertTrue @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) -class PrismAgentTests { +class EdgeAgentTests { lateinit var apolloMock: ApolloMock lateinit var castorMock: CastorMock @@ -75,7 +75,7 @@ class PrismAgentTests { val seed = Seed(MnemonicHelper.createRandomSeed()) val validDID = DID("did", "test", "123") castorMock.createPrismDIDReturn = validDID - val agent = PrismAgent( + val agent = EdgeAgent( apollo = apolloMock, castor = castorMock, pluto = plutoMock, @@ -99,7 +99,7 @@ class PrismAgentTests { fun testCreateNewPeerDID_shouldCreateNewDID_whenCalled() = runTest { val validDID = DID("did", "test", "123") castorMock.createPeerDIDReturn = validDID - val agent = PrismAgent( + val agent = EdgeAgent( apolloMock, castorMock, plutoMock, @@ -123,7 +123,7 @@ class PrismAgentTests { fun testCreateNewPeerDID_whenUpdateMediatorFalse_thenShouldUseProvidedServices() = runTest { val apollo = ApolloImpl() val castor = CastorImpl(apollo = apollo, logger = PrismLoggerMock()) - val agent = PrismAgent( + val agent = EdgeAgent( apollo, castor, plutoMock, @@ -157,8 +157,8 @@ class PrismAgentTests { } @Test - fun testPrismAgentOnboardingInvitation_shouldAcceptOnboardingInvitation_whenStatusIs200() = runTest { - val agent = PrismAgent( + fun testEdgeAgentOnboardingInvitation_shouldAcceptOnboardingInvitation_whenStatusIs200() = runTest { + val agent = EdgeAgent( apollo = apolloMock, castor = castorMock, pluto = plutoMock, @@ -183,9 +183,9 @@ class PrismAgentTests { } @Test - fun testPrismAgentOnboardingInvitation_shouldRejectOnboardingInvitation_whenStatusIsNot200() = runTest { + fun testEdgeAgentOnboardingInvitation_shouldRejectOnboardingInvitation_whenStatusIsNot200() = runTest { val api = ApiMock(HttpStatusCode.BadRequest, "{\"success\":\"true\"}") - val agent = PrismAgent( + val agent = EdgeAgent( apollo = apolloMock, castor = castorMock, pluto = plutoMock, @@ -205,14 +205,14 @@ class PrismAgentTests { } """ val invitation = agent.parseInvitation(invitationString) - assertFailsWith { + assertFailsWith { agent.acceptInvitation(invitation as PrismOnboardingInvitation) } } @Test - fun testPrismAgentOnboardingInvitation_shouldRejectOnboardingInvitation_whenBodyIsWrong() = runTest { - val agent = PrismAgent( + fun testEdgeAgentOnboardingInvitation_shouldRejectOnboardingInvitation_whenBodyIsWrong() = runTest { + val agent = EdgeAgent( apollo = apolloMock, castor = castorMock, pluto = plutoMock, @@ -237,8 +237,8 @@ class PrismAgentTests { } @Test - fun testPrismAgentSignWith_whenNoPrivateKeyAvailable_thenThrowCannotFindDIDPrivateKey() = runTest { - val agent = PrismAgent( + fun testEdgeAgentSignWith_whenNoPrivateKeyAvailable_thenThrowCannotFindDIDPrivateKey() = runTest { + val agent = EdgeAgent( apollo = apolloMock, castor = castorMock, pluto = plutoMock, @@ -256,14 +256,14 @@ class PrismAgentTests { val did = DID("did", "peer", "asdf1234asdf1234") val messageString = "This is a message" assertFalse { plutoMock.wasGetDIDPrivateKeysByDIDCalled } - assertFailsWith(PrismAgentError.CannotFindDIDPrivateKey::class, null) { + assertFailsWith(EdgeAgentError.CannotFindDIDPrivateKey::class, null) { agent.signWith(did, messageString.toByteArray()) } } @Test - fun testPrismAgentSignWith_whenPrivateKeyAvailable_thenSignatureReturned() = runTest { - val agent = PrismAgent( + fun testEdgeAgentSignWith_whenPrivateKeyAvailable_thenSignatureReturned() = runTest { + val agent = EdgeAgent( apollo = apolloMock, castor = castorMock, pluto = plutoMock, @@ -293,7 +293,7 @@ class PrismAgentTests { @Test fun testParseInvitation_whenOutOfBand_thenReturnsOutOfBandInvitationObject() = runTest { - val agent = PrismAgent( + val agent = EdgeAgent( apollo = apolloMock, castor = castorMock, pluto = plutoMock, @@ -339,7 +339,7 @@ class PrismAgentTests { @Test fun testParseInvitation_whenOutOfBandWrongBody_thenThrowsUnknownInvitationTypeError() = runTest { - val agent = PrismAgent( + val agent = EdgeAgent( apollo = apolloMock, castor = castorMock, pluto = plutoMock, @@ -367,10 +367,10 @@ class PrismAgentTests { } @Test - fun testStartPrismAgent_whenCalled_thenStatusIsRunning() = runTest { + fun testStartEdgeAgent_whenCalled_thenStatusIsRunning() = runTest { val getLinkSecretReturn = flow { emit("linkSecret") } plutoMock.getLinkSecretReturn = getLinkSecretReturn - val agent = PrismAgent( + val agent = EdgeAgent( apollo = apolloMock, castor = castorMock, pluto = plutoMock, @@ -388,8 +388,8 @@ class PrismAgentTests { } @Test - fun testStopPrismAgent_whenCalled_thenStatusIsStopped() = runTest { - val agent = PrismAgent( + fun testStopEdgeAgent_whenCalled_thenStatusIsStopped() = runTest { + val agent = EdgeAgent( apollo = apolloMock, castor = castorMock, pluto = plutoMock, @@ -402,14 +402,14 @@ class PrismAgentTests { agentOptions = AgentOptions() ) agent.stop() - assertEquals(PrismAgent.State.STOPPED, agent.state) + assertEquals(EdgeAgent.State.STOPPED, agent.state) } @Test fun test_OOPInvitationInURLFormat() = runTest { val oob = "https://my.domain.com/path?_oob=eyJpZCI6ImQzNjM3NzlhLWYyMmItNGFiNC1hYjY0LTkxZjkxNjgzNzYwNyIsInR5cGUiOiJodHRwczovL2RpZGNvbW0ub3JnL291dC1vZi1iYW5kLzIuMC9pbnZpdGF0aW9uIiwiZnJvbSI6ImRpZDpwZWVyOjIuRXo2TFNjcGZReGJ2VEhLaGpvbzVvMzlmc254VEp1RTRobVp3ckROUE5BVzI0dmFORi5WejZNa3UzSkpVTDNkaHpYQXB0RWpuUDFpNkF0TDlTNGlwRTNYOHM3MWV4MW9WVGNHLlNleUowSWpvaVpHMGlMQ0p6SWpvaWFIUjBjSE02THk5ck9ITXRaR1YyTG1GMFlXeGhjSEpwYzIwdWFXOHZjSEpwYzIwdFlXZGxiblF2Wkdsa1kyOXRiU0lzSW5JaU9sdGRMQ0poSWpwYkltUnBaR052YlcwdmRqSWlYWDAiLCJib2R5Ijp7ImdvYWxfY29kZSI6ImlvLmF0YWxhcHJpc20uY29ubmVjdCIsImdvYWwiOiJFc3RhYmxpc2ggYSB0cnVzdCBjb25uZWN0aW9uIGJldHdlZW4gdHdvIHBlZXJzIHVzaW5nIHRoZSBwcm90b2NvbCAnaHR0cHM6Ly9hdGFsYXByaXNtLmlvL21lcmN1cnkvY29ubmVjdGlvbnMvMS4wL3JlcXVlc3QnIiwiYWNjZXB0IjpbXX19" - val agent = PrismAgent( + val agent = EdgeAgent( apollo = apolloMock, castor = castorMock, pluto = plutoMock, @@ -439,7 +439,7 @@ class PrismAgentTests { val pollux = PolluxImpl(castorMock, apiMock) plutoMock.getLinkSecretReturn = flow { emit(LinkSecret().getValue()) } - val agent = PrismAgent( + val agent = EdgeAgent( apollo = apolloMock, castor = castorMock, pluto = plutoMock, @@ -500,7 +500,7 @@ class PrismAgentTests { ) plutoMock.getCredentialMetadataReturn = flow { emit(meta) } - val agent = PrismAgent( + val agent = EdgeAgent( apollo = apolloMock, castor = castorMock, pluto = plutoMock, diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/helpers/DID.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/helpers/DID.kt index ebeac062d..83af2fec2 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/helpers/DID.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/helpers/DID.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent.helpers +package org.hyperledger.identus.walletsdk.edgeagent.helpers import org.hyperledger.identus.walletsdk.domain.models.DID diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/MediationKeysUpdateListTest.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/MediationKeysUpdateListTest.kt index 04910193c..34337b4a1 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/MediationKeysUpdateListTest.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/MediationKeysUpdateListTest.kt @@ -1,9 +1,9 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols +package org.hyperledger.identus.walletsdk.edgeagent.protocols import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import org.hyperledger.identus.walletsdk.domain.models.DID -import org.hyperledger.identus.walletsdk.prismagent.protocols.mediation.MediationKeysUpdateList +import org.hyperledger.identus.walletsdk.edgeagent.protocols.mediation.MediationKeysUpdateList import kotlin.test.Test import kotlin.test.assertEquals diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/IssueCredentialTest.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/IssueCredentialTest.kt index 242c2a219..b7f87f6e1 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/IssueCredentialTest.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/IssueCredentialTest.kt @@ -1,9 +1,9 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.issueCredential +package org.hyperledger.identus.walletsdk.edgeagent.protocols.issueCredential import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.PrismAgentError -import org.hyperledger.identus.walletsdk.prismagent.helpers.fromIndex +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgentError +import org.hyperledger.identus.walletsdk.edgeagent.helpers.fromIndex import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith @@ -41,7 +41,7 @@ class IssueCredentialTest { to = null, body = "" ) - assertFailsWith { + assertFailsWith { IssueCredential.fromMessage(invalidIssueCredential) } } diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/OfferCredentialTest.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/OfferCredentialTest.kt index 0fcc8d2ec..a2ae8ec0d 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/OfferCredentialTest.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/OfferCredentialTest.kt @@ -1,9 +1,9 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.issueCredential +package org.hyperledger.identus.walletsdk.edgeagent.protocols.issueCredential import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.PrismAgentError -import org.hyperledger.identus.walletsdk.prismagent.helpers.fromIndex +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgentError +import org.hyperledger.identus.walletsdk.edgeagent.helpers.fromIndex import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith @@ -50,7 +50,7 @@ class OfferCredentialTest { to = null, body = "" ) - assertFailsWith { + assertFailsWith { OfferCredential.fromMessage(invalidOfferCredential) } } diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/ProposeCredentialTest.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/ProposeCredentialTest.kt index 2218f167e..9d124a579 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/ProposeCredentialTest.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/ProposeCredentialTest.kt @@ -1,9 +1,9 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.issueCredential +package org.hyperledger.identus.walletsdk.edgeagent.protocols.issueCredential import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.PrismAgentError -import org.hyperledger.identus.walletsdk.prismagent.helpers.fromIndex +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgentError +import org.hyperledger.identus.walletsdk.edgeagent.helpers.fromIndex import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith @@ -50,7 +50,7 @@ class ProposeCredentialTest { to = null, body = "" ) - assertFailsWith { + assertFailsWith { ProposeCredential.fromMessage(invalidProposeCredential) } } diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/RequestCredentialTest.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/RequestCredentialTest.kt index dfc7bdca0..0d437d710 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/RequestCredentialTest.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/issueCredential/RequestCredentialTest.kt @@ -1,9 +1,9 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.issueCredential +package org.hyperledger.identus.walletsdk.edgeagent.protocols.issueCredential import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.PrismAgentError -import org.hyperledger.identus.walletsdk.prismagent.helpers.fromIndex +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgentError +import org.hyperledger.identus.walletsdk.edgeagent.helpers.fromIndex import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith @@ -43,7 +43,7 @@ class RequestCredentialTest { to = null, body = "" ) - assertFailsWith { + assertFailsWith { RequestCredential.fromMessage(invalidRequestCredential) } } diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/OutOfBandInvitationTest.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/OutOfBandInvitationTest.kt index ba2df01ed..926296ecd 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/OutOfBandInvitationTest.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/OutOfBandInvitationTest.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.outOfBand +package org.hyperledger.identus.walletsdk.edgeagent.protocols.outOfBand import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/OutOfBandParserTest.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/OutOfBandParserTest.kt index 35414e2f8..23e59188f 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/OutOfBandParserTest.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/outOfBand/OutOfBandParserTest.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.outOfBand +package org.hyperledger.identus.walletsdk.edgeagent.protocols.outOfBand import io.ktor.http.Url import org.hyperledger.identus.walletsdk.domain.models.CommonError diff --git a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/pickup/PickupRunnerTest.kt b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/pickup/PickupRunnerTest.kt index 9bc341199..c52c87671 100644 --- a/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/pickup/PickupRunnerTest.kt +++ b/edge-agent-sdk/src/commonTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/protocols/pickup/PickupRunnerTest.kt @@ -1,13 +1,13 @@ -package org.hyperledger.identus.walletsdk.prismagent.protocols.pickup +package org.hyperledger.identus.walletsdk.edgeagent.protocols.pickup import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runTest import org.hyperledger.identus.walletsdk.domain.models.AttachmentDescriptor import org.hyperledger.identus.walletsdk.domain.models.AttachmentJsonData import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.MercuryMock -import org.hyperledger.identus.walletsdk.prismagent.PrismAgentError -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType +import org.hyperledger.identus.walletsdk.edgeagent.MercuryMock +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgentError +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType import org.junit.Before import org.junit.Test import java.util.UUID @@ -28,7 +28,7 @@ class PickupRunnerTest { @Test fun testPickupRun_whenPiuriNotValid_thenInvalidPickupDeliveryMessageError() { val message = Message(piuri = ProtocolType.DidcommRequestPresentation.value, body = "") - assertFailsWith(PrismAgentError.InvalidMessageType::class) { + assertFailsWith(EdgeAgentError.InvalidMessageType::class) { PickupRunner(message, mercury) } } diff --git a/edge-agent-sdk/src/jvmTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/AndroidIgnore.jvm.kt b/edge-agent-sdk/src/jvmTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/AndroidIgnore.jvm.kt index c4db54223..56a0049db 100644 --- a/edge-agent-sdk/src/jvmTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/AndroidIgnore.jvm.kt +++ b/edge-agent-sdk/src/jvmTest/kotlin/org/hyperledger/identus/walletsdk/prismagent/AndroidIgnore.jvm.kt @@ -1,4 +1,4 @@ -package org.hyperledger.identus.walletsdk.prismagent +package org.hyperledger.identus.walletsdk.edgeagent import org.junit.Ignore diff --git a/package.json b/package.json index a4bc56ebb..726be331d 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { - "name": "atala-prism-wallet-sdk-kmm", + "name": "edge-agent-sdk-kmm", "version": "0.0.1", - "description": "atala-prism-wallet-sdk-kmm", + "description": "edge-agent-sdk-kmm", "directories": { "example": "examples" }, diff --git a/sampleapp/src/main/java/io/iohk/atala/prism/sampleapp/Sdk.kt b/sampleapp/src/main/java/io/iohk/atala/prism/sampleapp/Sdk.kt index 9b4a080e6..59426c753 100644 --- a/sampleapp/src/main/java/io/iohk/atala/prism/sampleapp/Sdk.kt +++ b/sampleapp/src/main/java/io/iohk/atala/prism/sampleapp/Sdk.kt @@ -19,8 +19,8 @@ import io.iohk.atala.prism.walletsdk.mercury.resolvers.DIDCommWrapper import io.iohk.atala.prism.walletsdk.pluto.PlutoImpl import io.iohk.atala.prism.walletsdk.pluto.data.DbConnection import io.iohk.atala.prism.walletsdk.pollux.PolluxImpl -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgent -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgentError +import io.iohk.atala.prism.walletsdk.prismagent.EdgeAgent +import io.iohk.atala.prism.walletsdk.prismagent.EdgeAgentError import io.iohk.atala.prism.walletsdk.prismagent.helpers.AgentOptions import io.iohk.atala.prism.walletsdk.prismagent.helpers.Experiments import io.iohk.atala.prism.walletsdk.prismagent.mediation.BasicMediatorHandler @@ -35,15 +35,15 @@ class Sdk { private val castor: Castor = createCastor() private var pollux: Pollux = createPollux() private val seed: Seed = createSeed() - private val agentStatusStream: MutableLiveData = MutableLiveData() + private val agentStatusStream: MutableLiveData = MutableLiveData() val pluto: Pluto = createPluto() val mercury: Mercury = createMercury() lateinit var handler: MediationHandler - lateinit var agent: PrismAgent + lateinit var agent: EdgeAgent - @Throws(PrismAgentError.MediationRequestFailedError::class, UnknownHostException::class) + @Throws(EdgeAgentError.MediationRequestFailedError::class, UnknownHostException::class) suspend fun startAgent(mediatorDID: String, context: Application) { handler = createHandler(mediatorDID) agent = createAgent(handler) @@ -131,8 +131,8 @@ class Sdk { ) } - private fun createAgent(handler: MediationHandler): PrismAgent { - return PrismAgent( + private fun createAgent(handler: MediationHandler): EdgeAgent { + return EdgeAgent( apollo = apollo, castor = castor, pluto = pluto, diff --git a/sampleapp/src/main/java/io/iohk/atala/prism/sampleapp/ui/contacts/ContactsViewModel.kt b/sampleapp/src/main/java/io/iohk/atala/prism/sampleapp/ui/contacts/ContactsViewModel.kt index d1f7a0bdd..c061edcd5 100644 --- a/sampleapp/src/main/java/io/iohk/atala/prism/sampleapp/ui/contacts/ContactsViewModel.kt +++ b/sampleapp/src/main/java/io/iohk/atala/prism/sampleapp/ui/contacts/ContactsViewModel.kt @@ -7,7 +7,7 @@ import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import io.iohk.atala.prism.sampleapp.Sdk import io.iohk.atala.prism.walletsdk.domain.models.DIDPair -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgentError +import io.iohk.atala.prism.walletsdk.prismagent.EdgeAgentError import io.iohk.atala.prism.walletsdk.prismagent.protocols.outOfBand.OutOfBandInvitation import io.iohk.atala.prism.walletsdk.prismagent.protocols.outOfBand.PrismOnboardingInvitation import kotlinx.coroutines.launch @@ -32,7 +32,7 @@ class ContactsViewModel(application: Application) : AndroidViewModel(application return contactsStream } - @Throws(PrismAgentError.UnknownInvitationTypeError::class, Exception::class) + @Throws(EdgeAgentError.UnknownInvitationTypeError::class, Exception::class) fun parseAndAcceptOOB(oobUrl: String) { Sdk.getInstance().agent.let { agent -> viewModelScope.launch { @@ -46,7 +46,7 @@ class ContactsViewModel(application: Application) : AndroidViewModel(application } else -> { - throw PrismAgentError.UnknownInvitationTypeError(invitation.toString()) + throw EdgeAgentError.UnknownInvitationTypeError(invitation.toString()) } } } diff --git a/sampleapp/src/main/java/io/iohk/atala/prism/sampleapp/ui/main/MainActivity.kt b/sampleapp/src/main/java/io/iohk/atala/prism/sampleapp/ui/main/MainActivity.kt index 227589af6..13868828e 100644 --- a/sampleapp/src/main/java/io/iohk/atala/prism/sampleapp/ui/main/MainActivity.kt +++ b/sampleapp/src/main/java/io/iohk/atala/prism/sampleapp/ui/main/MainActivity.kt @@ -8,7 +8,7 @@ import com.google.android.material.snackbar.Snackbar import com.google.android.material.tabs.TabLayout import io.iohk.atala.prism.sampleapp.Sdk import io.iohk.atala.prism.sampleapp.databinding.ActivityMainBinding -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgent +import io.iohk.atala.prism.walletsdk.prismagent.EdgeAgent class MainActivity : AppCompatActivity() { diff --git a/sampleapp/src/main/java/org/hyperledger/identus/walletsdk/sampleapp/Sdk.kt b/sampleapp/src/main/java/org/hyperledger/identus/walletsdk/sampleapp/Sdk.kt index 8124292ea..1dcab339f 100644 --- a/sampleapp/src/main/java/org/hyperledger/identus/walletsdk/sampleapp/Sdk.kt +++ b/sampleapp/src/main/java/org/hyperledger/identus/walletsdk/sampleapp/Sdk.kt @@ -22,12 +22,12 @@ import org.hyperledger.identus.walletsdk.mercury.resolvers.DIDCommWrapper import org.hyperledger.identus.walletsdk.pluto.PlutoImpl import org.hyperledger.identus.walletsdk.pluto.data.DbConnection import org.hyperledger.identus.walletsdk.pollux.PolluxImpl -import org.hyperledger.identus.walletsdk.prismagent.PrismAgent -import org.hyperledger.identus.walletsdk.prismagent.PrismAgentError -import org.hyperledger.identus.walletsdk.prismagent.helpers.AgentOptions -import org.hyperledger.identus.walletsdk.prismagent.helpers.Experiments -import org.hyperledger.identus.walletsdk.prismagent.mediation.BasicMediatorHandler -import org.hyperledger.identus.walletsdk.prismagent.mediation.MediationHandler +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgent +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgentError +import org.hyperledger.identus.walletsdk.edgeagent.helpers.AgentOptions +import org.hyperledger.identus.walletsdk.edgeagent.helpers.Experiments +import org.hyperledger.identus.walletsdk.edgeagent.mediation.BasicMediatorHandler +import org.hyperledger.identus.walletsdk.edgeagent.mediation.MediationHandler import java.net.UnknownHostException class Sdk { @@ -41,9 +41,9 @@ class Sdk { val mercury: Mercury = createMercury() lateinit var handler: MediationHandler - lateinit var agent: PrismAgent + lateinit var agent: EdgeAgent - @Throws(PrismAgentError.MediationRequestFailedError::class, UnknownHostException::class) + @Throws(EdgeAgentError.MediationRequestFailedError::class, UnknownHostException::class) suspend fun startAgent(mediatorDID: String, context: Application) { handler = createHandler(mediatorDID) agent = createAgent(handler) @@ -131,8 +131,8 @@ class Sdk { ) } - private fun createAgent(handler: MediationHandler): PrismAgent { - return PrismAgent( + private fun createAgent(handler: MediationHandler): EdgeAgent { + return EdgeAgent( apollo = apollo, castor = castor, pluto = pluto, diff --git a/sampleapp/src/main/java/org/hyperledger/identus/walletsdk/sampleapp/ui/contacts/ContactsViewModel.kt b/sampleapp/src/main/java/org/hyperledger/identus/walletsdk/sampleapp/ui/contacts/ContactsViewModel.kt index a4bc41503..46b695b88 100644 --- a/sampleapp/src/main/java/org/hyperledger/identus/walletsdk/sampleapp/ui/contacts/ContactsViewModel.kt +++ b/sampleapp/src/main/java/org/hyperledger/identus/walletsdk/sampleapp/ui/contacts/ContactsViewModel.kt @@ -7,9 +7,9 @@ import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import kotlinx.coroutines.launch import org.hyperledger.identus.walletsdk.domain.models.DIDPair -import org.hyperledger.identus.walletsdk.prismagent.PrismAgentError -import org.hyperledger.identus.walletsdk.prismagent.protocols.outOfBand.OutOfBandInvitation -import org.hyperledger.identus.walletsdk.prismagent.protocols.outOfBand.PrismOnboardingInvitation +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgentError +import org.hyperledger.identus.walletsdk.edgeagent.protocols.outOfBand.OutOfBandInvitation +import org.hyperledger.identus.walletsdk.edgeagent.protocols.outOfBand.PrismOnboardingInvitation import org.hyperledger.identus.walletsdk.sampleapp.Sdk import java.net.MalformedURLException import java.net.URISyntaxException @@ -32,7 +32,7 @@ class ContactsViewModel(application: Application) : AndroidViewModel(application return contactsStream } - @Throws(PrismAgentError.UnknownInvitationTypeError::class, Exception::class) + @Throws(EdgeAgentError.UnknownInvitationTypeError::class, Exception::class) fun parseAndAcceptOOB(oobUrl: String) { Sdk.getInstance().agent.let { agent -> viewModelScope.launch { @@ -46,7 +46,7 @@ class ContactsViewModel(application: Application) : AndroidViewModel(application } else -> { - throw PrismAgentError.UnknownInvitationTypeError(invitation.toString()) + throw EdgeAgentError.UnknownInvitationTypeError(invitation.toString()) } } } diff --git a/sampleapp/src/main/java/org/hyperledger/identus/walletsdk/sampleapp/ui/dids/DIDsViewModel.kt b/sampleapp/src/main/java/org/hyperledger/identus/walletsdk/sampleapp/ui/dids/DIDsViewModel.kt index 47df608c0..89fd98ba3 100644 --- a/sampleapp/src/main/java/org/hyperledger/identus/walletsdk/sampleapp/ui/dids/DIDsViewModel.kt +++ b/sampleapp/src/main/java/org/hyperledger/identus/walletsdk/sampleapp/ui/dids/DIDsViewModel.kt @@ -8,8 +8,8 @@ import androidx.lifecycle.viewModelScope import kotlinx.coroutines.launch import org.hyperledger.identus.walletsdk.domain.models.DID import org.hyperledger.identus.walletsdk.domain.models.DIDDocument -import org.hyperledger.identus.walletsdk.prismagent.DIDCOMM1 -import org.hyperledger.identus.walletsdk.prismagent.DIDCOMM_MESSAGING +import org.hyperledger.identus.walletsdk.edgeagent.DIDCOMM1 +import org.hyperledger.identus.walletsdk.edgeagent.DIDCOMM_MESSAGING import org.hyperledger.identus.walletsdk.sampleapp.Sdk class DIDsViewModel(application: Application) : AndroidViewModel(application) { diff --git a/sampleapp/src/main/java/org/hyperledger/identus/walletsdk/sampleapp/ui/main/MainActivity.kt b/sampleapp/src/main/java/org/hyperledger/identus/walletsdk/sampleapp/ui/main/MainActivity.kt index 55a403cec..398bc15da 100644 --- a/sampleapp/src/main/java/org/hyperledger/identus/walletsdk/sampleapp/ui/main/MainActivity.kt +++ b/sampleapp/src/main/java/org/hyperledger/identus/walletsdk/sampleapp/ui/main/MainActivity.kt @@ -6,7 +6,7 @@ import androidx.appcompat.app.AppCompatActivity import androidx.viewpager.widget.ViewPager import com.google.android.material.snackbar.Snackbar import com.google.android.material.tabs.TabLayout -import org.hyperledger.identus.walletsdk.prismagent.PrismAgent +import org.hyperledger.identus.walletsdk.edgeagent.EdgeAgent import org.hyperledger.identus.walletsdk.sampleapp.Sdk import org.hyperledger.identus.walletsdk.sampleapp.databinding.ActivityMainBinding diff --git a/sampleapp/src/main/java/org/hyperledger/identus/walletsdk/sampleapp/ui/messages/MessagesViewModel.kt b/sampleapp/src/main/java/org/hyperledger/identus/walletsdk/sampleapp/ui/messages/MessagesViewModel.kt index ccc1af64f..a61b893ad 100644 --- a/sampleapp/src/main/java/org/hyperledger/identus/walletsdk/sampleapp/ui/messages/MessagesViewModel.kt +++ b/sampleapp/src/main/java/org/hyperledger/identus/walletsdk/sampleapp/ui/messages/MessagesViewModel.kt @@ -13,12 +13,12 @@ import org.hyperledger.identus.walletsdk.db.DatabaseClient import org.hyperledger.identus.walletsdk.domain.models.Credential import org.hyperledger.identus.walletsdk.domain.models.DIDDocument import org.hyperledger.identus.walletsdk.domain.models.Message -import org.hyperledger.identus.walletsdk.prismagent.DIDCOMM1 -import org.hyperledger.identus.walletsdk.prismagent.DIDCOMM_MESSAGING -import org.hyperledger.identus.walletsdk.prismagent.protocols.ProtocolType -import org.hyperledger.identus.walletsdk.prismagent.protocols.issueCredential.IssueCredential -import org.hyperledger.identus.walletsdk.prismagent.protocols.issueCredential.OfferCredential -import org.hyperledger.identus.walletsdk.prismagent.protocols.proofOfPresentation.RequestPresentation +import org.hyperledger.identus.walletsdk.edgeagent.DIDCOMM1 +import org.hyperledger.identus.walletsdk.edgeagent.DIDCOMM_MESSAGING +import org.hyperledger.identus.walletsdk.edgeagent.protocols.ProtocolType +import org.hyperledger.identus.walletsdk.edgeagent.protocols.issueCredential.IssueCredential +import org.hyperledger.identus.walletsdk.edgeagent.protocols.issueCredential.OfferCredential +import org.hyperledger.identus.walletsdk.edgeagent.protocols.proofOfPresentation.RequestPresentation import org.hyperledger.identus.walletsdk.sampleapp.Sdk import java.time.LocalDateTime import org.hyperledger.identus.walletsdk.db.Message as MessageEntity diff --git a/tests/end-to-end/src/test/kotlin/io/iohk/atala/prism/abilities/UseWalletSdk.kt b/tests/end-to-end/src/test/kotlin/io/iohk/atala/prism/abilities/UseWalletSdk.kt index 1a234ef92..9d993b853 100644 --- a/tests/end-to-end/src/test/kotlin/io/iohk/atala/prism/abilities/UseWalletSdk.kt +++ b/tests/end-to-end/src/test/kotlin/io/iohk/atala/prism/abilities/UseWalletSdk.kt @@ -14,7 +14,7 @@ import io.iohk.atala.prism.walletsdk.mercury.resolvers.DIDCommWrapper import io.iohk.atala.prism.walletsdk.pluto.PlutoImpl import io.iohk.atala.prism.walletsdk.pluto.data.DbConnection import io.iohk.atala.prism.walletsdk.pollux.PolluxImpl -import io.iohk.atala.prism.walletsdk.prismagent.PrismAgent +import io.iohk.atala.prism.walletsdk.prismagent.EdgeAgent import io.iohk.atala.prism.walletsdk.prismagent.mediation.BasicMediatorHandler import io.iohk.atala.prism.walletsdk.prismagent.protocols.ProtocolType import io.iohk.atala.prism.workflow.EdgeAgentWorkflow @@ -98,7 +98,7 @@ class UseWalletSdk : Ability { val handler = BasicMediatorHandler(mediatorDid, mercury, store) val seed = apollo.createRandomSeed().seed - val sdk = PrismAgent( + val sdk = EdgeAgent( apollo, castor, pluto, @@ -146,7 +146,7 @@ class UseWalletSdk : Ability { } data class SdkContext( - val sdk: PrismAgent, + val sdk: EdgeAgent, val credentialOfferStack: MutableList = Collections.synchronizedList(mutableListOf()), val proofRequestStack: MutableList = Collections.synchronizedList(mutableListOf()), val issuedCredentialStack: MutableList = Collections.synchronizedList(mutableListOf())