From a1e87d92e5f7c05ea983d8b4c4a2bb49cb66833c Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 16:23:15 +0200 Subject: [PATCH] feat(lightning): a distributed key generation for Iceberg (Phase 1) Co-Authored-By: Claude Opus 5.5 --- .../bennu/compose/managers/IcebergDkg.kt | 325 ++++++++++++++++++ .../bennu/compose/managers/IcebergDkgTest.kt | 210 +++++++++++ docs/group-lightning-wallet.md | 2 + 3 files changed, 537 insertions(+) create mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/IcebergDkg.kt create mode 100644 composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/IcebergDkgTest.kt diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/IcebergDkg.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/IcebergDkg.kt new file mode 100644 index 00000000..5e8f591c --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/IcebergDkg.kt @@ -0,0 +1,325 @@ +package com.machankura.bennu.compose.managers + +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.PublicKey +import fr.acinq.bitcoin.crypto.Pack +import fr.acinq.bitcoin.crypto.iceberg.Iceberg +import fr.acinq.bitcoin.crypto.iceberg.PublicShare +import fr.acinq.bitcoin.crypto.iceberg.Share +import fr.acinq.bitcoin.utils.Either + +/** + * A distributed key generation for Iceberg, which ships only a trusted dealer. + * + * An Iceberg share is replicated secret sharing, not a Shamir point: every + * `(t-1)`-subset `T` of the participants has its own 32-byte seed, held by every + * participant *outside* `T`, and a participant's share is the seeds of the + * subsets it is outside of, in the lexicographic rank order `rss.h` fixes. So a + * DKG only has to agree each seed among its holders without any member of `T` + * learning it: + * + * ``` + * round 1 each holder j of each T: c[j,T] = random, publish h[j,T] = H(commit, sid, T, j, c[j,T]) + * round 2 send c[j,T] to every other holder of T, encrypted to them + * round 3 each k checks every c[j,T] it was sent against h[j,T], then + * s[T] = H(seed, sid, T, c[j,T] for each holder j, ascending) + * share = 1 | n | t | k | s[T] for each T not containing k, in rank order + * and publishes its public share and a signature over the transcript + * done Iceberg.groupPublicKey over all n public shares + * ``` + * + * Why it is safe, in the three sentences it takes: + * + * - **Every seed is random.** `T` has `n - t + 1 >= t` holders and at most + * `t - 1` members are corrupt, so some holder's contribution is honest. + * - **Every seed is secret from `T`.** Its contributions only go to its holders, + * so a coalition of `t - 1` lacks exactly the seed named after itself, which + * is the scheme's whole margin (`rss.h`). + * - **Nobody chooses last.** Contributions are committed before any is revealed, + * so a contributor cannot grind the group key. + * + * A contributor who reveals something other than what it committed to is named + * ([Fault.BadReveal]). One who commits to two different values in front of two + * different members is not caught here; the transcript signature is what catches + * that, because the two members then sign different transcripts. + * + * ### Repair, which RSS gives away + * + * Every seed a participant holds is also held by `n - t` others. A participant + * that has lost its share can be sent its seeds again ([repairSeeds]); the share + * it rebuilds ([repair]) must reproduce the public share it published, which is + * the check on what it was sent. That replaces ChillDKG's recovery data. + * + * ### What this is not + * + * Reviewed. `iceberg.md` says the scheme must not protect anything of value, and + * this protocol is newer than the scheme. It lives in the app rather than in the + * bitcoin-kmp fork beside [Iceberg] only because it needs nothing from inside + * the library; see the build table in `docs/group-lightning-wallet.md`. + * + * Every function here is pure over inputs the ritual has stored, as + * [fr.acinq.bitcoin.crypto.dkg.chill.ChillDKG]'s are, so a ceremony resumes from + * its persisted messages after the app is killed. + */ +object IcebergDkg { + /** `SECP256K1_ICEBERG_MAX_PARTICIPANTS`, which sizes the library's ABI. */ + const val MAX_PARTICIPANTS = 10 + + private const val TAG_SESSION = "bennu/iceberg-dkg/session/v1" + private const val TAG_CONTRIBUTION = "bennu/iceberg-dkg/contribution/v1" + private const val TAG_COMMIT = "bennu/iceberg-dkg/commit/v1" + private const val TAG_SEED = "bennu/iceberg-dkg/seed/v1" + private const val TAG_TRANSCRIPT = "bennu/iceberg-dkg/transcript/v1" + + /** The share format version `secp256k1_iceberg_share_parse` accepts. */ + private const val SHARE_VERSION: Byte = 1 + + /** + * Whether a group of [n] with threshold [t] can be *expressed* by Iceberg: + * a round-one quorum of `2t-1` has to exist. + */ + fun isExpressible(n: Int, t: Int): Boolean = n in 1..MAX_PARTICIPANTS && t >= 1 && t <= (n + 1) / 2 + + /** + * Whether it can be *deployed*: expressible, a real threshold, and big + * enough for the group to agree what it signs while `t - 1` members + * misbehave, `n >= 3t - 2` (`secp256k1_iceberg.h`, constraint 3). 2-of-4 is + * the smallest group this admits, and 4-of-10 the largest threshold. + */ + fun isDeployable(n: Int, t: Int): Boolean = isExpressible(n, t) && t >= 2 && n >= 3 * t - 2 + + /** Every threshold a group of [n] could deploy, smallest first. */ + fun deployableThresholds(n: Int): List = (2..n).filter { isDeployable(n, it) } + + /** + * A ceremony's parameters, the same on every device. + * + * [hostKeys] are sorted bytewise and participant `k` is `hostKeys[k - 1]`, + * for the reason the ChillDKG ritual sorts its own: an order every device + * reaches without being told. [sessionId] binds all of it, so a device + * that ordered the participants differently computes another session and + * gets no key rather than a weaker one. + */ + class Params private constructor( + val n: Int, + val t: Int, + val hostKeys: List, + val sessionId: ByteVector32, + ) { + /** The `(t-1)`-subsets, as bitmasks over participants 1..n, in rank order. */ + val subsets: List = subsetsInRankOrder(n, t - 1) + + fun holders(subset: Int): List = (1..n).filter { subset and (1 shl it) == 0 } + + fun isHolder(participant: Int, subset: Int): Boolean = subset and (1 shl participant) == 0 + + /** The ranks whose seeds [participant] holds, ascending: its share's layout. */ + fun heldRanks(participant: Int): List = subsets.indices.filter { isHolder(participant, subsets[it]) } + + fun indexOf(hostKey: PublicKey): Int? = hostKeys.indexOf(hostKey).takeIf { it >= 0 }?.plus(1) + + companion object { + /** + * @param ceremonyId the proposal's own id, so two ceremonies over the + * same people and threshold are two sessions. + */ + fun of(t: Int, hostKeys: Collection, ceremonyId: ByteVector32): Params { + val sorted = hostKeys.distinct().sortedWith { a, b -> compareBytes(a.value.toByteArray(), b.value.toByteArray()) } + require(sorted.size == hostKeys.size) { "a participant appears twice" } + require(isDeployable(sorted.size, t)) { "$t-of-${sorted.size} is not a deployable Iceberg group" } + val sid = Crypto.taggedHash( + byteArrayOf(sorted.size.toByte(), t.toByte()) + sorted.flatMap { it.value.toByteArray().asList() } + ceremonyId.toByteArray(), + TAG_SESSION, + ) + return Params(sorted.size, t, sorted, sid) + } + } + } + + /** What went wrong, as a value: a faulty participant is an outcome of a DKG, not a bug in it. */ + sealed class Fault(val participant: Int?, message: String) : Exception(message) { + class MissingCommitment(participant: Int) : Fault(participant, "participant $participant sent no commitment") + class MissingReveal(participant: Int) : Fault(participant, "participant $participant revealed nothing to us") + class BadReveal(participant: Int) : Fault(participant, "participant $participant revealed a value it had not committed to") + class MalformedMessage(participant: Int, reason: String) : Fault(participant, "participant $participant sent a malformed message: $reason") + class InconsistentShares(reason: String) : Fault(null, "the public shares do not lie on one polynomial: $reason") + class RepairMismatch(reason: String) : Fault(null, "the repaired share does not reproduce the published public share: $reason") + } + + /** One participant's round-1 message: a commitment per subset it holds, by rank. */ + data class Commitments(val participant: Int, val byRank: Map) + + /** + * [participant]'s contribution to the seed at [rank], derived from the + * 32 random bytes it stored when it joined. Storing the root rather than the + * contributions is what lets a ritual stay a function of its stored inputs. + * The root is as secret as the share it becomes; drop it once the share is + * assembled. + */ + fun contribution(params: Params, participant: Int, root: ByteVector32, rank: Int): ByteVector32 { + require(params.isHolder(participant, params.subsets[rank])) { "participant $participant does not hold the seed at rank $rank" } + return Crypto.taggedHash(root.toByteArray() + params.sessionId.toByteArray() + Pack.writeInt32BE(rank) + byteArrayOf(participant.toByte()), TAG_CONTRIBUTION) + } + + fun commitment(params: Params, participant: Int, rank: Int, contribution: ByteVector32): ByteVector32 = + Crypto.taggedHash(params.sessionId.toByteArray() + Pack.writeInt32BE(rank) + byteArrayOf(participant.toByte()) + contribution.toByteArray(), TAG_COMMIT) + + /** Round 1: commit to every contribution, to be published to everyone. */ + fun round1(params: Params, participant: Int, root: ByteVector32): Commitments = + Commitments(participant, params.heldRanks(participant).associateWith { commitment(params, participant, it, contribution(params, participant, root, it)) }) + + /** + * Round 2: what [participant] reveals to [recipient], by rank -- its + * contributions to the seeds they both hold, and nothing else. The caller + * encrypts it to the recipient; it must never travel in the clear. + */ + fun round2(params: Params, participant: Int, root: ByteVector32, recipient: Int): Map { + require(participant != recipient) { "a participant does not reveal to itself" } + return params.heldRanks(participant) + .filter { params.isHolder(recipient, params.subsets[it]) } + .associateWith { contribution(params, participant, root, it) } + } + + /** + * Round 3: check every reveal against its commitment and assemble this + * participant's share. + * + * @param commitments every participant's round-1 message, own included. + * @param reveals what every other participant revealed to this one, by sender. + */ + fun assemble( + params: Params, + participant: Int, + root: ByteVector32, + commitments: Map, + reveals: Map>, + ): Either { + for (j in 1..params.n) { + val c = commitments[j] ?: return Either.Left(Fault.MissingCommitment(j)) + if (c.byRank.keys != params.heldRanks(j).toSet()) return Either.Left(Fault.MalformedMessage(j, "commitments for the wrong subsets")) + } + val seeds = params.heldRanks(participant).map { rank -> + val contributions = params.holders(params.subsets[rank]).map { j -> + val value = if (j == participant) { + contribution(params, participant, root, rank) + } else { + reveals[j]?.get(rank) ?: return Either.Left(Fault.MissingReveal(j)) + } + if (commitment(params, j, rank, value) != commitments.getValue(j).byRank.getValue(rank)) return Either.Left(Fault.BadReveal(j)) + value + } + seed(params, rank, contributions) + } + return Either.Right(share(params.n, params.t, participant, seeds)) + } + + /** The seed at [rank], from its holders' contributions in ascending participant order. */ + fun seed(params: Params, rank: Int, contributions: List): ByteVector32 = + Crypto.taggedHash(params.sessionId.toByteArray() + Pack.writeInt32BE(rank) + contributions.flatMap { it.toByteArray().asList() }, TAG_SEED) + + /** + * A share in `secp256k1_iceberg_share_serialize`'s encoding: version, n, t, + * the participant's index, then its seeds in rank order. Which seed is which + * follows from n, t and the index, so the order of [seeds] is the whole of + * the layout and has to be [Params.heldRanks]'s. + */ + fun share(n: Int, t: Int, participant: Int, seeds: List): Share { + require(isExpressible(n, t) && participant in 1..n) + require(seeds.size == binomial(n - 1, t - 1)) { "a share holds C(n-1, t-1) seeds" } + return Share(byteArrayOf(SHARE_VERSION, n.toByte(), t.toByte(), participant.toByte()) + seeds.flatMap { it.toByteArray().asList() }) + } + + /** + * The hash every participant signs once it has its share: the parameters, + * every commitment and every public share. Two members who were shown + * different commitments, or different public shares, sign different hashes, + * and the ritual refuses to finish on signatures that do not all agree. + */ + fun transcriptHash(params: Params, commitments: Map, publicShares: List, groupPublicKey: PublicKey): ByteVector32 { + require(publicShares.size == params.n && commitments.size == params.n) + val bytes = buildList { + addAll(params.sessionId.toByteArray().asList()) + for (j in 1..params.n) { + val c = commitments.getValue(j) + for (rank in params.heldRanks(j)) addAll(c.byRank.getValue(rank).toByteArray().asList()) + } + publicShares.forEach { addAll(it.toByteArray().asList()) } + addAll(groupPublicKey.value.toByteArray().asList()) + } + return Crypto.taggedHash(bytes.toByteArray(), TAG_TRANSCRIPT) + } + + /** + * The group key, from every participant's public share in participant + * order. Using all `n` rather than a quorum is the point: `groupPublicKey` + * checks the shares lie on one polynomial of degree `t-1`, and every share + * past `t` is one more constraint a wrong one has to satisfy. + */ + fun groupPublicKey(params: Params, publicShares: List): Either { + if (publicShares.size != params.n) return Either.Left(Fault.InconsistentShares("expected ${params.n} public shares, got ${publicShares.size}")) + return when (val key = Iceberg.groupPublicKey(publicShares, params.n, params.t)) { + is Either.Right -> Either.Right(key.value) + is Either.Left -> Either.Left(Fault.InconsistentShares(key.value.message ?: "rejected")) + } + } + + /** + * What [helper] sends [participant] to repair its share: the seeds they + * both hold. Encrypted to the participant, like a round-2 reveal. + */ + fun repairSeeds(params: Params, helper: Int, helperShare: Share, participant: Int): Map { + require(helper != participant) + val bytes = helperShare.toByteArray() + require(bytes[3].toInt() == helper) { "that is not the helper's share" } + return params.heldRanks(helper).withIndex() + .filter { (_, rank) -> params.isHolder(participant, params.subsets[rank]) } + .associate { (i, rank) -> rank to ByteVector32(bytes.copyOfRange(4 + 32 * i, 36 + 32 * i)) } + } + + /** + * Rebuild [participant]'s share from what helpers sent ([repairSeeds]). + * Where several helpers sent one seed they must agree, and the result must + * reproduce [publishedPublicShare] -- a wrong seed from anybody fails here + * rather than at a signature. + */ + fun repair(params: Params, participant: Int, received: Map>, publishedPublicShare: PublicShare): Either { + val seeds = params.heldRanks(participant).map { rank -> + val offered = received.values.mapNotNull { it[rank] }.toSet() + when (offered.size) { + 0 -> return Either.Left(Fault.RepairMismatch("nobody sent the seed at rank $rank")) + 1 -> offered.single() + else -> return Either.Left(Fault.RepairMismatch("helpers disagree on the seed at rank $rank")) + } + } + val share = share(params.n, params.t, participant, seeds) + if (Iceberg.publicShare(share, null) != publishedPublicShare) return Either.Left(Fault.RepairMismatch("public share differs")) + return Either.Right(share) + } + + /** All [size]-subsets of 1..[n] as bitmasks (bit j for participant j), in `rss.h`'s lexicographic rank order. */ + fun subsetsInRankOrder(n: Int, size: Int): List { + val out = mutableListOf() + fun walk(next: Int, remaining: Int, mask: Int) { + if (remaining == 0) { out += mask; return } + for (j in next..(n - remaining + 1)) walk(j + 1, remaining - 1, mask or (1 shl j)) + } + walk(1, size, 0) + return out + } + + fun binomial(n: Int, k: Int): Int { + if (k < 0 || k > n) return 0 + var r = 1L + for (i in 0 until k) r = r * (n - i) / (i + 1) + return r.toInt() + } + + private fun compareBytes(a: ByteArray, b: ByteArray): Int { + for (i in 0 until minOf(a.size, b.size)) { + val c = (a[i].toInt() and 0xff) - (b[i].toInt() and 0xff) + if (c != 0) return c + } + return a.size - b.size + } +} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/IcebergDkgTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/IcebergDkgTest.kt new file mode 100644 index 00000000..a8879ff6 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/IcebergDkgTest.kt @@ -0,0 +1,210 @@ +package com.machankura.bennu.compose.managers + +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.PublicKey +import fr.acinq.bitcoin.byteVector32 +import fr.acinq.bitcoin.crypto.Pack +import fr.acinq.bitcoin.crypto.iceberg.Iceberg +import fr.acinq.bitcoin.crypto.iceberg.PublicShare +import fr.acinq.bitcoin.crypto.iceberg.Share +import fr.acinq.bitcoin.crypto.musig2.IndividualNonce +import fr.acinq.bitcoin.crypto.musig2.KeyAggCache +import fr.acinq.bitcoin.crypto.musig2.SecretNonce +import fr.acinq.bitcoin.crypto.musig2.Session +import fr.acinq.bitcoin.utils.Either +import kotlin.random.Random +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNotEquals +import kotlin.test.assertTrue + +/** + * The Iceberg DKG, run between simulated participants against the real library. + * + * The layout test is the one to read first: it proves, against the library's + * own dealer, that a share this DKG assembles is laid out the way + * `secp256k1_iceberg_share_parse` reads it. Everything after it would pass for a + * DKG whose seeds were in the wrong order -- the shares would still parse and + * still aggregate -- right up to the signature that did not verify. + */ +class IcebergDkgTest { + private val random = Random(0x1ceb) + + private fun bytes32() = random.nextBytes(32).byteVector32() + + private fun hostKeys(n: Int): List = (1..n).map { PrivateKey(bytes32()).publicKey() } + + private class Run(val params: IcebergDkg.Params, val shares: List, val publicShares: List, val groupKey: PublicKey) + + /** Every participant runs every round, honestly. */ + private fun run(n: Int, t: Int): Run { + val params = IcebergDkg.Params.of(t, hostKeys(n), bytes32()) + val roots = (1..n).associateWith { bytes32() } + val commitments = (1..n).associateWith { IcebergDkg.round1(params, it, roots.getValue(it)) } + val shares = (1..n).map { k -> + val reveals = (1..n).filter { it != k }.associateWith { j -> IcebergDkg.round2(params, j, roots.getValue(j), k) } + val share = IcebergDkg.assemble(params, k, roots.getValue(k), commitments, reveals) + assertIs>(share).value + } + val publicShares = shares.map { Iceberg.publicShare(it, null) } + val key = assertIs>(IcebergDkg.groupPublicKey(params, publicShares)).value + return Run(params, shares, publicShares, key) + } + + /** One signature by [signers] (1-based) beside a stock MuSig2 cosigner, judged by BIP340. */ + private fun signs(run: Run, signers: List): Boolean { + val n = run.params.n + val t = run.params.t + val cosigner = PrivateKey(bytes32()) + val msg = bytes32() + val sid = bytes32() + val keys = listOf(run.groupKey, cosigner.publicKey()) + val (aggregateKey, cache) = KeyAggCache.create(keys) + val contributions = signers.map { Iceberg.generateNonce(run.shares[it - 1], null, sid) } + val groupNonce = Iceberg.aggregateNonces(contributions, n, t, run.groupKey).right ?: return false + val (cosignerSecret, cosignerPublic) = SecretNonce.generate(bytes32(), Either.Left(cosigner), msg, cache, null) + val aggregated = IndividualNonce.aggregate(listOf(groupNonce, cosignerPublic)).right ?: return false + val cosignerAggregated = IndividualNonce.aggregate(listOf(cosignerPublic)).right ?: return false + val session = Session.create(aggregated, msg, cache) + val signatureShares = signers.map { + Iceberg.partialSign(run.shares[it - 1], null, sid, contributions, run.groupKey, cache, msg, cosignerAggregated).right ?: return false + } + val groupPartial = Iceberg.aggregatePartialSignatures(signatureShares, n, t).right ?: return false + val cosignerPartial = session.sign(cosignerSecret, cosigner).right ?: return false + val sig = session.aggregateSigs(listOf(groupPartial, cosignerPartial)).right ?: return false + return Crypto.verifySignatureSchnorr(msg, sig, aggregateKey) + } + + private fun quorums(n: Int, t: Int): List> = + IcebergDkg.subsetsInRankOrder(n, 2 * t - 1).map { mask -> (1..n).filter { mask and (1 shl it) != 0 } } + + @Test + fun `an assembled share is laid out as the library's dealer lays one out`() { + for ((n, t) in listOf(4 to 2, 7 to 3, 10 to 4, 5 to 3)) { + val root = bytes32() + val dealt = Iceberg.dealShares(n, t, root) + val ranks = IcebergDkg.subsetsInRankOrder(n, t - 1) + for (k in 1..n) { + // keygen_impl.h: seed(rank) = H_"Iceberg/dealer"(root || n || t || rank), appended for every subset k is outside of. + val seeds = ranks.indices.filter { ranks[it] and (1 shl k) == 0 }.map { + Crypto.taggedHash(root.toByteArray() + byteArrayOf(n.toByte(), t.toByte()) + Pack.writeInt32BE(it), "Iceberg/dealer") + } + assertEquals(dealt[k - 1], IcebergDkg.share(n, t, k, seeds), "participant $k of $t-of-$n") + } + } + } + + @Test + fun `the rank order is rss_h's`() { + // The example rss.h writes out because the reference's docstring was off by one. + val expected = listOf(setOf(1, 2), setOf(1, 3), setOf(1, 4), setOf(1, 5), setOf(2, 3), setOf(2, 4), setOf(2, 5), setOf(3, 4), setOf(3, 5), setOf(4, 5)) + assertEquals(expected, IcebergDkg.subsetsInRankOrder(5, 2).map { mask -> (1..5).filter { mask and (1 shl it) != 0 }.toSet() }) + } + + @Test + fun `2-of-4 and 3-of-7 sign from every quorum, and every quorum agrees on the key`() { + for ((n, t) in listOf(4 to 2, 7 to 3)) { + val run = run(n, t) + for (q in quorums(n, t)) { + assertTrue(signs(run, q), "quorum $q of $t-of-$n") + val key = Iceberg.groupPublicKey(q.map { run.publicShares[it - 1] }, n, t).right + assertEquals(run.groupKey, key, "key over $q") + } + } + } + + @Test + fun `4-of-10 signs`() { + val run = run(10, 4) + assertTrue(signs(run, listOf(1, 2, 3, 4, 5, 6, 7))) + assertTrue(signs(run, listOf(4, 5, 6, 7, 8, 9, 10))) + assertTrue(signs(run, listOf(1, 3, 5, 7, 8, 9, 10))) + } + + @Test + fun `a reveal that was not committed to names its sender`() { + val params = IcebergDkg.Params.of(2, hostKeys(4), bytes32()) + val roots = (1..4).associateWith { bytes32() } + val commitments = (1..4).associateWith { IcebergDkg.round1(params, it, roots.getValue(it)) } + val reveals = (2..4).associateWith { j -> IcebergDkg.round2(params, j, roots.getValue(j), 1) }.toMutableMap() + reveals[3] = reveals.getValue(3).mapValues { bytes32() } + val result = IcebergDkg.assemble(params, 1, roots.getValue(1), commitments, reveals) + val fault = assertIs(assertIs>(result).value) + assertEquals(3, fault.participant) + } + + @Test + fun `a silent participant is named`() { + val params = IcebergDkg.Params.of(2, hostKeys(4), bytes32()) + val roots = (1..4).associateWith { bytes32() } + val commitments = (1..4).associateWith { IcebergDkg.round1(params, it, roots.getValue(it)) } + val reveals = (2..3).associateWith { j -> IcebergDkg.round2(params, j, roots.getValue(j), 1) } + assertEquals(4, (IcebergDkg.assemble(params, 1, roots.getValue(1), commitments, reveals) as Either.Left).value.participant) + assertEquals(2, (IcebergDkg.assemble(params, 1, roots.getValue(1), commitments - 2, reveals) as Either.Left).value.participant) + } + + @Test + fun `a share off the polynomial fails the group key`() { + val run = run(4, 2) + val bytes = run.shares[2].toByteArray().also { it[10] = (it[10] + 1).toByte() } + val tampered = run.publicShares.toMutableList().apply { this[2] = Iceberg.publicShare(Share(bytes), null) } + assertIs>(IcebergDkg.groupPublicKey(run.params, tampered)) + } + + @Test + fun `the session binds the participants, the threshold and the ceremony, but not the order they were listed in`() { + val keys = hostKeys(5) + val ceremony = bytes32() + val base = IcebergDkg.Params.of(2, keys, ceremony) + assertEquals(base.sessionId, IcebergDkg.Params.of(2, keys.reversed(), ceremony).sessionId) + assertEquals(base.hostKeys, IcebergDkg.Params.of(2, keys.shuffled(random), ceremony).hostKeys) + assertNotEquals(base.sessionId, IcebergDkg.Params.of(2, keys, bytes32()).sessionId) + assertNotEquals(base.sessionId, IcebergDkg.Params.of(2, keys.dropLast(1), ceremony).sessionId) + assertFailsWith { IcebergDkg.Params.of(2, keys + keys.first(), ceremony) } + } + + @Test + fun `only deployable groups are offered`() { + assertEquals(emptyList(), IcebergDkg.deployableThresholds(3)) + assertEquals(listOf(2), IcebergDkg.deployableThresholds(4)) + assertEquals(listOf(2), IcebergDkg.deployableThresholds(6)) + assertEquals(listOf(2, 3), IcebergDkg.deployableThresholds(7)) + assertEquals(listOf(2, 3, 4), IcebergDkg.deployableThresholds(10)) + assertEquals(emptyList(), IcebergDkg.deployableThresholds(11)) + assertTrue(IcebergDkg.isExpressible(3, 2)) + assertFalse(IcebergDkg.isDeployable(3, 2)) + assertFalse(IcebergDkg.isExpressible(4, 3)) + assertFailsWith { IcebergDkg.Params.of(3, hostKeys(5), bytes32()) } + } + + @Test + fun `a lost share is repaired from the other holders' seeds`() { + val run = run(7, 3) + val lost = 4 + val received = (1..7).filter { it != lost }.associateWith { IcebergDkg.repairSeeds(run.params, it, run.shares[it - 1], lost) } + val repaired = IcebergDkg.repair(run.params, lost, received, run.publicShares[lost - 1]) + assertEquals(run.shares[lost - 1], assertIs>(repaired).value) + + // One helper lying about one seed is caught, whether or not another helper sent the same seed. + val lying = received.toMutableMap().apply { this[1] = getValue(1).mapValues { bytes32() } } + assertIs>(IcebergDkg.repair(run.params, lost, lying, run.publicShares[lost - 1])) + val onlyTheLiar = mapOf(1 to lying.getValue(1)) + received.filterKeys { it != 1 }.mapValues { (_, seeds) -> seeds - lying.getValue(1).keys } + assertIs>(IcebergDkg.repair(run.params, lost, onlyTheLiar, run.publicShares[lost - 1])) + } + + @Test + fun `members shown different commitments sign different transcripts`() { + val params = IcebergDkg.Params.of(2, hostKeys(4), bytes32()) + val roots = (1..4).associateWith { bytes32() } + val commitments = (1..4).associateWith { IcebergDkg.round1(params, it, roots.getValue(it)) } + val run = run(4, 2) + val honest = IcebergDkg.transcriptHash(params, commitments, run.publicShares, run.groupKey) + val other = commitments + (2 to IcebergDkg.round1(params, 2, bytes32())) + assertNotEquals(honest, IcebergDkg.transcriptHash(params, other, run.publicShares, run.groupKey)) + } +} diff --git a/docs/group-lightning-wallet.md b/docs/group-lightning-wallet.md index 630c767c..368ca8d2 100644 --- a/docs/group-lightning-wallet.md +++ b/docs/group-lightning-wallet.md @@ -30,11 +30,13 @@ build chose differently, this table says so. | phase | state | |---|---| | 0 | done, except the two spikes (see below) | +| 1 | done: `IcebergDkg`, 11 tests, among them a byte-for-byte match against the library's dealer and a signature from every 2-of-4 and 3-of-7 quorum | | what the plan said | what it turned out to be | |---|---| | Phase 0's two spikes run against the testnet3 LSP | **not run.** Both need a channel that somebody pays into, and the regtest alternative means creating docker containers on a development machine that already runs other stacks. That should be somebody's deliberate act, not a side effect of a build. The signer's deadline is therefore a parameter, `RemoteIcebergFundingSigner.deadline`, and not a measured constant. Measuring it is the first thing to do with a funded testnet3 node | | the DKG goes in the bitcoin-kmp fork, beside `Iceberg.kt` | in the app, as `IcebergDkg` beside `GroupWalletDerivation`. It uses only `Iceberg`'s public API and SHA-256, so it needs nothing from inside the library, and putting it there would add a third nested fork branch to every bump. It moves down once it has been reviewed | +| a complaint round is left out, so equivocation is caught but not blamed | a reveal that does not match its commitment *is* blamed, as `Fault.BadReveal`. Only committing to two values in front of two members goes unblamed, and the transcript signature still catches it | | the kinds are reserved | in code: `GroupLightningEvents`, 30333-30349, with a test asserting the run is unbroken and touches no kind the app already dispatches on | | library phases land in the forks' `threshold` branches | on a new branch, `claude/group-lightning-wallet`, in `lightning-kmp-app` and in `experimental/lightning-kmp`. It is local and not pushed. The app's submodule pointer follows it, so a checkout of this branch needs those commits from the same machine until they are pushed |