Skip to content

Commit

Permalink
fix: request and achieve mediation (#62)
Browse files Browse the repository at this point in the history
  • Loading branch information
cristianIOHK authored May 8, 2023
1 parent e24f67a commit 73f98c5
Show file tree
Hide file tree
Showing 19 changed files with 272 additions and 154 deletions.
2 changes: 1 addition & 1 deletion atala-prism-sdk/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ android {

sqldelight {
database("PrismPlutoDb") {
packageName = "io.iohk.atala.prism.walletsdk.pluto"
packageName = "io.iohk.atala.prism.walletsdk"
sourceFolders = listOf("sqldelight")
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@ package io.iohk.atala.prism.walletsdk.pluto.data
import android.content.Context
import com.squareup.sqldelight.android.AndroidSqliteDriver
import com.squareup.sqldelight.db.SqlDriver
import io.iohk.atala.prism.walletsdk.PrismPlutoDb
import io.iohk.atala.prism.walletsdk.domain.models.PlutoError
import io.iohk.atala.prism.walletsdk.pluto.PrismPlutoDb

actual class DbConnection actual constructor() {
actual var driver: SqlDriver? = null
actual suspend fun connectDb(
context: Any?,
): PrismPlutoDb {
val androidContext: Context = (context as? Context) ?: throw PlutoError.DatabaseContextError()
val driver = AndroidSqliteDriver(PrismPlutoDb.Schema, androidContext)
val driver = AndroidSqliteDriver(PrismPlutoDb.Schema, androidContext, "prism.db")
this.driver = driver
return PrismPlutoDb(
driver,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,19 +68,18 @@ class MercuryImpl(

override suspend fun sendMessageParseResponse(message: Message): Message? {
val msg = sendMessage(message)
try {
val msgString = msg.toString()
msg?.let {
val msgString = String(msg)
if (msgString != "null" && msgString != "") {
return unpackMessage(msgString)
}
} catch (_: Exception) {
}
return null
}

private fun prepareForwardMessage(message: Message, encrypted: String, mediatorDid: DID): ForwardMessage {
return ForwardMessage(
body = message.to.toString(),
body = ForwardMessage.ForwardBody(message.to.toString()),
encryptedMessage = encrypted,
from = message.from!!,
to = mediatorDid,
Expand All @@ -100,9 +99,7 @@ class MercuryImpl(
arrayOf(KeyValue("Content-type", "application/didcomm-encrypted+json")),
message
)
val msg = "${result.status} ${result.jsonString}"
println(msg)
throw NotImplementedError(msg)
return result.jsonString.toByteArray()
}

@Throws(MercuryError.NoValidServiceFoundError::class)
Expand All @@ -112,11 +109,7 @@ class MercuryImpl(
}

val result = api.request("POST", uri, emptyArray(), emptyArray(), message)
if (result.jsonString == "") {
// SUCCESS
throw NotImplementedError()
}
throw NotImplementedError()
return result.jsonString.toByteArray()
}

private fun getMediatorDID(service: DIDDocument.Service?): DID? {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
package io.iohk.atala.prism.walletsdk.mercury.forward

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.AttachmentJsonData
import io.iohk.atala.prism.walletsdk.domain.models.DID
import io.iohk.atala.prism.walletsdk.domain.models.Message
import kotlinx.serialization.Serializable
Expand All @@ -11,23 +10,24 @@ import kotlinx.serialization.json.Json
import java.util.UUID

class ForwardMessage @JvmOverloads constructor(
val body: String,
val body: ForwardBody,
val from: DID,
val to: DID,
val encryptedMessage: String,
val id: String = UUID.randomUUID().toString()
) {
fun makeMessage(): Message {
val forwardBody = Json.encodeToString(ForwardBody(body)).base64UrlEncoded
val attachmentData = AttachmentBase64(encryptedMessage)
val forwardBody = Json.encodeToString(body)
val attachmentData = AttachmentJsonData(encryptedMessage)
val attachment = AttachmentDescriptor(UUID.randomUUID().toString(), "application/json", attachmentData)

val message = Message(
id = id,
piuri = type,
from = from,
to = to,
body = forwardBody,
attachments = arrayOf(attachment)
attachments = arrayOf(attachment),
)

return message
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,17 @@ import io.iohk.atala.prism.walletsdk.mercury.DIDCommProtocol
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
Expand All @@ -29,11 +40,83 @@ class DIDCommWrapper(castor: Castor, pluto: Pluto, apollo: Apollo) : DIDCommProt
private val secretsResolver = DIDCommSecretsResolver(pluto, apollo)
private val didComm = DIDComm(didDocResolver, secretsResolver)

private fun jsonObjectToMap(element: JsonElement): Map<String, Any?> {
var bodyMap = mutableMapOf<String, Any?>()
if (element is JsonPrimitive) {
} else {
val keys = element.jsonObject.keys
keys.forEach { key ->
when (val value = element.jsonObject[key]) {
is JsonObject -> {
bodyMap[key] = jsonObjectToMap(value)
}

is JsonArray -> {
var array = mutableListOf<Any>()
value.forEach {
when (it) {
is JsonObject -> {
array.add(jsonObjectToMap(it))
}

is JsonPrimitive -> {
if (it.isString) {
bodyMap[key] = it.content
} else if (it.intOrNull != null) {
bodyMap[key] = it.int
} else if (it.doubleOrNull != null) {
bodyMap[key] = it.double
} else if (it.booleanOrNull != null) {
bodyMap[key] = it.boolean
} else {
bodyMap[key] = it
}
}

else -> {
bodyMap[key] = 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
}
}
}
}
return bodyMap
}

override fun packEncrypted(message: Message): String {
val toString = message.to.toString()

val element = Json.parseToJsonElement(message.body)
val map = jsonObjectToMap(element)

val didCommMsg = org.didcommx.didcomm.message.Message(
id = message.id,
body = mapOf(),
body = map,
typ = Typ.Plaintext,
type = message.piuri,
to = listOf(toString),
Expand All @@ -50,11 +133,10 @@ class DIDCommWrapper(castor: Castor, pluto: Pluto, apollo: Apollo) : DIDCommProt
customHeaders = mapOf()
)

val builder = PackEncryptedParams.builder(didCommMsg, toString).forward(false)
val builder = PackEncryptedParams.builder(didCommMsg, toString).forward(false).protectSenderId(false)
didCommMsg.from?.let { builder.from(it) }
val params = builder.build()
val result = didComm.packEncrypted(params)

return result.packedMessage
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import io.iohk.atala.prism.apollo.base64.base64DecodedBytes
import io.iohk.atala.prism.apollo.base64.base64UrlDecodedBytes
import io.iohk.atala.prism.apollo.base64.base64UrlEncoded
import io.iohk.atala.prism.apollo.uuid.UUID
import io.iohk.atala.prism.walletsdk.PrismPlutoDb
import io.iohk.atala.prism.walletsdk.domain.buildingblocks.Pluto
import io.iohk.atala.prism.walletsdk.domain.models.CredentialType
import io.iohk.atala.prism.walletsdk.domain.models.DID
Expand Down Expand Up @@ -71,14 +72,14 @@ class PlutoImpl(private val connection: DbConnection) : Pluto {
alias: String?,
privateKeys: List<PrivateKey>
) {
getInstance().dIDQueries.insert(DIDDB(did.methodId, did.method, did.methodId, did.schema, alias))
getInstance().dIDQueries.insert(DIDDB(did.toString(), did.method, did.methodId, did.schema, alias))
privateKeys.map { privateKey ->
storePrivateKeys(privateKey, did, keyPathIndex)
}
}

override fun storePeerDIDAndPrivateKeys(did: DID, privateKeys: List<PrivateKey>) {
getInstance().dIDQueries.insert(DIDDB(did.methodId, did.method, did.methodId, did.schema, null))
getInstance().dIDQueries.insert(DIDDB(did.toString(), did.method, did.methodId, did.schema, null))
privateKeys.map { privateKey ->
storePrivateKeys(privateKey, did, privateKey.keyCurve.index ?: 0)
}
Expand Down Expand Up @@ -134,12 +135,24 @@ class PlutoImpl(private val connection: DbConnection) : Pluto {

override fun storeMessages(messages: List<Message>) {
messages.map { message ->
println("Message: ${message.toJsonString()}")
storeMessage(message)
}
}

override fun storeMediator(mediator: DID, host: DID, routing: DID) {
getInstance().mediatorQueries.insert(
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.randomUUID4().toString(),
mediator.methodId,
Expand Down Expand Up @@ -534,12 +547,13 @@ class PlutoImpl(private val connection: DbConnection) : Pluto {
return getInstance().mediatorQueries.fetchAllMediators()
.asFlow()
.map {
it.executeAsList().map { mediator ->
val fetchAllMediators = it.executeAsList()
fetchAllMediators.map {
Mediator(
mediator.id,
DID(mediator.MediatorDID),
DID(mediator.HostDID),
DID(mediator.RoutingDID)
it.id,
DID(it.MediatorDID),
DID(it.HostDID),
DID(it.RoutingDID)
)
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package io.iohk.atala.prism.walletsdk.pluto.data

import com.squareup.sqldelight.db.SqlDriver
import io.iohk.atala.prism.walletsdk.pluto.PrismPlutoDb
import io.iohk.atala.prism.walletsdk.PrismPlutoDb

expect class DbConnection() {
var driver: SqlDriver?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import io.iohk.atala.prism.walletsdk.domain.models.Message
import io.iohk.atala.prism.walletsdk.domain.models.PrismAgentError
import io.iohk.atala.prism.walletsdk.prismagent.connectionsmanager.ConnectionsManager
import io.iohk.atala.prism.walletsdk.prismagent.mediation.MediationHandler
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlin.jvm.Throws
Expand All @@ -23,12 +23,13 @@ class ConnectionManager(
) : ConnectionsManager {

suspend fun startMediator() {
mediationHandler.bootRegisteredMediator()
mediationHandler.bootRegisteredMediator() ?: throw PrismAgentError.NoMediatorAvailableError()
}

suspend fun registerMediator(host: DID) {
mediationHandler.achieveMediation(host)
.first()
mediationHandler.achieveMediation(host).collect {
println("Achieve mediation")
}
}

@Throws(PrismAgentError.NoMediatorAvailableError::class)
Expand All @@ -40,16 +41,17 @@ class ConnectionManager(
return mercury.sendMessageParseResponse(message)
}

fun awaitMessages(): Flow<Array<Message>> {
return mediationHandler.pickupUnreadMessages(NUMBER_OF_MESSAGES)
.map {
val messagesIds = it.map { it.first }.toTypedArray()
mediationHandler.registerMessagesAsRead(messagesIds)
it.map { it.second }.toTypedArray()
}
.map { messages ->
pluto.storeMessages(messages.toList())
messages
suspend fun awaitMessages() {
mediationHandler.pickupUnreadMessages(NUMBER_OF_MESSAGES)
.collect { array ->
val messagesIds = mutableListOf<String>()
val messages = mutableListOf<Message>()
array.map { pair ->
messagesIds.add(pair.first)
messages.add(pair.second)
}
mediationHandler.registerMessagesAsRead(messagesIds.toTypedArray())
pluto.storeMessages(messages)
}
}

Expand Down
Loading

0 comments on commit 73f98c5

Please sign in to comment.