Initial commit

This commit is contained in:
m724 2025-11-01 21:05:40 +01:00
commit 78e3d21ea2
Signed by untrusted user who does not match committer: m724
GPG key ID: A02E6E67AB961189
21 changed files with 889 additions and 0 deletions

45
.gitignore vendored Normal file
View file

@ -0,0 +1,45 @@
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### Kotlin ###
.kotlin
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

3
.idea/.gitignore generated vendored Normal file
View file

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

17
.idea/gradle.xml generated Normal file
View file

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleHome" value="" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>

6
.idea/kotlinc.xml generated Normal file
View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="KotlinJpsPluginSettings">
<option name="version" value="2.2.20" />
</component>
</project>

7
.idea/misc.xml generated Normal file
View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="21" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

6
.idea/vcs.xml generated Normal file
View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

49
build.gradle.kts Normal file
View file

@ -0,0 +1,49 @@
plugins {
kotlin("multiplatform") version "2.2.21"
kotlin("plugin.serialization") version "2.2.21"
//id("io.kotest") version "6.0.4"
//id("com.google.devtools.ksp") version "2.3.0"
//id("maven-publish")
}
group = "eu.m724"
version = "0.0.1-SNAPSHOT"
repositories {
mavenCentral()
}
kotlin {
val hostOs = System.getProperty("os.name")
val isArm64 = System.getProperty("os.arch") == "aarch64"
val isMingwX64 = hostOs.startsWith("Windows")
val nativeTarget = when { // not unused do not remove
hostOs == "Mac OS X" && isArm64 -> macosArm64("native")
hostOs == "Mac OS X" && !isArm64 -> macosX64("native")
hostOs == "Linux" && isArm64 -> linuxArm64("native")
hostOs == "Linux" && !isArm64 -> linuxX64("native")
isMingwX64 -> mingwX64("native")
else -> throw GradleException("Host OS is not supported in Kotlin/Native.")
}
sourceSets {
val ktorVersion = "3.3.1"
nativeMain.dependencies {
implementation("io.ktor:ktor-client-core:$ktorVersion")
implementation("io.ktor:ktor-client-cio:$ktorVersion")
implementation("io.ktor:ktor-client-content-negotiation:$ktorVersion")
implementation("io.ktor:ktor-serialization-kotlinx-json:$ktorVersion")
implementation("com.ionspin.kotlin:bignum:0.3.10")
}
nativeTest.dependencies {
//val kotestVersion = "6.0.4"
//val mockkVersion = "1.14.6"
//implementation("io.kotest:kotest-framework-engine:$kotestVersion")
//implementation("io.kotest:kotest-assertions-core:$kotestVersion")
//implementation("io.kotest:kotest-property:$kotestVersion")
//implementation("io.mockk:mockk:$mockkVersion")
implementation("io.ktor:ktor-client-mock:$ktorVersion")
}
}
}

1
gradle.properties Normal file
View file

@ -0,0 +1 @@
kotlin.code.style=official

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View file

@ -0,0 +1,6 @@
#Fri Oct 31 17:47:06 CET 2025
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
gradlew vendored Executable file
View file

@ -0,0 +1,234 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# 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
#
# https://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.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

89
gradlew.bat vendored Normal file
View file

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

4
settings.gradle.kts Normal file
View file

@ -0,0 +1,4 @@
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0"
}
rootProject.name = "nano-rpc-kotlin"

View file

