Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow client to be specified #24

Merged
merged 1 commit into from
Dec 14, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package org.web3j.quorum.enclave

import org.web3j.protocol.exceptions.ClientConnectionException

class EnclaveClientConnectionException(message: String) : ClientConnectionException(message)
Original file line number Diff line number Diff line change
Expand Up @@ -5,35 +5,42 @@ import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import org.web3j.quorum.enclave.protocol.EnclaveService
import okhttp3.*
import okhttp3.OkHttpClient
import org.web3j.quorum.enclave.EnclaveClientConnectionException


/**
* EnclaveHttpService implements send methods that support communication with the private enclave via Http.
* Currently Http communication is only supported in Tessera.
*/
class EnclaveHttpService(private val url: String, private val port: Int) : EnclaveService {
class EnclaveHttpService(private val url: String, private val port: Int, private val client: OkHttpClient = OkHttpClient()) : EnclaveService {

private val objectMapper = jacksonObjectMapper()
.setSerializationInclusion(JsonInclude.Include.NON_NULL)
private val JSON = MediaType.parse("application/json; charset=utf-8")
private val JSON_MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8")

/**
* Send a new raw payload to Enclave
*/
override fun <S, T> send(request: S, path: String, responseType: Class<T>): T {
val payload = objectMapper.writeValueAsString(request)
val client = OkHttpClient()
val uri = "$url:$port/$path"
val body = RequestBody.create(JSON, objectMapper.writeValueAsString(payload))
val body = RequestBody.create(JSON_MEDIA_TYPE, payload)
val request = Request.Builder()
.url(uri)
.post(body)
.build()

val response = client.newCall(request).execute()

val chunk = response.body().toString()
return objectMapper.readValue(chunk, responseType)
if(response.isSuccessful) {
val chunk = response.body()?.string()
return objectMapper.readValue(chunk, responseType)
} else {
val statusCode = response.code()
val text = if (response.body() == null) "N/A" else response.body()?.string()

throw EnclaveClientConnectionException("Invalid response received from enclave: $statusCode $text")
}
}

/**
Expand Down