Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

WIP: v0.3.0 #12

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ on:
push:
branches: [ main ]
pull_request:
branches: [ main, develop ]
branches: [ main, develop, 'v[0-9].[0-9]+.[0-9]+' ]
release:
types: [ published ]

Expand All @@ -23,9 +23,9 @@ jobs:
uses: gradle/wrapper-validation-action@v1

- name: Configure JDK
uses: actions/setup-java@v3
uses: actions/setup-java@v4
with:
java-version: '11'
java-version: '17'
distribution: 'temurin'
cache: gradle

Expand Down Expand Up @@ -60,9 +60,9 @@ jobs:
uses: actions/checkout@v3

- name: Configure JDK
uses: actions/setup-java@v3
uses: actions/setup-java@v4
with:
java-version: '11'
java-version: '17'
distribution: 'temurin'
cache: gradle

Expand Down
2 changes: 2 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
plugins {
alias(libs.plugins.kotlin.multiplatform) apply false
alias(libs.plugins.publish) apply false
alias(libs.plugins.android.library) apply false
alias(libs.plugins.kotlin.android) apply false
}

//tasks.register("clean", Delete::class) {
Expand Down
8 changes: 5 additions & 3 deletions core/src/commonMain/kotlin/com/solana/signer/Signer.kt
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package com.solana.signer

import com.solana.publickey.PublicKey

interface Signer {
val publicKey: ByteArray
val publicKey: PublicKey
val ownerLength: Number
val signatureLength: Number
suspend fun signPayload(payload: ByteArray): ByteArray
}
suspend fun signPayload(payload: ByteArray): Result<ByteArray>
}
3 changes: 3 additions & 0 deletions gradle.properties
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
kotlin.code.style=official
kotlin.js.compiler=ir

#Android
android.useAndroidX=true

# Group name and project version, used when publishing. For official releases, the version should be
# provided to Gradle via '-P version="1.0"'.
group=com.solanamobile
Expand Down
22 changes: 18 additions & 4 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
[versions]
kotlinxCoroutines = "1.7.3"
androidxActivityKtx = "1.9.0"
diglolCrypto="0.1.5"
kotlinxCoroutines= "1.7.3"
ktor = "2.3.11"
mobileWalletAdapter="2.0.2"
mockitoInline = "5.2.0"
mockitoKotlin = "4.1.0"
robolectric = "4.12.2"

# Plugin versions
androidGradlePlugin = "8.0.2"
Expand All @@ -9,20 +15,28 @@ kotlinSerialization = "1.6.2"
vanniktechMavenPublish = "0.25.3"

[libraries]
androidx-activity-ktx = { module = "androidx.activity:activity-ktx", version.ref = "androidxActivityKtx" }
borsh = { group = "io.github.funkatronics", name = "kborsh", version = "0.1.0" }
crypto = { group = "com.diglol.crypto", name = "crypto", version = "0.1.5" }
crypto = { group = "com.diglol.crypto", name = "crypto", version.ref = "diglolCrypto" }
pkc = { group = "com.diglol.crypto", name = "pkc", version.ref = "diglolCrypto" }
kotlin-test = { group = "org.jetbrains.kotlin", name = "kotlin-test" }
kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "kotlinSerialization" }
#kotlinx-coroutines-core = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-core", version.ref = "kotlinxCoroutines" }
kotlinx-coroutines-core = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-core", version.ref = "kotlinxCoroutines" }
kotlinx-coroutines-test = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-test", version.ref = "kotlinxCoroutines" }
kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "kotlinSerialization" }
ktor-client-core = { group = "io.ktor", name = "ktor-client-core", version.ref = "ktor" }
ktor-client-cio = { group = "io.ktor", name = "ktor-client-cio", version.ref = "ktor" }
mockito-inline = { module = "org.mockito:mockito-inline", version.ref = "mockitoInline" }
mockito-kotlin = { module = "org.mockito.kotlin:mockito-kotlin", version.ref = "mockitoKotlin" }
multimult = { group = "io.github.funkatronics", name = "multimult", version = "0.2.3" }
mwa-clientlib-ktx = { module = "com.solanamobile:mobile-wallet-adapter-clientlib-ktx", version.ref = "mobileWalletAdapter" }
mwa-walletlib = { module = "com.solanamobile:mobile-wallet-adapter-walletlib", version.ref = "mobileWalletAdapter" }
robolectric = { module = "org.robolectric:robolectric", version.ref = "robolectric" }
rpc-core = { group = "com.solanamobile", name = "rpc-core", version = "0.2.5" }
salkt = { group = "io.github.funkatronics", name = "salkt", version = "0.1.0" }

[plugins]
android-library = { id = "com.android.library", version.ref = "androidGradlePlugin" }
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
kotlin-multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
publish = { id = "com.vanniktech.maven.publish", version.ref = "vanniktechMavenPublish" }
55 changes: 55 additions & 0 deletions mwa-signer/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
@Suppress("DSL_SCOPE_VIOLATION") // TODO: Remove once KTIJ-19369 is fixed
plugins {
alias(libs.plugins.android.library)
alias(libs.plugins.kotlin.android)
alias(libs.plugins.publish)
}

val artifactIdPrefix: String by project
val moduleArtifactId = "$artifactIdPrefix-mwa-signer"

