From d414cd104b06dd11945d2ff7f4817f5a9a9d488b Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 15:04:58 +0200 Subject: [PATCH] feat(wallet): guardian keys a parent grants a subgroup, and the leaves they sit in (Phase 1) GuardianDerivation: a group's guardian root, the child index, the grant a certificate carries, the 12-block leaf, the caterpillar tree, the descriptor fragment and the cache an ancestor signs a leaf with. Pinned vectors checked against an independent implementation. Co-Authored-By: Claude Opus 5.5 --- .../compose/managers/GroupWalletDerivation.kt | 6 +- .../compose/managers/GuardianDerivation.kt | 287 ++++++++++++++++++ .../managers/GuardianDerivationTest.kt | 204 +++++++++++++ 3 files changed, 494 insertions(+), 3 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianDerivation.kt create mode 100644 composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GuardianDerivationTest.kt diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletDerivation.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletDerivation.kt index fa49f211..548a1b91 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletDerivation.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletDerivation.kt @@ -71,7 +71,7 @@ object GroupWalletDerivation { private const val ACCOUNT_TAG = "bennu/group-wallet/account/v1" /** The largest unhardened BIP32 index. Hardened ones cannot be walked here. */ - private const val MAX_INDEX: Long = 0x7FFFFFFFL + internal const val MAX_INDEX: Long = 0x7FFFFFFFL /** * One account of one group on one network: the extended public key every @@ -236,7 +236,7 @@ object GroupWalletDerivation { } /** BIP32's `I_L` for one unhardened step: the scalar CKDpub adds, which a FROST cache takes as a plain tweak. */ - private fun childTweak(parent: DeterministicWallet.ExtendedPublicKey, index: Long): ByteVector32 = + internal fun childTweak(parent: DeterministicWallet.ExtendedPublicKey, index: Long): ByteVector32 = ByteVector32( Crypto.hmac512( parent.chaincode.toByteArray(), @@ -244,7 +244,7 @@ object GroupWalletDerivation { ).copyOfRange(0, 32) ) - private fun plainTweak(cache: TweakCache, tweak: ByteVector32, step: String): TweakCache = + internal fun plainTweak(cache: TweakCache, tweak: ByteVector32, step: String): TweakCache = when (val tweaked = cache.tweak(tweak, isXonly = false)) { is Either.Left -> throw IllegalArgumentException("Could not apply $step to the group's key", tweaked.value) is Either.Right -> tweaked.value.first diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianDerivation.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianDerivation.kt new file mode 100644 index 00000000..84d756c2 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianDerivation.kt @@ -0,0 +1,287 @@ +package com.machankura.bennu.compose.managers + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.DeterministicWallet +import fr.acinq.bitcoin.KeyPath +import fr.acinq.bitcoin.OP_CHECKSEQUENCEVERIFY +import fr.acinq.bitcoin.OP_CHECKSIGVERIFY +import fr.acinq.bitcoin.OP_PUSHDATA +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.PublicKey +import fr.acinq.bitcoin.Script +import fr.acinq.bitcoin.ScriptElt +import fr.acinq.bitcoin.ScriptEltMapping +import fr.acinq.bitcoin.ScriptTree +import fr.acinq.bitcoin.XonlyPublicKey +import fr.acinq.bitcoin.crypto.Pack +import fr.acinq.bitcoin.crypto.frost.TweakCache + +/** + * The keys an ancestor group holds in a subgroup's wallet, and the leaves they + * sit in. + * + * Every group has one guardian root, a tagged HMAC away from its threshold key, + * which it never hands out. What a parent writes into a child's birth + * certificate is that root one public BIP32 step further, at an index taken + * from the child's room id -- and, behind it, every key the parent's own + * ancestors gave the parent, each one step further at the same index: + * + * ``` + * I = HMAC-SHA512("bennu/group-wallet/guardian/v1", serP(K_A)) + * R_A = K_A + I[0:32]·G, chain code I[32:64] A's guardian root + * i(C) = taggedHash("bennu/group-wallet/guardian/child/v1", C)[0:4] & 0x7fffffff + * grant(C) = [R_A/i(C)] ++ [g/i(C) for g in grant(A)] nearest first + * L = xonly(g / network / account / change / index) a leaf key in one address + * ``` + * + * See `docs/group-wallet-guardians.md` for why each step is what it is. In + * short: a fresh key per child is what lets the parent *agree* to guard it, a + * root nobody publishes is what keeps a guardian spend unlinkable to a Marmot + * room, and re-deriving every inherited key per child is what keeps a parent's + * wallet and its child's from sharing a leaf. + * + * ### The same rule as the wallet's + * + * Every step is a public tweak of the threshold key, so a leaked leaf private + * key recovers the group's threshold key. Nothing reconstructs one: a leaf is + * signed for by a FROST session over [signingCache]. + */ +object GuardianDerivation { + /** + * How many blocks a coin has to sit confirmed before an ancestor can take + * it. One value for every ancestor at every distance -- see the doc's + * "Why 12, and why for everybody". Written into every guardian tag rather + * than assumed, so a later delay is a later account's tags, not a new format. + */ + const val ANCESTOR_DELAY: Long = 12L + + /** + * The key of the guardian root's HMAC. An input to every guardian key, so it + * is frozen the moment a certificate carries one: a rename moves every leaf. + */ + private const val ROOT_TAG = "bennu/group-wallet/guardian/v1" + + /** The tag of the hash a child's index is taken from. Frozen for the same reason. */ + private const val CHILD_TAG = "bennu/group-wallet/guardian/child/v1" + + /** + * One ancestor's guardian key as granted to one group: whose it is, and the + * extended public key that group's addresses derive that ancestor's leaves + * from. + * + * Held as the key and the chain code rather than as an + * [DeterministicWallet.ExtendedPublicKey], whose depth, parent fingerprint and + * path would make two grants of the same key compare unequal depending on how + * each was reached. Only the 65 bytes take part in a derivation. + */ + data class Guardian( + /** The ancestor's room id, which its leaf is named by. */ + val chatRoomId: String, + val publicKey: PublicKey, + val chainCode: ByteVector32, + val delay: Long = ANCESTOR_DELAY, + ) { + /** As a depth-0 extended key, the form every derivation below starts from. */ + val extendedPublicKey: DeterministicWallet.ExtendedPublicKey + get() = DeterministicWallet.ExtendedPublicKey( + publickeybytes = publicKey.value, + chaincode = chainCode, + depth = 0, + path = KeyPath.empty, + parent = 0L, + ) + + /** `xpub` on mainnet and `tpub` on every test network, as the wallet's own xpub is. */ + fun encoded(chain: Chain): String = + extendedPublicKey.encode(if (chain.isMainnet()) DeterministicWallet.xpub else DeterministicWallet.tpub) + + /** The same ancestor, one public step further, for [childChatRoomId]. */ + fun grantedTo(childChatRoomId: String): Guardian { + val child = extendedPublicKey.derivePublicKey(childIndex(childChatRoomId)) + return copy(publicKey = child.publicKey, chainCode = child.chaincode) + } + } + + /** A group's guardian root, and the cache that signs as it. */ + class Root internal constructor( + val publicKey: PublicKey, + val chainCode: ByteVector32, + internal val cache: TweakCache, + ) { + val extendedPublicKey: DeterministicWallet.ExtendedPublicKey + get() = DeterministicWallet.ExtendedPublicKey(publicKey.value, chainCode, 0, KeyPath.empty, 0L) + } + + /** One guardian's leaf in one address, and -- on the guardian's side -- the cache that signs as it. */ + data class Signing( + val leafKey: XonlyPublicKey, + val cache: TweakCache, + ) + + /** + * The guardian root of the group holding [thresholdPublicKey]. + * + * @throws IllegalArgumentException if the key is not a point, or the HMAC + * lands on an invalid scalar -- around 2^-127, and BIP32 throws at the same place. + */ + fun root(thresholdPublicKey: HexKey): Root { + val threshold = PublicKey(ByteVector(thresholdPublicKey.hexToByteArray())) + require(threshold.isValid()) { "the threshold key is not a valid point" } + + val i = Crypto.hmac512(ROOT_TAG.encodeToByteArray(), threshold.value.toByteArray()) + val tweak = i.copyOfRange(0, 32) + require(Crypto.isPrivKeyValid(tweak)) { "the guardian root landed on an invalid scalar" } + + val rootKey = threshold + PrivateKey(tweak).publicKey() + val cache = GroupWalletDerivation.plainTweak(TweakCache.create(threshold), ByteVector32(tweak), "the guardian root") + require(cache.tweakedPublicKey == rootKey.xOnly()) { "the guardian root's cache does not reach its key" } + + return Root(publicKey = rootKey, chainCode = ByteVector32(i.copyOfRange(32, 64)), cache = cache) + } + + /** + * The unhardened index a child's keys are derived at: the first four bytes + * of a tagged hash of its room id, top bit cleared. + */ + fun childIndex(childChatRoomId: String): Long { + val roomId = childChatRoomId.lowercase().hexToByteArray() + require(roomId.size == 32) { "a room id is 32 bytes, not ${roomId.size}" } + return Pack.int32BE(Crypto.taggedHash(roomId, CHILD_TAG).toByteArray(), 0).toLong() and GroupWalletDerivation.MAX_INDEX + } + + /** + * The network's index under a guardian key. Not BIP44's coin type: the + * networks this app knows, numbered once, so a guardian key granted for no + * network in particular gives each one unrelated leaves. + */ + fun networkIndex(chain: Chain): Long = when (chain) { + Chain.Mainnet -> 0L + Chain.Testnet3 -> 1L + Chain.Testnet4 -> 2L + Chain.Signet -> 3L + Chain.Regtest -> 4L + } + + /** + * What the group holding [thresholdPublicKey], whose room is [ownChatRoomId], + * writes into [childChatRoomId]'s certificate: its own root one step further, + * then each of [inherited] -- the keys its own certificate carries, nearest + * first -- one step further, in the same order. + * + * The same function a signer's device runs to check a proposed certificate: + * a certificate whose guardians are not exactly this list is not one the + * group agreed to. + */ + fun grant( + thresholdPublicKey: HexKey, + ownChatRoomId: String, + inherited: List, + childChatRoomId: String, + ): List { + val own = root(thresholdPublicKey).extendedPublicKey.derivePublicKey(childIndex(childChatRoomId)) + return listOf(Guardian(ownChatRoomId, own.publicKey, own.chaincode)) + + inherited.map { it.grantedTo(childChatRoomId) } + } + + /** [guardian]'s key one level above the leaves of [account]'s `change` branch. */ + private fun branchKey(guardian: Guardian, chain: Chain, account: Long, change: Long): DeterministicWallet.ExtendedPublicKey = + guardian.extendedPublicKey.derivePublicKey(listOf(networkIndex(chain), account, change)) + + /** [guardian]'s leaf key in the address at `change/index` of [account] on [chain]. */ + fun leafKey(guardian: Guardian, chain: Chain, account: Long, change: Long, index: Long): XonlyPublicKey = + branchKey(guardian, chain, account, change).derivePublicKey(index).publicKey.xOnly() + + /** + * ` OP_CHECKSIGVERIFY OP_CHECKSEQUENCEVERIFY` -- miniscript's + * `and_v(v:pk(key),older(delay))`. A delay of 1-16 is the single opcode for + * it, as miniscript writes it; anything else is a minimal number push. + */ + fun leafScript(key: XonlyPublicKey, delay: Long): List { + require(delay in 1L..0xFFFFL) { "a relative lock in blocks is 1 to 65535, not $delay" } + val lock = if (delay <= 16) ScriptEltMapping.code2elt.getValue(0x50 + delay.toInt()) + else OP_PUSHDATA(Script.encodeNumber(delay)) + return listOf(OP_PUSHDATA(key), OP_CHECKSIGVERIFY, lock, OP_CHECKSEQUENCEVERIFY) + } + + /** One leaf per guardian in the address at `change/index`, nearest first. */ + fun leaves(guardians: List, chain: Chain, account: Long, change: Long, index: Long): List = + guardians.map { ScriptTree.Leaf(leafScript(leafKey(it, chain, account, change, index), it.delay)) } + + /** + * The leaves as a caterpillar, nearest first: the first leaf at depth one, + * the rest one level further down each. Every guardian can act at the same + * moment, so the order decides only whose control block is shortest -- and + * the parent, who knows the child best, gets the cheapest spend. + */ + fun tree(leaves: List): ScriptTree { + require(leaves.isNotEmpty()) { "a tree needs a leaf" } + return leaves.dropLast(1).foldRight(leaves.last() as ScriptTree) { leaf, rest -> ScriptTree.Branch(leaf, rest) } + } + + /** The tree in the address at `change/index`, or null for an unguarded one. */ + fun treeAt(guardians: List, chain: Chain, account: Long, change: Long, index: Long): ScriptTree? = + guardians.takeIf { it.isNotEmpty() }?.let { tree(leaves(it, chain, account, change, index)) } + + /** + * The tree half of a `tr()` descriptor over a whole branch: `{a,{b,c}}`, the + * same caterpillar [tree] builds, each leaf ranged over the branch's indices. + */ + fun descriptorTree(guardians: List, chain: Chain, account: Long, change: Long): String { + require(guardians.isNotEmpty()) { "a tree needs a leaf" } + val leaves = guardians.map { guardian -> + val path = "${networkIndex(chain)}/$account/$change/*" + "and_v(v:pk(${guardian.encoded(chain)}/$path),older(${guardian.delay}))" + } + return leaves.dropLast(1).foldRight(leaves.last()) { leaf, rest -> "{$leaf,$rest}" } + } + + /** + * The room ids an ancestor walks from its own root down to [childChatRoomId], + * through the line of descent [guardians] -- a certificate's guardian list, + * nearest first -- names. Null when [ancestorChatRoomId] is not among them. + * + * For `guardians = [A1, A2, A3]` and `ancestor = A3`, that is `[A2, A1, C]`: + * the generations below A3, its own child first. + */ + fun lineage(guardians: List, childChatRoomId: String, ancestorChatRoomId: String): List? { + val position = guardians.indexOfFirst { it.chatRoomId.equals(ancestorChatRoomId, ignoreCase = true) } + if (position < 0) return null + return guardians.take(position).map { it.chatRoomId }.reversed() + childChatRoomId + } + + /** + * The cache the group holding [thresholdPublicKey] signs a leaf with: its + * guardian root, then one plain step per generation down [lineage], then + * the network, the account and the address. Every step is a plain tweak, so + * the cache tracks exactly the point the descendant derives from its grant. + * + * No TapTweak follows: a script-path signature is by the leaf key itself. + */ + fun signingCache( + thresholdPublicKey: HexKey, + lineage: List, + chain: Chain, + account: Long, + change: Long, + index: Long, + ): Signing { + val root = root(thresholdPublicKey) + val path = lineage.map(::childIndex) + listOf(networkIndex(chain), account, change, index) + + var key = root.extendedPublicKey + var cache = root.cache + path.forEach { step -> + cache = GroupWalletDerivation.plainTweak(cache, GroupWalletDerivation.childTweak(key, step), "guardian step $step") + key = key.derivePublicKey(step) + } + + val leafKey = key.publicKey.xOnly() + require(cache.tweakedPublicKey == leafKey) { "the guardian cache does not reach its leaf key" } + return Signing(leafKey = leafKey, cache = cache) + } +} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GuardianDerivationTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GuardianDerivationTest.kt new file mode 100644 index 00000000..6c8debb2 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GuardianDerivationTest.kt @@ -0,0 +1,204 @@ +package com.machankura.bennu.compose.managers + +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.Descriptor +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.Script +import fr.acinq.bitcoin.ScriptTree +import fr.acinq.secp256k1.Hex +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * The guardian keys, pinned and walked. + * + * The pinned vector freezes the two tags and the order of every input, so a + * change to either fails here rather than moving every leaf a certificate has + * already granted. The rest is the one property everything else rests on: the + * key a descendant derives from its grant and the key an ancestor's cache signs + * as are the same point, at every depth and both parities. + */ +class GuardianDerivationTest { + /** A threshold key nobody needs the secret of: the test is about public derivation. */ + private fun thresholdKey(seed: Int): String = + PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))).publicKey().toString() + + private val rootKey = thresholdKey(0x600d) + private val middleKey = thresholdKey(0xbeef) + private val childKey = thresholdKey(0xcafe) + + private val rootRoom = SharedKeyDerivation.marmotGroupId(rootKey) + private val middleRoom = SharedKeyDerivation.marmotGroupId(middleKey) + private val childRoom = SharedKeyDerivation.marmotGroupId(childKey) + + /** root → middle → child, as the certificates would carry them. */ + private val middleGrant = GuardianDerivation.grant(rootKey, rootRoom, inherited = emptyList(), childChatRoomId = middleRoom) + private val childGrant = GuardianDerivation.grant(middleKey, middleRoom, inherited = middleGrant, childChatRoomId = childRoom) + + @Test + fun `the guardian root and the child index are pinned`() { + // Frozen. A failure here is not a test to update: every certificate + // already signed grants keys under these, and changing them moves every + // leaf in every guarded address. + val root = GuardianDerivation.root(rootKey) + assertEquals(PINNED_ROOT_KEY, root.publicKey.toString()) + assertEquals(PINNED_ROOT_CHAIN_CODE, root.chainCode.toHex()) + assertEquals(PINNED_CHILD_INDEX, GuardianDerivation.childIndex(middleRoom)) + assertEquals( + PINNED_LEAF, + GuardianDerivation.leafKey(childGrant[1], Chain.Mainnet, account = 0, change = 0, index = 7).value.toHex() + ) + } + + @Test + fun `a child index is unhardened and case-blind`() { + val index = GuardianDerivation.childIndex(childRoom) + assertTrue(index in 0L..0x7FFFFFFFL) + assertEquals(index, GuardianDerivation.childIndex(childRoom.uppercase())) + assertFailsWith { GuardianDerivation.childIndex("abcd") } + } + + @Test + fun `a grant is the parent's root and its own grant, each one step further`() { + assertEquals(listOf(rootRoom), middleGrant.map { it.chatRoomId }) + assertEquals(listOf(middleRoom, rootRoom), childGrant.map { it.chatRoomId }) + + val rootOfRoot = GuardianDerivation.root(rootKey).extendedPublicKey + val rootOfMiddle = GuardianDerivation.root(middleKey).extendedPublicKey + val middleIndex = GuardianDerivation.childIndex(middleRoom) + val childIndex = GuardianDerivation.childIndex(childRoom) + + assertEquals(rootOfMiddle.derivePublicKey(childIndex).publicKey, childGrant[0].publicKey) + assertEquals( + rootOfRoot.derivePublicKey(middleIndex).derivePublicKey(childIndex).publicKey, + childGrant[1].publicKey, + "the root's key in the grandchild is R_root / i(M) / i(C)" + ) + assertEquals(GuardianDerivation.ANCESTOR_DELAY, childGrant[1].delay) + } + + @Test + fun `an ancestor's cache signs as the leaf its descendant derives, at every depth`() { + val parities = mutableSetOf() + + (1..8).forEach { seed -> + val parent = thresholdKey(seed) + val parentRoom = SharedKeyDerivation.marmotGroupId(parent) + val grandparent = thresholdKey(seed + 100) + val grandparentRoom = SharedKeyDerivation.marmotGroupId(grandparent) + + val parentGrant = GuardianDerivation.grant(grandparent, grandparentRoom, emptyList(), parentRoom) + val grant = GuardianDerivation.grant(parent, parentRoom, parentGrant, childRoom) + + listOf(Chain.Mainnet, Chain.Regtest).forEach { chain -> + (0L..2L).forEach { index -> + listOf(parent to parentRoom, grandparent to grandparentRoom).forEachIndexed { position, (key, room) -> + val lineage = GuardianDerivation.lineage(grant, childRoom, room)!! + val signing = GuardianDerivation.signingCache(key, lineage, chain, account = 0, change = 1, index = index) + val derived = GuardianDerivation.leafKey(grant[position], chain, account = 0, change = 1, index = index) + assertEquals(derived, signing.leafKey) + assertEquals(derived, signing.cache.tweakedPublicKey) + parities += grant[position].extendedPublicKey + .derivePublicKey(listOf(GuardianDerivation.networkIndex(chain), 0L, 1L, index)) + .publicKey.isEven() + } + } + } + } + + assertEquals(setOf(true, false), parities, "the sweep has to cover both parities of a leaf key") + } + + @Test + fun `the lineage runs from the ancestor's child down to the descendant`() { + val a1 = "11".repeat(32) + val a2 = "22".repeat(32) + val a3 = "33".repeat(32) + val c = "cc".repeat(32) + val grant = listOf(a1, a2, a3).map { GuardianDerivation.Guardian(it, middleGrant[0].publicKey, middleGrant[0].chainCode) } + + assertEquals(listOf(c), GuardianDerivation.lineage(grant, c, a1)) + assertEquals(listOf(a2, a1, c), GuardianDerivation.lineage(grant, c, a3)) + assertNull(GuardianDerivation.lineage(grant, c, "44".repeat(32))) + } + + @Test + fun `no two places share a leaf`() { + val siblingRoom = SharedKeyDerivation.marmotGroupId(thresholdKey(0xd00d)) + val sibling = GuardianDerivation.grant(middleKey, middleRoom, middleGrant, siblingRoom) + + fun leaf(guardian: GuardianDerivation.Guardian, chain: Chain = Chain.Mainnet, account: Long = 0) = + GuardianDerivation.leafKey(guardian, chain, account, change = 0, index = 0) + + val leaves = listOf( + leaf(childGrant[0]), + leaf(childGrant[1]), + leaf(sibling[0]), + leaf(sibling[1]), + leaf(middleGrant[0]), + leaf(childGrant[1], Chain.Regtest), + leaf(childGrant[1], account = 1), + ) + assertEquals(leaves.size, leaves.toSet().size, "siblings, a parent and its child, networks and accounts all differ") + + val room = SharedKeyDerivation.derive(rootKey).publicKey + assertTrue(leaves.none { it == room }, "no leaf is a room key") + } + + @Test + fun `a leaf is and_v(v_pk, older 12) and 36 bytes`() { + val key = GuardianDerivation.leafKey(childGrant[0], Chain.Mainnet, 0, 0, 0) + val script = Script.write(GuardianDerivation.leafScript(key, GuardianDerivation.ANCESTOR_DELAY)) + + assertEquals(36, script.size) + assertEquals("20" + key.value.toHex() + "ad5cb2", Hex.encode(script)) + // Past sixteen the lock is a number push rather than an opcode. + assertEquals("02e803", Hex.encode(Script.write(GuardianDerivation.leafScript(key, 1000).subList(2, 3)))) + assertFailsWith { GuardianDerivation.leafScript(key, 0) } + } + + @Test + fun `the tree is a caterpillar, nearest first`() { + val leaves = (0..2).map { ScriptTree.Leaf(ByteVector(byteArrayOf(it.toByte())), Script.TAPROOT_LEAF_TAPSCRIPT) } + + assertEquals(leaves[0], GuardianDerivation.tree(leaves.take(1))) + assertEquals(ScriptTree.Branch(leaves[0], ScriptTree.Branch(leaves[1], leaves[2])), GuardianDerivation.tree(leaves)) + + // The control block grows by one hash per level: the parent's is the shortest. + val internalKey = GuardianDerivation.leafKey(childGrant[0], Chain.Mainnet, 0, 0, 0) + val tree = GuardianDerivation.tree(leaves) + assertEquals(65, Script.ControlBlock.build(internalKey, tree, leaves[0]).size()) + assertEquals(97, Script.ControlBlock.build(internalKey, tree, leaves[2]).size()) + } + + @Test + fun `the descriptor tree is the same caterpillar, ranged`() { + val tree = GuardianDerivation.descriptorTree(childGrant, Chain.Mainnet, account = 0, change = 0) + val parent = childGrant[0].encoded(Chain.Mainnet) + val root = childGrant[1].encoded(Chain.Mainnet) + + assertEquals("{and_v(v:pk($parent/0/0/0/*),older(12)),and_v(v:pk($root/0/0/0/*),older(12))}", tree) + assertTrue(childGrant[0].encoded(Chain.Signet).startsWith("tpub")) + // A descriptor with this tree in it is one bitcoin-kmp can checksum. + assertEquals(8, Descriptor.checksum("tr(${parent}/0/*,$tree)").length) + assertNotEquals(tree, GuardianDerivation.descriptorTree(childGrant, Chain.Mainnet, account = 0, change = 1)) + } + + /** + * Checked against an independent implementation -- HMAC-SHA512, SHA-256 and + * point arithmetic written out in plain Python -- before they were pinned, so + * they are BIP32 and the doc's formulas rather than this code's own output. + */ + private companion object { + const val PINNED_ROOT_KEY = "02437ef22d50eb95d81d3344b49d4872b23881fbd46f4c658fabfe5f7753db84e9" + const val PINNED_ROOT_CHAIN_CODE = "089593979b6055ff3b34dd2bc378160405108766f34c4804a37cf909a1246530" + const val PINNED_CHILD_INDEX = 977297025L + const val PINNED_LEAF = "ae5078c25c84b630c7ac199cdf86fb3f32b36c677f63415d3405222623359927" + } +}