- 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
@@ -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")
}
}
}
}