@ -0,0 +1,100 @@
package eu.m724.nanorpc
import eu.m724.nanorpc.model.request.AccountBalanceRequest
import eu.m724.nanorpc.model.request.SimpleActionRequest
import eu.m724.nanorpc.model.response.AccountBalanceResponse
import eu.m724.nanorpc.model.response.NodeVersionResponse
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.ClientRequestException
import io.ktor.client.plugins.ServerResponseException
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.request.HttpRequestBuilder
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.statement.bodyAsText
import io.ktor.http.ContentType
import io.ktor.http.Url
import io.ktor.http.contentType
import io.ktor.http.isSuccess
import io.ktor.serialization.kotlinx.json.json
/**
* A client for interacting with a Nano cryptocurrency RPC node. This class facilitates communication with the
* node using HTTP POST requests and allows for retrieving data or performing actions supported by the node.
*
* @param url The base URL of the Nano node to communicate with. Defaults to http://localhost:7075.
*/
class NanoRpcClient internal constructor(
private val url: Url,
engine: HttpClientEngine
) : AutoCloseable {
constructor(
url: Url = Url("http://localhost:7075"),
) : this(url, CIO.create())
private val httpClient = HttpClient(engine) {
install(ContentNegotiation) {
json()
}
}
private suspend inline fun <reified T> postJsonForResult(
body: Any,
requestBuilder: HttpRequestBuilder.() -> Unit = {}
): Result<T> {
return runCatching {
val response = httpClient.post(url) {
contentType(ContentType.Application.Json)
setBody(body)
requestBuilder()
}
return if (response.status.isSuccess()) {
Result.success(response.body<T>())
} else {
// TODO check for errors returned by the node
val exception = when (response.status.value) {
in 400..499 -> ClientRequestException(response, response.bodyAsText())
else -> ServerResponseException(response, response.bodyAsText())
// Redirects are followed, so no need to check that
}
Result.failure(exception)
}
}
}
/**
* Retrieves the balance and receivable balance of the specified Nano account.
*
* @param account The account for which the balance is to be retrieved, represented as a string.
* @return A [Result] containing an [AccountBalanceResponse], which includes the balance and
* receivable amounts, or an error if the request fails.
*/
suspend fun getAccountBalance(
account: String
): Result<AccountBalanceResponse> {
return postJsonForResult(
AccountBalanceRequest(account = account)
)
}
/**
* Retrieves the version information of the Nano node.
*
* @return A [Result] containing a [NodeVersionResponse] with the node's
* version information, or an error if the request fails.
*/
suspend fun getNodeVersion(): Result<NodeVersionResponse> {
return postJsonForResult(
SimpleActionRequest("version")
)
}
override fun close() {
httpClient.close()
}
}

View file

@ -0,0 +1,117 @@
package eu.m724.nanorpc.model
import com.ionspin.kotlin.bignum.decimal.BigDecimal
import com.ionspin.kotlin.bignum.decimal.toBigDecimal
import com.ionspin.kotlin.bignum.integer.BigInteger
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
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
// TODO perhaps a little overkill
/**
* A class representing an amount in the Nano cryptocurrency. NanoAmount internally stores
* the value in raw units (the smallest indivisible unit of a Nano) and provides methods for
* converting to and from Nano.
*
* @property raw The raw amount as a BigInteger, representing the base unit of Nano.
*/
@Serializable(with = NanoAmount.Serializer::class)
class NanoAmount private constructor(
val raw: BigInteger
): Comparable<NanoAmount> {
/**
* Represents the amount in Nano.
*/
val nano: BigDecimal = BigDecimal.fromBigInteger(raw).div(RAW_IN_NANO)
companion object {
val ZERO by lazy {
NanoAmount(BigInteger.ZERO)
}
val MAX by lazy { // yes, you need lazy; no, I don't know why
NanoAmount(BigInteger.TWO.pow(128) - 1)
}
private val RAW_IN_NANO = BigDecimal.TEN.pow(30)
/**
* Creates a [NanoAmount] instance from the given raw value.
*
* @param raw The raw value as a [BigInteger], representing the amount in raw units.
* @return A [NanoAmount] object corresponding to the provided raw value.
*/
fun fromRaw(raw: BigInteger): NanoAmount = NanoAmount(raw)
/**
* Converts the given Nano amount represented as a [BigDecimal] into a [NanoAmount] instance.
*
* @param nano The amount in Nano as a [BigDecimal].
* @return A [NanoAmount] instance representing the equivalent value in raw units.
*/
fun fromNano(nano: BigDecimal): NanoAmount {
require(nano.scale <= 30) { "Nano amount cannot have more than 30 decimal places" }
return NanoAmount(nano.multiply(RAW_IN_NANO).toBigInteger())
}
/**
* Creates a [NanoAmount] instance from the given numeric value in Nano.
* Converts the numeric value to a [BigDecimal] representation and then
* derives the corresponding [NanoAmount].
*
* @param nano The numeric value representing the amount in Nano.
* @return A [NanoAmount] object corresponding to the provided Nano value.
*/
fun fromNano(nano: Number): NanoAmount = fromNano(nano.toString().toBigDecimal())
}
/**
* Converts the internal `nano` BigDecimal representation of the amount to a Double representation
* in Nano.
*
* The returned value is not suitable for anything requiring precision.
*
* @param exactRequired A flag indicating whether the conversion must be performed with strict precision.
* If true, ArithmeticException is thrown if the value cannot be represented exactly
* as a Double.
* @return The amount in Nano as a Double representation.
*/
fun asNanosDouble(
exactRequired: Boolean = false
): Double {
return nano.doubleValue(exactRequired)
}
override fun toString(): String = nano.toString()
operator fun plus(other: NanoAmount): NanoAmount = NanoAmount(this.raw + other.raw)
operator fun minus(other: NanoAmount): NanoAmount = NanoAmount(this.raw - other.raw)
override fun compareTo(other: NanoAmount): Int = this.raw.compare(other.raw)
override fun equals(other: Any?): Boolean = other is NanoAmount && other.raw == this.raw
object Serializer : KSerializer<NanoAmount> {
override val descriptor: SerialDescriptor
get() = PrimitiveSerialDescriptor("NanoAmount", PrimitiveKind.STRING)
override fun serialize(
encoder: Encoder,
value: NanoAmount
) {
encoder.encodeString(value.raw.toString())
}
override fun deserialize(decoder: Decoder): NanoAmount {
return fromRaw(BigInteger.parseString(decoder.decodeString(), 10))
}
}
}
/**
* Converts the numeric value of the current [Number] instance into a [NanoAmount].
*
* @return A [NanoAmount] instance representing the equivalent value in Nanos.
*/
fun Number.toNanoAmount(): NanoAmount = NanoAmount.fromNano(this)

