diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/Dleq.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/Dleq.kt new file mode 100644 index 00000000..06073202 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/Dleq.kt @@ -0,0 +1,96 @@ +package mobi.giza.compose.cryptography.threshold + +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.PublicKey +import mobi.giza.compose.extensions.toHex + +/** + * A Chaum-Pedersen proof that `log_G(Yᵢ) = log_P(Dᵢ)`: that a partial was made with the share + * whose public half the group already knows (D3 of docs/group-threshold-ecdh.md). + * + * Without it a wrong partial would make the combined point wrong, NIP-44's MAC would catch + * that, and nobody could say whose partial it was. With it, a bad partial is dropped and its + * sender named. + * + * ``` + * k = H_nonce(s || P || D || aux) mod n R₁ = k·G, R₂ = k·P + * c = H(context || Y || P || D || R₁ || R₂) z = k + c·s + * verify: R₁ = z·G − c·Y, R₂ = z·P − c·D, and c recomputes + * ``` + * + * The one piece of cryptography the plan writes by hand. Every operation on `s` or `k` is a + * libsecp256k1 call. A hash at or above `n` is refused rather than reduced: bitcoin-kmp's + * `PrivateKey` does not range-check (Phase 0, check 4), so [scalarOrNull] does. + */ +object Dleq { + /** + * Hash inputs, and so protocol rather than brand: `mantra/` as every tag is + * (docs/giza-rebrand.md). Renaming one makes every proof from a peer fail. + */ + private const val NONCE_TAG = "mantra/threshold-ecdh/dleq-nonce/v1" + private const val CHALLENGE_TAG = "mantra/threshold-ecdh/dleq/v1" + + data class Proof(val c: ByteVector32, val z: ByteVector32) { + fun toHex(): String = c.toHex() + z.toHex() + + companion object { + fun fromHex(hex: String): Proof? { + if (hex.length != 128 || hex.any { it !in "0123456789abcdef" }) return null + return Proof(ByteVector32(hex.take(64)), ByteVector32(hex.drop(64))) + } + } + } + + /** + * What a proof is bound to, so it cannot be replayed into another round: the room, the + * share generation and the participant id. + */ + fun context(room: String, generation: Int, id: Int): ByteArray = + room.encodeToByteArray() + int(generation) + int(id) + + private fun int(v: Int) = byteArrayOf((v ushr 24).toByte(), (v ushr 16).toByte(), (v ushr 8).toByte(), v.toByte()) + + private fun scalarOrNull(hash: ByteVector32): PrivateKey? = PrivateKey(hash).takeIf { it.isValid() } + + private fun challenge(context: ByteArray, y: PublicKey, p: PublicKey, d: PublicKey, r1: PublicKey, r2: PublicKey): ByteVector32 = + Crypto.taggedHash( + context + y.value.toByteArray() + p.value.toByteArray() + d.value.toByteArray() + + r1.value.toByteArray() + r2.value.toByteArray(), + CHALLENGE_TAG, + ) + + /** + * @param aux 32 fresh random bytes, so a fault in one run cannot repeat a nonce in another. + * @throws IllegalStateException in the ~2⁻¹²⁸ case a hash is not a scalar; try other [aux]. + */ + fun prove(share: PrivateKey, y: PublicKey, p: PublicKey, d: PublicKey, context: ByteArray, aux: ByteArray): Proof { + require(aux.size == 32) { "aux is 32 bytes" } + val k = scalarOrNull( + Crypto.taggedHash(share.value.toByteArray() + p.value.toByteArray() + d.value.toByteArray() + aux, NONCE_TAG) + ) ?: error("The nonce hash was not a scalar") + val r1 = k.publicKey() + val r2 = p * k + val cHash = challenge(context, y, p, d, r1, r2) + val c = scalarOrNull(cHash) ?: error("The challenge hash was not a scalar") + val z = k + c * share + return Proof(cHash, z.value) + } + + fun verify(y: PublicKey, p: PublicKey, d: PublicKey, context: ByteArray, proof: Proof): Boolean = try { + val c = scalarOrNull(proof.c) + val z = scalarOrNull(proof.z) + if (c == null || z == null || !y.isValid() || !p.isValid() || !d.isValid()) { + false + } else { + // Either sum may be the point at infinity, which libsecp256k1 refuses to + // serialise: no valid proof gives one, so the throw is a failure. + val r1 = z.publicKey() - y * c + val r2 = p * z - d * c + challenge(context, y, p, d, r1, r2) == proof.c + } + } catch (_: Throwable) { + false + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/EcdhPartial.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/EcdhPartial.kt new file mode 100644 index 00000000..180ceb23 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/EcdhPartial.kt @@ -0,0 +1,22 @@ +package mobi.giza.compose.cryptography.threshold + +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.PublicKey + +/** + * One holder's part of `x·P`: `Dᵢ = sᵢ·P`. + * + * A Diffie-Hellman value, so it says nothing about `sᵢ`, and fewer than `t` of them say + * nothing about `x·P`. The one scalar multiplication by a share in the whole scheme, and it + * is libsecp256k1's. + * + * [point] has to be a key whose owner the caller has seen sign something (D5): a point + * nobody can sign for may be `x^k·G`, and answering those is how a Diffie-Hellman oracle is + * worn down. This function cannot check that; `Evidence` does, before it is called. + */ +object EcdhPartial { + fun compute(share: PrivateKey, point: PublicKey): PublicKey { + require(point.isValid()) { "Not a point on the curve" } + return point * share + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/Lagrange.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/Lagrange.kt new file mode 100644 index 00000000..209018e9 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/Lagrange.kt @@ -0,0 +1,48 @@ +package mobi.giza.compose.cryptography.threshold + +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.PublicKey + +/** + * Lagrange coefficients at zero, over FROST participant ids. + * + * A participant id is 0-based, as `KeyMaterial.publicSharesOf` and [mobi.giza.compose.managers.ShareGenerations] + * index it; the point its share was evaluated at is the id plus one, as BIP 445 says + * (docs/group-threshold-ecdh.md, Phase 0, check 1). + */ +object Lagrange { + /** + * A coefficient that can only scale a point. + * + * `Σ λᵢ·sᵢ` over shares is the group's secret, and building it is the thing + * shared-key-derivation.md forbids. So the scalar stays private, and the only thing a + * coefficient does is multiply a public point: `λᵢ·Dᵢ`, never `λᵢ·sᵢ`. The compiler + * keeps it that way, and `ThresholdEcdhJvmTest` reads this package's sources for the + * rest. + */ + class Coefficient internal constructor(private val scalar: PrivateKey) { + fun scale(point: PublicKey): PublicKey = point * scalar + + override fun equals(other: Any?): Boolean = other is Coefficient && other.scalar == scalar + override fun hashCode(): Int = scalar.hashCode() + override fun toString(): String = "Coefficient(${scalar.value.toHex()})" + } + + /** + * `λ_id = Π_{j ≠ id} xⱼ / (xⱼ − x_id)`, where `x = id + 1`. + * + * @throws IllegalArgumentException if [id] is not in [ids], or an id repeats. + */ + fun coefficient(id: Int, ids: Collection): Coefficient { + require(id in ids) { "participant $id is not among $ids" } + require(ids.size == ids.toSet().size) { "participant ids repeat: $ids" } + require(ids.all { it >= 0 }) { "participant ids are 0-based: $ids" } + + val xi = Scalars.of(id + 1) + val lambda = ids.filter { it != id }.fold(Scalars.ONE) { acc, j -> + val xj = Scalars.of(j + 1) + acc * xj * Scalars.inverse(xj - xi) + } + return Coefficient(lambda) + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/NpubTweak.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/NpubTweak.kt new file mode 100644 index 00000000..8ad2ba23 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/NpubTweak.kt @@ -0,0 +1,68 @@ +package mobi.giza.compose.cryptography.threshold + +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.PublicKey +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.managers.SharedKeyDerivation + +/** + * How a group's npub's secret relates to its threshold key's, as public values: + * `d = a·x + b`, with `a ∈ {1, −1}` (D2 of docs/group-threshold-ecdh.md). + * + * The npub is the threshold key walked through x-only tweaks, and BIP 327 negates the key + * before each x-only tweak when its y is odd. So the sign of `x` inside `d` is the product of + * those negations, and `b` collects the tweaks with the signs that came after them. The + * library's `TweakCache` is opaque, so this replays the walk rather than reading it. + * + * Getting [negate] wrong does not fail loudly: it gives another point, whose x-coordinate + * opens nothing. Phase 0's check 3 and `ThresholdEcdhJvmTest` pin it against quartz. + */ +class NpubTweak private constructor( + /** True when `a = −1`. */ + val negate: Boolean, + /** `b`, or null when no tweak was applied and `b = 0`, which libsecp256k1 cannot hold as a scalar. */ + private val b: PrivateKey?, + /** The x-only npub the walk reached, 32 bytes as hex. */ + val npub: String, +) { + /** `d·P`, from `x·P`: `a·(x·P) + b·P`. */ + fun apply(xP: PublicKey, p: PublicKey): PublicKey { + val signed = if (negate) -xP else xP + return if (b == null) signed else signed + p * b + } + + override fun toString(): String = "NpubTweak(negate=$negate, npub=$npub)" + + companion object { + /** + * The tweak for the key [SharedKeyDerivation.derive] reaches at [path]. + * + * @throws IllegalStateException if the replay does not reach the derived key, which + * would mean D2's signs are wrong and every conversation key with them would be too. + */ + fun of(thresholdPublicKey: PublicKey, path: List = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH): NpubTweak { + val derived = SharedKeyDerivation.derive(thresholdPublicKey.value.toByteArray().toHex(), path) + val tweak = replay(thresholdPublicKey, derived.tweaks) + check(tweak.npub == derived.hex) { "The tweak replay did not reach the group's npub" } + return tweak + } + + internal fun replay(x: PublicKey, tweaks: List): NpubTweak { + var negate = false + var b: PrivateKey? = null + var q = x + tweaks.forEach { scalar -> + val tau = PrivateKey(scalar) + if (q.isOdd()) { + q = -q + negate = !negate + b = b?.let { -it } + } + q += tau.publicKey() + b = b?.let { it + tau } ?: tau + } + return NpubTweak(negate, b, q.xOnly().value.toHex()) + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/Scalars.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/Scalars.kt new file mode 100644 index 00000000..fb1a0cfa --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/Scalars.kt @@ -0,0 +1,47 @@ +package mobi.giza.compose.cryptography.threshold + +import fr.acinq.bitcoin.PrivateKey + +/** + * The public scalars threshold ECDH needs, mod the curve order `n`: small integers, and their + * inverses. Every operation is a libsecp256k1 call through bitcoin-kmp's [PrivateKey], so + * nothing here is Kotlin arithmetic on a number, and none of it ever touches a share. + * + * Internal to the package. A scalar leaving it would be a scalar some other file could + * multiply a share by, which is the one thing [Lagrange] is shaped to prevent. + */ +internal object Scalars { + val ONE: PrivateKey = of(1) + + /** `n − 2`, Fermat's exponent: `v^(n−2) = v⁻¹` in a group of prime order `n`. */ + private const val N_MINUS_2 = "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd036413f" + + /** [v] as a scalar. Zero is not a scalar libsecp256k1 accepts, and is never asked for. */ + fun of(v: Int): PrivateKey { + require(v > 0) { "a scalar here is a positive integer, not $v" } + return 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() + }) + } + + /** + * `v⁻¹ mod n`, by square-and-multiply. 256 squarings and about 128 products, each one + * libsecp256k1 call: slow next to an extended Euclid, and fast next to anything a round + * waits on. Public values only, so constant time is not the point; using the library's + * own arithmetic is. + */ + fun inverse(v: PrivateKey): PrivateKey { + var result = ONE + N_MINUS_2.chunked(2).forEach { pair -> + val byte = pair.toInt(16) + for (bit in 7 downTo 0) { + result = result * result + if ((byte ushr bit) and 1 == 1) result = result * v + } + } + return result + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/ThresholdEcdh.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/ThresholdEcdh.kt new file mode 100644 index 00000000..4ff1a508 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/cryptography/threshold/ThresholdEcdh.kt @@ -0,0 +1,48 @@ +package mobi.giza.compose.cryptography.threshold + +import com.vitorpamplona.crypto.kdf.Hkdf +import fr.acinq.bitcoin.PublicKey +import fr.acinq.secp256k1.Hex + +/** + * Threshold ECDH for a group's npub: `d·P` from `t` holders' partials, and the NIP-44 + * conversation key it gives (docs/group-threshold-ecdh.md, *The arithmetic*). + * + * ``` + * x·P = Σ λᵢ·Dᵢ d·P = a·(x·P) + b·P convKey = HKDF-extract("nip44-v2", x(d·P)) + * ``` + * + * The key that comes out is the one any NIP-44 library computes from `d` and `P`, which is + * the whole of the interoperability argument: a sender's app cannot tell the group's key + * from a person's. Nothing here holds `x` or `d`; the only secret a device contributes is + * its own `Dᵢ`, made by [EcdhPartial]. + */ +object ThresholdEcdh { + private val SALT = "nip44-v2".encodeToByteArray() + + /** + * `d·P` from verified partials, keyed by 0-based participant id. Any `t` or more partials + * of one generation give the same point; fewer give a point that opens nothing, which a + * caller cannot tell from here, so it counts before calling. + */ + fun combine(partials: Map, tweak: NpubTweak, p: PublicKey): PublicKey { + require(partials.isNotEmpty()) { "Nothing to combine" } + val ids = partials.keys + val xP = partials.entries + .map { (id, d) -> Lagrange.coefficient(id, ids).scale(d) } + .reduce { acc, term -> acc + term } + return tweak.apply(xP, p) + } + + /** NIP-44's conversation key from the shared point: only its x-coordinate counts. */ + fun conversationKey(point: PublicKey): ByteArray = + Hkdf().extract(point.value.toByteArray().copyOfRange(1, 33), SALT) + + /** A nostr key, given as 32-byte x-only hex, as a point. Its parity does not matter (D2). */ + fun pointOf(xOnlyHex: String): PublicKey? = try { + if (xOnlyHex.length != 64) null + else PublicKey(byteArrayOf(2) + Hex.decode(xOnlyHex)).takeIf { it.isValid() } + } catch (_: Throwable) { + null + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/cryptography/threshold/ThresholdEcdhJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/cryptography/threshold/ThresholdEcdhJvmTest.kt new file mode 100644 index 00000000..35da0671 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/cryptography/threshold/ThresholdEcdhJvmTest.kt @@ -0,0 +1,213 @@ +package mobi.giza.compose.cryptography.threshold + +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 java.io.File +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertTrue +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.managers.SharedKeyDerivation + +/** + * Phase 2 of docs/group-threshold-ecdh.md: the arithmetic, alone, against quartz's NIP-44. + * + * The expected key is computed the ordinary way, from a whole `d`, which only a test with a + * dealer key made for it may build. The code under test never sees `d` or `x`. + */ +class ThresholdEcdhJvmTest { + private fun dealer(seed: Int, n: Int = 5, t: Int = 3): Pair { + val secret = PrivateKey(Crypto.sha256("threshold-ecdh/$seed".encodeToByteArray())) + return secret to Frost.trustedDealerKeygen(secret, n, t) + } + + /** The npub's secret, built whole -- here and nowhere else. */ + private fun npubSecret(x: PrivateKey, keys: KeyMaterial): PrivateKey { + val derived = SharedKeyDerivation.derive(keys.thresholdPublicKey.value.toByteArray().toHex()) + // (a, b) recomputed here, independently of NpubTweak, so the two check each other. + var q = keys.thresholdPublicKey + var a = false + var b: PrivateKey? = null + derived.tweaks.forEach { s -> + val tau = PrivateKey(s) + if (q.isOdd()) { q = -q; a = !a; b = b?.let { -it } } + q += tau.publicKey(); b = b?.let { it + tau } ?: tau + } + val d = (if (a) -x else x) + b!! + assertEquals(derived.publicKey, d.publicKey().xOnly()) + return d + } + + private fun subsets(ids: List, t: Int): List> = + 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) + + private fun peer(seed: Int) = PrivateKey(Crypto.sha256("peer/$seed".encodeToByteArray())) + + private fun partials(keys: KeyMaterial, ids: List, p: PublicKey) = + ids.associateWith { EcdhPartial.compute(keys.secretShares[it], p) } + + @Test + fun `every t-subset of a 3-of-5 key gives quartz's conversation key, and so does a larger one`() { + val (x, keys) = dealer(1) + val d = npubSecret(x, keys) + val tweak = NpubTweak.of(keys.thresholdPublicKey) + val other = peer(1) + val p = other.publicKey() + val expected = Nip44v2().computeConversationKey(d.value.toByteArray(), p.xOnly().value.toByteArray()) + + (subsets((0..4).toList(), 3) + subsets((0..4).toList(), 4) + listOf((0..4).toList())).forEach { ids -> + val key = ThresholdEcdh.conversationKey(ThresholdEcdh.combine(partials(keys, ids, p), tweak, p)) + assertContentEquals(expected, key, "subset $ids") + } + // The sender's side, as their own app computes it. + val npub = SharedKeyDerivation.derive(keys.thresholdPublicKey.value.toByteArray().toHex()).publicKey + assertContentEquals(expected, Nip44v2().computeConversationKey(other.value.toByteArray(), npub.value.toByteArray())) + } + + @Test + fun `t minus one partials give a key that does not match`() { + val (x, keys) = dealer(2) + val d = npubSecret(x, keys) + val tweak = NpubTweak.of(keys.thresholdPublicKey) + val p = peer(2).publicKey() + val expected = Nip44v2().computeConversationKey(d.value.toByteArray(), p.xOnly().value.toByteArray()) + subsets((0..4).toList(), 2).forEach { ids -> + assertFalse(expected.contentEquals(ThresholdEcdh.conversationKey(ThresholdEcdh.combine(partials(keys, ids, p), tweak, p)))) + } + } + + @Test + fun `the tweak replay matches derive in every parity case`() { + val seen = mutableSetOf>() + (1..40).forEach { seed -> + val (x, keys) = dealer(seed) + val tweak = NpubTweak.of(keys.thresholdPublicKey) + val derived = SharedKeyDerivation.derive(keys.thresholdPublicKey.value.toByteArray().toHex()) + assertEquals(derived.hex, tweak.npub) + npubSecret(x, keys) + var q = keys.thresholdPublicKey + derived.tweaks.forEachIndexed { step, s -> + seen += step to q.isEven() + if (q.isOdd()) q = -q + q += PrivateKey(s).publicKey() + } + // And the combined point lands for this seed too. + val p = peer(seed).publicKey() + val expected = Nip44v2().computeConversationKey(npubSecret(x, keys).value.toByteArray(), p.xOnly().value.toByteArray()) + assertContentEquals(expected, ThresholdEcdh.conversationKey(ThresholdEcdh.combine(partials(keys, listOf(0, 2, 4), p), tweak, p))) + } + assertEquals(6, seen.size, "both parities at every step: $seen") + } + + @Test + fun `P given as x-only lifts to the same key whichever parity is chosen`() { + val (x, keys) = dealer(3) + val tweak = NpubTweak.of(keys.thresholdPublicKey) + val p = peer(3).publicKey() + val lifted = ThresholdEcdh.pointOf(p.xOnly().value.toHex())!! + val even = ThresholdEcdh.conversationKey(ThresholdEcdh.combine(partials(keys, listOf(0, 1, 2), lifted), tweak, lifted)) + val odd = ThresholdEcdh.conversationKey(ThresholdEcdh.combine(partials(keys, listOf(0, 1, 2), -lifted), tweak, -lifted)) + assertContentEquals(even, odd) + assertContentEquals( + Nip44v2().computeConversationKey(npubSecret(x, keys).value.toByteArray(), p.xOnly().value.toByteArray()), + even, + ) + } + + @Test + fun `Lagrange coefficients over shifted ids rebuild the dealer's point`() { + val (_, keys) = dealer(4) + subsets((0..4).toList(), 3).forEach { ids -> + val rebuilt = ids.map { Lagrange.coefficient(it, ids).scale(keys.publicShares[it]) }.reduce { a, b -> a + b } + assertEquals(keys.thresholdPublicKey, rebuilt) + } + assertFailsWith { Lagrange.coefficient(5, listOf(0, 1, 2)) } + assertFailsWith { Lagrange.coefficient(1, listOf(1, 1, 2)) } + } + + @Test + fun `an inverse is an inverse`() { + (1..64).forEach { assertEquals(Scalars.ONE, Scalars.of(it) * Scalars.inverse(Scalars.of(it))) } + val big = PrivateKey(Crypto.sha256("big".encodeToByteArray())) + assertEquals(Scalars.ONE, big * Scalars.inverse(big)) + } + + // --- D3: the proof + + private val aux = ByteArray(32) { 9 } + + private data class Case(val share: PrivateKey, val y: PublicKey, val p: PublicKey, val d: PublicKey, val context: ByteArray) + + private fun case(): Case { + val (_, keys) = dealer(5) + val p = peer(5).publicKey() + val share = keys.secretShares[1] + return Case(share, keys.publicShares[1], p, EcdhPartial.compute(share, p), Dleq.context("a".repeat(64), 3, 1)) + } + + @Test + fun `a proof verifies`() { + val c = case() + val proof = Dleq.prove(c.share, c.y, c.p, c.d, c.context, aux) + assertTrue(Dleq.verify(c.y, c.p, c.d, c.context, proof)) + assertEquals(proof, Dleq.Proof.fromHex(proof.toHex())) + // Fresh aux, another proof, still valid. + val again = Dleq.prove(c.share, c.y, c.p, c.d, c.context, ByteArray(32) { 1 }) + assertFalse(again == proof) + assertTrue(Dleq.verify(c.y, c.p, c.d, c.context, again)) + } + + @Test + fun `a proof fails for another point, generation, id, partial, public share, or a changed c or z`() { + val c = case() + val proof = Dleq.prove(c.share, c.y, c.p, c.d, c.context, aux) + val otherP = peer(99).publicKey() + assertFalse(Dleq.verify(c.y, otherP, c.d, c.context, proof), "another point") + assertFalse(Dleq.verify(c.y, c.p, c.d, Dleq.context("a".repeat(64), 4, 1), proof), "another generation") + assertFalse(Dleq.verify(c.y, c.p, c.d, Dleq.context("a".repeat(64), 3, 2), proof), "another id") + assertFalse(Dleq.verify(c.y, c.p, c.d, Dleq.context("b".repeat(64), 3, 1), proof), "another room") + assertFalse(Dleq.verify(c.y, c.p, c.d + c.p, c.context, proof), "another partial") + assertFalse(Dleq.verify(c.y + c.p, c.p, c.d, c.context, proof), "another public share") + assertFalse(Dleq.verify(c.y, c.p, c.d, c.context, proof.copy(z = proof.c)), "z swapped") + assertFalse(Dleq.verify(c.y, c.p, c.d, c.context, Dleq.Proof(proof.z, proof.c)), "c and z swapped") + val flipped = proof.c.toByteArray().also { it[31] = (it[31].toInt() xor 1).toByte() } + assertFalse(Dleq.verify(c.y, c.p, c.d, c.context, proof.copy(c = ByteVector32(flipped))), "c changed") + assertFalse(Dleq.verify(c.y, c.p, c.d, c.context, proof.copy(z = ByteVector32("ff".repeat(32)))), "z out of range") + } + + @Test + fun `a wrong partial with an honest-looking proof is caught`() { + val c = case() + // A holder who answers with another scalar cannot prove it against their public share. + val forged = EcdhPartial.compute(PrivateKey(Crypto.sha256("forger".encodeToByteArray())), c.p) + val proof = Dleq.prove(c.share, c.y, c.p, forged, c.context, aux) + assertFalse(Dleq.verify(c.y, c.p, forged, c.context, proof)) + } + + // --- shared-key-derivation.md's rule, as a test + + @Test + fun `nothing in the package can build the group's secret`() { + val root = File("src").takeIf { it.resolve("commonMain").isDirectory } ?: File("composeApp/src") + val sources = root.resolve("commonMain/kotlin/mobi/giza/compose/cryptography/threshold") + .listFiles { f -> f.extension == "kt" }!!.associate { it.name to it.readText() } + assertTrue(sources.isNotEmpty()) + sources.forEach { (name, text) -> + // A list of every share is a dealer's, never a device's. + assertFalse("secretShares" in text, "$name reads a list of shares") + // A Lagrange coefficient leaves the class only through scale(point). + if (name != "Lagrange.kt") assertFalse(Regex("""Coefficient\(""").containsMatchIn(text), "$name builds a coefficient") + } + // The coefficient's scalar is private: scale(point) is its only use. + assertTrue("class Coefficient internal constructor(private val scalar: PrivateKey)" in sources.getValue("Lagrange.kt")) + } +}