feat: the group inbox's wire, in one package (group-inbox, Phase 2)
nostr/inbox: the inbox key ceremony's kinds (30410-30416) and tags; the group's 10044 and 10050 through quartz's own events, with the strict shape a group signs; NIP-17 seals and gift wraps with a decoupled key, built by hand per nostr-protocol/nips#2361 because quartz's encrypt to the key they tag; the reply manifest a signer reads, sealed to the inbox key; and the conversation id. InboxWireTest checks every layer, including both directions against quartz's own wraps. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
dd16df9c40
commit
e215cff843
8 files changed
+778
No files matched your search
@@ -0,0 +1,85 @@
|
||||
package mobi.giza.compose.nostr.inbox
|
||||
|
||||
import com.vitorpamplona.quartz.experimental.decoupling.setup.EncryptionKeyListEvent
|
||||
import com.vitorpamplona.quartz.experimental.decoupling.setup.tags.KeyTag
|
||||
import com.vitorpamplona.quartz.nip01Core.core.Event
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
|
||||
import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate
|
||||
import com.vitorpamplona.quartz.nip17Dm.settings.DmRelayListEvent
|
||||
import com.vitorpamplona.quartz.nip17Dm.settings.tags.RelayTag
|
||||
import mobi.giza.compose.nostr.RelayUrlInput
|
||||
|
||||
/**
|
||||
* The two public events that make a group writable to (docs/group-inbox.md, D5 and D6), both
|
||||
* signed by the group's quorum:
|
||||
*
|
||||
* - a kind **10044**, NIP-4E's announcement (nostr-protocol/nips#1647): `[["n", E]]` and nothing
|
||||
* else, where `E` is the inbox key;
|
||||
* - a kind **10050**, NIP-17's DM relay list: where senders should put what they write.
|
||||
*
|
||||
* Read by quartz's own [EncryptionKeyListEvent] and [DmRelayListEvent], so the group's events
|
||||
* parse the way every other client's do.
|
||||
*/
|
||||
object InboxAnnouncement {
|
||||
const val KEY_KIND = EncryptionKeyListEvent.KIND
|
||||
const val RELAYS_KIND = DmRelayListEvent.KIND
|
||||
|
||||
/** The group's 10044, naming [inboxKey] alone. */
|
||||
fun keyTemplate(inboxKey: HexKey, createdAt: Long): EventTemplate<Event> {
|
||||
require(InboxWire.isHex32(inboxKey)) { "an inbox key is a 32-byte x-only key" }
|
||||
val built = EncryptionKeyListEvent.build(inboxKey, createdAt)
|
||||
return EventTemplate(built.createdAt, built.kind, built.tags, built.content)
|
||||
}
|
||||
|
||||
/** The group's 10050, listing [relays]. */
|
||||
fun relaysTemplate(relays: List<NormalizedRelayUrl>, createdAt: Long): EventTemplate<Event> {
|
||||
require(relays.isNotEmpty()) { "an inbox nobody can deliver to is not an inbox" }
|
||||
return EventTemplate(createdAt, RELAYS_KIND, DmRelayListEvent.createTagArray(relays), "")
|
||||
}
|
||||
|
||||
/**
|
||||
* The key a 10044 announces, read as any NIP-4E client reads it: the first well-formed `n`.
|
||||
* For someone else's announcement, which may carry more than this app writes.
|
||||
*/
|
||||
fun announcedKeyOf(event: Event): HexKey? {
|
||||
if (event.kind != KEY_KIND) return null
|
||||
return event.tags.firstNotNullOfOrNull(KeyTag::parse)?.pubkey
|
||||
}
|
||||
|
||||
/**
|
||||
* The key a group's own 10044 announces, or null if [event] is not shaped the way this app
|
||||
* writes one: exactly one tag, an `n` with a key and no nonce, and no content. A signer
|
||||
* refuses anything else (docs/group-inbox.md, D5): a second `n`, or a legacy nonce, would be
|
||||
* the group announcing something nobody agreed to.
|
||||
*/
|
||||
fun groupKeyOf(event: Event): HexKey? = groupKeyOf(event.kind, event.tags, event.content)
|
||||
|
||||
fun groupKeyOf(kind: Int, tags: Array<Array<String>>, content: String): HexKey? {
|
||||
if (kind != KEY_KIND || content.isNotEmpty()) return null
|
||||
val tag = tags.singleOrNull() ?: return null
|
||||
if (tag.size != 2) return null
|
||||
val key = KeyTag.parse(tag) ?: return null
|
||||
return key.pubkey.takeIf { key.nonce == null && tag[1] == key.pubkey }
|
||||
}
|
||||
|
||||
/**
|
||||
* The relays a group's 10050 lists, or null if [event] is not one a group should sign: no
|
||||
* relays, anything but `relay` tags, content, or a relay a stranger could not reach
|
||||
* ([RelayUrlInput.relayUrlOrNull]: `wss://`, not loopback).
|
||||
*/
|
||||
fun groupRelaysOf(event: Event): List<NormalizedRelayUrl>? = groupRelaysOf(event.kind, event.tags, event.content)
|
||||
|
||||
fun groupRelaysOf(kind: Int, tags: Array<Array<String>>, content: String): List<NormalizedRelayUrl>? {
|
||||
if (kind != RELAYS_KIND || content.isNotEmpty() || tags.isEmpty()) return null
|
||||
val relays = tags.map { tag ->
|
||||
if (tag.size < 2 || tag[0] != RelayTag.TAG_NAME) return null
|
||||
RelayUrlInput.relayUrlOrNull(tag[1]) ?: return null
|
||||
}
|
||||
return relays.distinct()
|
||||
}
|
||||
|
||||
/** The relays anyone's 10050 lists, as NIP-17 senders read them. */
|
||||
fun announcedRelaysOf(event: Event): List<NormalizedRelayUrl> =
|
||||
if (event.kind != RELAYS_KIND) emptyList() else event.tags.mapNotNull(RelayTag::parse)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package mobi.giza.compose.nostr.inbox
|
||||
|
||||
import com.vitorpamplona.quartz.nip01Core.core.Event
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import fr.acinq.bitcoin.Crypto
|
||||
import mobi.giza.compose.extensions.toHex
|
||||
|
||||
/**
|
||||
* Which conversation a message in a group's inbox belongs to (docs/group-inbox.md, D8).
|
||||
*
|
||||
* NIP-17 defines a chat as the set of its author and its `p` tags. The group is in every one of
|
||||
* its own, so it is left out: a message from Alice to the group and the group's reply to Alice
|
||||
* are both the conversation `{Alice}`, whichever way round they were written.
|
||||
*/
|
||||
object InboxConversation {
|
||||
/** The people in [rumor]'s conversation other than [group], sorted and without repeats. */
|
||||
fun participantsOf(rumor: Event, group: HexKey): List<HexKey> =
|
||||
(listOf(rumor.pubKey) + rumor.tags.filter { it.size >= 2 && it[0] == "p" }.map { it[1] })
|
||||
.map { it.lowercase() }
|
||||
.filter { it != group.lowercase() && InboxWire.isHex32(it) }
|
||||
.distinct()
|
||||
.sorted()
|
||||
|
||||
/** A stable id for a set of [participants]: the same set gives the same id on every device. */
|
||||
fun idOf(participants: List<HexKey>): String =
|
||||
Crypto.sha256(participants.map { it.lowercase() }.distinct().sorted().joinToString(",").encodeToByteArray()).toHex()
|
||||
|
||||
fun idOf(rumor: Event, group: HexKey): String = idOf(participantsOf(rumor, group))
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package mobi.giza.compose.nostr.inbox
|
||||
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import com.vitorpamplona.quartz.nip01Core.core.Kind
|
||||
|
||||
/**
|
||||
* The group's inbox key ceremony on the wire (docs/group-inbox.md, D2 and D3): a ChillDKG
|
||||
* ceremony at threshold 1 over the room's admins, carried as MLS inner events in the group's
|
||||
* own Marmot room.
|
||||
*
|
||||
* The same seven steps as the group's signing ceremony ([mobi.giza.compose.nostr.dkg.DkgRitualEvents]),
|
||||
* on kinds of their own. A `t = 1` key must never be filed where a signing key could be found,
|
||||
* and a device that knows only the signing ceremony's kinds -- an older build, or a Bennu
|
||||
* admin's -- would take a 30310 over a subset of the room for a subgroup's ceremony. On kinds it
|
||||
* does not know it takes it for nothing.
|
||||
*
|
||||
* Rumor kinds: they only ever travel inside the group's encryption, so the replaceable range
|
||||
* means nothing for them. 30410-30416 are in no NIP, quartz, Curare or Bennu (Phase 0).
|
||||
*
|
||||
* ```
|
||||
* coordinator --[ 30410 proposal ]-> the room "let's make the inbox key", p-tagging the admins
|
||||
* admin --[ 30411 host key ]-> the room host pubkey
|
||||
* admin --[ 30412 round 1 ]-> the room pmsg1: a contribution, encrypted to the admins' host keys
|
||||
* coordinator --[ 30413 coord round 1 ]-> the room cmsg1
|
||||
* admin --[ 30414 round 2 ]-> the room CertEq signature
|
||||
* coordinator --[ 30415 certificate ]-> the room cmsg2
|
||||
* anyone --[ 30416 failure ]-> the room abort, with a reason
|
||||
* ```
|
||||
*
|
||||
* Every member of the room receives all of it. ChillDKG encrypts each contribution to its
|
||||
* recipients' host keys, so a member who is not an admin learns the inbox's public key and
|
||||
* nothing else.
|
||||
*/
|
||||
object InboxKeyRitualEvents {
|
||||
const val PROPOSAL: Kind = 30410
|
||||
const val HOST_KEY: Kind = 30411
|
||||
const val ROUND_1: Kind = 30412
|
||||
const val COORDINATOR_ROUND_1: Kind = 30413
|
||||
const val ROUND_2: Kind = 30414
|
||||
const val CERTIFICATE: Kind = 30415
|
||||
const val FAILURE: Kind = 30416
|
||||
|
||||
val ALL: Set<Kind> = setOf(PROPOSAL, HOST_KEY, ROUND_1, COORDINATOR_ROUND_1, ROUND_2, CERTIFICATE, FAILURE)
|
||||
|
||||
fun isInboxKeyKind(kind: Kind): Boolean = kind in ALL
|
||||
|
||||
/** Binds a message to one ceremony, so a late one from an abandoned attempt is dropped. */
|
||||
const val SESSION_TAG = "inbox_key_session"
|
||||
|
||||
/** Which generation of the room's inbox key the ceremony makes. On the proposal only. */
|
||||
const val GENERATION_TAG = "inbox_key_generation"
|
||||
|
||||
/** The ceremony's threshold. Always 1; carried so a device can refuse anything else. */
|
||||
const val THRESHOLD_TAG = "inbox_key_threshold"
|
||||
|
||||
const val THRESHOLD = 1
|
||||
|
||||
fun assembleTags(
|
||||
sessionId: String,
|
||||
generation: Int? = null,
|
||||
participants: List<HexKey> = emptyList(),
|
||||
): Array<Array<String>> = buildList {
|
||||
add(arrayOf(SESSION_TAG, sessionId))
|
||||
generation?.let {
|
||||
add(arrayOf(GENERATION_TAG, it.toString()))
|
||||
add(arrayOf(THRESHOLD_TAG, THRESHOLD.toString()))
|
||||
}
|
||||
participants.forEach { add(arrayOf("p", it)) }
|
||||
}.toTypedArray()
|
||||
|
||||
fun parseSessionId(tags: Array<Array<String>>): String? =
|
||||
tags.firstOrNull { it.size >= 2 && it[0] == SESSION_TAG }?.get(1)?.takeIf(InboxWire::isHex32)
|
||||
|
||||
fun parseGeneration(tags: Array<Array<String>>): Int? =
|
||||
tags.firstOrNull { it.size >= 2 && it[0] == GENERATION_TAG }?.get(1)?.toIntOrNull()?.takeIf { it >= 0 }
|
||||
|
||||
fun parseThreshold(tags: Array<Array<String>>): Int? =
|
||||
tags.firstOrNull { it.size >= 2 && it[0] == THRESHOLD_TAG }?.get(1)?.toIntOrNull()
|
||||
|
||||
/** The admins a proposal names, sorted and without repeats; null if any is malformed. */
|
||||
fun parseParticipants(tags: Array<Array<String>>): List<HexKey>? {
|
||||
val named = tags.filter { it.isNotEmpty() && it[0] == "p" }.map { it.getOrNull(1) }
|
||||
if (named.any { !InboxWire.isHex32(it) }) return null
|
||||
return named.filterNotNull().distinct().sorted()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package mobi.giza.compose.nostr.inbox
|
||||
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonNull
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.buildJsonArray
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.put
|
||||
|
||||
/**
|
||||
* What a signer of a reply needs beside the seals themselves (docs/group-inbox.md, D11): which
|
||||
* seal is for whom, the key each was sealed to, and the evidence for that key.
|
||||
*
|
||||
* It rides the FROST proposal as an `inbox_manifest` tag, encrypted to the inbox key, so a
|
||||
* member of the room who is not an admin sees how many seals the group is signing and nothing
|
||||
* else: not the reply, and not who it goes to.
|
||||
*
|
||||
* The encoding is this app's own and is decoded strictly: a manifest with a field it does not
|
||||
* know, or one missing, is no manifest, and a reply carrying one is declined.
|
||||
*/
|
||||
data class InboxReplyManifest(
|
||||
/** The inbox key generation every seal is sealed from. */
|
||||
val generation: Int,
|
||||
val seals: List<Entry>,
|
||||
/** Which of [seals] is the group's own copy, sealed to the inbox key itself. */
|
||||
val groupCopy: Int,
|
||||
) {
|
||||
data class Entry(
|
||||
val recipient: HexKey,
|
||||
/** The key the seal is encrypted to. */
|
||||
val key: HexKey,
|
||||
/** The recipient's signed 10044, as JSON, when [key] came from one; null when [key] is their identity. */
|
||||
val announcement: String?,
|
||||
)
|
||||
|
||||
fun encode(): String = buildJsonObject {
|
||||
put("v", 1)
|
||||
put("generation", generation)
|
||||
put("seals", buildJsonArray {
|
||||
seals.forEach { entry ->
|
||||
add(buildJsonObject {
|
||||
put("recipient", entry.recipient)
|
||||
put("key", entry.key)
|
||||
put("announcement", entry.announcement?.let(::JsonPrimitive) ?: JsonNull)
|
||||
})
|
||||
}
|
||||
})
|
||||
put("group_copy", groupCopy)
|
||||
}.toString()
|
||||
|
||||
/** Encrypted under `conv(e, E)`: only a holder of this generation's key reads it. */
|
||||
fun seal(inboxSecret: ByteArray): String =
|
||||
InboxWire.encrypt(encode(), selfConversationKey(inboxSecret))
|
||||
|
||||
companion object {
|
||||
const val TAG_NAME = "inbox_manifest"
|
||||
|
||||
private val json = Json { ignoreUnknownKeys = false }
|
||||
private val TOP = setOf("v", "generation", "seals", "group_copy")
|
||||
private val ENTRY = setOf("recipient", "key", "announcement")
|
||||
|
||||
fun tag(sealed: String): Array<String> = arrayOf(TAG_NAME, sealed)
|
||||
|
||||
/** The sealed manifest among a proposal's tags, or null. More than one is none. */
|
||||
fun sealedIn(tags: Array<Array<String>>): String? =
|
||||
tags.filter { it.isNotEmpty() && it[0] == TAG_NAME }.singleOrNull()?.getOrNull(1)?.ifBlank { null }
|
||||
|
||||
fun selfConversationKey(inboxSecret: ByteArray): ByteArray =
|
||||
InboxWire.conversationKey(inboxSecret, InboxWire.publicKeyOf(inboxSecret))
|
||||
|
||||
/** [sealed] opened with [inboxSecret], or null if that key does not open it or it is not a manifest. */
|
||||
fun open(sealed: String, inboxSecret: ByteArray): InboxReplyManifest? =
|
||||
InboxWire.decrypt(sealed, selfConversationKey(inboxSecret))?.let(::decode)
|
||||
|
||||
fun decode(text: String): InboxReplyManifest? = runCatching {
|
||||
val obj = json.parseToJsonElement(text) as JsonObject
|
||||
require(obj.keys == TOP)
|
||||
require((obj["v"] as JsonPrimitive).content == "1")
|
||||
val generation = (obj["generation"] as JsonPrimitive).content.toInt().also { require(it >= 0) }
|
||||
val seals = (obj["seals"] as JsonArray).map { element ->
|
||||
val entry = element as JsonObject
|
||||
require(entry.keys == ENTRY)
|
||||
val announcement = entry["announcement"]
|
||||
Entry(
|
||||
recipient = (entry["recipient"] as JsonPrimitive).content.also { require(InboxWire.isHex32(it)) },
|
||||
key = (entry["key"] as JsonPrimitive).content.also { require(InboxWire.isHex32(it)) },
|
||||
announcement = if (announcement is JsonNull) null else (announcement as JsonPrimitive).also { require(it.isString) }.content,
|
||||
)
|
||||
}
|
||||
val groupCopy = (obj["group_copy"] as JsonPrimitive).content.toInt()
|
||||
require(groupCopy in seals.indices)
|
||||
InboxReplyManifest(generation, seals, groupCopy)
|
||||
}.getOrNull()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package mobi.giza.compose.nostr.inbox
|
||||
|
||||
import com.vitorpamplona.quartz.nip01Core.core.Event
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher
|
||||
import com.vitorpamplona.quartz.nip01Core.crypto.verify
|
||||
import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate
|
||||
import com.vitorpamplona.quartz.nip59Giftwrap.rumors.Rumor
|
||||
import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent
|
||||
|
||||
/**
|
||||
* A NIP-17 seal with a decoupled encryption key, as nostr-protocol/nips#2361 has it
|
||||
* (docs/group-inbox.md):
|
||||
*
|
||||
* ```
|
||||
* seal (13) pubkey = the sender's identity signed by the identity
|
||||
* tags = [["n", the sender's encryption key]] when it is not the identity
|
||||
* content = nip44(rumor, conv(sender's encryption secret, receiver's encryption key))
|
||||
* ```
|
||||
*
|
||||
* The split is what lets a group answer at all: the admins hold the encryption secret and can
|
||||
* write the content; only the quorum can sign the seal. A group's seal is therefore built here
|
||||
* as an unsigned template, and signed by the FROST session.
|
||||
*/
|
||||
object InboxSeal {
|
||||
const val KIND = SealEvent.KIND
|
||||
const val ENCRYPTION_KEY_TAG = "n"
|
||||
|
||||
/**
|
||||
* The unsigned seal of [rumor] from the inbox key [inboxSecret] to [recipientEncryptionKey]:
|
||||
* the recipient's announced 10044 key, their identity if they announce none, or the inbox
|
||||
* key itself for the group's own copy.
|
||||
*/
|
||||
fun template(
|
||||
rumor: Event,
|
||||
inboxSecret: ByteArray,
|
||||
recipientEncryptionKey: HexKey,
|
||||
createdAt: Long,
|
||||
): EventTemplate<Event> = EventTemplate(
|
||||
createdAt = createdAt,
|
||||
kind = KIND,
|
||||
tags = arrayOf(arrayOf(ENCRYPTION_KEY_TAG, InboxWire.publicKeyOf(inboxSecret))),
|
||||
content = InboxWire.encrypt(rumorJson(rumor), InboxWire.conversationKey(inboxSecret, recipientEncryptionKey)),
|
||||
)
|
||||
|
||||
/** The rumor as NIP-59 puts it inside a seal: its id, no signature. */
|
||||
fun rumorJson(rumor: Event): String = Rumor.toJson(Rumor.create(rumor))
|
||||
|
||||
/** The `n` a seal names, or null when it names none or a malformed one. */
|
||||
fun encryptionKeyOf(tags: Array<Array<String>>): HexKey? {
|
||||
val named = tags.filter { it.isNotEmpty() && it[0] == ENCRYPTION_KEY_TAG }
|
||||
if (named.size != 1) return null
|
||||
return named.single().getOrNull(1)?.lowercase()?.takeIf(InboxWire::isHex32)
|
||||
}
|
||||
|
||||
/**
|
||||
* Which key the sender encrypted with, by #2361's rule and quartz's: the seal's `n` if it
|
||||
* has one, else the key the sender's own 10044 announces if this device has seen it, else
|
||||
* the sender's identity.
|
||||
*/
|
||||
fun senderEncryptionKey(seal: Event, senderAnnouncedKey: HexKey?): HexKey =
|
||||
encryptionKeyOf(seal.tags) ?: senderAnnouncedKey ?: seal.pubKey
|
||||
|
||||
data class Opened(val seal: Event, val rumor: Event, val senderEncryptionKey: HexKey)
|
||||
|
||||
/**
|
||||
* [seal], received, opened with [receiverSecret]. Null for every way that can fail: not a
|
||||
* seal, a signature that does not verify, a key that does not open it, a rumor that is not
|
||||
* one, or a rumor claiming an author the seal does not have -- NIP-17's impersonation check,
|
||||
* the one thing that makes the seal's signature mean the rumor's author.
|
||||
*
|
||||
* If the seal names no `n`, [senderAnnouncedKey] is tried before the identity, and then the
|
||||
* identity, since a sender's app may decouple without writing the tag.
|
||||
*/
|
||||
fun open(seal: Event, receiverSecret: ByteArray, senderAnnouncedKey: HexKey? = null): Opened? {
|
||||
if (seal.kind != KIND || !seal.verify()) return null
|
||||
val candidates = buildList {
|
||||
encryptionKeyOf(seal.tags)?.let(::add)
|
||||
senderAnnouncedKey?.let(::add)
|
||||
add(seal.pubKey)
|
||||
}.distinct()
|
||||
for (key in candidates) {
|
||||
val rumor = rumorInside(seal.content, InboxWire.conversationKey(receiverSecret, key), seal.pubKey) ?: continue
|
||||
return Opened(seal, rumor, key)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* The rumor inside a seal's [content] under [conversationKey], with its id computed rather
|
||||
* than trusted, or null. [author] is the seal's pubkey: a rumor claiming anyone else is
|
||||
* refused here, so no caller can forget to.
|
||||
*/
|
||||
fun rumorInside(content: String, conversationKey: ByteArray, author: HexKey): Event? {
|
||||
val json = InboxWire.decrypt(content, conversationKey) ?: return null
|
||||
val rumor = runCatching { Rumor.fromJson(json) }.getOrNull() ?: return null
|
||||
if (rumor.pubKey != author) return null
|
||||
val kind = rumor.kind ?: return null
|
||||
val createdAt = rumor.createdAt ?: return null
|
||||
val tags = rumor.tags ?: emptyArray()
|
||||
val content = rumor.content ?: ""
|
||||
val id = EventHasher.hashId(author, createdAt, kind, tags, content)
|
||||
return Event(id, author, createdAt, kind, tags, content, "")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package mobi.giza.compose.nostr.inbox
|
||||
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray
|
||||
import com.vitorpamplona.quartz.nip44Encryption.Nip44v2
|
||||
import fr.acinq.bitcoin.PrivateKey
|
||||
import mobi.giza.compose.extensions.toHex
|
||||
|
||||
/**
|
||||
* The arithmetic every piece of the group's inbox shares (docs/group-inbox.md).
|
||||
*
|
||||
* NIP-4E's keys are x-only, as every nostr key is. The inbox key's secret `e` comes out of a
|
||||
* ChillDKG ceremony whose public key may have either parity; NIP-44 uses only the x of the
|
||||
* shared point, which is the same for `e` and `-e`, so `e` is used as it is and nobody negates
|
||||
* anything. `InboxKeyPremiseTest` checks that from both sides.
|
||||
*/
|
||||
object InboxWire {
|
||||
/** One instance: [Nip44v2.computeConversationKey] is pure, and nothing here uses its cache. */
|
||||
val nip44 = Nip44v2()
|
||||
|
||||
fun isHex32(hex: String?): Boolean =
|
||||
hex != null && hex.length == 64 && hex.all { it in '0'..'9' || it in 'a'..'f' }
|
||||
|
||||
/** `E`, x-only, lowercase hex, as it goes in a 10044's `n` and a seal's `n`. */
|
||||
fun publicKeyOf(secret: ByteArray): HexKey = PrivateKey(secret).publicKey().xOnly().value.toHex()
|
||||
|
||||
/**
|
||||
* The NIP-44 conversation key between [secret] and [publicKey], uncached: an inbox key is
|
||||
* held by several admins and retired on rotation, and a process-wide cache of conversation
|
||||
* keys would keep a retired one alive in memory for no gain.
|
||||
*/
|
||||
fun conversationKey(secret: ByteArray, publicKey: HexKey): ByteArray =
|
||||
nip44.computeConversationKey(secret, publicKey.hexToByteArray())
|
||||
|
||||
fun encrypt(plaintext: String, conversationKey: ByteArray): String =
|
||||
nip44.encrypt(plaintext, conversationKey).encodePayload()
|
||||
|
||||
/** [payload] opened under [conversationKey], or null for any way that can fail. */
|
||||
fun decrypt(payload: String, conversationKey: ByteArray): String? =
|
||||
runCatching { nip44.decrypt(payload, conversationKey) }.getOrNull()
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package mobi.giza.compose.nostr.inbox
|
||||
|
||||
import com.vitorpamplona.quartz.nip01Core.core.Event
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
|
||||
import com.vitorpamplona.quartz.nip01Core.crypto.verify
|
||||
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
|
||||
import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync
|
||||
import com.vitorpamplona.quartz.nip01Core.tags.people.PTag
|
||||
import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent
|
||||
import com.vitorpamplona.quartz.utils.TimeUtils
|
||||
|
||||
/**
|
||||
* A NIP-59 gift wrap with a decoupled encryption key, as nostr-protocol/nips#2361 has it:
|
||||
*
|
||||
* ```
|
||||
* gift wrap (1059) pubkey = a fresh random key
|
||||
* tags = [["p", the recipient's identity, relay]]
|
||||
* content = nip44(seal, conv(wrapper secret, the recipient's encryption key))
|
||||
* ```
|
||||
*
|
||||
* quartz's [GiftWrapEvent.create] encrypts to the key it tags, which is right when they are the
|
||||
* same and wrong here, so the wrap is built by hand. The `p` stays the identity: it is how a
|
||||
* recipient's relays and apps find their mail, and it names nothing about which key opens it.
|
||||
* That is also why a reader with several keys has to try them ([open]).
|
||||
*/
|
||||
object InboxWrap {
|
||||
const val KIND = GiftWrapEvent.KIND
|
||||
|
||||
/**
|
||||
* [seal], already signed, wrapped for [recipientIdentity] under [recipientEncryptionKey] with a
|
||||
* throwaway key nobody keeps.
|
||||
*/
|
||||
fun wrap(
|
||||
seal: Event,
|
||||
recipientIdentity: HexKey,
|
||||
recipientEncryptionKey: HexKey,
|
||||
relayHint: NormalizedRelayUrl? = null,
|
||||
createdAt: Long = TimeUtils.randomWithTwoDays(),
|
||||
): Event {
|
||||
val signer = NostrSignerSync(KeyPair())
|
||||
val throwaway = requireNotNull(signer.keyPair.privKey)
|
||||
val content = InboxWire.encrypt(seal.toJson(), InboxWire.conversationKey(throwaway, recipientEncryptionKey))
|
||||
return signer.sign<GiftWrapEvent>(
|
||||
createdAt = createdAt,
|
||||
kind = KIND,
|
||||
tags = arrayOf(PTag.assemble(recipientIdentity, relayHint)),
|
||||
content = content,
|
||||
)
|
||||
}
|
||||
|
||||
/** Who a wrap is addressed to: its first `p`, which is a routing hint and proves nothing. */
|
||||
fun recipientOf(wrap: Event): HexKey? =
|
||||
wrap.tags.firstOrNull { it.size >= 2 && it[0] == "p" }?.get(1)
|
||||
|
||||
/**
|
||||
* The seal inside [wrap], and the index into [secrets] of the key that opened it, or null if
|
||||
* none does. Newest key first is the caller's order to give: a wrap is far likelier to be to
|
||||
* the key the group announces now than to one it retired.
|
||||
*/
|
||||
fun open(wrap: Event, secrets: List<ByteArray>): Pair<Int, Event>? {
|
||||
if (wrap.kind != KIND || !wrap.verify()) return null
|
||||
secrets.forEachIndexed { index, secret ->
|
||||
val json = InboxWire.decrypt(wrap.content, InboxWire.conversationKey(secret, wrap.pubKey)) ?: return@forEachIndexed
|
||||
val seal = Event.fromJsonOrNull(json) ?: return@forEachIndexed
|
||||
if (seal.kind == InboxSeal.KIND) return index to seal
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
package mobi.giza.compose.nostr.inbox
|
||||
|
||||
import com.vitorpamplona.quartz.experimental.decoupling.setup.EncryptionKeyListEvent
|
||||
import com.vitorpamplona.quartz.nip01Core.core.Event
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray
|
||||
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
|
||||
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
|
||||
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer
|
||||
import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate
|
||||
import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal
|
||||
import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync
|
||||
import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler
|
||||
import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent
|
||||
import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent
|
||||
import fr.acinq.bitcoin.Crypto
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNotNull
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
import kotlinx.coroutines.test.runTest
|
||||
|
||||
/**
|
||||
* The group inbox's wire, byte for byte where it matters (docs/group-inbox.md, Phase 2). The
|
||||
* group's FROST key is stood in for by a plain key here: what is under test is the layering, and
|
||||
* `SignedGroupKeyStateTest` shows the quorum signs a seal as the room.
|
||||
*/
|
||||
class InboxWireTest {
|
||||
private fun secret(label: String) = Crypto.sha256(label.encodeToByteArray())
|
||||
|
||||
private val group = KeyPair(secret("the group's identity"))
|
||||
private val inboxSecret = secret("the inbox key")
|
||||
private val inboxKey = InboxWire.publicKeyOf(inboxSecret)
|
||||
|
||||
private val alice = KeyPair(secret("alice"))
|
||||
private val aliceEncryptionSecret = secret("alice's encryption key")
|
||||
private val aliceEncryptionKey = InboxWire.publicKeyOf(aliceEncryptionSecret)
|
||||
|
||||
private fun KeyPair.hex(): HexKey = pubKey.toHexKey()
|
||||
|
||||
private fun rumor(author: HexKey, to: List<HexKey>, text: String, createdAt: Long = 1_700_000_000L): Event =
|
||||
RumorAssembler.assembleRumor(
|
||||
pubKey = author,
|
||||
ev = EventTemplate<Event>(createdAt, 14, to.map { arrayOf("p", it) }.toTypedArray(), text),
|
||||
)
|
||||
|
||||
// ---- the ceremony's tags
|
||||
|
||||
@Test
|
||||
fun `a proposal's tags carry the session, the generation, threshold 1 and the admins`() {
|
||||
val session = "ab".repeat(32)
|
||||
val admins = listOf("c".repeat(64), "b".repeat(64), "c".repeat(64))
|
||||
val tags = InboxKeyRitualEvents.assembleTags(session, generation = 2, participants = admins)
|
||||
|
||||
assertEquals(session, InboxKeyRitualEvents.parseSessionId(tags))
|
||||
assertEquals(2, InboxKeyRitualEvents.parseGeneration(tags))
|
||||
assertEquals(1, InboxKeyRitualEvents.parseThreshold(tags))
|
||||
assertEquals(listOf("b".repeat(64), "c".repeat(64)), InboxKeyRitualEvents.parseParticipants(tags))
|
||||
assertNull(InboxKeyRitualEvents.parseParticipants(tags + arrayOf(arrayOf("p", "not a key"))))
|
||||
}
|
||||
|
||||
// ---- the announcement
|
||||
|
||||
@Test
|
||||
fun `the group's 10044 names its key alone, and quartz reads it`() {
|
||||
val template = InboxAnnouncement.keyTemplate(inboxKey, 1_700_000_000L)
|
||||
val signed = NostrSignerSync(group).sign(template)
|
||||
|
||||
assertEquals(10044, signed.kind)
|
||||
assertEquals(inboxKey, InboxAnnouncement.groupKeyOf(signed))
|
||||
assertEquals(inboxKey, InboxAnnouncement.announcedKeyOf(signed))
|
||||
assertEquals(inboxKey, (signed as EncryptionKeyListEvent).encryptionKey()?.pubkey)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a 10044 with a second key, a nonce or content is not one the group would sign`() {
|
||||
val other = "d".repeat(64)
|
||||
assertNull(InboxAnnouncement.groupKeyOf(10044, arrayOf(arrayOf("n", inboxKey), arrayOf("n", other)), ""))
|
||||
assertNull(InboxAnnouncement.groupKeyOf(10044, arrayOf(arrayOf("n", inboxKey, "ab".repeat(16))), ""))
|
||||
assertNull(InboxAnnouncement.groupKeyOf(10044, arrayOf(arrayOf("n", inboxKey)), "hello"))
|
||||
assertNull(InboxAnnouncement.groupKeyOf(10044, arrayOf(arrayOf("n", inboxKey.uppercase())), ""))
|
||||
// Someone else's may carry more; the first key is still theirs.
|
||||
assertEquals(inboxKey, InboxAnnouncement.announcedKeyOf(
|
||||
Event("a".repeat(64), alice.hex(), 1, 10044, arrayOf(arrayOf("n", inboxKey), arrayOf("n", other)), "", ""),
|
||||
))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the group's 10050 lists public relays only`() {
|
||||
val relay = assertNotNull(RelayUrlNormalizer.normalizeOrNull("wss://relay.example.com"))
|
||||
val template = InboxAnnouncement.relaysTemplate(listOf(relay), 1_700_000_000L)
|
||||
assertEquals(listOf(relay), InboxAnnouncement.groupRelaysOf(template.kind, template.tags, template.content))
|
||||
|
||||
assertNull(InboxAnnouncement.groupRelaysOf(10050, arrayOf(arrayOf("relay", "ws://relay.example.com")), ""))
|
||||
assertNull(InboxAnnouncement.groupRelaysOf(10050, emptyArray(), ""))
|
||||
assertNull(InboxAnnouncement.groupRelaysOf(10050, arrayOf(arrayOf("r", "wss://relay.example.com")), ""))
|
||||
}
|
||||
|
||||
// ---- the seal
|
||||
|
||||
@Test
|
||||
fun `a seal from the inbox key opens with the recipient's encryption key`() {
|
||||
val reply = rumor(group.hex(), listOf(alice.hex()), "Thank you for writing")
|
||||
val seal = NostrSignerSync(group).sign(InboxSeal.template(reply, inboxSecret, aliceEncryptionKey, 1_700_000_000L))
|
||||
|
||||
assertEquals(listOf(listOf("n", inboxKey)), seal.tags.map { it.toList() })
|
||||
val opened = assertNotNull(InboxSeal.open(seal, aliceEncryptionSecret))
|
||||
assertEquals(reply.id, opened.rumor.id)
|
||||
assertEquals("Thank you for writing", opened.rumor.content)
|
||||
assertEquals(inboxKey, opened.senderEncryptionKey)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a seal to a recipient with no 10044 opens with their identity`() {
|
||||
val reply = rumor(group.hex(), listOf(alice.hex()), "Hello")
|
||||
val seal = NostrSignerSync(group).sign(InboxSeal.template(reply, inboxSecret, alice.hex(), 1_700_000_000L))
|
||||
|
||||
assertNotNull(InboxSeal.open(seal, assertNotNull(alice.privKey)))
|
||||
assertNull(InboxSeal.open(seal, aliceEncryptionSecret), "only the key it was sealed to opens it")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the group's own copy opens with the inbox key`() {
|
||||
val reply = rumor(group.hex(), listOf(alice.hex()), "Hello")
|
||||
val seal = NostrSignerSync(group).sign(InboxSeal.template(reply, inboxSecret, inboxKey, 1_700_000_000L))
|
||||
assertEquals("Hello", assertNotNull(InboxSeal.open(seal, inboxSecret)).rumor.content)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a seal from a sender who does not decouple opens with their identity`() {
|
||||
// A stock NIP-17 seal, as any app writes one, to the group's announced key.
|
||||
val message = rumor(alice.hex(), listOf(group.hex()), "Can I join?")
|
||||
val content = InboxWire.encrypt(InboxSeal.rumorJson(message), InboxWire.conversationKey(assertNotNull(alice.privKey), inboxKey))
|
||||
val seal = NostrSignerSync(alice).sign<Event>(1_700_000_000L, 13, emptyArray(), content)
|
||||
|
||||
val opened = assertNotNull(InboxSeal.open(seal, inboxSecret))
|
||||
assertEquals("Can I join?", opened.rumor.content)
|
||||
assertEquals(alice.hex(), opened.senderEncryptionKey)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a seal from a sender who decoupled opens by its n tag, or by their 10044 without one`() {
|
||||
val message = rumor(alice.hex(), listOf(group.hex()), "From my other key")
|
||||
val content = InboxWire.encrypt(InboxSeal.rumorJson(message), InboxWire.conversationKey(aliceEncryptionSecret, inboxKey))
|
||||
|
||||
val tagged = NostrSignerSync(alice).sign<Event>(1_700_000_000L, 13, arrayOf(arrayOf("n", aliceEncryptionKey)), content)
|
||||
assertEquals(aliceEncryptionKey, assertNotNull(InboxSeal.open(tagged, inboxSecret)).senderEncryptionKey)
|
||||
|
||||
val untagged = NostrSignerSync(alice).sign<Event>(1_700_000_000L, 13, emptyArray(), content)
|
||||
assertNull(InboxSeal.open(untagged, inboxSecret), "without the tag or the 10044 there is nothing to try but the identity")
|
||||
assertNotNull(InboxSeal.open(untagged, inboxSecret, senderAnnouncedKey = aliceEncryptionKey))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a rumor claiming another author is refused`() {
|
||||
val forged = rumor(group.hex(), listOf(group.hex()), "I am the group")
|
||||
val content = InboxWire.encrypt(InboxSeal.rumorJson(forged), InboxWire.conversationKey(assertNotNull(alice.privKey), inboxKey))
|
||||
val seal = NostrSignerSync(alice).sign<Event>(1_700_000_000L, 13, emptyArray(), content)
|
||||
assertNull(InboxSeal.open(seal, inboxSecret))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an unsigned or tampered seal is refused`() {
|
||||
val reply = rumor(group.hex(), listOf(alice.hex()), "Hello")
|
||||
val template = InboxSeal.template(reply, inboxSecret, aliceEncryptionKey, 1_700_000_000L)
|
||||
val unsigned = Event("a".repeat(64), group.hex(), template.createdAt, template.kind, template.tags, template.content, "")
|
||||
assertNull(InboxSeal.open(unsigned, aliceEncryptionSecret))
|
||||
}
|
||||
|
||||
// ---- the wrap
|
||||
|
||||
@Test
|
||||
fun `a wrap names the identity and opens with the encryption key`() {
|
||||
val seal = NostrSignerSync(group).sign(InboxSeal.template(rumor(group.hex(), listOf(alice.hex()), "Hi"), inboxSecret, aliceEncryptionKey, 1L))
|
||||
val relay = RelayUrlNormalizer.normalizeOrNull("wss://inbox.example.com")
|
||||
val wrap = InboxWrap.wrap(seal, alice.hex(), aliceEncryptionKey, relay, createdAt = 2L)
|
||||
|
||||
assertEquals(1059, wrap.kind)
|
||||
assertEquals(alice.hex(), InboxWrap.recipientOf(wrap))
|
||||
assertTrue(wrap.pubKey != group.hex() && wrap.pubKey != alice.hex(), "nothing outside names the sender")
|
||||
|
||||
val (index, opened) = assertNotNull(InboxWrap.open(wrap, listOf(secret("a retired key"), aliceEncryptionSecret)))
|
||||
assertEquals(1, index)
|
||||
assertEquals(seal.id, opened.id)
|
||||
assertNull(InboxWrap.open(wrap, listOf(assertNotNull(alice.privKey))), "the identity does not open a wrap to the encryption key")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a wrap built here is still a NIP-59 wrap to quartz, when the keys are the same`() = runTest {
|
||||
val message = rumor(group.hex(), listOf(alice.hex()), "Plain NIP-17")
|
||||
val content = InboxWire.encrypt(InboxSeal.rumorJson(message), InboxWire.conversationKey(assertNotNull(group.privKey), alice.hex()))
|
||||
val seal = NostrSignerSync(group).sign<Event>(1L, 13, emptyArray(), content)
|
||||
val wrap = InboxWrap.wrap(seal, alice.hex(), alice.hex(), createdAt = 2L) as GiftWrapEvent
|
||||
|
||||
val opened = assertNotNull(wrap.unwrapAndUnsealOrNull(NostrSignerInternal(alice)))
|
||||
assertEquals("Plain NIP-17", opened.content)
|
||||
assertEquals(group.hex(), opened.pubKey)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a wrap quartz builds to the inbox key opens here`() = runTest {
|
||||
// A sender whose app follows NIP-4E only so far as encrypting to the announced key.
|
||||
val message = rumor(alice.hex(), listOf(group.hex()), "Quartz wrote this")
|
||||
val seal = NostrSignerSync(alice).sign<SealEvent>(
|
||||
1L, 13, emptyArray(),
|
||||
InboxWire.encrypt(InboxSeal.rumorJson(message), InboxWire.conversationKey(assertNotNull(alice.privKey), inboxKey)),
|
||||
)
|
||||
val wrap = GiftWrapEvent.create(event = seal, recipientPubKey = inboxKey, createdAt = 2L)
|
||||
|
||||
val (_, unwrapped) = assertNotNull(InboxWrap.open(wrap, listOf(inboxSecret)))
|
||||
assertEquals("Quartz wrote this", assertNotNull(InboxSeal.open(unwrapped, inboxSecret)).rumor.content)
|
||||
}
|
||||
|
||||
// ---- the manifest
|
||||
|
||||
private val manifest = InboxReplyManifest(
|
||||
generation = 3,
|
||||
seals = listOf(
|
||||
InboxReplyManifest.Entry(alice.hex(), aliceEncryptionKey, """{"kind":10044}"""),
|
||||
InboxReplyManifest.Entry(group.hex(), inboxKey, null),
|
||||
),
|
||||
groupCopy = 1,
|
||||
)
|
||||
|
||||
@Test
|
||||
fun `a manifest opens only with the inbox key it was sealed under`() {
|
||||
val sealed = manifest.seal(inboxSecret)
|
||||
assertEquals(manifest, InboxReplyManifest.open(sealed, inboxSecret))
|
||||
assertNull(InboxReplyManifest.open(sealed, secret("another generation")))
|
||||
assertEquals(sealed, InboxReplyManifest.sealedIn(arrayOf(InboxReplyManifest.tag(sealed), arrayOf("x", "y"))))
|
||||
assertNull(InboxReplyManifest.sealedIn(arrayOf(InboxReplyManifest.tag(sealed), InboxReplyManifest.tag(sealed))))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a manifest with a stray field, a missing one or a copy out of range is none`() {
|
||||
val encoded = manifest.encode()
|
||||
assertEquals(manifest, InboxReplyManifest.decode(encoded))
|
||||
assertNull(InboxReplyManifest.decode(encoded.replaceFirst("{\"v\":1", "{\"v\":1,\"extra\":true")))
|
||||
assertNull(InboxReplyManifest.decode(encoded.replace(",\"group_copy\":1", "")))
|
||||
assertNull(InboxReplyManifest.decode(encoded.replace("\"group_copy\":1", "\"group_copy\":2")))
|
||||
assertNull(InboxReplyManifest.decode(encoded.replace("\"v\":1", "\"v\":2")))
|
||||
}
|
||||
|
||||
// ---- the conversation
|
||||
|
||||
@Test
|
||||
fun `a message and its reply are one conversation, whatever the order of its people`() {
|
||||
val bob = KeyPair(secret("bob")).hex()
|
||||
val incoming = rumor(alice.hex(), listOf(group.hex(), bob), "To the group and Bob")
|
||||
val reply = rumor(group.hex(), listOf(bob, alice.hex()), "To both")
|
||||
|
||||
assertEquals(listOf(alice.hex(), bob).sorted(), InboxConversation.participantsOf(incoming, group.hex()))
|
||||
assertEquals(InboxConversation.idOf(incoming, group.hex()), InboxConversation.idOf(reply, group.hex()))
|
||||
assertTrue(InboxConversation.idOf(rumor(alice.hex(), listOf(group.hex()), "Just us"), group.hex()) != InboxConversation.idOf(incoming, group.hex()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the inbox key's hex is the x-only key of its secret`() {
|
||||
assertEquals(64, inboxKey.length)
|
||||
assertEquals(32, inboxKey.hexToByteArray().size)
|
||||
assertEquals(inboxKey, inboxKey.lowercase())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user