feat: threshold ECDH's arithmetic, alone (group-threshold-ecdh, Phase 2)

Lagrange coefficients that can only scale a point, the npub's tweak replayed
with its signs, a holder's partial, a Chaum-Pedersen proof of it, and the
combination into NIP-44's conversation key. Every t-subset of a 3-of-5 key
gives quartz's own key; nothing in the package can build x or d.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-22 11:17:36 +02:00
1 parent c8df363318
commit 77e154d4f5
7 files changed
+542

No files matched your search

@@ -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
}
}
@@ -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
}
}
@@ -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<Int>): 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)
}
}
@@ -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<Long> = 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<ByteVector32>): 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())
}
}
}
@@ -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
}
}
@@ -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<Int, PublicKey>, 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
}
}