View file

@ -0,0 +1,13 @@
package eu.m724.nanorpc.model.request
import kotlinx.serialization.Serializable
@Serializable
data class AccountBalanceRequest(
val action: String = "account_balance",
val account: String
) {
init {
require(action == "account_balance") { "action must be account_balance" }
}
}

View file

@ -0,0 +1,8 @@
package eu.m724.nanorpc.model.request
import kotlinx.serialization.Serializable
@Serializable
data class SimpleActionRequest(
val action: String
)

View file

@ -0,0 +1,10 @@
package eu.m724.nanorpc.model.response
import eu.m724.nanorpc.model.NanoAmount
import kotlinx.serialization.Serializable
@Serializable
data class AccountBalanceResponse(
val balance: NanoAmount,
val receivable: NanoAmount
)

View file

@ -0,0 +1,33 @@
package eu.m724.nanorpc.model.response
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* Represents the response received from querying the version of a Nano node.
*
* This data class encapsulates versioning and identifying information provided
* by the Nano node, including the RPC version, store version, protocol version,
* vendor details, network name, and build metadata. These properties help
* determine the compatibility and configuration of the node in the Nano network.
*
* @property rpcVersion The version of the RPC protocol supported by the node.
* @property storeVersion The version of the node's storage layer.
* @property protocolVersion The version of the Nano protocol used by the node.
* @property nodeVendor The name of the node's vendor implementation.
* @property storeVendor The name of the storage layer vendor implementation.
* @property network The name of the Nano network the node is connected to (normally "live" or "beta" or "test").
* @property networkIdentifier A unique identifier for the Nano network, as a 64-character hex string.
* @property buildInfo Build information for the node, typically including version and commit hash details.
*/
@Serializable
data class NodeVersionResponse(
@SerialName("rpc_version") val rpcVersion: Int,
@SerialName("store_version") val storeVersion: Int,
@SerialName("protocol_version") val protocolVersion: Int,
@SerialName("node_vendor") val nodeVendor: String,
@SerialName("store_vendor") val storeVendor: String,
val network: String,
@SerialName("network_identifier") val networkIdentifier: String,
@SerialName("build_info") val buildInfo: String
)

View file

