feat: the wire for a group's direct messages (group-threshold-ecdh, Phase 3)
Kinds 30400 and 30401; a payload encrypted once under a key sealed to each admin's host key; partials that name a wrap by id; the manifest a signer reads; opening NIP-59's layers with a threshold key; conversation ids; and D5's evidence rule in one function. A seal the group builds opens in quartz's stock unwrap with the recipient's own key. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
77e154d4f5
commit
fcdc2db78e
9 files changed
+644
No files matched your search
@@ -0,0 +1,68 @@
|
||||
package mobi.giza.compose.nostr.groupdm
|
||||
|
||||
import com.vitorpamplona.crypto.random.RandomInstance
|
||||
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
|
||||
|
||||
/**
|
||||
* Something only the group's current admins may read, inside a room every member receives
|
||||
* (D4 and D12 of docs/group-threshold-ecdh.md).
|
||||
*
|
||||
* The plaintext is NIP-44-encrypted once, under a fresh 32-byte key used as the conversation
|
||||
* key, and only that key is sealed to each admin's ChillDKG host key over the share-repair
|
||||
* channel. Phase 0's check 6 is why: sealing the whole plaintext per admin multiplied a batch
|
||||
* of partials by the number of admins, past a relay's event.
|
||||
*
|
||||
* A host key is the 33-byte compressed one the roster carries, as 66 hex; NIP-44's ECDH reads
|
||||
* only its x-coordinate.
|
||||
*/
|
||||
object AdminSeal {
|
||||
private val nip44 = Nip44v2()
|
||||
|
||||
/** [content] for everyone; [slots] the content key, sealed per admin host key. */
|
||||
data class Sealed(val content: String, val slots: Map<HexKey, String>)
|
||||
|
||||
fun seal(
|
||||
plaintext: String,
|
||||
senderHostSecret: PrivateKey,
|
||||
recipientHostKeys: Collection<HexKey>,
|
||||
contentKey: ByteArray = RandomInstance.bytes(32),
|
||||
): Sealed {
|
||||
require(contentKey.size == 32) { "a content key is 32 bytes" }
|
||||
val content = nip44.encrypt(plaintext, contentKey).encodePayload()
|
||||
val slots = recipientHostKeys.distinct().associateWith { host ->
|
||||
nip44.encrypt(contentKey.toHex(), senderHostSecret.value.toByteArray(), xOnly(host)).encodePayload()
|
||||
}
|
||||
return Sealed(content, slots)
|
||||
}
|
||||
|
||||
/**
|
||||
* The plaintext, or null when this device has no slot, its slot does not open under
|
||||
* [senderHostKey], or the content does not open under what the slot held.
|
||||
*/
|
||||
fun open(sealed: Sealed, myHostSecret: PrivateKey, myHostKey: HexKey, senderHostKey: HexKey): String? = runCatching {
|
||||
val slot = sealed.slots[myHostKey.lowercase()] ?: return null
|
||||
val contentKey = nip44.decrypt(slot, myHostSecret.value.toByteArray(), xOnly(senderHostKey))
|
||||
.takeIf { it.length == 64 }?.hexToByteArray() ?: return null
|
||||
nip44.decrypt(sealed.content, contentKey)
|
||||
}.getOrNull()
|
||||
|
||||
/** The x-coordinate of a compressed host key, which is all NIP-44's ECDH reads. */
|
||||
private fun xOnly(hostPublicKey: HexKey): ByteArray {
|
||||
require(hostPublicKey.length == 66) { "a host key is 33 bytes" }
|
||||
return hostPublicKey.hexToByteArray().copyOfRange(1, 33)
|
||||
}
|
||||
|
||||
/** As tags: `["slot", <host key>, <sealed content key>]`, sorted so two devices agree byte for byte. */
|
||||
const val SLOT_TAG = "slot"
|
||||
|
||||
fun slotTags(slots: Map<HexKey, String>, name: String = SLOT_TAG): List<Array<String>> =
|
||||
slots.entries.sortedBy { it.key }.map { (host, sealed) -> arrayOf(name, host, sealed) }
|
||||
|
||||
fun parseSlots(tags: Array<Array<String>>, name: String = SLOT_TAG): Map<HexKey, String> =
|
||||
tags.filter { it.size >= 3 && it[0] == name && it[1].length == 66 }
|
||||
.associate { it[1].lowercase() to it[2] }
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package mobi.giza.compose.nostr.groupdm
|
||||
|
||||
/**
|
||||
* Why a device is asked to multiply by a point, which fixes what it must hold first (D5 of
|
||||
* docs/group-threshold-ecdh.md). The wire name is the lowercase name.
|
||||
*/
|
||||
enum class EcdhPurpose {
|
||||
/** The point is a gift wrap's pubkey `W`; the evidence is the wrap, p-tagged to the group. */
|
||||
WRAP,
|
||||
|
||||
/** The point is a seal's pubkey `S`; the evidence is the seal, out of a wrap the device opened. */
|
||||
SEAL,
|
||||
|
||||
/** The point is someone the group writes to, `R`; the evidence is any event `R` signed. */
|
||||
RECIPIENT;
|
||||
|
||||
val wire: String get() = name.lowercase()
|
||||
|
||||
companion object {
|
||||
fun fromWire(value: String): EcdhPurpose? = entries.firstOrNull { it.wire == value }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package mobi.giza.compose.nostr.groupdm
|
||||
|
||||
import com.vitorpamplona.quartz.nip01Core.core.Event
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import com.vitorpamplona.quartz.nip01Core.crypto.verify
|
||||
import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent
|
||||
import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent
|
||||
|
||||
/**
|
||||
* D5 of docs/group-threshold-ecdh.md, in one function, so the device answering a round and the
|
||||
* signer checking a message check the same thing: a device multiplies only by a key whose
|
||||
* owner has signed something it can check, of the right shape for the purpose.
|
||||
*
|
||||
* A signature by `P` proves its signer knows `log_G(P)`, so no point asked about can be
|
||||
* `x^k·G`, which is the query a static Diffie-Hellman oracle is worn down by. The group's own
|
||||
* npub is refused outright: `x·(x·G)` is exactly that query, and why the group never encrypts
|
||||
* to itself.
|
||||
*/
|
||||
object Evidence {
|
||||
enum class Refusal { WRONG_KIND, WRONG_KEY, NOT_TO_GROUP, BAD_SIGNATURE, THE_GROUP_ITSELF }
|
||||
|
||||
/** Null when [event] lets a device multiply by [point] for [purpose]; otherwise why not. */
|
||||
fun check(purpose: EcdhPurpose, point: HexKey, event: Event, groupNpub: HexKey): Refusal? {
|
||||
val p = point.lowercase()
|
||||
if (p == groupNpub.lowercase()) return Refusal.THE_GROUP_ITSELF
|
||||
if (event.pubKey.lowercase() != p) return Refusal.WRONG_KEY
|
||||
when (purpose) {
|
||||
EcdhPurpose.WRAP -> {
|
||||
if (event.kind != GiftWrapEvent.KIND) return Refusal.WRONG_KIND
|
||||
val addressed = event.tags.any { it.size >= 2 && it[0] == "p" && it[1].lowercase() == groupNpub.lowercase() }
|
||||
if (!addressed) return Refusal.NOT_TO_GROUP
|
||||
}
|
||||
EcdhPurpose.SEAL -> if (event.kind != SealEvent.KIND) return Refusal.WRONG_KIND
|
||||
EcdhPurpose.RECIPIENT -> Unit
|
||||
}
|
||||
if (!event.verify()) return Refusal.BAD_SIGNATURE
|
||||
return null
|
||||
}
|
||||
|
||||
fun allows(purpose: EcdhPurpose, point: HexKey, event: Event, groupNpub: HexKey): Boolean =
|
||||
check(purpose, point, event, groupNpub) == null
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package mobi.giza.compose.nostr.groupdm
|
||||
|
||||
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 of the group's conversations a message belongs to. 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, and
|
||||
* what remains is the group's correspondents.
|
||||
*/
|
||||
object GroupDmConversation {
|
||||
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() && it.length == 64 }
|
||||
.distinct()
|
||||
.sorted()
|
||||
|
||||
/** A hash of the sorted participants: the same conversation on every admin's device. */
|
||||
fun idOf(rumor: Event, group: HexKey): HexKey = idOf(participantsOf(rumor, group))
|
||||
|
||||
fun idOf(participants: Collection<HexKey>): HexKey =
|
||||
Crypto.sha256(participants.map { it.lowercase() }.distinct().sorted().joinToString(",").encodeToByteArray()).toHex()
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package mobi.giza.compose.nostr.groupdm
|
||||
|
||||
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.nip44Encryption.Nip44v2
|
||||
import com.vitorpamplona.quartz.nip59Giftwrap.rumors.Rumor
|
||||
import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent
|
||||
import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent
|
||||
|
||||
/**
|
||||
* NIP-59's two layers, opened and built with a conversation key that threshold ECDH gave,
|
||||
* rather than with a key this device holds. quartz's own `GiftWrapEvent` and `SealEvent` take
|
||||
* a signer, which the group does not have, so these are built by hand to the same shape
|
||||
* (docs/group-threshold-ecdh.md, Phase 3).
|
||||
*/
|
||||
object GroupDmWrap {
|
||||
private val nip44 = Nip44v2()
|
||||
|
||||
/** The seal inside [wrap], signed by its own pubkey, or null. */
|
||||
fun open(wrap: Event, conversationKey: ByteArray): Event? = runCatching {
|
||||
if (wrap.kind != GiftWrapEvent.KIND) return null
|
||||
val seal = Event.fromJson(nip44.decrypt(wrap.content, conversationKey))
|
||||
seal.takeIf { it.kind == SealEvent.KIND && it.verify() }
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
object GroupDmSeal {
|
||||
private val nip44 = Nip44v2()
|
||||
|
||||
/**
|
||||
* The rumor inside [seal], or null. NIP-59's anti-spoofing check is the caller's job in
|
||||
* quartz; here it is part of opening: a rumor whose pubkey is not the seal's is refused.
|
||||
* Its id is recomputed, never taken from the rumor (quartz's `mergeWith` says why).
|
||||
*/
|
||||
fun open(seal: Event, conversationKey: ByteArray): Event? = runCatching {
|
||||
if (seal.kind != SealEvent.KIND) return null
|
||||
val rumor = Rumor.fromJson(nip44.decrypt(seal.content, conversationKey))
|
||||
if (rumor.pubKey != null && rumor.pubKey != seal.pubKey) return null
|
||||
val tags = rumor.tags ?: emptyArray()
|
||||
val createdAt = rumor.createdAt ?: return null
|
||||
val kind = rumor.kind ?: return null
|
||||
val content = rumor.content ?: ""
|
||||
val id = EventHasher.hashId(seal.pubKey, createdAt, kind, tags, content)
|
||||
Event(id, seal.pubKey, createdAt, kind, tags, content, "")
|
||||
}.getOrNull()
|
||||
|
||||
/** The rumor as JSON, id included and no signature, as NIP-59 puts it inside a seal. */
|
||||
fun rumorJson(rumor: Event): String = Rumor.toJson(Rumor.create(rumor))
|
||||
|
||||
/**
|
||||
* An unsigned seal from the group to whoever [conversationKey] is shared with: kind 13,
|
||||
* no tags, the rumor NIP-44-encrypted. The group signs it; nothing else changes it after.
|
||||
*/
|
||||
fun build(rumor: Event, conversationKey: ByteArray, createdAt: Long): EventTemplate<Event> =
|
||||
EventTemplate(createdAt, SealEvent.KIND, emptyArray(), nip44.encrypt(rumorJson(rumor), conversationKey).encodePayload())
|
||||
|
||||
/** An unsigned rumor, its id computed, as the group would author it. */
|
||||
fun rumor(author: HexKey, createdAt: Long, kind: Int, tags: Array<Array<String>>, content: String): Event =
|
||||
Event(EventHasher.hashId(author, createdAt, kind, tags, content), author, createdAt, kind, tags, content, "")
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package mobi.giza.compose.nostr.groupdm
|
||||
|
||||
import com.vitorpamplona.quartz.nip01Core.core.Event
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
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.int
|
||||
import kotlinx.serialization.json.put
|
||||
|
||||
/**
|
||||
* What a group's message is, for the admins who sign it (D12 of docs/group-threshold-ecdh.md).
|
||||
*
|
||||
* A signing proposal reaches every member of the room, and its events are seals, which are
|
||||
* ciphertext. A signer also needs to know which seal is for whom and why its device may
|
||||
* multiply by each recipient's key. That is this manifest, sealed to the current admins'
|
||||
* host keys and carried as proposal tags:
|
||||
*
|
||||
* ```
|
||||
* ["dm_manifest", <content>] ["dm_slot", <host key>, <sealed content key>] one per admin
|
||||
*
|
||||
* {"v":1,"seals":[{"recipient":"<hex>","evidence":<event signed by the recipient>}, …],"replying_to":<id or null>}
|
||||
* ```
|
||||
*
|
||||
* The seals are in the same order as the batch's events. The decoder accepts only its own
|
||||
* encoding.
|
||||
*/
|
||||
class GroupDmManifest(
|
||||
val seals: List<Seal>,
|
||||
val replyingTo: HexKey?,
|
||||
) {
|
||||
class Seal(val recipient: HexKey, val evidence: Event)
|
||||
|
||||
val recipients: List<HexKey> get() = seals.map { it.recipient }
|
||||
|
||||
fun encode(): String = Json.encodeToString(JsonElement.serializer(), buildJsonObject {
|
||||
put("v", VERSION)
|
||||
put("seals", buildJsonArray {
|
||||
seals.forEach { seal ->
|
||||
add(buildJsonObject {
|
||||
put("recipient", seal.recipient)
|
||||
put("evidence", Json.parseToJsonElement(seal.evidence.toJson()))
|
||||
})
|
||||
}
|
||||
})
|
||||
put("replying_to", replyingTo?.let(::JsonPrimitive) ?: JsonNull)
|
||||
})
|
||||
|
||||
/** As proposal tags, sealed to [adminHostKeys] from the proposer's host key. */
|
||||
fun toTags(sealed: AdminSeal.Sealed): Array<Array<String>> =
|
||||
(listOf(arrayOf(MANIFEST_TAG, sealed.content)) + AdminSeal.slotTags(sealed.slots, SLOT_TAG)).toTypedArray()
|
||||
|
||||
companion object {
|
||||
const val VERSION = 1
|
||||
const val MANIFEST_TAG = "dm_manifest"
|
||||
const val SLOT_TAG = "dm_slot"
|
||||
|
||||
private fun isHex64(value: String) = value.length == 64 && value.all { it in "0123456789abcdef" }
|
||||
|
||||
/** Whether [tags] carry a manifest at all: what marks a batch of seals as the group's message. */
|
||||
fun isCarriedBy(tags: Array<Array<String>>): Boolean = tags.any { it.size >= 2 && it[0] == MANIFEST_TAG }
|
||||
|
||||
/** The sealed manifest in [tags], or null if there is none. */
|
||||
fun sealedIn(tags: Array<Array<String>>): AdminSeal.Sealed? {
|
||||
val content = tags.firstOrNull { it.size >= 2 && it[0] == MANIFEST_TAG }?.get(1) ?: return null
|
||||
return AdminSeal.Sealed(content, AdminSeal.parseSlots(tags, SLOT_TAG))
|
||||
}
|
||||
|
||||
fun decode(text: String): GroupDmManifest? = runCatching {
|
||||
val root = Json.parseToJsonElement(text) as? JsonObject ?: return null
|
||||
if ((root["v"] as? JsonPrimitive)?.takeIf { !it.isString }?.int != VERSION) return null
|
||||
val seals = (root["seals"] as? JsonArray)?.map { element ->
|
||||
val o = element as? JsonObject ?: return null
|
||||
val recipient = (o["recipient"] as? JsonPrimitive)?.takeIf { it.isString }?.content?.takeIf(::isHex64) ?: return null
|
||||
val evidence = o["evidence"]?.let { Event.fromJson(Json.encodeToString(JsonElement.serializer(), it)) } ?: return null
|
||||
Seal(recipient, evidence)
|
||||
} ?: return null
|
||||
if (seals.isEmpty()) return null
|
||||
val replyingTo = when (val r = root["replying_to"]) {
|
||||
null, JsonNull -> null
|
||||
is JsonPrimitive -> r.takeIf { it.isString }?.content?.takeIf(::isHex64) ?: return null
|
||||
else -> return null
|
||||
}
|
||||
GroupDmManifest(seals, replyingTo).takeIf { it.encode() == text }
|
||||
}.getOrNull()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package mobi.giza.compose.nostr.groupdm
|
||||
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import com.vitorpamplona.quartz.nip01Core.core.Kind
|
||||
|
||||
/**
|
||||
* The kinds threshold ECDH travels on (docs/group-threshold-ecdh.md, D4, D11 and Phase 0's
|
||||
* check 5). Marmot inner events in the group's own room, like the signing and share refresh
|
||||
* families.
|
||||
*
|
||||
* 30400 and 30401 were free in the NIP README (30402 and 30403 are NIP-99's), quartz, Bennu,
|
||||
* and `RetiredKinds` when they were chosen.
|
||||
*/
|
||||
object GroupEcdhEvents {
|
||||
/** An admin's partials for one or more rounds: [GroupEcdhPayload], sealed to the admins by [AdminSeal]. */
|
||||
val PARTIALS: Kind = 30400
|
||||
|
||||
/** A round whose partial from [BLAME_TAG] did not prove. Content is the reason, in words. */
|
||||
val FAILURE: Kind = 30401
|
||||
|
||||
val ALL: Set<Kind> = setOf(PARTIALS, FAILURE)
|
||||
|
||||
const val ROUND_TAG = "ecdh_round"
|
||||
const val BLAME_TAG = "ecdh_blame"
|
||||
|
||||
/** A partials message's tags: the slots, and nothing else a member who is not an admin can read. */
|
||||
fun partialsTags(sealed: AdminSeal.Sealed): Array<Array<String>> = AdminSeal.slotTags(sealed.slots).toTypedArray()
|
||||
|
||||
fun failureTags(roundId: HexKey, participantId: Int): Array<Array<String>> =
|
||||
arrayOf(arrayOf(ROUND_TAG, roundId), arrayOf(BLAME_TAG, participantId.toString()))
|
||||
|
||||
fun parseFailure(tags: Array<Array<String>>): Pair<HexKey, Int>? {
|
||||
val round = tags.firstOrNull { it.size >= 2 && it[0] == ROUND_TAG }?.get(1)?.takeIf { it.length == 64 } ?: return null
|
||||
val blamed = tags.firstOrNull { it.size >= 2 && it[0] == BLAME_TAG }?.get(1)?.toIntOrNull()?.takeIf { it >= 0 } ?: return null
|
||||
return round to blamed
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package mobi.giza.compose.nostr.groupdm
|
||||
|
||||
import com.vitorpamplona.quartz.nip01Core.core.Event
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray
|
||||
import fr.acinq.bitcoin.Crypto
|
||||
import fr.acinq.bitcoin.PublicKey
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.buildJsonArray
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.int
|
||||
import kotlinx.serialization.json.put
|
||||
import mobi.giza.compose.cryptography.threshold.Dleq
|
||||
import mobi.giza.compose.extensions.toHex
|
||||
|
||||
/**
|
||||
* What a partials message carries, once its [AdminSeal] is opened (D11 of
|
||||
* docs/group-threshold-ecdh.md):
|
||||
*
|
||||
* ```
|
||||
* {"v":1,"generation":g,"from":id,"items":[{"point","purpose","ref"?,"evidence"?,"partial","proof"}, …]}
|
||||
* ```
|
||||
*
|
||||
* [Item.point] is the x-only key multiplied, lifted to even y by everyone; [Item.partial] is
|
||||
* `sᵢ·P`, compressed. A wrap or a seal is named by the wrap's id in [Item.ref], since every
|
||||
* admin's device holds the wrap and opens the same seal from it (Phase 0, check 6). Only a
|
||||
* recipient's evidence travels whole, in [Item.evidence].
|
||||
*
|
||||
* The decoder accepts only its own encoding, so there is one spelling of a payload.
|
||||
*/
|
||||
class GroupEcdhPayload(
|
||||
val generation: Int,
|
||||
val from: Int,
|
||||
val items: List<Item>,
|
||||
) {
|
||||
class Item(
|
||||
val point: HexKey,
|
||||
val purpose: EcdhPurpose,
|
||||
val ref: HexKey? = null,
|
||||
val evidence: Event? = null,
|
||||
val partial: PublicKey,
|
||||
val proof: Dleq.Proof,
|
||||
)
|
||||
|
||||
fun encode(): String = json.encodeToString(JsonElement.serializer(), toJson())
|
||||
|
||||
private fun toJson(): JsonObject = buildJsonObject {
|
||||
put("v", VERSION)
|
||||
put("generation", generation)
|
||||
put("from", from)
|
||||
put("items", buildJsonArray {
|
||||
items.forEach { item ->
|
||||
add(buildJsonObject {
|
||||
put("point", item.point)
|
||||
put("purpose", item.purpose.wire)
|
||||
item.ref?.let { put("ref", it) }
|
||||
item.evidence?.let { put("evidence", json.parseToJsonElement(it.toJson())) }
|
||||
put("partial", item.partial.value.toHex())
|
||||
put("proof", item.proof.toHex())
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val VERSION = 1
|
||||
|
||||
private val json = Json
|
||||
|
||||
/** A round: its id commits to the room, the generation and the point (D11). */
|
||||
fun roundId(room: HexKey, generation: Int, point: HexKey): HexKey =
|
||||
Crypto.sha256(room.hexToByteArray() + "$generation".encodeToByteArray() + point.hexToByteArray()).toHex()
|
||||
|
||||
private fun isHex(value: String, length: Int) = value.length == length && value.all { it in "0123456789abcdef" }
|
||||
|
||||
fun decode(text: String): GroupEcdhPayload? = runCatching {
|
||||
val root = json.parseToJsonElement(text) as? JsonObject ?: return null
|
||||
if ((root["v"] as? JsonPrimitive)?.takeIf { !it.isString }?.int != VERSION) return null
|
||||
val generation = (root["generation"] as? JsonPrimitive)?.takeIf { !it.isString }?.int?.takeIf { it >= 0 } ?: return null
|
||||
val from = (root["from"] as? JsonPrimitive)?.takeIf { !it.isString }?.int?.takeIf { it >= 0 } ?: return null
|
||||
val items = (root["items"] as? JsonArray)?.map { element ->
|
||||
val o = element as? JsonObject ?: return null
|
||||
fun string(name: String) = (o[name] as? JsonPrimitive)?.takeIf { it.isString }?.content
|
||||
val point = string("point")?.takeIf { isHex(it, 64) } ?: return null
|
||||
val purpose = string("purpose")?.let(EcdhPurpose::fromWire) ?: return null
|
||||
val ref = string("ref")?.also { if (!isHex(it, 64)) return null }
|
||||
val evidence = o["evidence"]?.let { Event.fromJson(json.encodeToString(JsonElement.serializer(), it)) }
|
||||
val partial = string("partial")?.takeIf { isHex(it, 66) }?.let { PublicKey(it.hexToByteArray()) }
|
||||
?.takeIf { it.isValid() } ?: return null
|
||||
val proof = string("proof")?.let(Dleq.Proof::fromHex) ?: return null
|
||||
// What each purpose names its evidence by, and nothing else.
|
||||
when (purpose) {
|
||||
EcdhPurpose.WRAP, EcdhPurpose.SEAL -> if (ref == null || evidence != null) return null
|
||||
EcdhPurpose.RECIPIENT -> if (ref != null || evidence == null) return null
|
||||
}
|
||||
Item(point, purpose, ref, evidence, partial, proof)
|
||||
} ?: return null
|
||||
if (items.isEmpty()) return null
|
||||
GroupEcdhPayload(generation, from, items).takeIf { it.encode() == text }
|
||||
}.getOrNull()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package mobi.giza.compose.nostr.groupdm
|
||||
|
||||
import com.vitorpamplona.quartz.nip01Core.core.Event
|
||||
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
|
||||
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
|
||||
import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal
|
||||
import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync
|
||||
import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent
|
||||
import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent
|
||||
import fr.acinq.bitcoin.Crypto
|
||||
import fr.acinq.bitcoin.PrivateKey
|
||||
import fr.acinq.bitcoin.PublicKey
|
||||
import fr.acinq.bitcoin.crypto.frost.Frost
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNotNull
|
||||
import kotlin.test.assertNull
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import mobi.giza.compose.cryptography.threshold.Dleq
|
||||
import mobi.giza.compose.cryptography.threshold.EcdhPartial
|
||||
import mobi.giza.compose.cryptography.threshold.NpubTweak
|
||||
import mobi.giza.compose.cryptography.threshold.ThresholdEcdh
|
||||
import mobi.giza.compose.extensions.toHex
|
||||
import mobi.giza.compose.managers.SharedKeyDerivation
|
||||
|
||||
/**
|
||||
* Phase 3 of docs/group-threshold-ecdh.md: the wire, against quartz's stock NIP-17. A message
|
||||
* from a person opens through the admins' shares, and a message from the group opens in a
|
||||
* stock client with the recipient's own key.
|
||||
*/
|
||||
class GroupDmWireTest {
|
||||
private val x = PrivateKey(Crypto.sha256("group-dm-wire".encodeToByteArray()))
|
||||
private val keys = Frost.trustedDealerKeygen(x, 5, 3)
|
||||
private val tweak = NpubTweak.of(keys.thresholdPublicKey)
|
||||
private val group = SharedKeyDerivation.derive(keys.thresholdPublicKey.value.toByteArray().toHex()).hex
|
||||
|
||||
/** The npub's secret, whole: only to stand in for a FROST signature in a test. */
|
||||
private val d: PrivateKey = run {
|
||||
var q = keys.thresholdPublicKey
|
||||
var negate = false
|
||||
var b: PrivateKey? = null
|
||||
SharedKeyDerivation.derive(keys.thresholdPublicKey.value.toByteArray().toHex()).tweaks.forEach { s ->
|
||||
val tau = PrivateKey(s)
|
||||
if (q.isOdd()) { q = -q; negate = !negate; b = b?.let { -it } }
|
||||
q += tau.publicKey(); b = b?.let { it + tau } ?: tau
|
||||
}
|
||||
(if (negate) -x else x) + b!!
|
||||
}
|
||||
|
||||
/** What three admins' devices would agree on, without any of them holding `d`. */
|
||||
private fun thresholdKey(point: String, ids: List<Int> = listOf(0, 2, 4)): ByteArray {
|
||||
val p = ThresholdEcdh.pointOf(point)!!
|
||||
val partials = ids.associateWith { EcdhPartial.compute(keys.secretShares[it], p) }
|
||||
return ThresholdEcdh.conversationKey(ThresholdEcdh.combine(partials, tweak, p))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a message from a person, wrapped by quartz, opens through the admins' shares`() = runBlocking {
|
||||
val sender = KeyPair()
|
||||
val signer = NostrSignerInternal(sender)
|
||||
val rumor = Event(
|
||||
id = "", pubKey = sender.pubKey.toHexKey(), createdAt = 1_700_000_000, kind = 14,
|
||||
tags = arrayOf(arrayOf("p", group)), content = "dumela", sig = "",
|
||||
)
|
||||
val seal = SealEvent.create(rumor, group, signer)
|
||||
val wrap = GiftWrapEvent.create(seal, group)
|
||||
|
||||
val openedSeal = assertNotNull(GroupDmWrap.open(wrap, thresholdKey(wrap.pubKey)))
|
||||
assertEquals(sender.pubKey.toHexKey(), openedSeal.pubKey)
|
||||
val opened = assertNotNull(GroupDmSeal.open(openedSeal, thresholdKey(openedSeal.pubKey, listOf(1, 2, 3))))
|
||||
assertEquals("dumela", opened.content)
|
||||
assertEquals(sender.pubKey.toHexKey(), opened.pubKey)
|
||||
assertEquals(listOf(sender.pubKey.toHexKey()), GroupDmConversation.participantsOf(opened, group))
|
||||
// The wrong key opens neither.
|
||||
assertNull(GroupDmWrap.open(wrap, thresholdKey(openedSeal.pubKey)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a message from the group opens in quartz's stock unwrap with the recipient's own key`() = runBlocking {
|
||||
val recipient = KeyPair()
|
||||
val r = recipient.pubKey.toHexKey()
|
||||
val rumor = GroupDmSeal.rumor(group, 1_700_000_000, 14, arrayOf(arrayOf("p", r)), "the group says hello")
|
||||
val template = GroupDmSeal.build(rumor, thresholdKey(r), createdAt = 1_699_990_000)
|
||||
// FROST's signature stands in as a signature by d.
|
||||
val signedSeal = NostrSignerSync(KeyPair(privKey = d.value.toByteArray()))
|
||||
.sign<Event>(template.createdAt, template.kind, template.tags, template.content)
|
||||
assertEquals(group, signedSeal.pubKey)
|
||||
val wrap = GiftWrapEvent.create(signedSeal, r)
|
||||
|
||||
val opened = assertNotNull(wrap.unwrapAndUnsealOrNull(NostrSignerInternal(recipient)))
|
||||
assertEquals("the group says hello", opened.content)
|
||||
assertEquals(group, opened.pubKey)
|
||||
assertEquals(rumor.id, opened.id)
|
||||
}
|
||||
|
||||
// --- D5
|
||||
|
||||
private fun signedBy(keyPair: KeyPair, kind: Int, tags: Array<Array<String>> = emptyArray()): Event =
|
||||
NostrSignerSync(keyPair).sign(1_700_000_000, kind, tags, "x")
|
||||
|
||||
@Test
|
||||
fun `evidence is refused unless the point signed something of the right shape`() = runBlocking {
|
||||
val person = KeyPair()
|
||||
val p = person.pubKey.toHexKey()
|
||||
val toGroup = GiftWrapEvent.create(signedBy(person, 13), group)
|
||||
assertNull(Evidence.check(EcdhPurpose.WRAP, toGroup.pubKey, toGroup, group))
|
||||
|
||||
val toSomeoneElse = GiftWrapEvent.create(signedBy(person, 13), p)
|
||||
assertEquals(Evidence.Refusal.NOT_TO_GROUP, Evidence.check(EcdhPurpose.WRAP, toSomeoneElse.pubKey, toSomeoneElse, group))
|
||||
|
||||
val seal = signedBy(person, 13)
|
||||
assertNull(Evidence.check(EcdhPurpose.SEAL, p, seal, group))
|
||||
val unsigned = Event(seal.id, seal.pubKey, seal.createdAt, seal.kind, seal.tags, seal.content, "")
|
||||
assertEquals(Evidence.Refusal.BAD_SIGNATURE, Evidence.check(EcdhPurpose.SEAL, p, unsigned, group))
|
||||
assertEquals(Evidence.Refusal.WRONG_KIND, Evidence.check(EcdhPurpose.SEAL, p, signedBy(person, 1), group))
|
||||
|
||||
assertNull(Evidence.check(EcdhPurpose.RECIPIENT, p, signedBy(person, 0), group))
|
||||
assertEquals(Evidence.Refusal.WRONG_KEY, Evidence.check(EcdhPurpose.RECIPIENT, p, signedBy(KeyPair(), 0), group))
|
||||
val groupSigned = NostrSignerSync(KeyPair(privKey = d.value.toByteArray())).sign<Event>(1_700_000_000, 0, emptyArray(), "{}")
|
||||
assertEquals(Evidence.Refusal.THE_GROUP_ITSELF, Evidence.check(EcdhPurpose.RECIPIENT, group, groupSigned, group))
|
||||
}
|
||||
|
||||
// --- the payload, the manifest and the admin seal
|
||||
|
||||
private val hostA = PrivateKey(Crypto.sha256("host-a".encodeToByteArray()))
|
||||
private val hostB = PrivateKey(Crypto.sha256("host-b".encodeToByteArray()))
|
||||
private val hostC = PrivateKey(Crypto.sha256("host-c".encodeToByteArray()))
|
||||
private fun hex(k: PrivateKey) = k.publicKey().value.toHex()
|
||||
|
||||
@Test
|
||||
fun `an admin seal opens for the admins it was sealed to and nobody else`() {
|
||||
val sealed = AdminSeal.seal("partials", hostA, listOf(hex(hostA), hex(hostB)))
|
||||
assertEquals("partials", AdminSeal.open(sealed, hostB, hex(hostB), hex(hostA)))
|
||||
assertEquals("partials", AdminSeal.open(sealed, hostA, hex(hostA), hex(hostA)))
|
||||
assertNull(AdminSeal.open(sealed, hostC, hex(hostC), hex(hostA)), "no slot")
|
||||
assertNull(AdminSeal.open(sealed, hostB, hex(hostB), hex(hostC)), "another sender")
|
||||
val roundTrip = AdminSeal.Sealed(sealed.content, AdminSeal.parseSlots(GroupEcdhEvents.partialsTags(sealed)))
|
||||
assertEquals("partials", AdminSeal.open(roundTrip, hostB, hex(hostB), hex(hostA)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a payload round-trips, and only its own encoding decodes`() {
|
||||
val w = KeyPair().pubKey.toHexKey()
|
||||
val p = ThresholdEcdh.pointOf(w)!!
|
||||
val partial = EcdhPartial.compute(keys.secretShares[0], p)
|
||||
val proof = Dleq.prove(keys.secretShares[0], keys.publicShares[0], p, partial, Dleq.context(group, 0, 0), ByteArray(32))
|
||||
val evidence = signedBy(KeyPair(), 0)
|
||||
val payload = GroupEcdhPayload(
|
||||
generation = 0, from = 0,
|
||||
items = listOf(
|
||||
GroupEcdhPayload.Item(w, EcdhPurpose.WRAP, ref = "a".repeat(64), partial = partial, proof = proof),
|
||||
GroupEcdhPayload.Item(evidence.pubKey, EcdhPurpose.RECIPIENT, evidence = evidence, partial = partial, proof = proof),
|
||||
),
|
||||
)
|
||||
val text = payload.encode()
|
||||
val decoded = assertNotNull(GroupEcdhPayload.decode(text))
|
||||
assertEquals(text, decoded.encode())
|
||||
assertEquals(evidence.id, decoded.items[1].evidence?.id)
|
||||
assertNull(GroupEcdhPayload.decode(text.replace("\"v\":1", "\"v\": 1")), "another spelling")
|
||||
assertNull(GroupEcdhPayload.decode(text.replace("\"purpose\":\"wrap\"", "\"purpose\":\"recipient\"")), "a recipient with a ref")
|
||||
assertNull(GroupEcdhPayload.decode("""{"v":1,"generation":0,"from":0,"items":[]}"""), "nothing in it")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a manifest round-trips, and only its own encoding decodes`() {
|
||||
val evidence = signedBy(KeyPair(), 0)
|
||||
val manifest = GroupDmManifest(listOf(GroupDmManifest.Seal(evidence.pubKey, evidence)), replyingTo = null)
|
||||
val text = manifest.encode()
|
||||
assertEquals(text, GroupDmManifest.decode(text)?.encode())
|
||||
assertNull(GroupDmManifest.decode(text.replace("null", "\"zz\"")))
|
||||
val reply = GroupDmManifest(manifest.seals, replyingTo = "b".repeat(64))
|
||||
assertEquals("b".repeat(64), GroupDmManifest.decode(reply.encode())?.replyingTo)
|
||||
|
||||
val sealed = AdminSeal.seal(text, hostA, listOf(hex(hostB)))
|
||||
val tags = manifest.toTags(sealed)
|
||||
val carried = assertNotNull(GroupDmManifest.sealedIn(tags))
|
||||
assertEquals(text, AdminSeal.open(carried, hostB, hex(hostB), hex(hostA)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a conversation is its correspondents, in any order, without the group`() {
|
||||
val a = "a".repeat(64); val b = "b".repeat(64)
|
||||
val one = GroupDmSeal.rumor(a, 1, 14, arrayOf(arrayOf("p", group), arrayOf("p", b)), "hi")
|
||||
val two = GroupDmSeal.rumor(b, 2, 14, arrayOf(arrayOf("p", a), arrayOf("p", group)), "hi")
|
||||
assertEquals(GroupDmConversation.idOf(one, group), GroupDmConversation.idOf(two, group))
|
||||
assertEquals(listOf(a, b), GroupDmConversation.participantsOf(one, group))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user