65 lines
2.4 KiB
Kotlin
65 lines
2.4 KiB
Kotlin
/**
|
|
* Copyright (c) 2020 EmeraldPay, Inc
|
|
* Copyright (c) 2019 ETCDEV GmbH
|
|
*
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
*/
|
|
package io.emeraldpay.dshackle.upstream.ethereum
|
|
|
|
import com.fasterxml.jackson.databind.ObjectMapper
|
|
import io.emeraldpay.dshackle.reader.Reader
|
|
import io.emeraldpay.dshackle.upstream.Upstream
|
|
import io.emeraldpay.dshackle.upstream.UpstreamApi
|
|
import io.infinitape.etherjar.rpc.*
|
|
import io.infinitape.etherjar.rpc.json.BlockJson
|
|
import io.infinitape.etherjar.rpc.json.TransactionRefJson
|
|
import org.slf4j.LoggerFactory
|
|
import reactor.core.publisher.Mono
|
|
import java.io.InputStream
|
|
|
|
abstract class EthereumApi(
|
|
objectMapper: ObjectMapper
|
|
) : UpstreamApi {
|
|
|
|
companion object {
|
|
private val log = LoggerFactory.getLogger(EthereumApi::class.java)
|
|
}
|
|
|
|
private val jacksonRpcConverter = JacksonRpcConverter(objectMapper)
|
|
var upstream: Upstream<EthereumApi>? = null
|
|
|
|
fun <JS, RS> reader(): Reader<RpcCall<JS, RS>, RS> {
|
|
return object : Reader<RpcCall<JS, RS>, RS> {
|
|
override fun read(key: RpcCall<JS, RS>): Mono<RS> {
|
|
return this@EthereumApi.executeAndConvert(key)
|
|
}
|
|
}
|
|
}
|
|
|
|
fun <JS, RS> execute(rpcCall: RpcCall<JS, RS>): Mono<ByteArray> {
|
|
return execute(0, rpcCall.method, rpcCall.params as List<Any>)
|
|
}
|
|
|
|
fun <JS, RS> executeAndConvert(rpcCall: RpcCall<JS, RS>): Mono<RS> {
|
|
val convertToJS = java.util.function.Function<ByteArray, Mono<JS>> { resp ->
|
|
val inputStream: InputStream = resp.inputStream()
|
|
val jsonValue: JS? = jacksonRpcConverter.fromJson(inputStream, rpcCall.jsonType, Int::class.java)
|
|
if (jsonValue == null) Mono.empty<JS>()
|
|
else Mono.just(jsonValue)
|
|
}
|
|
return execute(rpcCall)
|
|
.flatMap(convertToJS)
|
|
.map(rpcCall.converter::apply)
|
|
.doOnError { err -> log.debug("Failed to read from upstream", err) }
|
|
}
|
|
} |