@ -0,0 +1,128 @@
package eu.m724.nanorpc
import eu.m724.nanorpc.model.NanoAmount
import eu.m724.nanorpc.model.request.AccountBalanceRequest
import eu.m724.nanorpc.model.request.SimpleActionRequest
import eu.m724.nanorpc.model.response.AccountBalanceResponse
import eu.m724.nanorpc.model.response.NodeVersionResponse
import io.ktor.client.engine.mock.MockEngine
import io.ktor.client.engine.mock.respond
import io.ktor.client.plugins.ServerResponseException
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpMethod
import io.ktor.http.HttpStatusCode
import io.ktor.http.Url
import io.ktor.http.content.OutgoingContent
import io.ktor.http.content.TextContent
import io.ktor.http.headersOf
import io.ktor.serialization.JsonConvertException
import io.ktor.utils.io.ByteReadChannel
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.Json
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertIs
class NanoRpcClientTest {
@Test
fun `getNodeVersion should return node version information on success`() {
runBlocking {
val expectedResponse = NodeVersionResponse(
rpcVersion = 1,
storeVersion = 24,
protocolVersion = 21,
nodeVendor = "Nano V28.2",
storeVendor = "LMDB 0.9.70",
network = "live",
networkIdentifier = "991CF190094C00F0B68E2E5F75F6BEE95A2E0BD93CEAA4A6734DB9F19B728948",
buildInfo = "0d8eea4 \"GNU C++ version \" \"11.4.0\" \"BOOST 108600\" BUILT \"Aug 20 2025\""
)
val (client, mockEngine) = createMockClient(Json.encodeToString(expectedResponse))
val version = client.getNodeVersion().getOrThrow()
version shouldBe expectedResponse
val request = mockEngine.requestHistory.single()
request.url shouldBe Url("http://localhost:7075")
request.method shouldBe HttpMethod.Post
request.body shouldBeJson SimpleActionRequest("version")
}
}
@Test
fun `getNodeVersion should throw JsonConvertException on invalid JSON response`() {
runBlocking {
val (client, _) = createMockClient("""{"key": 0}""")
val result = client.getNodeVersion()
assertIs<JsonConvertException>(result.exceptionOrNull())
}
}
@Test
fun `getNodeVersion should throw JsonConvertException on server error`() {
runBlocking {
val (client, _) = createMockClient(
content = "",
status = HttpStatusCode.InternalServerError
)
val result = client.getNodeVersion()
assertIs<ServerResponseException>(result.exceptionOrNull())
}
}
// What else? ...everything?
@Test
fun `getAccountBalance should return account balance on success`() {
runBlocking {
val expectedRequest =
AccountBalanceRequest(account = BURN_ADDRESS)
val expectedResponse = AccountBalanceResponse(
balance = NanoAmount.MAX,
receivable = NanoAmount.MAX
)
val (client, mockEngine) = createMockClient(Json.encodeToString(expectedResponse))
val balance = client.getAccountBalance(BURN_ADDRESS).getOrThrow()
balance shouldBe expectedResponse
val request = mockEngine.requestHistory.single()
request.url shouldBe Url("http://localhost:7075")
request.method shouldBe HttpMethod.Post
request.body shouldBeJson expectedRequest
}
}
}
const val BURN_ADDRESS = "nano_1111111111111111111111111111111111111111111111111111hifc8npp"
private inline infix fun <reified T> OutgoingContent.shouldBeJson(expected: T) {
assertIs<TextContent>(this)
assertEquals(expected, Json.decodeFromString<T>(this.text))
}
private fun createMockClient(
content: String,
status: HttpStatusCode = HttpStatusCode.OK
): Pair<NanoRpcClient, MockEngine> {
val mockEngine = MockEngine {
respond(
content = ByteReadChannel(content),
status = status,
headers = headersOf(HttpHeaders.ContentType, "application/json")
)
}
val client = NanoRpcClient(
url = Url("http://localhost:7075"),
engine = mockEngine
)
return Pair(client, mockEngine)
}

View file

@ -0,0 +1,13 @@
package eu.m724.nanorpc
import kotlin.test.assertEquals
/**
* Asserts that the current value is equal to the specified value.
*
* @param other The value to compare with the current value.
* @see assertEquals
*/
infix fun Any.shouldBe(other: Any) { // No, <T> does nothing
assertEquals(other, this)
}