android {
namespace = "com.solana.signer.mwa"
compileSdk = 34

defaultConfig {
minSdk = 24

testInstrumentationRunner = "android.support.test.runner.AndroidJUnitRunner"
consumerProguardFiles("consumer-rules.pro")
}

buildTypes {
release {
isMinifyEnabled = false
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
kotlinOptions {
jvmTarget = "11"
}
}

dependencies {
api(project(mapOf("path" to ":solana")))
implementation(libs.mwa.clientlib.ktx)
implementation(libs.kotlinx.coroutines.core)
implementation(libs.multimult)

testImplementation(libs.kotlin.test)
testImplementation(libs.kotlinx.coroutines.test)
testImplementation(libs.androidx.activity.ktx)
testImplementation(libs.mockito.inline)
testImplementation(libs.mockito.kotlin)
testImplementation(libs.mwa.walletlib)
testImplementation(libs.pkc)
testImplementation(libs.robolectric)
}

mavenPublishing {
coordinates(group as String, moduleArtifactId, "0.1.0")
}
Empty file added mwa-signer/consumer-rules.pro
Empty file.
21 changes: 21 additions & 0 deletions mwa-signer/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
2 changes: 2 additions & 0 deletions mwa-signer/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest />
107 changes: 107 additions & 0 deletions mwa-signer/src/main/java/com/solana/signer/mwa/MwaSigner.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package com.solana.signer.mwa

import com.funkatronics.encoders.Base64
import com.solana.publickey.SolanaPublicKey
import com.solana.transaction.Message
import com.solana.transaction.Transaction
import com.solana.mobilewalletadapter.clientlib.ActivityResultSender
import com.solana.mobilewalletadapter.clientlib.ConnectionIdentity
import com.solana.mobilewalletadapter.clientlib.MobileWalletAdapter
import com.solana.mobilewalletadapter.clientlib.TransactionResult
import com.solana.mobilewalletadapter.clientlib.successPayload
import com.solana.signer.SolanaSigner

private typealias SignedPayloadResult = Pair<ByteArray, ByteArray>
private infix fun ByteArray.withSignature(signature: ByteArray): SignedPayloadResult = Pair(this, signature)
private val SignedPayloadResult.payload get() = first
private val SignedPayloadResult.signature get() = second

class MwaSigner(val walletAdapter: MobileWalletAdapter, val sender: ActivityResultSender) : SolanaSigner() {

constructor(connectionIdentity: ConnectionIdentity, sender: ActivityResultSender)
: this(MobileWalletAdapter(connectionIdentity), sender)

private val placeholderPublicKey = SolanaPublicKey.from("Mobi1eWa11etAdapter111111111111111111111111")
private var authorizedPublicKey: SolanaPublicKey? = null

override val publicKey: SolanaPublicKey
get() = authorizedPublicKey ?: placeholderPublicKey//throw IllegalStateException("No wallet connected, call MwaSigner.connect()")

suspend fun connect(): TransactionResult<Unit> {
return walletAdapter.transact(sender) { authResult ->
authorizedPublicKey = SolanaPublicKey(authResult.accounts.first().publicKey)
}
}

override suspend fun signPayload(payload: ByteArray): Result<ByteArray> =
signPayloadInternal(payload).map { it.signature }

override suspend fun signAndSendTransaction(transaction: Transaction): Result<String> =
when (val result = walletAdapter.transact(sender) { authResult ->
authorizedPublicKey = SolanaPublicKey(authResult.accounts.first().publicKey)
signAndSendTransactions(arrayOf(transaction.serialize()))
}) {
is TransactionResult.Success ->
Result.success(Base64.encodeToString(result.payload.signatures.first()))
is TransactionResult.Failure ->
Result.failure(SignPayloadException(result.message, result.e))
is TransactionResult.NoWalletFound ->
Result.failure(NoWalletFoundException())
}

override suspend fun signTransaction(transactionMessage: Message): Result<Transaction> {
val signers = transactionMessage.accounts.take(transactionMessage.signatureCount.toInt())
val signerIndex = signers.indexOf(publicKey)
if (signerIndex == -1) {
return Result.failure(IllegalArgumentException(
"Transaction does not require a signature from this public key (${publicKey.base58()})"
))
}

return signPayloadInternal(transactionMessage.serialize()).map { result ->
Transaction(MutableList(transactionMessage.signatureCount.toInt()) { ByteArray(ownerLength) }.apply {
set(signerIndex, result.signature)
}, Message.from(result.payload))
}
}

class SignPayloadException(message: String, cause: Throwable): Exception(message, cause)
class NoWalletFoundException: Exception("Cannot sign payload: no wallet found")

private suspend fun signPayloadInternal(payload: ByteArray): Result<SignedPayloadResult> =
when (val result = walletAdapter.transact(sender) { authResult ->
authorizedPublicKey = SolanaPublicKey(authResult.accounts.first().publicKey)
if (runCatching {
Message.from(payload)
}.isSuccess) {
// replace the placeholder pubkey with the real one (authorizedPublicKey)
val newPayload = payload.replace(placeholderPublicKey.bytes, authorizedPublicKey!!.bytes)
newPayload withSignature signTransactions(arrayOf(newPayload)).signedPayloads.first()
} else {
payload withSignature signMessagesDetached(
arrayOf(payload),
arrayOf(authorizedPublicKey!!.bytes)
).messages.first().signatures.first()
}
}) {
is TransactionResult.Success ->
Result.success(result.successPayload!!)
is TransactionResult.Failure ->
Result.failure(SignPayloadException(result.message, result.e))
is TransactionResult.NoWalletFound ->
Result.failure(NoWalletFoundException())
}

private fun ByteArray.replace(oldBytes: ByteArray, newBytes: ByteArray): ByteArray {
var pos = 0
forEachIndexed { index, byte ->
if (byte == oldBytes[pos]) pos++ else pos = 0

if (pos == oldBytes.size) {
newBytes.copyInto(this, index - pos + 1)
pos = 0
}
}
return this
}
}
Loading
Loading