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

Mdavis/kt uma invoice #54

Merged
merged 11 commits into from
Aug 22, 2024
4 changes: 4 additions & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,23 @@ kotlin = "1.9.0"
kotlinCoroutines = "1.6.4"
kotlinxDateTime = "0.4.0"
kotlinSerializationJson = "1.4.1"
kotlinReflect = "2.0.0"
ktlint = "11.3.1"
ktor = "2.2.3"
mavenPublish = "0.25.2"
mockitoCore = "5.5.0"
taskTree = "2.1.1"
junit = "4.13.2"
bitcoinj-core = "0.16.3"

[libraries]
gradleClasspath-dokka = { module = "org.jetbrains.dokka:dokka-gradle-plugin", version.ref = "dokka" }
gradleClasspath-ktlint = { module = "org.jlleitschuh.gradle:ktlint-gradle", version.ref = "ktlint" }
gradleClasspath-kotlin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin" }
gradleClasspath-mavenPublish = { module = "com.vanniktech:gradle-maven-publish-plugin", version.ref = "mavenPublish" }

bitcoin-core = { module = "org.bitcoinj:bitcoinj-core", version.ref = "bitcoinj-core" }

task-tree = { module = "com.dorongold.plugins:task-tree", version.ref = "taskTree" }

kotlin-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinSerializationJson" }
Expand Down
1 change: 1 addition & 0 deletions uma-sdk/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ kotlin {
implementation(libs.kotlinx.coroutines.core)
implementation(libs.ktor.client.core)
implementation(libs.jna)
implementation(libs.bitcoin.core)
}
}
val commonTest by getting {
Expand Down
37 changes: 37 additions & 0 deletions uma-sdk/src/commonMain/kotlin/me/uma/UmaProtocolHelper.kt
Original file line number Diff line number Diff line change
Expand Up @@ -881,6 +881,43 @@ class UmaProtocolHelper @JvmOverloads constructor(
}
return identifier.substring(atIndex + 1)
}

/**
* Create an UMA invoice object
*/
fun getInvoice(
receiverUma: String,
invoiceUUID: String,
amount: Int,
receivingCurrency: InvoiceCurrency,
expiration: Int,
isSubjectToTravelRule: Boolean,
umaVersion: String,
commentCharsAllowed: Int? = null,
senderUma: String? = null,
invoiceLimit: Int? = null,
callback: String,
signature: ByteArray? = null,
kycStatus: KycStatus? = null,
requiredPayerData: CounterPartyDataOptions? = null
): Invoice {
return Invoice(
receiverUma = receiverUma,
invoiceUUID = invoiceUUID,
amount = amount,
receivingCurrency = receivingCurrency,
expiration = expiration,
isSubjectToTravelRule = isSubjectToTravelRule,
umaVersion = umaVersion,
commentCharsAllowed = commentCharsAllowed,
senderUma = senderUma,
invoiceLimit = invoiceLimit,
callback = callback,
signature = signature,
kycStatus = kycStatus,
requiredPayerData = requiredPayerData,
)
}
}

