- Adds nembed

- Redesigns NIP-19 returns to allow nembeds and give more nuance to the UI.
This commit is contained in:
Vitor Pamplona
2024-02-27 15:39:15 -05:00
parent 87fabd54de
commit f78a252c8f
23 changed files with 710 additions and 517 deletions
@@ -22,9 +22,8 @@ package com.vitorpamplona.quartz
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.vitorpamplona.quartz.crypto.KeyPair
import com.vitorpamplona.quartz.encoders.Bech32
import com.vitorpamplona.quartz.encoders.Hex
import com.vitorpamplona.quartz.encoders.bechToBytes
import com.vitorpamplona.quartz.encoders.Nip19Bech32
import com.vitorpamplona.quartz.events.Event
import com.vitorpamplona.quartz.events.FhirResourceEvent
import com.vitorpamplona.quartz.events.TextNoteEvent
@@ -35,17 +34,13 @@ import junit.framework.TestCase.assertTrue
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import java.io.ByteArrayOutputStream
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
import kotlin.time.measureTimedValue
@RunWith(AndroidJUnit4::class)
class NIP19EmbedTests {
@Test
fun testEmbedEvent() {
fun testEmbedKind1Event() {
val signer =
NostrSignerInternal(
KeyPair(Hex.decode("e8e7197ccc53c9ed4cf9b1c8dce085475fa1ffdd71f2c14e44fe23d0bdf77598")),
@@ -64,12 +59,11 @@ class NIP19EmbedTests {
assertNotNull(textNote)
val bech32 = Bech32.encodeBytes(hrp = "n", textNote!!.toJson().toByteArray(Charsets.UTF_8), Bech32.Encoding.Bech32)
val bech32 = Nip19Bech32.createNEmbed(textNote!!)
println(bech32)
val decoded = String(bech32.bechToBytes())
val decodedNote = Event.fromJson(decoded)
val decodedNote = (Nip19Bech32.uriToRoute(bech32)?.entity as Nip19Bech32.NEmbed).event
assertTrue(decodedNote.hasValidSignature())
@@ -96,52 +90,19 @@ class NIP19EmbedTests {
assertNotNull(eyeglassesPrescriptionEvent)
val bech32 = Bech32.encodeBytes(hrp = "nembed", eyeglassesPrescriptionEvent!!.toJson().toByteArray(Charsets.UTF_8), Bech32.Encoding.Bech32)
val bech32 = Nip19Bech32.createNEmbed(eyeglassesPrescriptionEvent!!)
println(eyeglassesPrescriptionEvent!!.toJson())
println(bech32)
val decoded = String(bech32.bechToBytes())
val decodedNote = Event.fromJson(decoded)
assertTrue(decodedNote.hasValidSignature())
assertEquals(eyeglassesPrescriptionEvent!!.toJson(), decodedNote.toJson())
}
@Test
fun testVisionPrescriptionEmbedEventCompression() {
val signer =
NostrSignerInternal(
KeyPair(Hex.decode("e8e7197ccc53c9ed4cf9b1c8dce085475fa1ffdd71f2c14e44fe23d0bdf77598")),
)
var eyeglassesPrescriptionEvent: Event? = null
val countDownLatch = CountDownLatch(1)
FhirResourceEvent.create(fhirPayload = visionPrescriptionFhir, signer = signer) {
eyeglassesPrescriptionEvent = it
countDownLatch.countDown()
}
Assert.assertTrue(countDownLatch.await(1, TimeUnit.SECONDS))
assertNotNull(eyeglassesPrescriptionEvent)
val bech32 = Bech32.encodeBytes(hrp = "nembed", gzip(eyeglassesPrescriptionEvent!!.toJson()), Bech32.Encoding.Bech32)
println(eyeglassesPrescriptionEvent!!.toJson())
println(bech32)
val decoded = ungzip(bech32.bechToBytes())
val decodedNote = Event.fromJson(decoded)
val decodedNote = (Nip19Bech32.uriToRoute(bech32)?.entity as Nip19Bech32.NEmbed).event
assertTrue(decodedNote.hasValidSignature())
assertEquals(eyeglassesPrescriptionEvent!!.toJson(), decodedNote.toJson())
}
/*
@Test
fun testCompressionSizes() {
val signer =
@@ -167,24 +128,15 @@ class NIP19EmbedTests {
Bech32.encodeBytes(hrp = "nembed", json.toByteArray(), Bech32.Encoding.Bech32)
Bech32.encodeBytes(hrp = "nembed", gzip(json), Bech32.Encoding.Bech32)
val (bech32json, elapsedjson) = measureTimedValue { Bech32.encodeBytes(hrp = "nembed", json.toByteArray(), Bech32.Encoding.Bech32) }
val (bech32gzip, elapsedgzip) = measureTimedValue { Bech32.encodeBytes(hrp = "nembed", gzip(json), Bech32.Encoding.Bech32) }
val (bech32json, elapsedjson) = measureTimedValue { json.toByteArray().toNEmbed() }
val (bech32gzip, elapsedgzip) = measureTimedValue { gzip(json).toNEmbed() }
println("Raw JSON ${json.length} chars")
println("Bech32 JSON ${bech32json.length} chars in $elapsedjson")
println("Bech32 GZIP ${bech32gzip.length} chars in $elapsedgzip")
assertTrue(true)
}
}*/
val visionPrescriptionFhir = "{\"resourceType\":\"VisionPrescription\",\"status\":\"active\",\"created\":\"2014-06-15\",\"patient\":{\"reference\":\"Patient/example\"},\"dateWritten\":\"2014-06-15\",\"prescriber\":{\"reference\":\"Practitioner/example\"},\"lensSpecification\":[{\"eye\":\"right\",\"sphere\":-2,\"prism\":[{\"amount\":0.5,\"base\":\"down\"}],\"add\":2},{\"eye\":\"left\",\"sphere\":-1,\"cylinder\":-0.5,\"axis\":180,\"prism\":[{\"amount\":0.5,\"base\":\"up\"}],\"add\":2}]}"
}
fun gzip(content: String): ByteArray {
val bos = ByteArrayOutputStream()
GZIPOutputStream(bos).bufferedWriter(Charsets.UTF_8).use { it.write(content) }
val array = bos.toByteArray()
return array
}
fun ungzip(content: ByteArray): String = GZIPInputStream(content.inputStream()).bufferedReader(Charsets.UTF_8).use { it.readText() }
@@ -271,18 +271,6 @@ object Bech32 {
}
}
fun ByteArray.toNsec() = Bech32.encodeBytes(hrp = "nsec", this, Bech32.Encoding.Bech32)
fun ByteArray.toNpub() = Bech32.encodeBytes(hrp = "npub", this, Bech32.Encoding.Bech32)
fun ByteArray.toNote() = Bech32.encodeBytes(hrp = "note", this, Bech32.Encoding.Bech32)
fun ByteArray.toNEvent() = Bech32.encodeBytes(hrp = "nevent", this, Bech32.Encoding.Bech32)
fun ByteArray.toNAddress() = Bech32.encodeBytes(hrp = "naddr", this, Bech32.Encoding.Bech32)
fun ByteArray.toLnUrl() = Bech32.encodeBytes(hrp = "lnurl", this, Bech32.Encoding.Bech32)
fun String.bechToBytes(hrp: String? = null): ByteArray {
val decodedForm = Bech32.decodeBytes(this)
hrp?.also {
@@ -23,7 +23,12 @@ package com.vitorpamplona.quartz.encoders
import android.util.Log
import androidx.compose.runtime.Immutable
import com.vitorpamplona.quartz.crypto.KeyPair
import com.vitorpamplona.quartz.events.Event
import kotlinx.coroutines.CancellationException
import java.io.ByteArrayOutputStream
import java.util.regex.Pattern
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
object Nip19Bech32 {
enum class Type {
@@ -43,21 +48,40 @@ object Nip19Bech32 {
val nip19regex =
Pattern.compile(
"(nostr:)?@?(nsec1|npub1|nevent1|naddr1|note1|nprofile1|nrelay1)([qpzry9x8gf2tvdw0s3jn54khce6mua7l]+)([\\S]*)",
"(nostr:)?@?(nsec1|npub1|nevent1|naddr1|note1|nprofile1|nrelay1|nembed1)([qpzry9x8gf2tvdw0s3jn54khce6mua7l]+)([\\S]*)",
Pattern.CASE_INSENSITIVE,
)
@Immutable
data class Return(
val type: Type,
val hex: String,
val relay: String? = null,
val author: String? = null,
val kind: Int? = null,
val additionalChars: String = "",
)
data class ParseReturn(val entity: Entity, val additionalChars: String = "")
fun uriToRoute(uri: String?): Return? {
interface Entity
@Immutable
data class NSec(val hex: String) : Entity
@Immutable
data class NPub(val hex: String) : Entity
@Immutable
data class Note(val hex: String) : Entity
@Immutable
data class NProfile(val hex: String, val relay: List<String>) : Entity
@Immutable
data class NEvent(val hex: String, val relay: List<String>, val author: String?, val kind: Int?) : Entity
@Immutable
data class NAddress(val atag: String, val relay: List<String>, val author: String, val kind: Int) : Entity
@Immutable
data class NRelay(val relay: List<String>) : Entity
@Immutable
data class NEmbed(val event: Event) : Entity
fun uriToRoute(uri: String?): ParseReturn? {
if (uri == null) return null
try {
@@ -66,12 +90,11 @@ object Nip19Bech32 {
return null
}
val uriScheme = matcher.group(1) // nostr:
val type = matcher.group(2) // npub1
val key = matcher.group(3) // bech32
val additionalChars = matcher.group(4) // additional chars
return parseComponents(uriScheme, type, key, additionalChars)
return parseComponents(type!!, key, additionalChars)
} catch (e: Throwable) {
Log.e("NIP19 Parser", "Issue trying to Decode NIP19 $uri: ${e.message}", e)
}
@@ -80,28 +103,24 @@ object Nip19Bech32 {
}
fun parseComponents(
uriScheme: String?,
type: String,
key: String?,
additionalChars: String?,
): Return? {
): ParseReturn? {
return try {
val bytes = (type + key).bechToBytes()
val parsed =
when (type.lowercase()) {
"npub1" -> npub(bytes)
"note1" -> note(bytes)
"nprofile1" -> nprofile(bytes)
"nevent1" -> nevent(bytes)
"nrelay1" -> nrelay(bytes)
"naddr1" -> naddr(bytes)
else -> null
}
if (parsed?.hex?.isBlank() == true) {
null
} else {
parsed?.copy(additionalChars = additionalChars ?: "")
when (type.lowercase()) {
"npub1" -> npub(bytes)
"note1" -> note(bytes)
"nprofile1" -> nprofile(bytes)
"nevent1" -> nevent(bytes)
"nrelay1" -> nrelay(bytes)
"naddr1" -> naddr(bytes)
"nembed1" -> nembed(bytes)
else -> null
}?.let {
ParseReturn(it, additionalChars ?: "")
}
} catch (e: Throwable) {
Log.w("NIP19 Parser", "Issue trying to Decode NIP19 $key: ${e.message}", e)
@@ -109,52 +128,71 @@ object Nip19Bech32 {
}
}
private fun npub(bytes: ByteArray): Return {
return Return(Type.USER, bytes.toHexKey())
private fun nembed(bytes: ByteArray): NEmbed? {
if (bytes.isEmpty()) return null
return NEmbed(Event.fromJson(ungzip(bytes)))
}
private fun note(bytes: ByteArray): Return {
return Return(Type.NOTE, bytes.toHexKey())
private fun npub(bytes: ByteArray): NPub? {
if (bytes.isEmpty()) return null
return NPub(bytes.toHexKey())
}
private fun nprofile(bytes: ByteArray): Return? {
private fun note(bytes: ByteArray): Note? {
if (bytes.isEmpty()) return null
return Note(bytes.toHexKey())
}
private fun nprofile(bytes: ByteArray): NProfile? {
if (bytes.isEmpty()) return null
val tlv = Tlv.parse(bytes)
val hex = tlv.firstAsHex(TlvTypes.SPECIAL) ?: return null
val relay = tlv.firstAsString(TlvTypes.RELAY)
val relay = tlv.asStringList(TlvTypes.RELAY) ?: emptyList()
return Return(Type.USER, hex, relay)
if (hex.isBlank()) return null
return NProfile(hex, relay)
}
private fun nevent(bytes: ByteArray): Return? {
private fun nevent(bytes: ByteArray): NEvent? {
if (bytes.isEmpty()) return null
val tlv = Tlv.parse(bytes)
val hex = tlv.firstAsHex(TlvTypes.SPECIAL) ?: return null
val relay = tlv.firstAsString(TlvTypes.RELAY)
val relay = tlv.asStringList(TlvTypes.RELAY) ?: emptyList()
val author = tlv.firstAsHex(TlvTypes.AUTHOR)
val kind = tlv.firstAsInt(TlvTypes.KIND.id)
return Return(Type.EVENT, hex, relay, author, kind)
if (hex.isBlank()) return null
return NEvent(hex, relay, author, kind)
}
private fun nrelay(bytes: ByteArray): Return? {
val relayUrl = Tlv.parse(bytes).firstAsString(TlvTypes.SPECIAL.id) ?: return null
private fun nrelay(bytes: ByteArray): NRelay? {
if (bytes.isEmpty()) return null
return Return(Type.RELAY, relayUrl)
val relayUrl = Tlv.parse(bytes).asStringList(TlvTypes.SPECIAL.id) ?: return null
return NRelay(relayUrl)
}
private fun naddr(bytes: ByteArray): Return? {
private fun naddr(bytes: ByteArray): NAddress? {
if (bytes.isEmpty()) return null
val tlv = Tlv.parse(bytes)
val d = tlv.firstAsString(TlvTypes.SPECIAL.id) ?: ""
val relay = tlv.firstAsString(TlvTypes.RELAY.id)
val relay = tlv.asStringList(TlvTypes.RELAY.id) ?: emptyList()
val author = tlv.firstAsHex(TlvTypes.AUTHOR.id) ?: return null
val kind = tlv.firstAsInt(TlvTypes.KIND.id) ?: return null
return Return(Type.ADDRESS, "$kind:$author:$d", relay, author, kind)
return NAddress("$kind:$author:$d", relay, author, kind)
}
public fun createNEvent(
fun createNEvent(
idHex: String,
author: String?,
kind: Int?,
@@ -170,34 +208,97 @@ object Nip19Bech32 {
.build()
.toNEvent()
}
fun createNEmbed(event: Event): String {
return gzip(event.toJson()).toNEmbed()
}
fun gzip(content: String): ByteArray {
val bos = ByteArrayOutputStream()
GZIPOutputStream(bos).bufferedWriter(Charsets.UTF_8).use { it.write(content) }
val array = bos.toByteArray()
return array
}
fun ungzip(content: ByteArray): String = GZIPInputStream(content.inputStream()).bufferedReader(Charsets.UTF_8).use { it.readText() }
}
fun decodePublicKey(key: String): ByteArray {
val parsed = Nip19Bech32.uriToRoute(key)
val pubKeyParsed = parsed?.hex?.hexToByteArray()
fun ByteArray.toNsec() = Bech32.encodeBytes(hrp = "nsec", this, Bech32.Encoding.Bech32)
return if (key.startsWith("nsec")) {
KeyPair(privKey = key.bechToBytes()).pubKey
} else if (pubKeyParsed != null) {
pubKeyParsed
} else {
Hex.decode(key)
fun ByteArray.toNpub() = Bech32.encodeBytes(hrp = "npub", this, Bech32.Encoding.Bech32)
fun ByteArray.toNote() = Bech32.encodeBytes(hrp = "note", this, Bech32.Encoding.Bech32)
fun ByteArray.toNEvent() = Bech32.encodeBytes(hrp = "nevent", this, Bech32.Encoding.Bech32)
fun ByteArray.toNAddress() = Bech32.encodeBytes(hrp = "naddr", this, Bech32.Encoding.Bech32)
fun ByteArray.toLnUrl() = Bech32.encodeBytes(hrp = "lnurl", this, Bech32.Encoding.Bech32)
fun ByteArray.toNEmbed() = Bech32.encodeBytes(hrp = "nembed", this, Bech32.Encoding.Bech32)
fun decodePublicKey(key: String): ByteArray {
return when (val parsed = Nip19Bech32.uriToRoute(key)?.entity) {
is Nip19Bech32.NSec -> KeyPair(privKey = key.bechToBytes()).pubKey
is Nip19Bech32.NPub -> parsed.hex.hexToByteArray()
is Nip19Bech32.NProfile -> parsed.hex.hexToByteArray()
else -> Hex.decode(key) // crashes on purpose
}
}
fun decodePrivateKeyAsHexOrNull(key: String): HexKey? {
return try {
when (val parsed = Nip19Bech32.uriToRoute(key)?.entity) {
is Nip19Bech32.NSec -> parsed.hex
is Nip19Bech32.NPub -> null
is Nip19Bech32.NProfile -> null
is Nip19Bech32.Note -> null
is Nip19Bech32.NEvent -> null
is Nip19Bech32.NEmbed -> null
is Nip19Bech32.NRelay -> null
is Nip19Bech32.NAddress -> null
else -> Hex.decode(key).toHexKey()
}
} catch (e: Exception) {
if (e is CancellationException) throw e
null
}
}
fun decodePublicKeyAsHexOrNull(key: String): HexKey? {
return try {
val parsed = Nip19Bech32.uriToRoute(key)
val pubKeyParsed = parsed?.hex
if (key.startsWith("nsec")) {
KeyPair(privKey = key.bechToBytes()).pubKey.toHexKey()
} else if (pubKeyParsed != null) {
pubKeyParsed
} else {
Hex.decode(key).toHexKey()
when (val parsed = Nip19Bech32.uriToRoute(key)?.entity) {
is Nip19Bech32.NSec -> KeyPair(privKey = key.bechToBytes()).pubKey.toHexKey()
is Nip19Bech32.NPub -> parsed.hex
is Nip19Bech32.NProfile -> parsed.hex
is Nip19Bech32.Note -> null
is Nip19Bech32.NEvent -> null
is Nip19Bech32.NEmbed -> null
is Nip19Bech32.NRelay -> null
is Nip19Bech32.NAddress -> null
else -> Hex.decode(key).toHexKey()
}
} catch (e: Exception) {
if (e is CancellationException) throw e
null
}
}
fun decodeEventIdAsHexOrNull(key: String): HexKey? {
return try {
when (val parsed = Nip19Bech32.uriToRoute(key)?.entity) {
is Nip19Bech32.NSec -> null
is Nip19Bech32.NPub -> null
is Nip19Bech32.NProfile -> null
is Nip19Bech32.Note -> parsed.hex
is Nip19Bech32.NEvent -> parsed.hex
is Nip19Bech32.NAddress -> parsed.atag
is Nip19Bech32.NEmbed -> null
is Nip19Bech32.NRelay -> null
else -> Hex.decode(key).toHexKey()
}
} catch (e: Exception) {
if (e is CancellationException) throw e
null
}
}
@@ -237,3 +338,5 @@ fun Tlv.firstAsInt(type: Nip19Bech32.TlvTypes) = firstAsInt(type.id)
fun Tlv.firstAsHex(type: Nip19Bech32.TlvTypes) = firstAsHex(type.id)
fun Tlv.firstAsString(type: Nip19Bech32.TlvTypes) = firstAsString(type.id)
fun Tlv.asStringList(type: Nip19Bech32.TlvTypes) = asStringList(type.id)
@@ -94,6 +94,8 @@ class Tlv(val data: Map<Byte, List<ByteArray>>) {
fun firstAsString(type: Byte) = data[type]?.firstOrNull()?.toString(Charsets.UTF_8)
fun asStringList(type: Byte) = data[type]?.map { it.toString(Charsets.UTF_8) }
companion object {
fun parse(data: ByteArray): Tlv {
val result = mutableMapOf<Byte, MutableList<ByteArray>>()
@@ -100,16 +100,18 @@ open class BaseTextNoteEvent(
val matcher2 = nip19regex.matcher(content)
while (matcher2.find()) {
val uriScheme = matcher2.group(1) // nostr:
val type = matcher2.group(2) // npub1
val key = matcher2.group(3) // bech32
val additionalChars = matcher2.group(4) // additional chars
try {
val parsed = Nip19Bech32.parseComponents(uriScheme, type, key, additionalChars)
val parsed = Nip19Bech32.parseComponents(type, key, additionalChars)?.entity
if (parsed != null) {
if (parsed.type == Nip19Bech32.Type.USER) {
if (parsed is Nip19Bech32.NProfile) {
returningList.add(parsed.hex)
}
if (parsed is Nip19Bech32.NPub) {
returningList.add(parsed.hex)
}
}
@@ -145,16 +147,18 @@ open class BaseTextNoteEvent(
val matcher2 = nip19regex.matcher(content)
while (matcher2.find()) {
val uriScheme = matcher2.group(1) // nostr:
val type = matcher2.group(2) // npub1
val key = matcher2.group(3) // bech32
val additionalChars = matcher2.group(4) // additional chars
val parsed = Nip19Bech32.parseComponents(uriScheme, type, key, additionalChars)
val parsed = Nip19Bech32.parseComponents(type, key, additionalChars)?.entity
if (parsed != null) {
if (parsed.type == Nip19Bech32.Type.EVENT || parsed.type == Nip19Bech32.Type.ADDRESS || parsed.type == Nip19Bech32.Type.NOTE) {
citations.add(parsed.hex)
when (parsed) {
is Nip19Bech32.NEvent -> citations.add(parsed.hex)
is Nip19Bech32.NAddress -> citations.add(parsed.atag)
is Nip19Bech32.Note -> citations.add(parsed.hex)
is Nip19Bech32.NEmbed -> citations.add(parsed.event.id)
}
}
}
@@ -48,17 +48,18 @@ class ContactListEvent(
@delegate:Transient
val verifiedFollowKeySet: Set<HexKey> by lazy {
tags
.filter { it.size > 1 && it[0] == "p" }
.mapNotNull {
try {
tags.mapNotNullTo(HashSet()) {
try {
if (it.size > 1 && it[0] == "p") {
decodePublicKey(it[1]).toHexKey()
} catch (e: Exception) {
Log.w("ContactListEvent", "Can't parse tags as a follows: ${it[1]}", e)
} else {
null
}
} catch (e: Exception) {
Log.w("ContactListEvent", "Can't parse tags as a follows: ${it[1]}", e)
null
}
.toSet()
}
}
@delegate:Transient
@@ -77,27 +78,29 @@ class ContactListEvent(
@delegate:Transient
val verifiedFollowKeySetAndMe: Set<HexKey> by lazy { verifiedFollowKeySet + pubKey }
fun unverifiedFollowKeySet() = tags.filter { it[0] == "p" }.mapNotNull { it.getOrNull(1) }
fun unverifiedFollowKeySet() = tags.filter { it.size > 1 && it[0] == "p" }.mapNotNull { it.getOrNull(1) }
fun unverifiedFollowTagSet() = tags.filter { it[0] == "t" }.mapNotNull { it.getOrNull(1) }
fun unverifiedFollowTagSet() = tags.filter { it.size > 1 && it[0] == "t" }.mapNotNull { it.getOrNull(1) }
fun unverifiedFollowGeohashSet() = tags.filter { it[0] == "g" }.mapNotNull { it.getOrNull(1) }
fun unverifiedFollowGeohashSet() = tags.filter { it.size > 1 && it[0] == "g" }.mapNotNull { it.getOrNull(1) }
fun unverifiedFollowAddressSet() = tags.filter { it[0] == "a" }.mapNotNull { it.getOrNull(1) }
fun unverifiedFollowAddressSet() = tags.filter { it.size > 1 && it[0] == "a" }.mapNotNull { it.getOrNull(1) }
fun follows() =
tags
.filter { it[0] == "p" }
.mapNotNull {
try {
tags.mapNotNull {
try {
if (it.size > 1 && it[0] == "p") {
Contact(decodePublicKey(it[1]).toHexKey(), it.getOrNull(2))
} catch (e: Exception) {
Log.w("ContactListEvent", "Can't parse tags as a follows: ${it[1]}", e)
} else {
null
}
} catch (e: Exception) {
Log.w("ContactListEvent", "Can't parse tags as a follows: ${it[1]}", e)
null
}
}
fun followsTags() = tags.filter { it[0] == "t" }.mapNotNull { it.getOrNull(2) }
fun followsTags() = tags.filter { it.size > 1 && it[0] == "t" }.mapNotNull { it.getOrNull(1) }
fun relays(): Map<String, ReadWrite>? =
try {
@@ -28,7 +28,7 @@ public class StreamSerializationContext {
}
public void writeBool(boolean value) {
if (value == true) {
if (value) {
this.writeByte((byte) 0xff);
} else {
this.writeByte((byte) 0x00);
@@ -58,7 +58,7 @@ public class StreamSerializationContext {
}
public void writeByte(byte value) {
this.buffer.add(new Byte(value));
this.buffer.add(Byte.valueOf(value));
}
public void writeByte(Byte value) {
@@ -66,8 +66,8 @@ public class StreamSerializationContext {
}
public void writeBytes(byte[] value) {
for (int i = 0; i < value.length; i++) {
this.writeByte(value[i]);
for (byte b : value) {
this.writeByte(b);
}
}
@@ -150,15 +150,12 @@ class NostrSignerExternal(
event: LnZapRequestEvent,
onReady: (LnZapPrivateEvent) -> Unit,
) {
return launcher.decryptZapEvent(event) {
val event =
try {
Event.fromJson(it)
} catch (e: Exception) {
Log.e("NostrExternalSigner", "Unable to parse returned decrypted Zap: $it")
null
}
(event as? LnZapPrivateEvent)?.let { onReady(event) }
return launcher.decryptZapEvent(event) { jsonEvent ->
try {
(Event.fromJson(jsonEvent) as? LnZapPrivateEvent)?.let { onReady(it) }
} catch (e: Exception) {
Log.e("NostrExternalSigner", "Unable to parse returned decrypted Zap: $jsonEvent")
}
}
}
}
@@ -21,6 +21,8 @@
package com.vitorpamplona.quartz.encoders
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Test
class NIP19ParserTest {
@@ -32,7 +34,7 @@ class NIP19ParserTest {
)
assertEquals(
"30023:460c25e682fda7832b52d1f22d3d22b3176d972f60dcdc3212ed8c92ef85065c:",
result?.hex,
(result?.entity as? Nip19Bech32.NAddress)?.atag,
)
}
@@ -44,7 +46,7 @@ class NIP19ParserTest {
)
assertEquals(
"30023:d0debf9fb12def81f43d7c69429bb784812ac1e4d2d53a202db6aac7ea4b466c:guide-wireguard",
result?.hex,
(result?.entity as? Nip19Bech32.NAddress)?.atag,
)
}
@@ -54,12 +56,12 @@ class NIP19ParserTest {
Nip19Bech32.uriToRoute(
"naddr1qqyrswtyv5mnjv3sqy28wumn8ghj7un9d3shjtnyv9kh2uewd9hsygx3uczxts4hwue9ayfn7ggq62anzstde2qs749pm9tx2csuthhpjvpsgqqqw4rs8pmj38",
)
assertEquals(Nip19Bech32.Type.ADDRESS, result?.type)
assertTrue(result?.entity is Nip19Bech32.NAddress)
assertEquals(
"30023:d1e60465c2b777325e9133f2100d2bb31416dca810f54a1d95665621c5dee193:89de7920",
result?.hex,
(result?.entity as? Nip19Bech32.NAddress)?.atag,
)
assertEquals("wss://relay.damus.io", result?.relay)
assertEquals("wss://relay.damus.io", (result?.entity as? Nip19Bech32.NAddress)?.relay?.get(0))
}
@Test
@@ -132,13 +134,14 @@ class NIP19ParserTest {
val result =
Nip19Bech32.uriToRoute(
"naddr1qq2hs7p30p6kcunxxamkgcnyd33xxve3veshyq3qyujphdcz69z6jafxpnldae3xtymdekfeatkt3r4qusr3w5krqspqxpqqqpaxjlg805f",
)
assertEquals(Nip19Bech32.Type.ADDRESS, result?.type)
)?.entity as? Nip19Bech32.NAddress
assertNotNull(result)
assertEquals(
"31337:27241bb702d145a975260cfedee6265936dcd939eaecb88ea0e4071752c30402:xx1xulrf7wdbdlbc31far",
result?.hex,
result?.atag,
)
assertEquals(null, result?.relay)
assertEquals(true, result?.relay?.isEmpty())
assertEquals("27241bb702d145a975260cfedee6265936dcd939eaecb88ea0e4071752c30402", result?.author)
assertEquals(31337, result?.kind)
}
@@ -148,13 +151,14 @@ class NIP19ParserTest {
val result =
Nip19Bech32.uriToRoute(
"naddr1qpqrvvfnvccrzdryxgunzvtxvgukge34xfjnqdpcv9sk2desxgmrscesvserzd3h8ycrywphvg6nsvf58ycnqef3v5mnsvt98pjnqdfs8ypzq3huhccxt6h34eupz3jeynjgjgek8lel2f4adaea0svyk94a3njdqvzqqqr4gudhrkyk",
)
assertEquals(Nip19Bech32.Type.ADDRESS, result?.type)
)?.entity as? Nip19Bech32.NAddress
assertNotNull(result)
assertEquals(
"30023:46fcbe3065eaf1ae7811465924e48923363ff3f526bd6f73d7c184b16bd8ce4d:613f014d2911fb9df52e048aae70268c0d216790287b5814910e1e781e8e0509",
result?.hex,
result?.atag,
)
assertEquals(null, result?.relay)
assertEquals(true, result?.relay?.isEmpty())
assertEquals("46fcbe3065eaf1ae7811465924e48923363ff3f526bd6f73d7c184b16bd8ce4d", result?.author)
assertEquals(30023, result?.kind)
}
@@ -164,13 +168,14 @@ class NIP19ParserTest {
val result =
Nip19Bech32.uriToRoute(
"naddr1qq9rzd3h8y6nqwf5xyuqygzxljlrqe027xh8sy2xtyjwfzfrxcll8afxh4hh847psjckhkxwf5psgqqqw4rsty50fx",
)
assertEquals(Nip19Bech32.Type.ADDRESS, result?.type)
)?.entity as? Nip19Bech32.NAddress
assertNotNull(result)
assertEquals(
"30023:46fcbe3065eaf1ae7811465924e48923363ff3f526bd6f73d7c184b16bd8ce4d:1679509418",
result?.hex,
result?.atag,
)
assertEquals(null, result?.relay)
assertEquals(true, result?.relay?.isEmpty())
assertEquals("46fcbe3065eaf1ae7811465924e48923363ff3f526bd6f73d7c184b16bd8ce4d", result?.author)
assertEquals(30023, result?.kind)
}
@@ -178,10 +183,11 @@ class NIP19ParserTest {
@Test
fun nEventParserTest() {
val result =
Nip19Bech32.uriToRoute("nostr:nevent1qqs0tsw8hjacs4fppgdg7f5yhgwwfkyua4xcs3re9wwkpkk2qeu6mhql22rcy")
assertEquals(Nip19Bech32.Type.EVENT, result?.type)
Nip19Bech32.uriToRoute("nostr:nevent1qqs0tsw8hjacs4fppgdg7f5yhgwwfkyua4xcs3re9wwkpkk2qeu6mhql22rcy")?.entity as? Nip19Bech32.NEvent
assertNotNull(result)
assertEquals("f5c1c7bcbb8855210a1a8f2684ba1ce4d89ced4d8844792b9d60daca0679addc", result?.hex)
assertEquals(null, result?.relay)
assertEquals(true, result?.relay?.isEmpty())
assertEquals(null, result?.author)
assertEquals(null, result?.kind)
}
@@ -191,10 +197,11 @@ class NIP19ParserTest {
val result =
Nip19Bech32.uriToRoute(
"nostr:nevent1qqstvrl6wftd8ht4g0vrp6m30tjs6pdxcvk977g769dcvlptkzu4ftqppamhxue69uhkummnw3ezumt0d5pzp78lz8r60568sd2a8dx3wnj6gume02gxaf92vx4fk67qv5kpagt6qvzqqqqqqygqr86c",
)
assertEquals(Nip19Bech32.Type.EVENT, result?.type)
)?.entity as? Nip19Bech32.NEvent
assertNotNull(result)
assertEquals("b60ffa7256d3dd7543d830eb717ae50d05a6c32c5f791ed15b867c2bb0b954ac", result?.hex)
assertEquals("wss://nostr.mom", result?.relay)
assertEquals("wss://nostr.mom", result?.relay?.get(0))
assertEquals("f8ff11c7a7d3478355d3b4d174e5a473797a906ea4aa61aa9b6bc0652c1ea17a", result?.author)
assertEquals(1, result?.kind)
}
@@ -204,11 +211,11 @@ class NIP19ParserTest {
val result =
Nip19Bech32.uriToRoute(
"nostr:nevent1qqsplpuwsgrrmq85rfup6w3w777rxmcmadu590emfx6z4msj2844euqpz3mhxue69uhhyetvv9ujuerpd46hxtnfdupzq3svyhng9ld8sv44950j957j9vchdktj7cxumsep9mvvjthc2pjuqvzqqqqqqye3a70w",
)
)?.entity as? Nip19Bech32.NEvent
assertEquals(Nip19Bech32.Type.EVENT, result?.type)
assertNotNull(result)
assertEquals("1f878e82063d80f41a781d3a2ef7bc336f1beb7942bf3b49b42aee1251eb5cf0", result?.hex)
assertEquals("wss://relay.damus.io", result?.relay)
assertEquals("wss://relay.damus.io", result?.relay?.get(0))
assertEquals("460c25e682fda7832b52d1f22d3d22b3176d972f60dcdc3212ed8c92ef85065c", result?.author)
assertEquals(1, result?.kind)
}
@@ -218,13 +225,13 @@ class NIP19ParserTest {
val result =
Nip19Bech32.uriToRoute(
"nostr:nevent1qqsg6gechd3dhzx38n4z8a2lylzgsmmgeamhmtzz72m9ummsnf0xjfspsdmhxue69uhkummn9ekx7mpvwaehxw309ahx7um5wghx77r5wghxgetk93mhxue69uhhyetvv9ujumn0wd68ytnzvuk8wumn8ghj7mn0wd68ytn9d9h82mny0fmkzmn6d9njuumsv93k2trhwden5te0wfjkccte9ehx7um5wghxyctwvsk8wumn8ghj7un9d3shjtnyv9kh2uewd9hs3kqsdn",
)
)?.entity as? Nip19Bech32.NEvent
assertEquals(Nip19Bech32.Type.EVENT, result?.type)
assertNotNull(result)
assertEquals("8d2338bb62db88d13cea23f55f27c4886f68cf777dac42f2b65e6f709a5e6926", result?.hex)
assertEquals(
"wss://nos.lol,wss://nostr.oxtr.dev,wss://relay.nostr.bg,wss://nostr.einundzwanzig.space,wss://relay.nostr.band,wss://relay.damus.io",
result?.relay,
result?.relay?.joinToString(","),
)
}
@@ -233,11 +240,11 @@ class NIP19ParserTest {
val result =
Nip19Bech32.uriToRoute(
"nostr:nevent1qqsyxq8v0730nz38dupnjzp5jegkyz4gu2ptwcps4v32hjnrap0q0espz3mhxue69uhhyetvv9ujuerpd46hxtnfdupzq3svyhng9ld8sv44950j957j9vchdktj7cxumsep9mvvjthc2pjuqvzqqqqqqyn3t9gj",
)
)?.entity as? Nip19Bech32.NEvent
assertEquals(Nip19Bech32.Type.EVENT, result?.type)
assertNotNull(result)
assertEquals("4300ec7fa2f98a276f033908349651620aa8e282b76030ab22abca63e85e07e6", result?.hex)
assertEquals("wss://relay.damus.io", result?.relay)
assertEquals("wss://relay.damus.io", result?.relay?.get(0))
assertEquals("460c25e682fda7832b52d1f22d3d22b3176d972f60dcdc3212ed8c92ef85065c", result?.author)
assertEquals(1, result?.kind)
}
@@ -21,7 +21,7 @@
package com.vitorpamplona.quartz.encoders
import org.junit.Assert
import org.junit.Ignore
import org.junit.Assert.assertNotNull
import org.junit.Test
class Nip19Bech32Test {
@@ -44,58 +44,74 @@ class Nip19Bech32Test {
val actual =
Nip19Bech32.uriToRoute("nostr:npub1hv7k2s755n697sptva8vkh9jz40lzfzklnwj6ekewfmxp5crwdjs27007y")
Assert.assertEquals(Nip19Bech32.Type.USER, actual?.type)
Assert.assertTrue(actual?.entity is Nip19Bech32.NPub)
Assert.assertEquals(
"bb3d6543d4a4f45f402b674ecb5cb2155ff12456fcdd2d66d9727660d3037365",
actual?.hex,
(actual?.entity as? Nip19Bech32.NPub)?.hex,
)
}
@Test()
fun uri_to_route_note() {
val actual =
Nip19Bech32.uriToRoute("nostr:note1stqea6wmwezg9x6yyr6qkukw95ewtdukyaztycws65l8wppjmtpscawevv")
val result =
Nip19Bech32.uriToRoute("nostr:note1stqea6wmwezg9x6yyr6qkukw95ewtdukyaztycws65l8wppjmtpscawevv")?.entity as? Nip19Bech32.Note
Assert.assertEquals(Nip19Bech32.Type.NOTE, actual?.type)
assertNotNull(result)
Assert.assertEquals(
"82c19ee9db7644829b4420f40b72ce2d32e5b7962744b261d0d53e770432dac3",
actual?.hex,
result?.hex,
)
}
@Ignore("Test not implemented yet")
@Test()
fun uri_to_route_nprofile() {
val actual = Nip19Bech32.uriToRoute("nostr:nprofile")
Assert.assertEquals(Nip19Bech32.Type.USER, actual?.type)
Assert.assertEquals("*", actual?.hex)
Assert.assertEquals(null, actual)
}
@Ignore("Test not implemented yet")
@Test()
fun uri_to_route_nevent() {
fun uri_to_route_incomplete_nevent() {
val actual = Nip19Bech32.uriToRoute("nostr:nevent")
Assert.assertEquals(Nip19Bech32.Type.USER, actual?.type)
Assert.assertEquals("*", actual?.hex)
Assert.assertEquals(null, actual)
}
@Ignore("Test not implemented yet")
@Test()
fun uri_to_route_nrelay() {
fun uri_to_route_incomplete_nrelay() {
val actual = Nip19Bech32.uriToRoute("nostr:nrelay")
Assert.assertEquals(Nip19Bech32.Type.RELAY, actual?.type)
Assert.assertEquals("*", actual?.hex)
Assert.assertEquals(null, actual)
}
@Ignore("Test not implemented yet")
@Test()
fun uri_to_route_naddr() {
fun uri_to_route_incomplete_naddr() {
val actual = Nip19Bech32.uriToRoute("nostr:naddr")
Assert.assertEquals(Nip19Bech32.Type.ADDRESS, actual?.type)
Assert.assertEquals("*", actual?.hex)
Assert.assertEquals(null, actual)
}
@Test()
fun uri_to_route_complete_nprofile() {
val actual = Nip19Bech32.uriToRoute("nostr:nprofile1qy2hwumn8ghj7un9d3shjtnyv9kh2uewd9hj7qgwwaehxw309ahx7uewd3hkctcpr9mhxue69uhhyetvv9ujuumwdae8gtnnda3kjctv9uqzq9thu3vem5gvsc6f3l3uyz7c92h6lq56t9wws0zulzkrgc6nrvym5jfztf")
Assert.assertTrue(actual?.entity is Nip19Bech32.NProfile)
Assert.assertEquals("1577e4599dd10c863498fe3c20bd82aafaf829a595ce83c5cf8ac3463531b09b", (actual?.entity as? Nip19Bech32.NProfile)?.hex)
}
@Test()
fun uri_to_route_complete_nevent() {
val actual = Nip19Bech32.uriToRoute("nostr:nevent1qy2hwumn8ghj7un9d3shjtnyv9kh2uewd9hj7qgwwaehxw309ahx7uewd3hkctcpr9mhxue69uhhyetvv9ujuumwdae8gtnnda3kjctv9uq36amnwvaz7tmjv4kxz7fwvd5xjcmpvahhqmr9vfejucm0d5hsz9mhwden5te0wfjkccte9ec8y6tdv9kzumn9wshsz8thwden5te0dehhxarj9ekh2arfdeuhwctvd3jhgtnrdakj7qg3waehxw309ucngvpwvcmh5tnfduhszythwden5te0dehhxarj9emkjmn99uq3jamnwvaz7tmhv4kxxmmdv5hxummnw3ezuamfdejj7qpqvsup5xk3e2quedxjvn2gjppc0lqny5dmnr2ypc9tftwmdxta0yjqrd6n50")
Assert.assertTrue(actual?.entity is Nip19Bech32.NEvent)
Assert.assertEquals("64381a1ad1ca81ccb4d264d48904387fc13251bb98d440e0ab4addb6997d7924", (actual?.entity as? Nip19Bech32.NEvent)?.hex)
}
@Test()
fun uri_to_route_complete_naddr() {
val actual = Nip19Bech32.uriToRoute("nostr:naddr1qqyxzmt9w358jum5qyt8wumn8ghj7un9d3shjtnwdaehgu3wvfskueqzypd7v3r24z33cydnk3fmlrd0exe5dlej3506zxs05q4puerp765mzqcyqqq8scsq6mk7u")
Assert.assertTrue(actual?.entity is Nip19Bech32.NAddress)
Assert.assertEquals("30818:5be6446aa8a31c11b3b453bf8dafc9b346ff328d1fa11a0fa02a1e6461f6a9b1:amethyst", (actual?.entity as? Nip19Bech32.NAddress)?.atag)
}
}