test: threshold ECDH's six premises, against the real libraries (group-threshold-ecdh, Phase 0)
The combined point gives quartz's own NIP-44 conversation key for every 3-subset of a dealer key. Check 6 changed the wire: a payload encrypted once under a key sealed per admin, with wraps and seals carried by reference. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
dae0a345d2
commit
0d33923877
2 files changed
+236
-11
No files matched your search
@@ -0,0 +1,205 @@
|
||||
package mobi.giza.compose
|
||||
|
||||
import com.vitorpamplona.crypto.kdf.Hkdf
|
||||
import com.vitorpamplona.quartz.nip44Encryption.Nip44v2
|
||||
import fr.acinq.bitcoin.ByteVector32
|
||||
import fr.acinq.bitcoin.Crypto
|
||||
import fr.acinq.bitcoin.PrivateKey
|
||||
import fr.acinq.bitcoin.PublicKey
|
||||
import fr.acinq.bitcoin.crypto.frost.Frost
|
||||
import fr.acinq.bitcoin.crypto.frost.KeyMaterial
|
||||
import mobi.giza.compose.extensions.toHex
|
||||
import mobi.giza.compose.managers.SharedKeyDerivation
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFalse
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
/**
|
||||
* Phase 0 of docs/group-threshold-ecdh.md: the six facts the plan rests on, checked against
|
||||
* the real libraries before anything is built over them.
|
||||
*
|
||||
* This is the one file allowed to build the group's secret whole. Every key in it is a
|
||||
* throwaway made by `Frost.trustedDealerKeygen` for the test, and building `x` and `d` is the
|
||||
* only way to show that the threshold arithmetic lands where single-key NIP-44 does. The app's
|
||||
* own code never does (shared-key-derivation.md's rule), and Phase 2's test enforces that.
|
||||
*/
|
||||
class ThresholdEcdhPremiseJvmTest {
|
||||
private val one = scalar(1)
|
||||
|
||||
private fun scalar(v: Int): PrivateKey = PrivateKey(ByteArray(32).also {
|
||||
it[28] = (v ushr 24).toByte(); it[29] = (v ushr 16).toByte(); it[30] = (v ushr 8).toByte(); it[31] = v.toByte()
|
||||
})
|
||||
|
||||
/** `n − 2`, the exponent of Fermat's inverse in the group of order `n`. */
|
||||
private val nMinus2 = "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd036413f"
|
||||
|
||||
private fun inverse(v: PrivateKey): PrivateKey {
|
||||
var result = one
|
||||
nMinus2.chunked(2).map { it.toInt(16) }.forEach { byte ->
|
||||
for (bit in 7 downTo 0) {
|
||||
result = result * result
|
||||
if ((byte ushr bit) and 1 == 1) result = result * v
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/** λᵢ at zero over the evaluation points [xs], each a holder's id plus one (check 1). */
|
||||
private fun lagrange(xi: Int, xs: List<Int>): PrivateKey =
|
||||
xs.filter { it != xi }.fold(one) { acc, xj -> acc * scalar(xj) * inverse(scalar(xj) - scalar(xi)) }
|
||||
|
||||
private fun dealer(seed: Int, n: Int = 5, t: Int = 3): Pair<PrivateKey, KeyMaterial> {
|
||||
val secret = PrivateKey(Crypto.sha256("threshold-ecdh-premise/$seed".encodeToByteArray()))
|
||||
return secret to Frost.trustedDealerKeygen(secret, n, t)
|
||||
}
|
||||
|
||||
private fun subsets(ids: List<Int>, t: Int): List<List<Int>> =
|
||||
if (t == 0) listOf(emptyList()) else if (ids.size < t) emptyList()
|
||||
else subsets(ids.drop(1), t - 1).map { listOf(ids.first()) + it } + subsets(ids.drop(1), t)
|
||||
|
||||
/** D2, replayed: `(a, b)` with `d = a·x + b`, and the point the replay reaches. */
|
||||
private data class Replay(val aNegative: Boolean, val b: PrivateKey?, val q: PublicKey, val parities: List<Boolean>)
|
||||
|
||||
private fun replay(x: PublicKey, tweaks: List<ByteVector32>): Replay {
|
||||
var aNegative = false
|
||||
var b: PrivateKey? = null
|
||||
var q = x
|
||||
val parities = mutableListOf<Boolean>()
|
||||
tweaks.forEach { tau ->
|
||||
val even = q.isEven()
|
||||
parities += even
|
||||
val t = PrivateKey(tau)
|
||||
if (!even) {
|
||||
q = -q
|
||||
aNegative = !aNegative
|
||||
b = b?.let { -it }
|
||||
}
|
||||
q += t.publicKey()
|
||||
b = b?.let { it + t } ?: t
|
||||
}
|
||||
return Replay(aNegative, b, q, parities)
|
||||
}
|
||||
|
||||
private fun conversationKey(point: PublicKey): ByteArray =
|
||||
Hkdf().extract(point.value.toByteArray().copyOfRange(1, 33), "nip44-v2".encodeToByteArray())
|
||||
|
||||
@Test
|
||||
fun `check 1 - the Shamir evaluation point is the id plus one`() {
|
||||
val (secret, keys) = dealer(1)
|
||||
subsets((0 until 5).toList(), 3).forEach { ids ->
|
||||
val xs = ids.map { it + 1 }
|
||||
val rebuilt = ids.map { id -> keys.secretShares[id] * lagrange(id + 1, xs) }.reduce { a, b -> a + b }
|
||||
assertEquals(keys.thresholdPublicKey, rebuilt.publicKey(), "subset $ids")
|
||||
assertEquals(secret.publicKey(), rebuilt.publicKey())
|
||||
}
|
||||
// The id itself, unshifted, does not reconstruct: the convention is not a no-op.
|
||||
val wrong = listOf(0, 1, 2).map { id -> keys.secretShares[id] * lagrange(id + 1, listOf(1, 2, 3).map { it + 1 }) }
|
||||
.reduce { a, b -> a + b }
|
||||
assertTrue(wrong.publicKey() != keys.thresholdPublicKey)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `check 2 - replaying the tweaks with their signs reaches the npub, in every parity case`() {
|
||||
val seen = mutableSetOf<Pair<Int, Boolean>>()
|
||||
(1..40).forEach { seed ->
|
||||
val (secret, keys) = dealer(seed)
|
||||
val derived = SharedKeyDerivation.derive(keys.thresholdPublicKey.value.toByteArray().toHex())
|
||||
val r = replay(keys.thresholdPublicKey, derived.tweaks)
|
||||
assertEquals(derived.publicKey, r.q.xOnly(), "seed $seed")
|
||||
// And the scalar side: d = a·x + b has the npub as its public key.
|
||||
val d = (if (r.aNegative) -secret else secret) + r.b!!
|
||||
assertEquals(derived.publicKey, d.publicKey().xOnly(), "seed $seed")
|
||||
r.parities.forEachIndexed { step, even -> seen += step to even }
|
||||
}
|
||||
assertEquals(6, seen.size, "every step met both parities somewhere in the seeds: $seen")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `check 3 - the combined point gives quartz's own conversation key`() {
|
||||
(1..12).forEach { seed ->
|
||||
val (secret, keys) = dealer(seed)
|
||||
val derived = SharedKeyDerivation.derive(keys.thresholdPublicKey.value.toByteArray().toHex())
|
||||
val r = replay(keys.thresholdPublicKey, derived.tweaks)
|
||||
val d = (if (r.aNegative) -secret else secret) + r.b!!
|
||||
|
||||
val other = PrivateKey(Crypto.sha256("peer/$seed".encodeToByteArray()))
|
||||
val p = other.publicKey()
|
||||
val expected = Nip44v2().computeConversationKey(d.value.toByteArray(), p.xOnly().value.toByteArray())
|
||||
// And from the other side, as a sender's app would compute it.
|
||||
val fromPeer = Nip44v2().computeConversationKey(other.value.toByteArray(), derived.publicKey.value.toByteArray())
|
||||
assertEquals(expected.toHex(), fromPeer.toHex())
|
||||
|
||||
subsets((0 until 5).toList(), 3).forEach { ids ->
|
||||
val xs = ids.map { it + 1 }
|
||||
val xP = ids.map { id -> (p * keys.secretShares[id]) * lagrange(id + 1, xs) }.reduce { a, b -> a + b }
|
||||
val dP = (if (r.aNegative) -xP else xP) + p * r.b!!
|
||||
assertEquals(expected.toHex(), conversationKey(dP).toHex(), "seed $seed, subset $ids")
|
||||
// Either lift of P gives the same x-coordinate.
|
||||
val xPNeg = ids.map { id -> ((-p) * keys.secretShares[id]) * lagrange(id + 1, xs) }.reduce { a, b -> a + b }
|
||||
val dPNeg = (if (r.aNegative) -xPNeg else xPNeg) + (-p) * r.b!!
|
||||
assertEquals(expected.toHex(), conversationKey(dPNeg).toHex())
|
||||
}
|
||||
// The sign inside the sum matters: the wrong a gives a different key.
|
||||
val xP = listOf(0, 1, 2).map { id -> (p * keys.secretShares[id]) * lagrange(id + 1, listOf(1, 2, 3)) }.reduce { a, b -> a + b }
|
||||
val wrongSign = (if (r.aNegative) xP else -xP) + p * r.b!!
|
||||
assertFalse(expected.contentEquals(conversationKey(wrongSign)))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `check 4 - scalars reduce mod n, the inverse is Fermat's, and the constructor does not range-check`() {
|
||||
val nMinus1 = -one
|
||||
assertEquals(one, nMinus1 * nMinus1)
|
||||
(2..40).forEach { assertEquals(one, scalar(it) * inverse(scalar(it))) }
|
||||
assertEquals(scalar(5), scalar(2) + scalar(3))
|
||||
// A hash at or above n is NOT rejected by the constructor; isValid() is the check D3 needs.
|
||||
val n = PrivateKey(ByteVector32("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"))
|
||||
assertFalse(n.isValid())
|
||||
assertFalse(PrivateKey(ByteVector32("ff".repeat(32))).isValid())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `check 6 - a batch of partials fits a relay's event when the payload is encrypted once`() {
|
||||
val nip44 = Nip44v2()
|
||||
val key = ByteArray(32) { 7 }
|
||||
// A wrap of a 1,000-character message, as evidence: rumor, seal and wrap layers.
|
||||
val rumor = """{"kind":14,"content":"${"x".repeat(1000)}","tags":[["p","${"a".repeat(64)}"]],"pubkey":"${"b".repeat(64)}","created_at":1700000000,"id":"${"c".repeat(64)}"}"""
|
||||
val seal = """{"kind":13,"content":"${nip44.encrypt(rumor, key).encodePayload()}","tags":[],"pubkey":"${"b".repeat(64)}","created_at":1700000000,"id":"${"c".repeat(64)}","sig":"${"d".repeat(128)}"}"""
|
||||
val wrap = """{"kind":1059,"content":"${nip44.encrypt(seal, key).encodePayload()}","tags":[["p","${"a".repeat(64)}"]],"pubkey":"${"b".repeat(64)}","created_at":1700000000,"id":"${"c".repeat(64)}","sig":"${"d".repeat(128)}"}"""
|
||||
val item = """{"point":"${"02" + "e".repeat(64)}","purpose":"wrap","evidence":$wrap,"partial":"${"02" + "f".repeat(64)}","proof":"${"1".repeat(128)}"}"""
|
||||
val bare = """{"point":"${"02" + "e".repeat(64)}","purpose":"wrap","partial":"${"02" + "f".repeat(64)}","proof":"${"1".repeat(128)}"}"""
|
||||
|
||||
fun sealedPerAdmin(items: List<String>, admins: Int): Int {
|
||||
val payload = """{"v":1,"generation":1,"from":0,"items":[${items.joinToString(",")}]}"""
|
||||
return admins * nip44.encrypt(payload, key).encodePayload().length
|
||||
}
|
||||
|
||||
fun sealedOnce(items: List<String>, admins: Int): Int {
|
||||
val payload = """{"v":1,"generation":1,"from":0,"items":[${items.joinToString(",")}]}"""
|
||||
return nip44.encrypt(payload, key).encodePayload().length + admins * nip44.encrypt("f".repeat(64), key).encodePayload().length
|
||||
}
|
||||
|
||||
println("wrap as evidence: ${wrap.length} bytes")
|
||||
println("20 items with evidence, 7 admins, per admin: ${sealedPerAdmin(List(20) { item }, 7)}")
|
||||
println("20 items with evidence, 7 admins, once: ${sealedOnce(List(20) { item }, 7)}")
|
||||
println("20 bare items, 7 admins, once: ${sealedOnce(List(20) { bare }, 7)}")
|
||||
// The plan as first written -- each payload sealed per admin, the wrap carried as
|
||||
// evidence -- is fourteen times a relay's 64 KB at this size.
|
||||
assertTrue(sealedPerAdmin(List(20) { item }, 7) > 65_536)
|
||||
// Carried once, evidence still outgrows a relay's event: NIP-44 pads to the next
|
||||
// power of two, and one wrap of a long message is most of 64 KB on its own.
|
||||
assertTrue(sealedOnce(List(20) { item }, 7) > 65_536)
|
||||
// So the payload is encrypted once under a key sealed per admin, and a wrap or a seal
|
||||
// travels by reference (every admin's device subscribes to the same wraps, and opens
|
||||
// the same seals). Twenty bare items for seven admins fit in 16 KB.
|
||||
assertTrue(sealedOnce(List(20) { bare }, 7) < 16_384)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `check 5 - kinds 30400 and 30401 are free here`() {
|
||||
val retired = mobi.giza.compose.nostr.RetiredKinds.WALLET + mobi.giza.compose.nostr.RetiredKinds.GROUP_LIGHTNING
|
||||
assertFalse(30400 in retired)
|
||||
assertFalse(30401 in retired)
|
||||
}
|
||||
}
|
||||
@@ -36,7 +36,7 @@ by its own ceremony and held whole by every admin (`group-inbox.md`, written alo
|
||||
one and not merged). *Against the NIP-4E plan* below says where the two differ, and how
|
||||
they fit together if both are built.
|
||||
|
||||
**Planned, not built.** Written against `5ac4c053`, on 2026-11-22. Paths starting `K/` are
|
||||
**Being built.** Phase 0 is done, and its findings changed D4 and D11. Written against `5ac4c053`, on 2026-11-22. Paths starting `K/` are
|
||||
under `composeApp/src/commonMain/kotlin/mobi/giza/compose/`, and `B/` is bitcoin-kmp's
|
||||
`src/commonMain/kotlin/fr/acinq/bitcoin/`, under
|
||||
`lightning-kmp-app/experimental/lightning-kmp/experimental/bitcoin-kmp/`.
|
||||
@@ -209,7 +209,9 @@ verify: R₁ = z·G − c·Yᵢ, R₂ = z·P − c·Dᵢ, and c recomputes
|
||||
`aux` is 32 fresh random bytes, so a fault in one run cannot repeat a nonce across two.
|
||||
The challenge binds the room, the generation and the id, so a proof cannot be replayed into
|
||||
another round. A hash that lands at or above `n` fails the proof rather than being reduced,
|
||||
which happens with probability about 2⁻¹²⁸. The tags are hash inputs, spelled `mantra/` as
|
||||
which happens with probability about 2⁻¹²⁸. bitcoin-kmp's `PrivateKey` constructor does not
|
||||
range-check (Phase 0, check 4), so the proof calls `isValid()` on every hash it reads as a
|
||||
scalar. The tags are hash inputs, spelled `mantra/` as
|
||||
every protocol tag is ([giza-rebrand.md](./giza-rebrand.md)).
|
||||
|
||||
A partial whose proof fails is dropped, its sender is named in the inbox's diagnostics
|
||||
@@ -223,7 +225,9 @@ do not.
|
||||
Partials travel as MLS inner events in the group's Marmot room, the room its key lives in,
|
||||
which every member receives. A member who is not an admin must not be able to combine
|
||||
them, so each partial message's payload is NIP-44-encrypted once per current admin, to that
|
||||
admin's host key from the roster (the share-repair channel).
|
||||
admin's host key from the roster (the share-repair channel). Phase 0 (check 6) changed how:
|
||||
the payload is NIP-44-encrypted **once**, under a fresh 32-byte key, and only that key is
|
||||
sealed per admin. Sealing the whole payload per admin multiplied it by the number of admins.
|
||||
|
||||
**Current admin** means `RoomAdmins.of(room)` intersected with the holders of the active
|
||||
generation. A device sends its partials only if its own member is in that set, and seals
|
||||
@@ -315,8 +319,10 @@ admin's own DM list. So the group's mail has its own path, and writes no `GiftWr
|
||||
2. **Ledger.** Every wrap goes into `GroupDmWrap`, keyed by id, with its state. Redelivery
|
||||
is a no-op.
|
||||
3. **Wrap round.** For a new wrap, the device opens a round for `W` (D11) and sends its own
|
||||
partial at once. The first partial message for a round carries the wrap itself, so an
|
||||
admin whose relays missed it can check the evidence and answer too.
|
||||
partial at once. The partial names the wrap by its id rather than carrying it (Phase 0,
|
||||
check 6): every admin's device subscribes to the same wraps, and one wrap of a long
|
||||
message is most of a relay's event on its own. A device that has not seen the wrap yet
|
||||
holds the partial and answers when the wrap arrives.
|
||||
4. **Open the wrap.** At `t` valid partials: `d·W`, the conversation key, the seal. Verify
|
||||
the seal's signature.
|
||||
5. **Seal round.** If `conv(group, S)` is kept, use it. Otherwise open a round for `S`,
|
||||
@@ -367,11 +373,13 @@ through the room, and that is where the group's sent messages are read from (D12
|
||||
|
||||
A round is `(room, generation, P)`. Its id is a hash of those three, so two devices that
|
||||
open a round for the same wrap open the same round. A partial message carries, per item,
|
||||
the round's point, the purpose, the evidence when the sender is the first to carry it, `Dᵢ`
|
||||
and the proof. Each device:
|
||||
the round's point, the purpose, the evidence's reference, `Dᵢ` and the proof. A wrap and a
|
||||
seal are referenced by the wrap's id: every admin's device holds the wrap, and opens the
|
||||
same seal from it. Only a recipient's evidence (D10) is carried, since it is a small event
|
||||
no other device need have. Each device:
|
||||
|
||||
- **batches**: every point it owes a partial for goes into one message per sync pass, not
|
||||
one message per point;
|
||||
one message per point, up to 16,000 bytes of plaintext (about thirty items) per message;
|
||||
- **answers** a round it has evidence for and has not answered, once (keyed by round and
|
||||
participant id, as `DkgParticipantMessage` absorbs redelivery);
|
||||
- **combines** as soon as it holds `t` verified partials of the same generation;
|
||||
@@ -499,7 +507,20 @@ One commit per phase, in the repository's style
|
||||
`./gradlew :composeApp:jvmTest` and `:composeApp:m3Audit` green, and `check`'s brand and
|
||||
wallet audits at budget.
|
||||
|
||||
### Phase 0: this document, and six checks
|
||||
### Phase 0: this document, and six checks (done)
|
||||
|
||||
`ThresholdEcdhPremiseJvmTest` keeps all six. What they found:
|
||||
|
||||
| check | result |
|
||||
|---|---|
|
||||
| 1. ids | the evaluation point is the id plus one, as BIP 445 says; every 3-subset of a 3-of-5 dealer key rebuilds `x`, and the unshifted ids do not |
|
||||
| 2. tweaks | D2's replay reaches `Derived.publicKey` for forty dealer seeds, which between them meet both parities at all three steps |
|
||||
| 3. the conversation key | **holds.** Every 3-subset, either lift of `P`, gives quartz's `computeConversationKey(d, P)`, which equals the sender's side; the wrong sign of `a` gives another key |
|
||||
| 4. scalars | `times` and `plus` reduce mod `n`; Fermat's inverse works; **the `PrivateKey` constructor does not range-check**, so D3 calls `isValid()` |
|
||||
| 5. kinds | 30400 and 30401 are free in the NIP README, quartz, Bennu's tree, this one and `RetiredKinds` (30402 and 30403 are NIP-99's) |
|
||||
| 6. size | **D4 and D11 changed.** Sealing each payload per admin with the wrap as evidence was 918 KB for 20 items and 7 admins. The payload is now encrypted once under a key sealed per admin, and wraps and seals travel by reference: 20 items for 7 admins is 10.9 KB |
|
||||
|
||||
The original text of the checks:
|
||||
|
||||
This document and its row in [README.md](./README.md). Then, before code, as scratch
|
||||
jvmTests against bitcoin-kmp's `Frost.trustedDealerKeygen` (`B/crypto/frost/Frost.kt:313`),
|
||||
@@ -657,8 +678,7 @@ messages.
|
||||
- `DirectMessagePeerSync` fetches the 10050 and kind 0 of each correspondent, for D10's
|
||||
relays, D5's evidence, and names on the screen.
|
||||
- **Rate.** Anyone can make the group's admins do work by sending wraps. The receiver opens
|
||||
at most a fixed number of new wrap rounds per room per hour (Phase 0 sets it from the
|
||||
batch size). Beyond that, wraps wait in the ledger, newest first, and the inbox says some
|
||||
at most 60 new wrap rounds per room per hour, two batches' worth at Phase 0's size. Beyond that, wraps wait in the ledger, newest first, and the inbox says some
|
||||
are queued. The group's 10050 relays are its first line here, which the setup screen says.
|
||||
- Tests (`GroupDmReceiveJvmTest`):
|
||||
- a message from an outside identity, wrapped by quartz's stock code, opens on all three
|
||||
|
||||
Reference in new issue
Block a user