interface UmaInvoiceCreator {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

package me.uma.protocol

import io.ktor.utils.io.core.toByteArray
import me.uma.utils.ByteCodeable
import kotlinx.serialization.Serializable

@Serializable
Expand Down
275 changes: 275 additions & 0 deletions uma-sdk/src/commonMain/kotlin/me/uma/protocol/Invoice.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,275 @@
package me.uma.protocol

import io.ktor.utils.io.core.toByteArray
import me.uma.utils.ByteCodeable
import me.uma.utils.TLVCodeable
import me.uma.utils.array
import me.uma.utils.getBoolean
import me.uma.utils.getByteCodeable
import me.uma.utils.getNumber
import me.uma.utils.getString
import me.uma.utils.getTLV
import me.uma.utils.lengthOffset
import me.uma.utils.putByteCodeable
import me.uma.utils.putBoolean
import me.uma.utils.putByteArray
import me.uma.utils.putTLVCodeable
import me.uma.utils.putNumber
import me.uma.utils.putString
import me.uma.utils.valueOffset
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.ByteArraySerializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import org.bitcoinj.core.Bech32

private const val UMA_BECH32_PREFIX = "uma"

@Serializable(with = InvoiceCurrencyTLVSerializer::class)
data class InvoiceCurrency(
val code: String,
val name: String,
val symbol: String,
val decimals: Int,
) : TLVCodeable {

companion object {
val EMPTY = InvoiceCurrency("","","",0)

fun fromTLV(bytes: ByteArray): InvoiceCurrency {
var code = ""
var name = ""
var symbol = ""
var decimals = -1
var offset = 0
while(offset < bytes.size) {
val length = bytes[offset.lengthOffset()].toInt()
when(bytes[offset].toInt()) {
0 -> code = bytes.getString(offset.valueOffset(), length)
1 -> name = bytes.getString(offset.valueOffset(), length)
2 -> symbol = bytes.getString(offset.valueOffset(), length)
3 -> decimals = bytes.getNumber(offset.valueOffset(), length)
}
offset = offset.valueOffset() + length
}
return InvoiceCurrency(code=code, name=name, symbol=symbol, decimals=decimals)
}
}

override fun toTLV() = mutableListOf<ByteArray>()
.putString(0, code)
.putString(1, name)
.putString(2, symbol)
.putNumber(3, decimals)
.array()
}

@OptIn(ExperimentalSerializationApi::class)
class InvoiceCurrencyTLVSerializer: KSerializer<InvoiceCurrency> {
private val delegateSerializer = ByteArraySerializer()
override val descriptor = SerialDescriptor("InvoiceCurrency", delegateSerializer.descriptor)

override fun serialize(encoder: Encoder, value: InvoiceCurrency) {
encoder.encodeSerializableValue(
delegateSerializer,
value.toTLV()
)
}

override fun deserialize(decoder: Decoder) = InvoiceCurrency.fromTLV(
decoder.decodeSerializableValue(delegateSerializer)
)
}

@Serializable(with = InvoiceTLVSerializer::class)
class Invoice(
val receiverUma: String,

/** Invoice UUID Served as both the identifier of the UMA invoice, and the validation of proof of payment.*/
val invoiceUUID: String,

/** The amount of invoice to be paid in the smalest unit of the ReceivingCurrency. */
val amount: Int,

/** The currency of the invoice */
val receivingCurrency: InvoiceCurrency,

/** The unix timestamp the UMA invoice expires */
val expiration: Int,

/** Indicates whether the VASP is a financial institution that requires travel rule information. */
val isSubjectToTravelRule: Boolean,

/** RequiredPayerData the data about the payer that the sending VASP must provide in order to send a payment. */
val requiredPayerData: CounterPartyDataOptions? = null,

/** UmaVersion is a list of UMA versions that the VASP supports for this transaction. It should be
* containing the lowest minor version of each major version it supported, separated by commas.
*/
val umaVersion: String,

/** CommentCharsAllowed is the number of characters that the sender can include in the comment field of the pay request. */
val commentCharsAllowed: Int? = null,

/** The sender's UMA address. If this field presents, the UMA invoice should directly go to the sending VASP instead of showing in other formats. */
val senderUma: String? = null,

/** The maximum number of the invoice can be paid */
val invoiceLimit: Int? = null,

/** YC status of the receiver, default is verified. */
val kycStatus: KycStatus? = null,

/** The callback url that the sender should send the PayRequest to. */
val callback: String,

/** The signature of the UMA invoice */
val signature: ByteArray? = null,
) : TLVCodeable {

override fun toTLV() = mutableListOf<ByteArray>()
.putString(0, receiverUma)
.putString(1, invoiceUUID)
.putNumber(2, amount)
.putTLVCodeable(3, receivingCurrency)
.putNumber(4, expiration)
.putBoolean(5, isSubjectToTravelRule)
.putByteCodeable(6, requiredPayerData?.let(::InvoiceCounterPartyDataOptions))
.putString(7, umaVersion)
.putNumber(8, commentCharsAllowed)
.putString(9, senderUma)
.putNumber(10, invoiceLimit)
.putByteCodeable(11, kycStatus?.let(::InvoiceKycStatus))
.putString(12, callback)
.putByteArray(100, signature)
.array()

fun toBech32(): String = Bech32.encode(Bech32.Encoding.BECH32, UMA_BECH32_PREFIX, this.toTLV())

companion object {
fun fromTLV(bytes: ByteArray): Invoice {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If a non-optional field is not presented, we should throw an error here.

var receiverUma = ""
var invoiceUUID = ""
var amount = -1
var receivingCurrency = InvoiceCurrency.EMPTY
var expiration = -1
var isSubjectToTravelRule = false
var requiredPayerData: CounterPartyDataOptions? = null
var umaVersion = ""
var commentCharsAllowed: Int? = null
var senderUma: String? = null
var invoiceLimit: Int? = null
var kycStatus: KycStatus? = null
var callback = ""
var signature: ByteArray? = null
var offset = 0
while(offset < bytes.size) {
val length = bytes[offset.lengthOffset()].toInt()
when(bytes[offset].toInt()) {
0 -> receiverUma = bytes.getString(offset.valueOffset(), length)
1 -> invoiceUUID = bytes.getString(offset.valueOffset(), length)
2 -> amount = bytes.getNumber(offset.valueOffset(), length)
3 -> receivingCurrency = bytes.getTLV(offset.valueOffset(), length, InvoiceCurrency::fromTLV) as InvoiceCurrency
4 -> expiration = bytes.getNumber(offset.valueOffset(), length)
5 -> isSubjectToTravelRule = bytes.getBoolean(offset.valueOffset())
6 -> requiredPayerData = (bytes.getByteCodeable(
offset.valueOffset(),
length,
InvoiceCounterPartyDataOptions::fromBytes) as InvoiceCounterPartyDataOptions
).options
7 -> umaVersion = bytes.getString(offset.valueOffset(), length)
8 -> commentCharsAllowed = bytes.getNumber(offset.valueOffset(), length)
9 -> senderUma = bytes.getString(offset.valueOffset(), length)
10 -> invoiceLimit = bytes.getNumber(offset.valueOffset(), length)
11 -> kycStatus = (bytes.getByteCodeable(offset.valueOffset(), length, InvoiceKycStatus::fromBytes) as InvoiceKycStatus).status
12 -> callback = bytes.getString(offset.valueOffset(), length)
100 -> signature = bytes.sliceArray(offset.valueOffset()..< offset.valueOffset()+length
)
}
offset = offset.valueOffset() + length
}
return Invoice(
receiverUma = receiverUma,
invoiceUUID = invoiceUUID,
amount = amount,
receivingCurrency = receivingCurrency,
expiration = expiration,
isSubjectToTravelRule = isSubjectToTravelRule,
requiredPayerData = requiredPayerData,
umaVersion = umaVersion,
commentCharsAllowed = commentCharsAllowed,
senderUma = senderUma,
invoiceLimit = invoiceLimit,
kycStatus = kycStatus,
callback = callback,
signature = signature,
)
}

fun fromBech32(bech32String: String): Invoice {
val b32data = Bech32.decode(bech32String)
return fromTLV(b32data.data)
}
}
}

@OptIn(ExperimentalSerializationApi::class)
class InvoiceTLVSerializer: KSerializer<Invoice> {
private val delegateSerializer = ByteArraySerializer()
override val descriptor = SerialDescriptor("Invoice", delegateSerializer.descriptor)

override fun serialize(encoder: Encoder, value: Invoice) {
encoder.encodeSerializableValue(
delegateSerializer,
value.toTLV()
)
}

override fun deserialize(decoder: Decoder) = Invoice.fromTLV(
decoder.decodeSerializableValue(delegateSerializer)
)
}

data class InvoiceCounterPartyDataOptions(
val options: CounterPartyDataOptions
) : ByteCodeable {
override fun toBytes(): ByteArray {
return options.entries
.sortedBy { it.key }
.joinToString(",") { (key, option) ->
"${key}:${if (option.mandatory) 1 else 0}"
}
.toByteArray(Charsets.UTF_8)
}

companion object {
fun fromBytes(bytes: ByteArray): InvoiceCounterPartyDataOptions {
val optionsString = String(bytes)
return InvoiceCounterPartyDataOptions(
optionsString.split(",").mapNotNull {
val options = it.split(':')
if (options.size == 2) {
options[0] to CounterPartyDataOption(options[1] == "1")
} else null
}.toMap()
)
}
}
}

data class InvoiceKycStatus(val status: KycStatus): ByteCodeable {
override fun toBytes(): ByteArray {
return status.rawValue.toByteArray()
}

companion object {
fun fromBytes(bytes: ByteArray): InvoiceKycStatus {
return InvoiceKycStatus(
KycStatus.fromRawValue(bytes.toString(Charsets.UTF_8))
)
}
}
}
11 changes: 11 additions & 0 deletions uma-sdk/src/commonMain/kotlin/me/uma/protocol/KycStatus.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package me.uma.protocol

import me.uma.utils.ByteCodeable
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import me.uma.utils.EnumSerializer
Expand All @@ -17,6 +18,16 @@ enum class KycStatus(val rawValue: String) {
VERIFIED("VERIFIED"),
;
fun toJson() = serialFormat.encodeToString(this)

companion object {
fun fromRawValue(rawValue: String) = when(rawValue) {
"UNKNOWN" -> UNKNOWN
"NOT_VERIFIED" -> NOT_VERIFIED
"PENDING" -> PENDING
"VERIFIED" -> VERIFIED
else -> UNKNOWN
}
}
}

object KycStatusSerializer :
Expand Down
Loading
Loading