diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..fd50ebd --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,67 @@ +name: Kotlin CI + +on: + push: + branches: [ main ] + pull_request: + branches: [ main, develop ] + release: + types: [ published ] + +jobs: + build: + runs-on: macos-latest + + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Validate Gradle Wrapper + uses: gradle/wrapper-validation-action@v1 + + - name: Configure JDK + uses: actions/setup-java@v3 + with: + java-version: '11' + distribution: 'temurin' + cache: gradle + + # Build + - name: Grant execute permission for gradlew + run: chmod +x gradlew + - name: Test + run: ./gradlew build + + - name: Save Test Reports + if: failure() + uses: actions/upload-artifact@v3 + with: + name: test-reports + path: '**/build/reports' + + publish: + runs-on: macos-latest + needs: build + if: ${{ github.event_name == 'release' }} + + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Configure JDK + uses: actions/setup-java@v3 + with: + java-version: '11' + distribution: 'temurin' + cache: gradle + + - name: Grant execute permission for gradlew + run: chmod +x gradlew + - name: Publish to Maven Central + run: ./gradlew clean publishAllPublicationsToMavenCentral --stacktrace + env: + ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.SONATYPE_NEXUS_USERNAME }} + ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.SONATYPE_NEXUS_PASSWORD }} + ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.ARTIFACT_SIGNING_PRIVATE_KEY }} + ORG_GRADLE_PROJECT_signingInMemoryKeyId: ${{ secrets.ARTIFACT_SIGNING_PRIVATE_KEY_ID }} + ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.ARTIFACT_SIGNING_PRIVATE_KEY_PASSWORD }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1209939 --- /dev/null +++ b/.gitignore @@ -0,0 +1,34 @@ +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# Build Files +/build +*/build +/.gradle + +# IDE Files +/.idea + +# Local Only Files +local.properties + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* diff --git a/README.md b/README.md new file mode 100644 index 0000000..a221555 --- /dev/null +++ b/README.md @@ -0,0 +1,4 @@ +# Web3Kt +Multiplatform Web3 Library + + diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..2d6bec5 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,8 @@ +plugins { + kotlin("multiplatform") version "1.9.0" apply false + id("com.vanniktech.maven.publish") version "0.25.3" apply false +} + +//tasks.register("clean", Delete::class) { +// delete(rootProject.buildDir) +//} \ No newline at end of file diff --git a/core/build.gradle.kts b/core/build.gradle.kts new file mode 100644 index 0000000..a39fae5 --- /dev/null +++ b/core/build.gradle.kts @@ -0,0 +1,44 @@ +plugins { + kotlin("multiplatform") + kotlin("plugin.serialization") version "1.9.0" + id("com.vanniktech.maven.publish") +} + +val artifactId: String by project + +kotlin { + jvm { + jvmToolchain(11) + withJava() + testRuns["test"].executionTask.configure { + useJUnitPlatform() + } + } + listOf( + iosX64(), + iosArm64(), + iosSimulatorArm64(), + macosX64(), + macosArm64() + ).forEach { + it.binaries.framework { + baseName = artifactId + } + } + sourceSets { + val commonMain by getting { + dependencies { + implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0-RC") + } + } + val commonTest by getting { + dependencies { + implementation(kotlin("test")) + } + } + } +} + +mavenPublishing { + coordinates(group as String, artifactId, version as String) +} diff --git a/core/src/commonMain/kotlin/com/funkatronics/publickey/PublicKey.kt b/core/src/commonMain/kotlin/com/funkatronics/publickey/PublicKey.kt new file mode 100644 index 0000000..b9bf244 --- /dev/null +++ b/core/src/commonMain/kotlin/com/funkatronics/publickey/PublicKey.kt @@ -0,0 +1,23 @@ +package com.funkatronics.publickey + +/** + * PublicKey Interface + * + * @author Funkatronics + */ +interface PublicKey { + /** + * byte length of the public key + */ + val length: Number + + /** + * the bytes making up the public key + */ + val bytes: ByteArray + + /** + * returns a string representation of the Public Key + */ + fun string(): String +} \ No newline at end of file diff --git a/core/src/commonMain/kotlin/com/funkatronics/serialization/ByteStringSerializer.kt b/core/src/commonMain/kotlin/com/funkatronics/serialization/ByteStringSerializer.kt new file mode 100644 index 0000000..951ac07 --- /dev/null +++ b/core/src/commonMain/kotlin/com/funkatronics/serialization/ByteStringSerializer.kt @@ -0,0 +1,20 @@ +package com.funkatronics.serialization + +import kotlinx.serialization.KSerializer +import kotlinx.serialization.builtins.ByteArraySerializer +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder + +open class ByteStringSerializer(val length: Int) : KSerializer { + override val descriptor: SerialDescriptor = ByteArraySerializer().descriptor + + override fun deserialize(decoder: Decoder) = + ByteArray(length) { + decoder.decodeByte() + } + + override fun serialize(encoder: Encoder, value: ByteArray) { + value.forEach { encoder.encodeByte(it) } + } +} \ No newline at end of file diff --git a/core/src/commonMain/kotlin/com/funkatronics/serialization/CompactArraySerializer.kt b/core/src/commonMain/kotlin/com/funkatronics/serialization/CompactArraySerializer.kt new file mode 100644 index 0000000..06fe676 --- /dev/null +++ b/core/src/commonMain/kotlin/com/funkatronics/serialization/CompactArraySerializer.kt @@ -0,0 +1,80 @@ +package com.funkatronics.serialization + +import com.funkatronics.util.asVarint +import kotlinx.serialization.KSerializer +import kotlinx.serialization.builtins.ByteArraySerializer +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder + +class CompactArraySerializer(val valueSerializer: KSerializer) : KSerializer> { + override val descriptor: SerialDescriptor = ListSerializer(valueSerializer).descriptor + + override fun deserialize(decoder: Decoder): Collection { + var size = 0 // decoder.decodeByte().toInt() + var shift = 0 + do { + val b = decoder.decodeByte().toInt() and 0xFF + size = ((b and 0x7f) shl shift) or size + shift += 7 + } while (b and 0x80 != 0) + + return List(size) { + decoder.decodeSerializableValue(valueSerializer) + } + } + + override fun serialize(encoder: Encoder, value: Collection) { + value.size.asVarint().forEach { encoder.encodeByte(it) } + value.forEach { encoder.encodeSerializableValue(valueSerializer, it) } + } +} + +object CompactByteArraySerializer : KSerializer { + override val descriptor: SerialDescriptor = ByteArraySerializer().descriptor + + override fun deserialize(decoder: Decoder): ByteArray { + var size = 0 // decoder.decodeByte().toInt() + var shift = 0 + do { + val b = decoder.decodeByte().toInt() and 0xFF + size = ((b and 0x7f) shl shift) or size + shift += 7 + } while (b and 0x80 != 0) + + return ByteArray(size) { + decoder.decodeByte() + } + } + + override fun serialize(encoder: Encoder, value: ByteArray) { + value.size.asVarint().forEach { encoder.encodeByte(it) } + value.forEach { encoder.encodeByte(it) } + } +} + +object CompactSignatureArraySerializer : KSerializer> { + override val descriptor: SerialDescriptor = ByteArraySerializer().descriptor + + override fun deserialize(decoder: Decoder): List { + var size = 0 // decoder.decodeByte().toInt() + var shift = 0 + do { + val b = decoder.decodeByte().toInt() and 0xFF + size = ((b and 0x7f) shl shift) or size + shift += 7 + } while (b and 0x80 != 0) + + return List(size) { + ByteArray(64) { + decoder.decodeByte() + } + } + } + + override fun serialize(encoder: Encoder, value: List) { + value.size.asVarint().forEach { encoder.encodeByte(it) } + value.forEach { it.forEach { encoder.encodeByte(it) } } + } +} \ No newline at end of file diff --git a/core/src/commonMain/kotlin/com/funkatronics/signer/Ed25519Signer.kt b/core/src/commonMain/kotlin/com/funkatronics/signer/Ed25519Signer.kt new file mode 100644 index 0000000..a199227 --- /dev/null +++ b/core/src/commonMain/kotlin/com/funkatronics/signer/Ed25519Signer.kt @@ -0,0 +1,6 @@ +package com.funkatronics.signer + +abstract class Ed25519Signer : Signer { + override val ownerLength = 32 + override val signatureLength = 64 +} \ No newline at end of file diff --git a/core/src/commonMain/kotlin/com/funkatronics/signer/Signer.kt b/core/src/commonMain/kotlin/com/funkatronics/signer/Signer.kt new file mode 100644 index 0000000..8d0e0ba --- /dev/null +++ b/core/src/commonMain/kotlin/com/funkatronics/signer/Signer.kt @@ -0,0 +1,8 @@ +package com.funkatronics.signer + +interface Signer { + val publicKey: ByteArray + val ownerLength: Number + val signatureLength: Number + suspend fun signPayload(payload: ByteArray): ByteArray +} \ No newline at end of file diff --git a/core/src/commonMain/kotlin/com/funkatronics/util/Varint.kt b/core/src/commonMain/kotlin/com/funkatronics/util/Varint.kt new file mode 100644 index 0000000..f80c8a2 --- /dev/null +++ b/core/src/commonMain/kotlin/com/funkatronics/util/Varint.kt @@ -0,0 +1,39 @@ +package com.funkatronics.util + +import kotlin.experimental.and +import kotlin.math.ceil + +object Varint { + + fun encode(value: Int): ByteArray { + if (value == 0) return byteArrayOf(0) + var num = value + val encodedSize = ceil((Int.SIZE_BITS - value.countLeadingZeroBits()) / 7f).toInt() + return ByteArray(encodedSize) { + (num and 0x7F or if (num < 128) 0 else 128).toByte().also { + num /= 128 + } + } + } + + fun encode(value: Long): ByteArray { + if (value == 0L) return byteArrayOf(0) + var num = value + val encodedSize = ceil((Long.SIZE_BITS - value.countLeadingZeroBits()) / 7f).toInt() + return ByteArray(encodedSize) { + (num and 0x7F or if (num < 128) 0 else 128).toByte().also { + num /= 128 + } + } + } + + fun decode(bytes: ByteArray): Long = + bytes.takeWhile { it and 0x80.toByte() < 0 }.run { + this + bytes[this.size] + }.foldIndexed(0L) { index, value, byte -> + ((byte and 0x7f).toLong() shl (7*index)) or value + } +} + +fun Int.asVarint() = Varint.encode(this) +fun Long.asVarint() = Varint.encode(this) \ No newline at end of file diff --git a/core/src/commonTest/kotlin/com/funkatronics/util/VarintTests.kt b/core/src/commonTest/kotlin/com/funkatronics/util/VarintTests.kt new file mode 100644 index 0000000..dbea80d --- /dev/null +++ b/core/src/commonTest/kotlin/com/funkatronics/util/VarintTests.kt @@ -0,0 +1,73 @@ +package com.funkatronics.util + +import kotlin.test.assertEquals +import kotlin.test.assertContentEquals +import kotlin.test.Test + +class VarintTests { + + @Test + fun testVarintEncode() { + // given + val value = 16385 + val expected = byteArrayOf(-127, -128, 1) + + // when + val result = Varint.encode(value) + + // then + assertContentEquals(expected, result) + } + + @Test + fun testVarintEncode0() { + // given + val value = 0 + val expected = byteArrayOf(0) + + // when + val result = Varint.encode(value) + + // then + assertContentEquals(expected, result) + } + + @Test + fun testVarintDecode() { + // given + val bytes = byteArrayOf(-127, -128, 1) + val expected = 16385L + + // when + val result = Varint.decode(bytes) + + // then + assertEquals(expected, result) + } + + @Test + fun testVarintDecode0() { + // given + val bytes = byteArrayOf(0) + val expected = 0L + + // when + val result = Varint.decode(bytes) + + // then + assertEquals(expected, result) + } + + @Test + fun testVarintEncodeDecode() { + // given + val value = 375847L + + // when + val encoded = Varint.encode(value) + val decoded = Varint.decode(encoded) + + // then + assertEquals(value, decoded) + } +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..83eb989 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,32 @@ +kotlin.code.style=official +kotlin.js.compiler=ir + +# Group name and project version, used when publishing. For official releases, the version should be +# provided to Gradle via '-P version="1.0"'. +group=io.github.funkatronics +artifactId=web3kt +version=main-SNAPSHOT + +SONATYPE_HOST=S01 +RELEASE_SIGNING_ENABLED=true + +SONATYPE_AUTOMATIC_RELEASE=true +SONATYPE_CONNECT_TIMEOUT_SECONDS=60 +SONATYPE_CLOSE_TIMEOUT_SECONDS=900 + +POM_NAME=RpcCore +POM_DESCRIPTION=Multiplatform JSON RPC Library using Kotlin Serialization +POM_INCEPTION_YEAR=2023 +POM_URL=https://github.com/Funkatronics/Web3Kt + +POM_LICENSE_NAME=The Apache Software License, Version 2.0 +POM_LICENSE_URL=https://www.apache.org/licenses/LICENSE-2.0.txt +POM_LICENSE_DIST=repo + +POM_SCM_URL=https://github.com/Funkatronics/Web3Kt +POM_SCM_CONNECTION=scm:git:git://github.com/Funkatronics/Web3Kt.git +POM_SCM_DEV_CONNECTION=scm:git:ssh://git@github.com/Funkatronics/Web3Kt.git + +POM_DEVELOPER_ID=Funkatronics +POM_DEVELOPER_NAME=Marco Martinez +POM_DEVELOPER_URL=https://github.com/Funkatronics/ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..fae0804 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -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" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -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 diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..848d01c --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,20 @@ +pluginManagement { + repositories { + gradlePluginPortal() + google() + mavenCentral() + } +} + +dependencyResolutionManagement { + repositories { + google() + mavenCentral() + maven(url = "https://jitpack.io") + } +} + +rootProject.name = "Web3Kt" +include(":core") +include(":solana") + diff --git a/solana/build.gradle.kts b/solana/build.gradle.kts new file mode 100644 index 0000000..f038ef8 --- /dev/null +++ b/solana/build.gradle.kts @@ -0,0 +1,47 @@ +plugins { + kotlin("multiplatform") + kotlin("plugin.serialization") version "1.9.0" + id("com.vanniktech.maven.publish") +} + +val artifactId: String by project + +kotlin { + jvm { + jvmToolchain(11) + withJava() + testRuns["test"].executionTask.configure { + useJUnitPlatform() + } + } + listOf( + iosX64(), + iosArm64(), + iosSimulatorArm64(), + macosX64(), + macosArm64() + ).forEach { + it.binaries.framework { + baseName = artifactId + } + } + sourceSets { + val commonMain by getting { + dependencies { + implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0-RC") + implementation(project(mapOf("path" to ":core"))) + implementation("io.github.funkatronics:multimult:0.2.0") + } + } + val commonTest by getting { + dependencies { + implementation(kotlin("test")) +// implementation("io.github.funkatronics:kborsh:0.1.0") + } + } + } +} + +mavenPublishing { + coordinates(group as String, artifactId, version as String) +} diff --git a/solana/src/commonMain/kotlin/com/funkatronics/publickey/SolanaPublicKey.kt b/solana/src/commonMain/kotlin/com/funkatronics/publickey/SolanaPublicKey.kt new file mode 100644 index 0000000..3df8fd2 --- /dev/null +++ b/solana/src/commonMain/kotlin/com/funkatronics/publickey/SolanaPublicKey.kt @@ -0,0 +1,43 @@ +package com.funkatronics.publickey + +import com.funkatronics.encoders.Base58 +import com.funkatronics.serialization.ByteStringSerializer +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializable +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder + +@Serializable(with=SolanaPublicKeySerializer::class) +open class SolanaPublicKey(override val bytes: ByteArray) : PublicKey { + + init { + check (bytes.size == PUBLIC_KEY_LENGTH) + } + + override val length = PUBLIC_KEY_LENGTH + override fun string(): String = base58() + + fun base58(): String = Base58.encodeToString(bytes) + + companion object { + const val PUBLIC_KEY_LENGTH = 32 + fun from(base58: String) = SolanaPublicKey(Base58.decode(base58)) + } + + override fun equals(other: Any?): Boolean { + return (other is PublicKey) && this.bytes.contentEquals(other.bytes) + } +} + +object SolanaPublicKeySerializer : KSerializer { + private val delegate = ByteStringSerializer(SolanaPublicKey.PUBLIC_KEY_LENGTH) + override val descriptor: SerialDescriptor = delegate.descriptor + + override fun deserialize(decoder: Decoder): SolanaPublicKey = + SolanaPublicKey(decoder.decodeSerializableValue(delegate)) + + override fun serialize(encoder: Encoder, value: SolanaPublicKey) { + encoder.encodeSerializableValue(delegate, value.bytes) + } +} diff --git a/solana/src/commonMain/kotlin/com/funkatronics/serialization/TransactionFormat.kt b/solana/src/commonMain/kotlin/com/funkatronics/serialization/TransactionFormat.kt new file mode 100644 index 0000000..fd64f82 --- /dev/null +++ b/solana/src/commonMain/kotlin/com/funkatronics/serialization/TransactionFormat.kt @@ -0,0 +1,64 @@ +package com.funkatronics.serialization + +import com.funkatronics.util.asVarint +import kotlinx.serialization.BinaryFormat +import kotlinx.serialization.DeserializationStrategy +import kotlinx.serialization.SerializationStrategy +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.AbstractDecoder +import kotlinx.serialization.encoding.AbstractEncoder +import kotlinx.serialization.encoding.CompositeEncoder +import kotlinx.serialization.modules.EmptySerializersModule + +sealed class TransactionFormat : BinaryFormat { + + companion object Default : TransactionFormat() + + override val serializersModule = EmptySerializersModule() + + override fun decodeFromByteArray(deserializer: DeserializationStrategy, + bytes: ByteArray): T = + TransactionDecoder(bytes).decodeSerializableValue(deserializer) + + override fun encodeToByteArray(serializer: SerializationStrategy, value: T): ByteArray = + TransactionEncoder().apply { encodeSerializableValue(serializer, value) }.encodedBytes +} + +class TransactionEncoder : AbstractEncoder() { + private val bytes = mutableListOf() + + val encodedBytes get() = bytes.toByteArray() + + override val serializersModule = EmptySerializersModule() + + override fun encodeByte(value: Byte) { bytes.add(value) } + + override fun beginCollection(descriptor: SerialDescriptor, collectionSize: Int): CompositeEncoder { + collectionSize.asVarint().forEach { encodeByte(it) } + return super.beginCollection(descriptor, collectionSize) + } +} + +class TransactionDecoder(val bytes: ByteArray) : AbstractDecoder() { + private var position = 0 + + override val serializersModule = EmptySerializersModule() + + override fun decodeByte(): Byte = bytes[position++] + + // Not called for sequential decoders + override fun decodeElementIndex(descriptor: SerialDescriptor): Int = 0 + override fun decodeSequentially(): Boolean = true + + override fun decodeCollectionSize(descriptor: SerialDescriptor): Int { + var size = 0 + var shift = 0 + do { + val b = decodeByte().toInt() and 0xFF + size = ((b and 0x7f) shl shift) or size + shift += 7 + } while (b and 0x80 != 0) + + return size + } +} \ No newline at end of file diff --git a/solana/src/commonMain/kotlin/com/funkatronics/signer/SolanaSigner.kt b/solana/src/commonMain/kotlin/com/funkatronics/signer/SolanaSigner.kt new file mode 100644 index 0000000..dfb1e72 --- /dev/null +++ b/solana/src/commonMain/kotlin/com/funkatronics/signer/SolanaSigner.kt @@ -0,0 +1,9 @@ +package com.funkatronics.signer + +import com.funkatronics.transaction.Transaction + +abstract class SolanaSigner : Ed25519Signer() { + abstract fun signMessage(message: ByteArray): ByteArray + abstract fun signTransaction(transaction: ByteArray): ByteArray + abstract suspend fun signAndSendTransaction(transaction: Transaction): Result +} \ No newline at end of file diff --git a/solana/src/commonMain/kotlin/com/funkatronics/transaction/Instruction.kt b/solana/src/commonMain/kotlin/com/funkatronics/transaction/Instruction.kt new file mode 100644 index 0000000..5e31653 --- /dev/null +++ b/solana/src/commonMain/kotlin/com/funkatronics/transaction/Instruction.kt @@ -0,0 +1,41 @@ +package com.funkatronics.transaction + +import com.funkatronics.publickey.SolanaPublicKey +import kotlinx.serialization.Serializable + +@Serializable +data class Instruction( + val programIdIndex: UByte, + val accountIndices: ByteArray, + val data: ByteArray +) { + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other == null || this::class != other::class) return false + + other as Instruction + + if (programIdIndex != other.programIdIndex) return false + if (!accountIndices.contentEquals(other.accountIndices)) return false + return data.contentEquals(other.data) + } + + override fun hashCode(): Int { + var result = programIdIndex.hashCode() + result = 31 * result + accountIndices.contentHashCode() + result = 31 * result + data.contentHashCode() + return result + } +} + +data class TransactionInstruction( + val programId: SolanaPublicKey, + val accounts: List, + val data: ByteArray +) + +data class AccountMeta( + val publicKey: SolanaPublicKey, + val isSigner: Boolean, + val isWritable: Boolean, +) \ No newline at end of file diff --git a/solana/src/commonMain/kotlin/com/funkatronics/transaction/Message.kt b/solana/src/commonMain/kotlin/com/funkatronics/transaction/Message.kt new file mode 100644 index 0000000..681b26e --- /dev/null +++ b/solana/src/commonMain/kotlin/com/funkatronics/transaction/Message.kt @@ -0,0 +1,146 @@ +package com.funkatronics.transaction + +import com.funkatronics.publickey.SolanaPublicKey +import com.funkatronics.publickey.SolanaPublicKeySerializer +import com.funkatronics.serialization.TransactionFormat +import kotlinx.serialization.* +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.descriptors.buildClassSerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlin.experimental.and +import kotlin.experimental.or + +typealias Blockhash = SolanaPublicKey +val Blockhash.blockhash get() = this.bytes + +sealed class Message { + + companion object { + fun from(bytes: ByteArray) = TransactionFormat.decodeFromByteArray(MessageSerializer, bytes) + } + + fun serialize(): ByteArray = TransactionFormat.encodeToByteArray(MessageSerializer, this) + + data class Builder( + val instructions: MutableList = mutableListOf(), + var blockhash: Blockhash? = null + ) { + + fun addInstruction(instruction: TransactionInstruction) = apply { + instructions.add(instruction) + } + + fun setRecentBlockhash(blockhash: String) = setRecentBlockhash(Blockhash.from(blockhash)) + fun setRecentBlockhash(blockhash: Blockhash) = apply { + this.blockhash = blockhash + } + + fun build(): Message { + check(blockhash != null) + val writableSigners = mutableSetOf() + val readOnlySigners = mutableSetOf() + val writableNonSigners = mutableSetOf() + val readOnlyNonSigners = mutableSetOf() + instructions.forEach { instruction -> + instruction.accounts.forEach { account -> + if (account.isSigner) { + if (account.isWritable) writableSigners.add(account.publicKey) + else readOnlySigners.add(account.publicKey) + } else { + if (account.isWritable) writableNonSigners.add(account.publicKey) + else readOnlyNonSigners.add(account.publicKey) + } + } + readOnlyNonSigners.add(instruction.programId) + } + + val signers = writableSigners + readOnlySigners + val accounts = signers + writableNonSigners + readOnlyNonSigners + val compiledInstructions = instructions.map { instruction -> + Instruction( + accounts.indexOf(instruction.programId).toUByte(), + instruction.accounts.map { + accounts.indexOf(it.publicKey).toByte() + }.toByteArray(), + instruction.data + ) + } + + return LegacyMessage( + signers.size.toUByte(), + readOnlySigners.size.toUByte(), + readOnlyNonSigners.size.toUByte(), + accounts.toList(), + blockhash!!, + compiledInstructions + ) + } + } +} + +@Serializable +data class LegacyMessage( + val signatureCount: UByte, + val readOnlyAccounts: UByte, + val readOnlyNonSigners: UByte, + val accounts: List, + val blockhash: Blockhash, + val instructions: List +) : Message() + +@Serializable +data class VersionedMessage( + @Transient val version: Byte = 0, + val signatureCount: UByte, + val readOnlyAccounts: UByte, + val readOnlyNonSigners: UByte, + val accounts: List, + val blockhash: Blockhash, + val instructions: List, + val addressTableLookups: List +) : Message() + +@Serializable +data class AddressTableLookup( + val account: SolanaPublicKey, + val writableIndexes: List, + val readOnlyIndexes: List +) + +object MessageSerializer : KSerializer { + override val descriptor: SerialDescriptor = + buildClassSerialDescriptor("com.funkatronics.transaction.Message") + + override fun deserialize(decoder: Decoder): Message { + val firstByte = decoder.decodeByte() + val version = if (firstByte.toInt() and 0x80 == 0) -1 else firstByte and 0x7f + val signatureCount = if (version >= 0) decoder.decodeByte().toUByte() else firstByte.toUByte() + val readOnlyAccounts = decoder.decodeByte().toUByte() + val readOnlyNonSigners = decoder.decodeByte().toUByte() + val accounts = decoder.decodeSerializableValue(ListSerializer(SolanaPublicKeySerializer)) + val blockhash = Blockhash(decoder.decodeSerializableValue(SolanaPublicKeySerializer).bytes) + val instructions = decoder.decodeSerializableValue(ListSerializer(Instruction.serializer())) + return if (version >= 0) + VersionedMessage( + version, + signatureCount, readOnlyAccounts, readOnlyNonSigners, + accounts, blockhash, instructions, + decoder.decodeSerializableValue(ListSerializer(AddressTableLookup.serializer())) + ) + else + LegacyMessage( + signatureCount, readOnlyAccounts, readOnlyNonSigners, + accounts, blockhash, instructions, + ) + } + + override fun serialize(encoder: Encoder, value: Message) { + if (value is VersionedMessage) encoder.encodeByte(0x80.toByte() or value.version) + when (value) { + is LegacyMessage -> encoder.encodeSerializableValue(LegacyMessage.serializer(), value) + is VersionedMessage -> encoder.encodeSerializableValue(VersionedMessage.serializer(), value) + } + } +} \ No newline at end of file diff --git a/solana/src/commonMain/kotlin/com/funkatronics/transaction/Transaction.kt b/solana/src/commonMain/kotlin/com/funkatronics/transaction/Transaction.kt new file mode 100644 index 0000000..3529032 --- /dev/null +++ b/solana/src/commonMain/kotlin/com/funkatronics/transaction/Transaction.kt @@ -0,0 +1,20 @@ +package com.funkatronics.transaction + +import com.funkatronics.serialization.ByteStringSerializer +import com.funkatronics.serialization.TransactionFormat +import kotlinx.serialization.* + +object SignatureSerializer : ByteStringSerializer(64) + +@Serializable +data class Transaction( + val signatures: List<@Serializable(with = SignatureSerializer::class) ByteArray>, + @Serializable(with = MessageSerializer::class) val message: Message +) { + + companion object { + fun from(bytes: ByteArray) = TransactionFormat.decodeFromByteArray(serializer(), bytes) + } + + fun serialize(): ByteArray = TransactionFormat.encodeToByteArray(serializer(), this) +} \ No newline at end of file diff --git a/solana/src/commonTest/kotlin/com/funkatronics/publickey/PublicKeyTests.kt b/solana/src/commonTest/kotlin/com/funkatronics/publickey/PublicKeyTests.kt new file mode 100644 index 0000000..64083ca --- /dev/null +++ b/solana/src/commonTest/kotlin/com/funkatronics/publickey/PublicKeyTests.kt @@ -0,0 +1,44 @@ +package com.funkatronics.publickey + +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals + +class PublicKeyTests { + + @Test + fun testPublicKeyFromBase58String() { + // given + val base58 = "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr" // Memo program v2 account address + val expectedPublicKeyBytes = byteArrayOf( + 0x05.toByte(), 0x4a.toByte(), 0x53.toByte(), 0x5a.toByte(), 0x99.toByte(), 0x29.toByte(), 0x21.toByte(), 0x06.toByte(), + 0x4d.toByte(), 0x24.toByte(), 0xe8.toByte(), 0x71.toByte(), 0x60.toByte(), 0xda.toByte(), 0x38.toByte(), 0x7c.toByte(), + 0x7c.toByte(), 0x35.toByte(), 0xb5.toByte(), 0xdd.toByte(), 0xbc.toByte(), 0x92.toByte(), 0xbb.toByte(), 0x81.toByte(), + 0xe4.toByte(), 0x1f.toByte(), 0xa8.toByte(), 0x40.toByte(), 0x41.toByte(), 0x05.toByte(), 0x44.toByte(), 0x8d.toByte() + ) + + // when + val publicKey = SolanaPublicKey.from(base58) + + // then + assertContentEquals(expectedPublicKeyBytes, publicKey.bytes) + } + + @Test + fun testPublicKeyToString() { + // given + val expectedBase58 = "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr" // Memo program v2 account address + val publicKeyBytes = byteArrayOf( + 0x05.toByte(), 0x4a.toByte(), 0x53.toByte(), 0x5a.toByte(), 0x99.toByte(), 0x29.toByte(), 0x21.toByte(), 0x06.toByte(), + 0x4d.toByte(), 0x24.toByte(), 0xe8.toByte(), 0x71.toByte(), 0x60.toByte(), 0xda.toByte(), 0x38.toByte(), 0x7c.toByte(), + 0x7c.toByte(), 0x35.toByte(), 0xb5.toByte(), 0xdd.toByte(), 0xbc.toByte(), 0x92.toByte(), 0xbb.toByte(), 0x81.toByte(), + 0xe4.toByte(), 0x1f.toByte(), 0xa8.toByte(), 0x40.toByte(), 0x41.toByte(), 0x05.toByte(), 0x44.toByte(), 0x8d.toByte() + ) + + // when + val publicKey = SolanaPublicKey(publicKeyBytes) + + // then + assertEquals(expectedBase58, publicKey.string()) + } +} \ No newline at end of file diff --git a/solana/src/commonTest/kotlin/com/funkatronics/transaction/InstructionTests.kt b/solana/src/commonTest/kotlin/com/funkatronics/transaction/InstructionTests.kt new file mode 100644 index 0000000..692a56c --- /dev/null +++ b/solana/src/commonTest/kotlin/com/funkatronics/transaction/InstructionTests.kt @@ -0,0 +1,28 @@ +package com.funkatronics.transaction + +import com.funkatronics.serialization.TransactionFormat +import com.funkatronics.util.asVarint +import kotlin.test.Test +import kotlin.test.assertContentEquals + +class InstructionTests { + + @Test + fun testInstructionSerialize() { + // given + val programIdIndex = 1.toUByte() + val accountAddressIndices = byteArrayOf(0) + val data = "hello world".encodeToByteArray() + val instruction = Instruction(programIdIndex, accountAddressIndices, data) + + val expectedBytes = byteArrayOf(programIdIndex.toByte()) + + accountAddressIndices.size.asVarint() + accountAddressIndices + + data.size.asVarint() + data + + // when + val serializedTransaction = TransactionFormat.encodeToByteArray(Instruction.serializer(), instruction) + + // then + assertContentEquals(expectedBytes, serializedTransaction) + } +} \ No newline at end of file diff --git a/solana/src/commonTest/kotlin/com/funkatronics/transaction/MessageTests.kt b/solana/src/commonTest/kotlin/com/funkatronics/transaction/MessageTests.kt new file mode 100644 index 0000000..9524c01 --- /dev/null +++ b/solana/src/commonTest/kotlin/com/funkatronics/transaction/MessageTests.kt @@ -0,0 +1,86 @@ +package com.funkatronics.transaction + +import com.funkatronics.encoders.Base64 +import com.funkatronics.publickey.SolanaPublicKey +import com.funkatronics.util.asVarint +import kotlin.test.Test +import kotlin.test.assertContentEquals + +class MessageTests { + + @Test + fun testMessageSerialize() { + // given + val accounts = listOf( + SolanaPublicKey(ByteArray(32) {0}), + SolanaPublicKey(ByteArray(32) {1}), + SolanaPublicKey(ByteArray(32) {2}), + SolanaPublicKey(ByteArray(32) {3}) + ) + + val blockhash = Blockhash(ByteArray(32) {9}) + + val programIdIndex = 1.toUByte() + val accountAddressIndices = byteArrayOf(0) + val data = "hello world".encodeToByteArray() + val instruction = Instruction(programIdIndex, accountAddressIndices, data) + + val message = LegacyMessage(1.toUByte(), 2.toUByte(), 3.toUByte(), accounts, blockhash, listOf(instruction)) + + val expectedBytes = + byteArrayOf(message.signatureCount.toByte(), message.readOnlyAccounts.toByte(), message.readOnlyNonSigners.toByte()) + + 4.asVarint() + ByteArray(32) {0} + ByteArray(32) {1} + ByteArray(32) {2} + ByteArray(32) {3} + + ByteArray(32) {9} + + 1.asVarint() + programIdIndex.toInt().asVarint() + byteArrayOf(1, 0) + data.size.asVarint() + data + + // when + val serializedMessage = message.serialize() + + // then + assertContentEquals(expectedBytes, serializedMessage) + } + + @Test + fun testBuildMessage() { + // given + val account = SolanaPublicKey(Base64.decode("XJy50755nz75BGthIrxe7XIQ9WkcMxgIOCmqEM30qq4")) + val programId = SolanaPublicKey.from("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr") + val blockhash = Blockhash(ByteArray(32)) + val data = "hello world ".encodeToByteArray() + + val memoInstruction = TransactionInstruction( + programId, + listOf(AccountMeta(account, true, true)), + data + ) + + val memoInstructionTemplate = + //region sign data + byteArrayOf( + 0x01.toByte(), // 1 signature required (fee payer) + 0x00.toByte(), // 0 read-only account signatures + 0x01.toByte(), // 1 read-only account not requiring a signature + 0x02.toByte(), // 2 accounts + ) + account.bytes + programId.bytes + blockhash.bytes + + //endregion + //region instructions + byteArrayOf( + 0x01.toByte(), // 1 instruction (memo) + 0x01.toByte(), // program ID (index into list of accounts) + 0x01.toByte(), // 1 account + 0x00.toByte(), // account index 0 + 0x0C.toByte(), // 20 byte payload + ) + data + + // when + val message = Message.Builder() + .addInstruction(memoInstruction) + .setRecentBlockhash(blockhash) + .build() + + val serializedMessage = message.serialize() + + // then + assertContentEquals(memoInstructionTemplate, serializedMessage) + } +} \ No newline at end of file diff --git a/solana/src/commonTest/kotlin/com/funkatronics/transaction/TransactionFormatTests.kt b/solana/src/commonTest/kotlin/com/funkatronics/transaction/TransactionFormatTests.kt new file mode 100644 index 0000000..a95ea6e --- /dev/null +++ b/solana/src/commonTest/kotlin/com/funkatronics/transaction/TransactionFormatTests.kt @@ -0,0 +1,398 @@ +package com.funkatronics.transaction + +import com.funkatronics.encoders.Base64 +import com.funkatronics.publickey.SolanaPublicKey +import com.funkatronics.serialization.TransactionFormat +import com.funkatronics.util.asVarint +import kotlin.experimental.or +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals + +class TransactionFormatTests { + + @Test + fun testSerializeInstruction() { + // given + val programIdIndex = 1.toUByte() + val accountAddressIndices = byteArrayOf(0) + val data = "hello world".encodeToByteArray() + val instruction = Instruction(programIdIndex, accountAddressIndices, data) + + val expectedBytes = byteArrayOf(programIdIndex.toByte()) + + accountAddressIndices.size.asVarint() + accountAddressIndices + + data.size.asVarint() + data + + // when + val serializedTransaction = TransactionFormat.encodeToByteArray(Instruction.serializer(), instruction) + + // then + assertContentEquals(expectedBytes, serializedTransaction) + } + + @Test + fun testSerializeLegacyMessage() { + // given + val accounts = listOf( + SolanaPublicKey(ByteArray(32) {0}), + SolanaPublicKey(ByteArray(32) {1}), + SolanaPublicKey(ByteArray(32) {2}), + SolanaPublicKey(ByteArray(32) {3}) + ) + + val blockhash = Blockhash(ByteArray(32) {9}) + + val programIdIndex = 1.toUByte() + val accountAddressIndices = byteArrayOf(0) + val data = "hello world".encodeToByteArray() + val instruction = Instruction(programIdIndex, accountAddressIndices, data) + + val message = LegacyMessage(1.toUByte(), 2.toUByte(), 3.toUByte(), accounts, blockhash, listOf(instruction)) + + val expectedBytes = + byteArrayOf(message.signatureCount.toByte(), message.readOnlyAccounts.toByte(), message.readOnlyNonSigners.toByte()) + + 4.asVarint() + ByteArray(32) {0} + ByteArray(32) {1} + ByteArray(32) {2} + ByteArray(32) {3} + + ByteArray(32) {9} + + 1.asVarint() + programIdIndex.toInt().asVarint() + byteArrayOf(1, 0) + data.size.asVarint() + data + + // when + val serializedMessage = TransactionFormat.encodeToByteArray(MessageSerializer, message) + + // then + assertContentEquals(expectedBytes, serializedMessage) + } + + @Test + fun testSerializeVersionedMessage() { + // given + val accounts = listOf( + SolanaPublicKey(ByteArray(32) {0}), + SolanaPublicKey(ByteArray(32) {1}), + SolanaPublicKey(ByteArray(32) {2}), + SolanaPublicKey(ByteArray(32) {3}) + ) + + val blockhash = Blockhash(ByteArray(32) {9}) + + val programIdIndex = 1.toUByte() + val accountAddressIndices = byteArrayOf(0) + val data = "hello world".encodeToByteArray() + val instruction = Instruction(programIdIndex, accountAddressIndices, data) + + val message = VersionedMessage(0, 1.toUByte(), 2.toUByte(), 3.toUByte(), accounts, blockhash, listOf(instruction), listOf()) + + val expectedBytes = + byteArrayOf(0x80.toByte() or message.version, message.signatureCount.toByte(), message.readOnlyAccounts.toByte(), message.readOnlyNonSigners.toByte()) + + 4.asVarint() + ByteArray(32) {0} + ByteArray(32) {1} + ByteArray(32) {2} + ByteArray(32) {3} + + ByteArray(32) {9} + + 1.asVarint() + programIdIndex.toInt().asVarint() + byteArrayOf(1, 0) + data.size.asVarint() + data + byteArrayOf(0) + + // when + val serializedMessage = TransactionFormat.encodeToByteArray(MessageSerializer, message) + + // then + assertContentEquals(expectedBytes, serializedMessage) + } + + @Test + fun testSerializeLegacyTransaction() { + // given + val account = SolanaPublicKey(Base64.decode("XJy50755nz75BGthIrxe7XIQ9WkcMxgIOCmqEM30qq4")) + val programId = SolanaPublicKey.from("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr") + val blockhash = Blockhash(ByteArray(32)) + val signature = ByteArray(64) + val data = "hello world ".encodeToByteArray() + + val memoTransactionTemplate = + //region signature + byteArrayOf(1) + // 1 signature required (fee payer) + signature + + //endregion + //region sign data + byteArrayOf( + 0x01.toByte(), // 1 signature required (fee payer) + 0x00.toByte(), // 0 read-only account signatures + 0x01.toByte(), // 1 read-only account not requiring a signature + 0x02.toByte(), // 2 accounts + ) + account.bytes + programId.bytes + blockhash.bytes + + //endregion + //region instructions + byteArrayOf( + 0x01.toByte(), // 1 instruction (memo) + 0x01.toByte(), // program ID (index into list of accounts) + 0x01.toByte(), // 1 account + 0x00.toByte(), // account index 0 + 0x0C.toByte(), // 20 byte payload + ) + data + + val accounts = listOf(account, programId) + val instructions = listOf(Instruction(1u, byteArrayOf(0), data)) + val memoTxMessage = LegacyMessage( + 1u, + 0u, + 1u, + accounts, + blockhash, + instructions + ) + + val transaction = Transaction(listOf(signature), memoTxMessage) + + // when + val transactionBytes = TransactionFormat.encodeToByteArray(Transaction.serializer(), transaction) + + val accountsOffset = 1 + 64 + 4 + val blockhashOffset = accountsOffset + 2*SolanaPublicKey.PUBLIC_KEY_LENGTH + val instructionOffset = blockhashOffset + SolanaPublicKey.PUBLIC_KEY_LENGTH + + // then + assertEquals(memoTransactionTemplate[0], transactionBytes[0]) // signature count + assertContentEquals(memoTransactionTemplate.slice(1 .. signature.size), transactionBytes.slice(1 .. signature.size)) + assertEquals(memoTransactionTemplate[signature.size + 1].toUByte(), memoTxMessage.signatureCount) + assertEquals(memoTransactionTemplate[signature.size + 2].toUByte(), memoTxMessage.readOnlyAccounts) + assertEquals(memoTransactionTemplate[signature.size + 3].toUByte(), memoTxMessage.readOnlyNonSigners) + assertEquals(memoTransactionTemplate[signature.size + 4], 2) // number of accounts + + assertContentEquals( + account.bytes.asList(), + transactionBytes.slice(accountsOffset until accountsOffset + SolanaPublicKey.PUBLIC_KEY_LENGTH) + ) + assertContentEquals( + programId.bytes.asList(), + transactionBytes.slice(accountsOffset + SolanaPublicKey.PUBLIC_KEY_LENGTH until blockhashOffset) + ) + + assertContentEquals( + blockhash.bytes.asList(), + transactionBytes.slice(blockhashOffset until blockhashOffset + SolanaPublicKey.PUBLIC_KEY_LENGTH) + ) + + assertEquals(1, transactionBytes[instructionOffset]) // instruction count + assertEquals(1, transactionBytes[instructionOffset + 1]) // program id index + assertEquals(1, transactionBytes[instructionOffset + 2]) // account count + assertEquals(0, transactionBytes[instructionOffset + 3]) // account index + + assertEquals(12, transactionBytes[instructionOffset + 4]) // data length + assertContentEquals(data, transactionBytes.sliceArray(instructionOffset + 5 .. instructionOffset + 4 + 12)) + + assertContentEquals(memoTransactionTemplate, transactionBytes) + } + + @Test + fun testSerializeVersionedTransaction() { + // given + val account = SolanaPublicKey(Base64.decode("XJy50755nz75BGthIrxe7XIQ9WkcMxgIOCmqEM30qq4")) + val programId = SolanaPublicKey.from("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr") + val blockhash = Blockhash(ByteArray(32)) + val signature = ByteArray(64) + val data = "hello world ".encodeToByteArray() + + val memoTransactionTemplate = + //region signature + byteArrayOf(1) + // 1 signature required (fee payer) + signature + + //endregion + byteArrayOf(0x80.toByte()) + // prefix 0b10000000 + //region sign data + byteArrayOf( + 0x01.toByte(), // 1 signature required (fee payer) + 0x00.toByte(), // 0 read-only account signatures + 0x01.toByte(), // 1 read-only account not requiring a signature + 0x02.toByte(), // 2 accounts + ) + account.bytes + programId.bytes + blockhash.bytes + + //endregion + //region instructions + byteArrayOf( + 0x01.toByte(), // 1 instruction (memo) + 0x01.toByte(), // program ID (index into list of accounts) + 0x01.toByte(), // 1 account + 0x00.toByte(), // account index 0 + 0x0C.toByte(), // 20 byte payload + ) + data + + //endregion + //region address table lookups + byteArrayOf(0x00.toByte()) // 0 address table lookups + //endregion + + val accounts = listOf(account, programId) + val instructions = listOf(Instruction(1u, byteArrayOf(0), data)) + val memoTxMessage = VersionedMessage( + 0, + 1u, + 0u, + 1u, + accounts, + blockhash, + instructions, + listOf() + ) + + val transaction = Transaction(listOf(signature), memoTxMessage) + + // when + val transactionBytes = TransactionFormat.encodeToByteArray(Transaction.serializer(), transaction) + + val accountsOffset = 1 + 64 + 4 + 1 + val blockhashOffset = accountsOffset + 2*SolanaPublicKey.PUBLIC_KEY_LENGTH + val instructionOffset = blockhashOffset + SolanaPublicKey.PUBLIC_KEY_LENGTH + + // then + assertEquals(memoTransactionTemplate[0], transactionBytes[0]) // signature count + assertContentEquals(memoTransactionTemplate.slice(1 .. signature.size), transactionBytes.slice(1 .. signature.size)) + assertEquals(memoTransactionTemplate[signature.size + 2].toUByte(), memoTxMessage.signatureCount) + assertEquals(memoTransactionTemplate[signature.size + 3].toUByte(), memoTxMessage.readOnlyAccounts) + assertEquals(memoTransactionTemplate[signature.size + 4].toUByte(), memoTxMessage.readOnlyNonSigners) + assertEquals(memoTransactionTemplate[signature.size + 5], 2) // number of accounts + + assertContentEquals( + account.bytes.asList(), + transactionBytes.slice(accountsOffset until accountsOffset + SolanaPublicKey.PUBLIC_KEY_LENGTH) + ) + assertContentEquals( + programId.bytes.asList(), + transactionBytes.slice(accountsOffset + SolanaPublicKey.PUBLIC_KEY_LENGTH until blockhashOffset) + ) + + assertContentEquals( + blockhash.bytes.asList(), + transactionBytes.slice(blockhashOffset until blockhashOffset + SolanaPublicKey.PUBLIC_KEY_LENGTH) + ) + + assertEquals(1, transactionBytes[instructionOffset]) // instruction count + assertEquals(1, transactionBytes[instructionOffset + 1]) // program id index + assertEquals(1, transactionBytes[instructionOffset + 2]) // account count + assertEquals(0, transactionBytes[instructionOffset + 3]) // account index + + assertEquals(12, transactionBytes[instructionOffset + 4]) // data length + assertContentEquals(data, transactionBytes.sliceArray(instructionOffset + 5 .. instructionOffset + 4 + 12)) + + assertContentEquals(memoTransactionTemplate, transactionBytes) + } + + @Test + fun testDeserializeLegacyTransaction() { + // given + val account = SolanaPublicKey(Base64.decode("XJy50755nz75BGthIrxe7XIQ9WkcMxgIOCmqEM30qq4")) + val programId = SolanaPublicKey.from("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr") + val blockhash = Blockhash(ByteArray(32)) + val signature = ByteArray(64) + val data = "hello world ".encodeToByteArray() + + val memoTransactionBytes = + //region signature + byteArrayOf(1) + // 1 signature required (fee payer) + signature + + //endregion + //region sign data + byteArrayOf( + 0x01.toByte(), // 1 signature required (fee payer) + 0x00.toByte(), // 0 read-only account signatures + 0x01.toByte(), // 1 read-only account not requiring a signature + 0x02.toByte(), // 2 accounts + ) + account.bytes + programId.bytes + blockhash.bytes + + //endregion + //region instructions + byteArrayOf( + 0x01.toByte(), // 1 instruction (memo) + 0x01.toByte(), // program ID (index into list of accounts) + 0x01.toByte(), // 1 account + 0x00.toByte(), // account index 0 + 0x0C.toByte(), // 20 byte payload + ) + data + + val accounts = listOf(account, programId) + val instructions = listOf(Instruction(1u, byteArrayOf(0), data)) + val memoTxMessage = LegacyMessage( + 1u, + 0u, + 1u, + accounts, + blockhash, + instructions + ) + + // when + val transaction = TransactionFormat.decodeFromByteArray(Transaction.serializer(), memoTransactionBytes) + val transactionBytes = TransactionFormat.encodeToByteArray(Transaction.serializer(), transaction) + + // then + assertEquals(1, transaction.signatures.size) + assertContentEquals(signature, transaction.signatures.first()) + assertEquals(memoTxMessage.signatureCount, (transaction.message as LegacyMessage).signatureCount) + assertEquals(memoTxMessage.readOnlyAccounts, (transaction.message as LegacyMessage).readOnlyAccounts) + assertEquals(memoTxMessage.readOnlyNonSigners, (transaction.message as LegacyMessage).readOnlyNonSigners) + assertContentEquals(memoTxMessage.accounts, (transaction.message as LegacyMessage).accounts) + assertEquals(memoTxMessage.blockhash, (transaction.message as LegacyMessage).blockhash) + assertContentEquals(memoTxMessage.instructions, (transaction.message as LegacyMessage).instructions) + + assertContentEquals(memoTransactionBytes, transactionBytes) + } + + @Test + fun testDeserializeVersionedTransaction() { + // given + val account = SolanaPublicKey(Base64.decode("XJy50755nz75BGthIrxe7XIQ9WkcMxgIOCmqEM30qq4")) + val programId = SolanaPublicKey.from("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr") + val blockhash = Blockhash(ByteArray(32)) + val signature = ByteArray(64) + val data = "hello world ".encodeToByteArray() + + val memoTransactionBytes = + //region signature + byteArrayOf(1) + // 1 signature required (fee payer) + signature + + //endregion + byteArrayOf(0x80.toByte()) + // prefix 0b10000000 + //region sign data + byteArrayOf( + 0x01.toByte(), // 1 signature required (fee payer) + 0x00.toByte(), // 0 read-only account signatures + 0x01.toByte(), // 1 read-only account not requiring a signature + 0x02.toByte(), // 2 accounts + ) + account.bytes + programId.bytes + blockhash.bytes + + //endregion + //region instructions + byteArrayOf( + 0x01.toByte(), // 1 instruction (memo) + 0x01.toByte(), // program ID (index into list of accounts) + 0x01.toByte(), // 1 account + 0x00.toByte(), // account index 0 + 0x0C.toByte(), // 20 byte payload + ) + data + + //endregion + //region address table lookups + byteArrayOf(0x00.toByte()) // 0 address table lookups + //endregion + + val accounts = listOf(account, programId) + val instructions = listOf(Instruction(1u, byteArrayOf(0), data)) + val memoTxMessage = VersionedMessage( + 0, + 1u, + 0u, + 1u, + accounts, + blockhash, + instructions, + listOf() + ) + + // when + val transaction = TransactionFormat.decodeFromByteArray(Transaction.serializer(), memoTransactionBytes) + val transactionBytes = TransactionFormat.encodeToByteArray(Transaction.serializer(), transaction) + + // then + assertEquals(1, transaction.signatures.size) + assertContentEquals(signature, transaction.signatures.first()) + assertEquals(memoTxMessage.version, (transaction.message as VersionedMessage).version) + assertEquals(memoTxMessage.signatureCount, (transaction.message as VersionedMessage).signatureCount) + assertEquals(memoTxMessage.readOnlyAccounts, (transaction.message as VersionedMessage).readOnlyAccounts) + assertEquals(memoTxMessage.readOnlyNonSigners, (transaction.message as VersionedMessage).readOnlyNonSigners) + assertContentEquals(memoTxMessage.accounts, (transaction.message as VersionedMessage).accounts) + assertEquals(memoTxMessage.blockhash, (transaction.message as VersionedMessage).blockhash) + assertContentEquals(memoTxMessage.instructions, (transaction.message as VersionedMessage).instructions) + assertContentEquals(memoTxMessage.addressTableLookups, (transaction.message as VersionedMessage).addressTableLookups) + + assertContentEquals(memoTransactionBytes, transactionBytes) + } +} \ No newline at end of file diff --git a/solana/src/commonTest/kotlin/com/funkatronics/transaction/TransactionTests.kt b/solana/src/commonTest/kotlin/com/funkatronics/transaction/TransactionTests.kt new file mode 100644 index 0000000..e2c4155 --- /dev/null +++ b/solana/src/commonTest/kotlin/com/funkatronics/transaction/TransactionTests.kt @@ -0,0 +1,100 @@ +package com.funkatronics.transaction + +import com.funkatronics.encoders.Base64 +import com.funkatronics.publickey.SolanaPublicKey +import com.funkatronics.serialization.TransactionFormat +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals + +class TransactionTests { + + @Test + fun testTransaction() { + // given + val account = SolanaPublicKey(Base64.decode("XJy50755nz75BGthIrxe7XIQ9WkcMxgIOCmqEM30qq4")) + val programId = SolanaPublicKey.from("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr") + val blockhash = Blockhash(ByteArray(32)) + val signature = ByteArray(64) + val data = "hello world ".encodeToByteArray() + + val memoTransactionTemplate = + //region signature + byteArrayOf(1) + // 1 signature required (fee payer) + signature + + //endregion +// byteArrayOf(0x80.toByte()) + // prefix 0b10000000 + //region sign data + byteArrayOf( + 0x01.toByte(), // 1 signature required (fee payer) + 0x00.toByte(), // 0 read-only account signatures + 0x01.toByte(), // 1 read-only account not requiring a signature + 0x02.toByte(), // 2 accounts + ) + account.bytes + programId.bytes + blockhash.bytes + + //endregion + //region instructions + byteArrayOf( + 0x01.toByte(), // 1 instruction (memo) + 0x01.toByte(), // program ID (index into list of accounts) + 0x01.toByte(), // 1 account + 0x00.toByte(), // account index 0 + 0x0C.toByte(), // 20 byte payload + ) + data //+ + //endregion + //region address table lookups +// byteArrayOf(0x00.toByte()) // 0 address table lookups + //endregion + + val accounts = listOf(account, programId) + val instructions = listOf(Instruction(1u, byteArrayOf(0), data)) + val memoTxMessage = LegacyMessage( + 1u, + 0u, + 1u, + accounts, + blockhash, + instructions + ) + + val transaction = Transaction(listOf(signature), memoTxMessage) + + // when + val transactionBytes = TransactionFormat.encodeToByteArray(Transaction.serializer(), transaction) + + val accountsOffset = 1 + 64 + 4 + val blockhashOffset = accountsOffset + 2*SolanaPublicKey.PUBLIC_KEY_LENGTH + val instructionOffset = blockhashOffset + SolanaPublicKey.PUBLIC_KEY_LENGTH + + // then + assertEquals(memoTransactionTemplate[0], transactionBytes[0]) // signature count + assertContentEquals(memoTransactionTemplate.slice(1 .. signature.size), transactionBytes.slice(1 .. signature.size)) + assertEquals(memoTransactionTemplate[signature.size + 1].toUByte(), memoTxMessage.signatureCount) + assertEquals(memoTransactionTemplate[signature.size + 2].toUByte(), memoTxMessage.readOnlyAccounts) + assertEquals(memoTransactionTemplate[signature.size + 3].toUByte(), memoTxMessage.readOnlyNonSigners) + assertEquals(memoTransactionTemplate[signature.size + 4], 2) // number of accounts + + assertContentEquals( + account.bytes.asList(), + transactionBytes.slice(accountsOffset until accountsOffset + SolanaPublicKey.PUBLIC_KEY_LENGTH) + ) + assertContentEquals( + programId.bytes.asList(), + transactionBytes.slice(accountsOffset + SolanaPublicKey.PUBLIC_KEY_LENGTH until blockhashOffset) + ) + + assertContentEquals( + blockhash.bytes.asList(), + transactionBytes.slice(blockhashOffset until blockhashOffset + SolanaPublicKey.PUBLIC_KEY_LENGTH) + ) + + assertEquals(1, transactionBytes[instructionOffset]) // instruction count + assertEquals(1, transactionBytes[instructionOffset + 1]) // program id index + assertEquals(1, transactionBytes[instructionOffset + 2]) // account count + assertEquals(0, transactionBytes[instructionOffset + 3]) // account index + + assertEquals(12, transactionBytes[instructionOffset + 4]) // data length + assertContentEquals(data, transactionBytes.sliceArray(instructionOffset + 5 .. instructionOffset + 4 + 12)) + + assertContentEquals(memoTransactionTemplate, transactionBytes) + } +} \ No newline at end of file