Skip to content

Commit

Permalink
refactor: drop gson dependency
Browse files Browse the repository at this point in the history
Use kotlinx.serialization instead of GSON to deserialize Keyset from JSON.

Work towards resolving issue #3.
  • Loading branch information
kirillzh committed Jun 25, 2024
1 parent bcd9bec commit b1b8e84
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 9 deletions.
1 change: 0 additions & 1 deletion lib/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ repositories {

dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0")
implementation("com.google.code.gson:gson:2.10.1")

// Bitcoin
implementation("fr.acinq.bitcoin:bitcoin-kmp-jvm:0.14.0")
Expand Down
18 changes: 10 additions & 8 deletions lib/src/main/kotlin/me/tb/cashuclient/types/Keyset.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@
* Copyright 2023 thunderbiscuit and contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the ./LICENSE.txt file.
*/

package me.tb.cashuclient.types

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import fr.acinq.bitcoin.PublicKey
import fr.acinq.bitcoin.crypto.Digest
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import java.util.SortedMap

/**
Expand Down Expand Up @@ -59,7 +60,8 @@ public class Keyset(
* @throws Exception if no key is found for the given token value.
*/
public fun getKey(tokenValue: ULong): PublicKey {
return sortedKeyset[tokenValue] ?: throw Exception("No key found in keyset for token value $tokenValue")
return sortedKeyset[tokenValue]
?: throw Exception("No key found in keyset for token value $tokenValue")
}

public fun toKeysetJson(): KeysetJson {
Expand Down Expand Up @@ -97,12 +99,12 @@ public class Keyset(
* @return The [Keyset] created from the JSON string.
*/
public fun fromJson(jsonString: String): Keyset {
val typeToken = object : TypeToken<Map<String, String>>() {}.type
val json: Map<String, String> = Gson().fromJson(jsonString, typeToken)
val jsonObject = Json.parseToJsonElement(jsonString).jsonObject

val keyset: Map<ULong, PublicKey> = json.map { (tokenValue, publicKeyHex) ->
val keyset: Map<ULong, PublicKey> = jsonObject.entries.associate { (tokenValue, element) ->
val publicKeyHex = element.jsonPrimitive.content
tokenValue.toULong() to PublicKey.fromHex(publicKeyHex)
}.toMap()
}

return Keyset(keyset)
}
Expand Down

0 comments on commit b1b8e84

Please sign in to comment.