From 75bdb25783d2711c6da9fcc9a4026225689043e1 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 15:00:37 +0200 Subject: [PATCH 01/15] docs: plan guardian leaves for ancestor groups in a subgroup's wallet The parent signs a guardian key for the child into its birth certificate, beside its own ancestors' keys derived one step further, and the child's guarded wallet puts each in a 12-block leaf. Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 3 + docs/group-wallet-guardians.md | 415 +++++++++++++++++++++++++++++++++ 2 files changed, 418 insertions(+) create mode 100644 docs/group-wallet-guardians.md diff --git a/docs/README.md b/docs/README.md index 5c195699..5fc4c619 100644 --- a/docs/README.md +++ b/docs/README.md @@ -12,6 +12,7 @@ silent, or a decision that looked arbitrary and was not. | [frost-batch-signing.md](./frost-batch-signing.md) | signing several events in one ceremony — why one nonce can never cover two messages, and the phased schema, wire and UI work that follows from it | | [group-chain-wallet.md](./group-chain-wallet.md) | an on-chain wallet the group's threshold key holds, modelled on Phoenix's final wallet — why the path is BIP86's unhardened tail under a public account step, why each input is a batch item with its own cache, and the seven checks a member makes before signing a spend | | [group-send-an-amount.md](./group-send-an-amount.md) | sending an amount in sats from the group's wallet, with change — why the gate as written could never lift and is removed in favour of the mainnet cap, the decimal point the gated form multiplies by ten, and change addresses reserved like coins | +| [group-wallet-guardians.md](./group-wallet-guardians.md) | letting an ancestor group spend from a subgroup's wallet through a taproot leaf — why the parent signs the guardian keys into the child's certificate, why every inherited key is derived one step further per child, and why every ancestor waits 12 blocks | | [group-wallet-addresses.md](./group-wallet-addresses.md) | listing the group wallet's receive addresses as Phoenix lists its swap-in ones — why the list stops at the current address plus two, why a paid address past that still shows, and why a used address can be copied but never shown as a QR code | | [frost-session-resend.md](./frost-session-resend.md) | asking the members who never got a signing proposal to look again — why a proposer can repeat only what it wrote, why a member's availability signal needs no repeating, and the one half that has to come from the silent member's own device | | [marmot-membership.md](./marmot-membership.md) | how members join an MLS group, and the epoch race that makes a missing member look like a successful invite | @@ -47,6 +48,8 @@ The group-wallet-addresses note is a phased plan that has been built, and is the group-chain-wallet note's Phase 5 taken one screen further: read that note's Phases 4 and 5 first, and its own table of where the build chose differently before the code. +The group-wallet-guardians note is a phased plan; it assumes the subgroups and group-chain-wallet notes, and changes one sentence in +each. The Material Design note is a phased plan that has not been built, and is the only one about what the app looks like rather than what it does; read the jvm-target note first if you want to know why its adaptive-layout phase exists. diff --git a/docs/group-wallet-guardians.md b/docs/group-wallet-guardians.md new file mode 100644 index 00000000..b1032c08 --- /dev/null +++ b/docs/group-wallet-guardians.md @@ -0,0 +1,415 @@ +# Guardians: an ancestor group's leaf in a subgroup's wallet + +A subgroup's onchain wallet can carry its ancestry in its addresses: one taproot +leaf per ancestor group, each spendable by that ancestor's quorum, so the root of +a hierarchy can move the coins of any group beneath it. The child's own spends +stay on the key path, look like any single-key taproot spend, and never reveal +that the tree exists. + +Read [subgroups.md](./subgroups.md) and [group-chain-wallet.md](./group-chain-wallet.md) +first. This builds on the birth certificate from the first and the account +derivation from the second, and it changes one sentence in each. + +**A phased plan**, written against the code as it stood at `409be6db`, with the +`lightning-kmp-app` submodule at `e0d2b82`. + +The headline: **the parent puts a guardian key for the child into the child's +birth certificate, beside the keys its own ancestors gave it, each derived one +public step further for this child. Each becomes a leaf +` OP_CHECKSIGVERIFY 12 OP_CHECKSEQUENCEVERIFY` in every address of the child's +wallet.** Every ancestor can take a coin once it has 12 confirmations. The +ancestor's quorum signs for its leaf with the FROST session it already runs, +under plain tweaks of its own threshold key. + +--- + +## What this reverses, and why it is still the child's choice + +[subgroups.md](./subgroups.md#what-this-does-not-do) says: + +> A subgroup cannot sign for its parent, and the parent cannot sign for it. […] +> If delegation is ever wanted it is a different mechanism and it should not be +> built on top of this one silently. + +This is that mechanism, and it is not silent. It takes two signatures, one from +each side: + +- the **parent's** quorum signs the guardian keys into the certificate, so the + parent agrees to be a guardian and every one of its signers' devices has + checked the keys it is vouching for; +- the **child's** quorum signs a wallet statement that names them, so the child + agrees to be guarded. + +The certificate on its own delegates nothing. A child that never opens a guarded +wallet has a certificate with keys in it and no address that uses them. + +**The parent cannot impose this.** The child's threshold key is the child's. Its +quorum can always pay to a plain BIP86 address under its own key, and no script +in any address can stop it. Bennu opens a guarded wallet by default for a child +whose certificate carries guardian keys, and offers a plain one beside it; that +is a client's default, not a cryptographic rule, and the UI never describes it +as one. + +**The child gives up a real thing.** An ancestor can take any coin in the wallet +that has been confirmed for two hours, without the child's agreement and without +warning — the first the child learns of it is a spend none of its members +signed. That is the honest description of "the root can spend from its +descendants". + +--- + +## The shape of an address + +``` + Q = P + H_TapTweak(P ‖ root)·G output key + ╱ ╲ + key path: P the child's own key, as today + root + ╱ ╲ + leaf(parent) • + ╱ ╲ + leaf(grandparent) • + ╱ ╲ + … leaf(root group) +``` + +- `P` is exactly today's internal key, `account(K_child, network, n)/change/index`. + A spend by the child is a key-path spend, signed exactly as today; the only + change on that side is that the final tweak is BIP341's script-path tweak over + `root` rather than BIP86's empty one. +- The leaves form a caterpillar, nearest ancestor shallowest. Every ancestor can + act at the same moment, so the order decides only cost: the parent's control + block is the shortest and the root's the longest, at `33 + 32·(k − 1)` bytes + for `k` ancestors. +- One ancestor is a tree of one leaf, with a 33-byte control block. + +### The leaf + +``` + OP_CHECKSIGVERIFY 12 OP_CHECKSEQUENCEVERIFY +``` + +Miniscript's `and_v(v:pk(L),older(12))`. The delay is a BIP68 relative lock in +blocks and counts from the confirmation of the coin being spent, not from +anything the group did: a coin with 12 confirmations is the guardian's to take, +and one that arrived or was moved within the last two hours is not. `12` is the +single opcode `OP_12`, so the script is 36 bytes. + +**Why 12, and why for everybody.** It is `GuardianDerivation.ANCESTOR_DELAY`, one +constant, the same at every distance. What it buys: + +- **Not autonomy.** Two hours is not long enough for a child to notice a coin + coming within reach and move it. In practice this is an override, and it is + meant as one: ancestors have control now, not as a last resort. +- **The child's own spends always go first.** A guardian cannot race the child + for a payment that has only just arrived, nor take change from a spend the + child made an hour ago. +- **It is a relative lock**, so every guardian input carries `nSequence = 12` in + a version-2 transaction. That is far below `GroupSpend.MAX_SEQUENCE`, so a + guardian spend still signals replaceability and *Bump the fee* still works. + +The delay is written into every `guardian` tag rather than assumed, so a later, +different delay is a later account's tags, not a new format. + +--- + +## The guardian keys + +### Each group has one guardian root, which it never hands out + +``` +I = HMAC-SHA512(key = "bennu/group-wallet/guardian/v1", + data = serP(K_A)) +R_A = K_A + I[0:32]·G plain tweak, like the wallet's account step +c_A = I[32:64] + +(R_A, c_A) A's guardian root, an xpub at depth 0 +``` + +The same shape as `GroupWalletDerivation.account` without the network and the +account number, which come lower down. It is not the room key: a room id is the +`h` tag on every message the room publishes, so a relay knows it, and a leaf +built on it would tie an onchain spend to a Marmot room for anyone who has +watched the relay. Nothing about `R_A` is published anywhere. + +### A child's index comes from its room id + +``` +i(C) = taggedHash("bennu/group-wallet/guardian/child/v1", C)[0:4] & 0x7fffffff +``` + +Unhardened, so anyone holding the parent's copy of an xpub can take the next +step, and nobody holding only the child's copy can go back up or across to a +sibling. + +### What A writes into C's certificate + +``` +guardians(C) = [ R_A / i(C) ] A's own key, granted to C + ++ [ g / i(C) for g in guardians(A) ] A's ancestors' keys, as A received them +``` + +Nearest first, each tagged with the room it belongs to. A root group — or any +group whose own certificate carries no guardian keys — writes only its own entry. + +For root → middle `M` → grandchild `C`: + +``` +cert(M), signed by root: [ R_root/i(M) ] +cert(C), signed by M: [ R_M/i(C), R_root/i(M)/i(C) ] +``` + +Re-deriving each inherited key at every level is what keeps a parent's wallet and +its child's from sharing a leaf: the root's key in `M`'s wallet is +`…/i(M)/n/a/…` and in `C`'s it is `…/i(M)/i(C)/n/a/…`. And siblings cannot link +each other: `C₁` holds `R_A/i(C₁)` and cannot compute `R_A/i(C₂)` without `R_A`'s +chain code. + +`i(C)` is 31 bits, so two siblings could share an index; the odds pass even at +around 55,000 children of one parent, and the consequence is only that those two +siblings' guardian leaves become linkable onchain. + +### The leaf for one of C's addresses + +At network `n`, account `a` and address `change/index`: + +``` +L = xonly( guardian / n / a / change / index ) + n: 0 mainnet, 1 testnet3, 2 testnet4, 3 signet, 4 regtest +``` + +So the root's leaf in `C`'s receive address 7 of mainnet account 0 is +`R_root / i(M) / i(C) / 0 / 0 / 0 / 7`. Everything below the guardian root is +ordinary CKDpub, so the descriptor stays one Bitcoin Core imports: + +``` +tr([fp]xpub_C/0/*,{and_v(v:pk(xpub_M→C/0/0/0/*),older(12)),and_v(v:pk(xpub_root→C/0/0/0/*),older(12))}) +``` + +### Who checks what + +- **When A's quorum signs C's certificate**, each signer's device rederives + `R_A/i(C)` from `K_A`, and checks every inherited entry is exactly the matching + entry of A's own verified certificate one step further, in the same order. A + coordinator cannot add, drop or swap a key without every honest signer's + device refusing the proposal. +- **The child trusts the parent's quorum for the inherited entries**, and it is + no new trust: that quorum can already take every coin through its own leaf. + A reader holding the parent's certificate can check them anyway, since each is + a public step from an entry one certificate up. +- **When ancestor X signs for a coin in descendant C**, its FROST cache is plain + tweaks all the way down the line of descent from X: + +```kotlin +TweakCache.create(K_X) + .tweak(I[0:32], isXonly = false) // guardian root + .tweak(IL(i(A1)), isXonly = false) // one step per generation, X's child first + … + .tweak(IL(i(C)), isXonly = false) + .tweak(IL(n), isXonly = false) + .tweak(IL(a), isXonly = false) + .tweak(IL(change), isXonly = false) + .tweak(IL(index), isXonly = false) +// xonly(cache.tweakedPublicKey) == L; no TapTweak, since it signs as the leaf key itself +``` + + X reads the line of descent off the room ids in C's certificate, and checks + that the entry there for X is the key this walk reaches before it signs + anything. There are no x-only tweaks before the last step, so there is no + parity to get wrong. + +--- + +## The statement + +The opt-in is the child's `GroupWalletStatementEvent`, signed by its quorum as +today, with two kinds of tag added: + +``` +["guardian", , , , "12"] one per ancestor, nearest first +["birth_certificate", ] +["descriptor", tr(…,{…}), "receive"] as today, with the tree +["descriptor", tr(…,{…}), "change"] +``` + +`verifiedAgainst` grows the same way: it rederives the account from `K_child`, +checks the certificate certifies this room, checks the `guardian` tags are +exactly the certificate's entries with the delay this build writes, rebuilds the +tree, and compares the descriptors. The statement stays *a record that the group +agreed, not a source of keys*. Carrying the certificate makes it self-contained: +a member welcomed into the child after its birth, who holds no key state, can +still check every address — the gap [subgroups.md](./subgroups.md#what-this-does-not-do) +names, closed for the wallet. + +Three rules, each closing a way to lose coins: + +1. **A guarded statement outranks a plain one for the same account.** An account + opened guarded stays guarded; a later plain statement for it, from a client + that predates this, is ignored rather than allowed to move every address. +2. **A guardian set is fixed for its account.** Among guarded statements for one + account the earliest decides the guardians, and a later one naming others is + ignored. Changing who guards a wallet is another account. +3. **Old clients refuse it**, which is the right failure: `verifiedAgainst` + compares the descriptors byte for byte, and theirs have no tree, so a client + that predates this rejects the statement rather than handing out unguarded + addresses under the guarded account's name. + +What an old client can still do is see no wallet and open a plain one. Rule 1 +keeps every new client on the guarded addresses, but the old client then hands +out plain ones that new clients do not watch. That is a mixed-version risk, and +it is why the guarded wallet ships behind a gate that stays shut on mainnet. + +### The rule from the wallet note, restated + +[group-chain-wallet.md](./group-chain-wallet.md#why-each-level-is-what-it-is) +says having no script tree is a security property: a member can check alone that +no back door is hidden in an address. That stays true with one word changed — +**every member derives every address, tree included, and compares it byte for +byte.** The tree is a pure function of the child's key, the account and a +certificate every member verifies, so a proposer still cannot slip a leaf in. + +--- + +## How an ancestor finds the coins + +To spend from a descendant, an ancestor's members need the descendant's account +xpub and its tree. Both are in the descendant's guarded statement, which checks +out against things the ancestor can verify alone: it is signed by the +descendant's room id, the certificate inside it is signed by the descendant's +parent and certifies that room, the certificate's `subgroup_key` is the key the +xpub rederives from, and the guardian entry for the ancestor is the key its own +walk reaches. + +What the ancestor does not have is the statement: it is signed in the child's +room, and the root's members are not in it. So a member who sits in both rooms +**forwards** it, as an ordinary message in the ancestor's MLS room — never to a +relay, under the same `NEVER_BROADCAST` rule. The forwarder is trusted with +nothing but the act of forwarding. + +That depends on membership overlapping, which it does at birth — a child's +admins are chosen from its parent's members — and may not later. A grandchild +whose middle group no longer shares a member with the root has a root leaf in +every address and a root that cannot find a coin to use it on. A statement +forwarded into the middle group can be forwarded again from there, so overlap is +needed one level at a time, not between the grandchild and the root directly. + +Once it has the statement, the ancestor watches the descendant's addresses on the +Electrum client it already holds — unknown script hashes are ignored, so this +costs subscriptions and nothing else — and its wallet screen grows a *Guarded +wallets* section. + +--- + +## A guardian spend, end to end + +An ancestor's FROST session in the ancestor's room, with the existing proposal, +approval and completion steps, and three differences. + +**The claim rides in tags, not PSBT fields.** bitcoin-kmp does not parse +`tap_leaf_script`, `tap_merkle_root` or `tap_script_sig` — they land in +`unknown`, which is why `GroupSpend.check` refuses any input carrying them. +Rather than teach the library those fields, keep the refusal and put the claim +where a spend's other claims already go: the proposal names the descendant +wallet, and each input's `tap_bip32_derivation` names its place under the +descendant's account, exactly as a child's own spend does. Every signer then +rebuilds the leaf, the tree, the control block and the script-path sighash from +the forwarded statement it holds. A proposer who names the wrong place gets a +sighash nobody else computes. + +**Sequence and version.** `check` grows one rule: a guardian input's sequence is +exactly 12, and — on the proposer's device, which can see the chain — the coin +already has 12 confirmations, so a spend that cannot go in the next block is not +put in front of a quorum. Signers without a node rely on the script: a coin +spent too early is a transaction nobody can mine, never a loss. + +**The witness** is `[sig, script, control block]`, from +`Script.witnessScriptPathPay2tr`, and `correctlySpends` is still the last word. + +### What the child sees + +Nothing until it happens. `GroupTransactionWatcher` on a child's device sees one +of its coins spent by a transaction it has no row for, reads the witness, finds +a leaf it can name, and writes a transcript line saying which ancestor took it. + +### What it costs onchain + +A key-path input's witness is 66 weight units. A guardian input with one ancestor +is about 137 — the signature, the 36-byte script and a 33-byte control block — +so about 18 vbytes more, and 8 vbytes more for each further level of depth. Only +paid when a guardian spends; the child's own spends cost exactly what they cost +today. + +### What it reveals + +| spend | a chain observer learns | +|---|---| +| the child, key path | nothing beyond any single-key taproot spend, as today | +| a guardian | that the output had a script tree; the one leaf used and its delay; its depth in the tree, so a lower bound on the hierarchy's depth. The leaf key is unlinkable to any room id | + +--- + +## Phases + +One commit each. + +1. **`GuardianDerivation`**, pure, commonMain: `ANCESTOR_DELAY`, the guardian + root, the child index, the grant, the leaf key, script and tree, the + descriptor fragment, and the signing cache. Vectors: the root and grant by + point arithmetic and by cache, agreeing; a three-level grant; a tree of one + and of three; the descriptor through bitcoin-kmp's checksum. +2. **Signing a leaf.** A jvmTest in the shape of `GroupSpendSigningJvmTest`: a + parent ceremony's shares sign a script-path spend of a child's coin, and + `correctlySpends` accepts it at sequence 12 and refuses it at 11. +3. **The certificate carries the keys.** `guardian` tags on + `SubgroupBirthCertificateEvent`, written by `proposeBirthCertificate` from + the parent's key and its own verified certificate, and checked by every + parent signer before a certificate proposal is accepted. +4. **The guarded statement.** Tags, `read`, `verifiedAgainst`, an `Account` that + knows its guardians, and the three rules in `GroupWallet`. +5. **The child's side.** Addresses with the tree, `GroupSpend` checking against + them, and the wallet screen opening a guarded wallet when the room's + certificate carries guardian keys. +6. **Forwarding upward**, and the ancestor watching what it was forwarded. +7. **The guardian spend**: the builder, the proposal, `GroupSpend`'s guardian + arm, `FrostSigningManager` signing with the guardian cache over the + script-path sighash, and the witness at completion. +8. **The child's notice**: the watcher naming the ancestor that spent. +9. **Rollout**: `GroupWalletRollout.GUARDIANS`, on for test networks, shut on + mainnet until a guardian spend has been made on signet by a real three-level + hierarchy. + +--- + +## What this does not do + +**It does not guard a wallet that is already open.** A subgroup that opened a +plain wallet before its certificate carried keys keeps it. Guarding it would be a +second account and a spend into it, and the wallet screen shows one account per +room today. + +**It does not reach a subgroup certified before this.** Its certificate has no +keys. Its parent can sign a fresh one — certificates are replaceable per child, +newest winning — but nothing here prompts it to. + +**It does not survive a re-keyed ancestor.** A leaf is bound to the ancestor's +threshold key, so to the shares of the ceremony that made it, including the +shares of members who have since left. This is the wallet note's *removal from +the group does not un-know a key*, inherited one level down. + +**It does not tell the child before it happens**, and it does not constrain where +the coins go. "Only back into the child, at a new address" is a covenant, and +there is none on mainnet to write it with (`OP_CHECKTEMPLATEVERIFY`, +`OP_VAULT`). + +## Appendix — what was considered and rejected + +| idea | why not | +|---|---| +| derive the child's key from the parent's | the child is then the parent wearing a different hat — [subgroups.md](./subgroups.md#why-the-key-is-fresh-rather-than-derived) | +| the ancestor's room key as the leaf key, tweaked by the child's chain code | the parent never agrees to anything, the child has to find every ancestor's room key itself, and the first tweak has to be x-only to agree on parity. A key the parent signs into the certificate fixes all three | +| the ancestor's threshold key `K_A` | the child does not have it, and handing it over gives every child member the ancestor's whole wallet and room identity | +| a `k`-of-`n` `OP_CHECKSIGADD` over the ancestor's admins' own keys | it reveals the admins onchain, changes with every membership change, and bypasses the quorum the ancestor's FROST key already is | +| passing inherited keys down unchanged | a grandchild's leaves would equal its parent's wallet's at the same index, and a guardian spend from one would link the two | +| the whole certificate chain in the statement | nobody needs it to be safe — the parent's quorum vouches for the inherited keys and already holds more power than they give — and nesting signed events inside signed events escapes JSON once per level | +| the tree in PSBT fields | bitcoin-kmp does not parse them; every signer rebuilds them anyway | +| delays escalating with distance | asked for and replaced: every ancestor at 12 blocks, for now | From d414cd104b06dd11945d2ff7f4817f5a9a9d488b Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 15:04:58 +0200 Subject: [PATCH 02/15] 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" + } +} From 6a4bea0cf49e7fafa59fbd6f1167bc2c948bb628 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 15:06:11 +0200 Subject: [PATCH 03/15] test(wallet): an ancestor's shares spend a descendant's coin through its leaf (Phase 2) Real ChillDKG, real FROST, judged by correctlySpends: a parent's leaf and a grandparent's one level down both spend, sequence 11 does not, and the room key's, the guardian root's, a sibling's and the next address's caches all sign for keys the leaf does not name. Co-Authored-By: Claude Opus 5.5 --- .../managers/GuardianSpendRoundTest.kt | 240 ++++++++++++++++++ 1 file changed, 240 insertions(+) create mode 100644 composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GuardianSpendRoundTest.kt diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GuardianSpendRoundTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GuardianSpendRoundTest.kt new file mode 100644 index 00000000..3cd67962 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GuardianSpendRoundTest.kt @@ -0,0 +1,240 @@ +package com.machankura.bennu.compose.managers + +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.ByteVector64 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.OutPoint +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.PublicKey +import fr.acinq.bitcoin.Satoshi +import fr.acinq.bitcoin.Script +import fr.acinq.bitcoin.ScriptFlags +import fr.acinq.bitcoin.ScriptTree +import fr.acinq.bitcoin.ScriptWitness +import fr.acinq.bitcoin.SigHash +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxId +import fr.acinq.bitcoin.TxIn +import fr.acinq.bitcoin.TxOut +import fr.acinq.bitcoin.crypto.dkg.chill.ChillDKG +import fr.acinq.bitcoin.crypto.dkg.chill.ParticipantFinalizeResult +import fr.acinq.bitcoin.crypto.frost.IndividualNonce +import fr.acinq.bitcoin.crypto.frost.SecretNonce +import fr.acinq.bitcoin.crypto.frost.Session +import fr.acinq.bitcoin.crypto.frost.TweakCache +import fr.acinq.secp256k1.Hex +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFails +import kotlin.test.assertTrue + +/** + * An ancestor group spending a descendant's coin through its guardian leaf, + * against real ChillDKG and real FROST, with no database and no manager. + * + * The counterpart of `GroupWalletSpendRoundTest` for the script path, and judged + * the same way: by `correctlySpends`, the script interpreter, which is the only + * check that asks what the network will -- including whether the coin has sat + * long enough for the leaf's relative lock. + * + * The ceremony is the ancestor's. The descendants' keys are anybody's, since + * nothing here signs as them: what is under test is that the key a descendant + * derives from its certificate's grant is the key the ancestor's shares sign as. + */ +class GuardianSpendRoundTest { + private val participants = 3 + private val threshold = 2 + + /** The ancestor's ceremony, as in `GroupWalletSpendRoundTest`. */ + private val dkg: List = run { + val hostSecretKeys = (1..participants).map { PrivateKey(ByteVector32(ByteArray(32) { i -> (it * 5 + i).toByte() })) } + val hostPublicKeys = hostSecretKeys.map { ChillDKG.hostPublicKey(it) } + val step1 = hostSecretKeys.mapIndexed { i, key -> + ChillDKG.participantStep1(key, hostPublicKeys, threshold, ByteVector32(ByteArray(32) { (i + 3).toByte() })) + } + val coordinator1 = ChillDKG.coordinatorStep1(step1.map { it.message }, hostPublicKeys, threshold) + val step2 = hostSecretKeys.mapIndexed { i, key -> + ChillDKG.participantStep2(key, step1[i].state, coordinator1.message, ByteVector32(ByteArray(32) { (i + 17).toByte() })) + } + val certificate = ChillDKG.coordinatorFinalize(coordinator1.state, step2.map { it.certEqSignature }, threshold).certificate + (0 until participants).map { i -> ChillDKG.participantFinalize(step2[i].state, certificate, participants, threshold) } + .onEach { assertTrue(it.fault.isOk, "the ceremony has to succeed for the rest to mean anything") } + } + + private val ancestorKey: PublicKey = dkg[0].thresholdPublicKey!! + private val publicShares: List = dkg[0].publicShares + private val ancestorRoom = SharedKeyDerivation.marmotGroupId(ancestorKey.toString()) + + private fun someKey(seed: Int): String = + PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))).publicKey().toString() + + private val chain = Chain.Regtest + + /** A guarded address of [childKey]'s wallet, under [grant]: its internal key, its tree, and its script. */ + private class Address(val internalKey: fr.acinq.bitcoin.XonlyPublicKey, val leaves: List, val tree: ScriptTree) { + val pubkeyScript: ByteVector get() = ByteVector(Script.write(Script.pay2tr(internalKey, tree))) + } + + private fun address(childKey: String, grant: List, change: Long = 0, index: Long = 0): Address { + val account = GroupWalletDerivation.account(childKey, chain) + val internalKey = account.extendedPublicKey.derivePublicKey(change).derivePublicKey(index).publicKey.xOnly() + val leaves = GuardianDerivation.leaves(grant, chain, 0, change, index) + return Address(internalKey, leaves, GuardianDerivation.tree(leaves)) + } + + private fun funding(address: Address) = Transaction( + version = 2, + txIn = listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 0x24 })), 0), ByteVector.empty, 0xffffffffL)), + txOut = listOf(TxOut(Satoshi(50_000), address.pubkeyScript)), + lockTime = 0, + ) + + private fun spend(funding: Transaction, sequence: Long = GuardianDerivation.ANCESTOR_DELAY) = Transaction( + version = 2, + txIn = listOf(TxIn(OutPoint(funding, 0), ByteVector.empty, sequence)), + txOut = listOf(TxOut(Satoshi(49_000), Script.pay2wpkh(PrivateKey(ByteVector32(ByteArray(32) { 9 })).publicKey()))), + lockTime = 0, + ) + + /** One FROST instance over [message] with [cache], by signers 0 and 2. */ + private fun sign(message: ByteVector32, cache: TweakCache): ByteVector64 { + val signerIds = listOf(0, 2) + val nonces = signerIds.map { id -> + SecretNonce.generate( + sessionRandom = ByteVector32(ByteArray(32) { (id + 40).toByte() }), + secretShare = dkg[id].secretShare!!, + publicShare = publicShares[id], + tweakedThresholdPublicKey = cache.tweakedPublicKey, + message = message, + extraInput = null, + ) + } + val session = Session.create( + aggregatedNonce = IndividualNonce.aggregate(nonces.map { it.second }).right!!, + signerIds = signerIds.map { it.toUInt() }, + signerPublicShares = signerIds.map { publicShares[it] }, + nParticipants = participants, + threshold = threshold, + tweakCache = cache, + message = message, + ) + val partials = signerIds.mapIndexed { position, id -> + session.sign(nonces[position].first, dkg[id].secretShare!!, id.toUInt()).right!!.also { + assertTrue(session.verify(it, nonces[position].second, publicShares[id], position), "signer $id's partial signature") + } + } + return session.aggregateSigs(partials).right!! + } + + /** The ancestor signs [leaf] of [address] in [tx] with [cache], and the witness goes on. */ + private fun guardianSpend(tx: Transaction, funding: Transaction, address: Address, leaf: ScriptTree.Leaf, cache: TweakCache): Transaction { + val sighash = tx.hashForSigningTaprootScriptPath(0, funding.txOut, SigHash.SIGHASH_DEFAULT, leaf.hash()) + val signature = sign(sighash, cache) + return tx.updateWitness(0, Script.witnessScriptPathPay2tr(address.internalKey, leaf, ScriptWitness(listOf(signature)), address.tree)) + } + + private fun assertSpends(tx: Transaction, funding: Transaction) = + tx.correctlySpends(mapOf(OutPoint(funding, 0) to funding.txOut[0]), ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) + + @Test + fun `a parent's quorum spends its child's coin through its leaf`() { + val child = someKey(0xc1) + val childRoom = SharedKeyDerivation.marmotGroupId(child) + val grant = GuardianDerivation.grant(ancestorKey.toString(), ancestorRoom, emptyList(), childRoom) + val address = address(child, grant) + val funding = funding(address) + + val signing = GuardianDerivation.signingCache(ancestorKey.toString(), listOf(childRoom), chain, 0, 0, 0) + val signed = guardianSpend(spend(funding), funding, address, address.leaves[0], signing.cache) + + assertEquals(1, address.leaves.size) + assertEquals(33, signed.txIn[0].witness.stack.last().size(), "a tree of one leaf has a bare control block") + assertSpends(signed, funding) + } + + @Test + fun `a grandparent's quorum spends its grandchild's coin from the bottom of the tree`() { + val middle = someKey(0xb1) + val middleRoom = SharedKeyDerivation.marmotGroupId(middle) + val child = someKey(0xc2) + val childRoom = SharedKeyDerivation.marmotGroupId(child) + + val middleGrant = GuardianDerivation.grant(ancestorKey.toString(), ancestorRoom, emptyList(), middleRoom) + val grant = GuardianDerivation.grant(middle, middleRoom, middleGrant, childRoom) + val address = address(child, grant, change = 1, index = 3) + val funding = funding(address) + + val lineage = GuardianDerivation.lineage(grant, childRoom, ancestorRoom)!! + assertEquals(listOf(middleRoom, childRoom), lineage) + val signing = GuardianDerivation.signingCache(ancestorKey.toString(), lineage, chain, 0, 1, 3) + val signed = guardianSpend(spend(funding), funding, address, address.leaves[1], signing.cache) + + assertEquals(65, signed.txIn[0].witness.stack.last().size(), "the root's leaf is one level down") + assertSpends(signed, funding) + } + + @Test + fun `the coin has to have sat for 12 blocks`() { + val child = someKey(0xc3) + val childRoom = SharedKeyDerivation.marmotGroupId(child) + val grant = GuardianDerivation.grant(ancestorKey.toString(), ancestorRoom, emptyList(), childRoom) + val address = address(child, grant) + val funding = funding(address) + val cache = GuardianDerivation.signingCache(ancestorKey.toString(), listOf(childRoom), chain, 0, 0, 0).cache + + assertSpends(guardianSpend(spend(funding, sequence = 12), funding, address, address.leaves[0], cache), funding) + assertFails("eleven blocks") { + assertSpends(guardianSpend(spend(funding, sequence = 11), funding, address, address.leaves[0], cache), funding) + } + assertFails("no relative lock at all") { + assertSpends(guardianSpend(spend(funding, sequence = 0xfffffffdL), funding, address, address.leaves[0], cache), funding) + } + } + + @Test + fun `the wrong cache signs for a key the leaf does not name`() { + val child = someKey(0xc4) + val childRoom = SharedKeyDerivation.marmotGroupId(child) + val sibling = SharedKeyDerivation.marmotGroupId(someKey(0xc5)) + val grant = GuardianDerivation.grant(ancestorKey.toString(), ancestorRoom, emptyList(), childRoom) + val address = address(child, grant) + val funding = funding(address) + + val wrongCaches = mapOf( + "the room key's" to SharedKeyDerivation.derive(ancestorKey.toString()).cache, + "the guardian root's" to GuardianDerivation.root(ancestorKey.toString()).cache, + "a sibling's leaf" to GuardianDerivation.signingCache(ancestorKey.toString(), listOf(sibling), chain, 0, 0, 0).cache, + "the next address's leaf" to GuardianDerivation.signingCache(ancestorKey.toString(), listOf(childRoom), chain, 0, 0, 1).cache, + "the wallet's own key" to GroupWalletDerivation.account(ancestorKey.toString(), chain).cache, + ) + + wrongCaches.forEach { (name, cache) -> + assertFails("$name cache") { + assertSpends(guardianSpend(spend(funding), funding, address, address.leaves[0], cache), funding) + } + } + } + + @Test + fun `a guardian signature is over the leaf it names`() { + // Sign the parent's leaf and present it as the grandparent's: the leaf hash + // is in the sighash, so a signature cannot be moved between leaves. + val middle = someKey(0xb2) + val middleRoom = SharedKeyDerivation.marmotGroupId(middle) + val child = someKey(0xc6) + val childRoom = SharedKeyDerivation.marmotGroupId(child) + val grant = GuardianDerivation.grant(middle, middleRoom, GuardianDerivation.grant(ancestorKey.toString(), ancestorRoom, emptyList(), middleRoom), childRoom) + val address = address(child, grant) + val funding = funding(address) + val tx = spend(funding) + val cache = GuardianDerivation.signingCache(ancestorKey.toString(), listOf(middleRoom, childRoom), chain, 0, 0, 0).cache + + val overParentLeaf = sign(tx.hashForSigningTaprootScriptPath(0, funding.txOut, SigHash.SIGHASH_DEFAULT, address.leaves[0].hash()), cache) + val moved = tx.updateWitness(0, Script.witnessScriptPathPay2tr(address.internalKey, address.leaves[1], ScriptWitness(listOf(overParentLeaf)), address.tree)) + + assertTrue(!Crypto.verifySignatureSchnorr(tx.hashForSigningTaprootScriptPath(0, funding.txOut, SigHash.SIGHASH_DEFAULT, address.leaves[1].hash()), overParentLeaf, GuardianDerivation.leafKey(grant[1], chain, 0, 0, 0))) + assertFails { assertSpends(moved, funding) } + } +} From e32419f0d8f0f11164cb8f44fb0d9f7fe1722b4f Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 15:10:30 +0200 Subject: [PATCH 04/15] feat(subgroup): a birth certificate carries the parent's guardian keys (Phase 3) The parent grants the child its own guardian key and every key its own certificate carries, one step further each, as guardian tags. Every parent signer recomputes the grant and drops a certificate proposal carrying any other keys before it is shown; one carrying none still signs. Co-Authored-By: Claude Opus 5.5 --- .../compose/managers/FrostSigningManager.kt | 15 ++ .../bennu/compose/managers/SubgroupManager.kt | 71 ++++++- .../subgroup/SubgroupBirthCertificateEvent.kt | 29 ++- .../nostr/subgroup/tags/GuardianTag.kt | 68 +++++++ .../bennu/compose/text/ProposedEvent.kt | 15 +- .../SubgroupBirthCertificateEventTest.kt | 25 +++ .../managers/GuardianSigningJvmTest.kt | 190 ++++++++++++++++++ .../managers/SubgroupManagerJvmTest.kt | 111 ++++++++++ 8 files changed, 520 insertions(+), 4 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/subgroup/tags/GuardianTag.kt create mode 100644 composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt index b56c419d..e469a04a 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt @@ -55,6 +55,7 @@ import com.machankura.bennu.compose.database.model.types.FrostSigningStage import com.machankura.bennu.compose.extensions.toHex import com.machankura.bennu.compose.nostr.dkg.DkgRitualEvents import com.machankura.bennu.compose.nostr.frost.FrostSigningEvents +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent /** * Signs a nostr event with a group's FROST threshold key, in one of its rooms. @@ -555,6 +556,20 @@ object FrostSigningManager { } } + // A birth certificate's guardian keys are a promise by the group signing + // it, so they have to be the keys it grants: recomputed here from the key + // this session signs with and the group's own certificate, never taken + // from the proposer. Refused before anything is shown, for the reason a + // mismatched id is. + val thresholdPublicKey = key.thresholdPublicKey + unsignedEvents.forEach { rebuilt -> + if (rebuilt.kind != SubgroupBirthCertificateEvent.KIND || thresholdPublicKey == null) return@forEach + SubgroupManager.refuseGrant(database, rebuilt.pubKey, thresholdPublicKey, rebuilt)?.let { reason -> + logger.w("Signing proposal $sessionId carries a birth certificate that $reason; dropping") + return null + } + } + val session = FrostSigningSession( id = sessionId, chatRoomId = localChatRoom.chatRoom.id, diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/SubgroupManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/SubgroupManager.kt index c6bee971..f94af125 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/SubgroupManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/SubgroupManager.kt @@ -229,6 +229,14 @@ object SubgroupManager { "$parentChatRoomId has already certified $subgroupChatRoomId" } + // The parent's guardian keys for the child: its own, and the ones its + // ancestors granted it. Every signer recomputes this list and refuses a + // certificate carrying any other -- see [refuseGrant]. + val parentKey = FrostSigningManager.completedKey(database, parentChatRoomId)?.thresholdPublicKey + ?: throw IllegalStateException("$parentChatRoomId has no key to grant a guardian key under") + val guardians = grantFor(database, parentChatRoomId, parentKey, subgroupChatRoomId) + ?: throw IllegalStateException("$parentChatRoomId's own certificate carries guardian keys this build cannot read") + logger.i("Asking $parentChatRoomId to certify $subgroupChatRoomId as its subgroup") return FrostSigningManager.proposeSigning( @@ -242,12 +250,73 @@ object SubgroupManager { thresholdPublicKey = thresholdPublicKey, adminPublicKeys = adminPublicKeys, name = subgroupName, - path = path + path = path, + guardians = guardians ), content = subgroupChatRoomId ) } + /** + * The guardian keys [chatRoomId]'s own certificate grants it, nearest first: + * empty for a group with no parent, or whose certificate predates guardian + * keys -- either way it grants only its own key onward -- and null when the + * certificate carries keys this build cannot read. + * + * Off the verified key state, which only holds a certificate + * `GroupKeyStateManager.stateFrom` checked. + */ + suspend fun guardiansOf(database: BennuDatabase, chatRoomId: String): List? { + val certificate = database.groupKeyStateDao().getByChatRoomId(chatRoomId) + ?.birthCertificateJson + ?.let { Event.fromJsonOrNull(it) } + ?: return emptyList() + return SubgroupBirthCertificateEvent.parseGuardians(certificate.tags) + } + + /** + * What [parentChatRoomId], signing as [thresholdPublicKey], grants + * [subgroupChatRoomId]: `GuardianDerivation.grant` over the keys its own + * certificate carries. Null when those cannot be read. + */ + suspend fun grantFor( + database: BennuDatabase, + parentChatRoomId: String, + thresholdPublicKey: HexKey, + subgroupChatRoomId: String + ): List? { + val inherited = guardiansOf(database, parentChatRoomId) ?: return null + return GuardianDerivation.grant(thresholdPublicKey, parentChatRoomId, inherited, subgroupChatRoomId) + } + + /** + * Why a proposed certificate's guardian keys are not the ones [chatRoomId] + * grants, or null when they are -- or when it carries none, which an older + * proposer's certificate does and which grants nothing. + * + * The check every parent signer makes before agreeing to guard a child. A + * coordinator who slipped a key of their own into the list, dropped an + * ancestor, or reordered the leaves would be asking the group to vouch for a + * wallet tree it did not make, so the proposal is refused rather than shown. + */ + suspend fun refuseGrant( + database: BennuDatabase, + chatRoomId: String, + thresholdPublicKey: HexKey, + certificate: Event + ): String? { + val proposed = SubgroupBirthCertificateEvent.parseGuardians(certificate.tags) + ?: return "carries a guardian key that does not read" + if (proposed.isEmpty()) return null + + val subgroupChatRoomId = SubgroupBirthCertificateEvent.parseSubgroupChatRoomId(certificate.tags) + ?: return "names no subgroup" + val expected = runCatching { grantFor(database, chatRoomId, thresholdPublicKey, subgroupChatRoomId) }.getOrNull() + ?: return "grants keys this device cannot check" + + return if (proposed == expected) null else "grants guardian keys this group does not" + } + /** * The newest certificate by [parentChatRoomId] that actually certifies * [subgroupChatRoomId], or null if this device holds none. diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/subgroup/SubgroupBirthCertificateEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/subgroup/SubgroupBirthCertificateEvent.kt index 3a37c245..e0af2e31 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/subgroup/SubgroupBirthCertificateEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/subgroup/SubgroupBirthCertificateEvent.kt @@ -5,9 +5,11 @@ import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.core.Kind import com.vitorpamplona.quartz.nip01Core.tags.dTag.DTag import com.vitorpamplona.quartz.nip01Core.tags.people.PTag +import com.machankura.bennu.compose.managers.GuardianDerivation import com.machankura.bennu.compose.managers.SharedKeyDerivation import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent import com.machankura.bennu.compose.nostr.frost.tags.FrostDerivationPathTag +import com.machankura.bennu.compose.nostr.subgroup.tags.GuardianTag import com.machankura.bennu.compose.nostr.subgroup.tags.SubgroupKeyTag import com.machankura.bennu.compose.nostr.subgroup.tags.SubgroupParentTag @@ -50,6 +52,19 @@ import com.machankura.bennu.compose.nostr.subgroup.tags.SubgroupParentTag * can check `marmotGroupId(key, path) == content` for itself, which is the * difference between approving a hash and approving a group. * + * ### Guardian keys + * + * A certificate may also carry [GuardianTag]s: the parent's own guardian key for + * this child, and behind it every key the parent's ancestors granted the parent, + * each one public step further -- `GuardianDerivation.grant`. Carrying them is + * the parent agreeing to guard the child's wallet, if the child ever opens a + * guarded one; it delegates nothing on its own. They are not among the checks in + * [certifies], which is about lineage. Whether they are the keys the parent + * grants is checked by every parent signer before the certificate is signed -- + * `SubgroupManager.refuseGrant` -- and nowhere after, because nobody else holds + * the key that check needs and nobody else needs it: the parent's quorum can + * already spend through its own leaf whatever the others would let it. + * * ### What [certifies] deliberately does not check * * The name and the `p` tags are the **founding** roster. A certificate is signed @@ -95,14 +110,24 @@ object SubgroupBirthCertificateEvent { thresholdPublicKey: HexKey, adminPublicKeys: List, name: String, - path: List = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH + path: List = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH, + guardians: List = emptyList() ): Array> = arrayOf( DTag.assemble(subgroupChatRoomId), SubgroupParentTag.assemble(parentChatRoomId), SubgroupKeyTag.assemble(thresholdPublicKey), FrostDerivationPathTag.assemble(path), arrayOf(NAME_TAG_NAME, name) - ) + adminPublicKeys.distinct().map { PTag.assemble(it, null) } + ) + adminPublicKeys.distinct().map { PTag.assemble(it, null) } + + guardians.map(GuardianTag::assemble) + + /** + * The guardian keys the parent grants the child, nearest first -- empty for a + * certificate that carries none, and null when one is unreadable, so that a + * list with an entry quietly dropped is never mistaken for the list. + */ + fun parseGuardians(tags: Array>): List? = + GuardianTag.parseAll(tags) /** The child this certificate is about, or null if it names none. */ fun parseSubgroupChatRoomId(tags: Array>): String? = diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/subgroup/tags/GuardianTag.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/subgroup/tags/GuardianTag.kt new file mode 100644 index 00000000..23f18784 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/subgroup/tags/GuardianTag.kt @@ -0,0 +1,68 @@ +package com.machankura.bennu.compose.nostr.subgroup.tags + +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.vitorpamplona.quartz.nip01Core.core.has +import com.vitorpamplona.quartz.utils.ensure +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.PublicKey + +/** + * One ancestor's guardian key, as granted to the group a statement is about: + * + * ``` + * ["guardian", , <33-byte key hex>, <32-byte chain code hex>, ] + * ``` + * + * On a birth certificate it is the parent agreeing to guard the child -- its + * own key and every key its own ancestors gave it, one step further each, in + * that order -- and on a guarded wallet statement it is the child agreeing to be + * guarded by exactly those keys. See `GuardianDerivation` and + * `docs/group-wallet-guardians.md`. + * + * Shape only, as `SubgroupKeyTag` is. Whether a key is the one the ancestor + * actually grants is settled by rederiving it, never by looking at it. + */ +object GuardianTag { + const val TAG_NAME = "guardian" + + private val ROOM_ID = Regex("^[0-9a-f]{64}$") + private val KEY = Regex("^0[23][0-9a-f]{64}$") + private val CHAIN_CODE = Regex("^[0-9a-f]{64}$") + + fun assemble(guardian: GuardianDerivation.Guardian): Array = arrayOf( + TAG_NAME, + guardian.chatRoomId.lowercase(), + guardian.publicKey.toString(), + guardian.chainCode.toHex(), + guardian.delay.toString(), + ) + + /** The guardian [tag] names, or null when it is not a guardian tag or any of its fields is the wrong shape. */ + fun parse(tag: Array): GuardianDerivation.Guardian? { + ensure(tag.has(4)) { return null } + ensure(tag[0] == TAG_NAME) { return null } + ensure(ROOM_ID.matches(tag[1])) { return null } + ensure(KEY.matches(tag[2])) { return null } + ensure(CHAIN_CODE.matches(tag[3])) { return null } + val delay = tag[4].toLongOrNull()?.takeIf { it in 1L..0xFFFFL } ?: return null + + val publicKey = runCatching { PublicKey.fromHex(tag[2]) }.getOrNull()?.takeIf { it.isValid() } ?: return null + return GuardianDerivation.Guardian( + chatRoomId = tag[1], + publicKey = publicKey, + chainCode = ByteVector32(tag[3]), + delay = delay, + ) + } + + /** + * Every guardian in [tags], in order -- or null when any tag *named* + * `guardian` fails to read. A list with one entry quietly dropped is a + * different list, and the order is the tree. + */ + fun parseAll(tags: Array>): List? { + val named = tags.filter { it.isNotEmpty() && it[0] == TAG_NAME } + val parsed = named.mapNotNull(::parse) + return parsed.takeIf { it.size == named.size } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt index 3bf966d2..68bf3f42 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt @@ -155,7 +155,20 @@ object ProposedEvent { SubgroupBirthCertificateEvent.parseAdminPublicKeys(event.tags) .size .takeIf { it > 0 } - ?.let { "run by $it members" } + ?.let { "run by $it members" }, + // The promise this certificate makes on the group's behalf, said + // as one: a guardian key is this group, and every group above it, + // able to spend from the subgroup's wallet if it opens a guarded one. + SubgroupBirthCertificateEvent.parseGuardians(event.tags) + ?.size + ?.takeIf { it > 0 } + ?.let { count -> + when (count) { + 1 -> "this group can spend from its wallet" + 2 -> "this group and the one above it can spend from its wallet" + else -> "this group and the ${count - 1} above it can spend from its wallet" + } + } ).joinToString(" · ") ) diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/subgroup/SubgroupBirthCertificateEventTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/subgroup/SubgroupBirthCertificateEventTest.kt index c9f643ff..0fbf30f5 100644 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/subgroup/SubgroupBirthCertificateEventTest.kt +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/subgroup/SubgroupBirthCertificateEventTest.kt @@ -17,7 +17,9 @@ import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue import com.machankura.bennu.compose.extensions.toHex +import com.machankura.bennu.compose.managers.GuardianDerivation import com.machankura.bennu.compose.managers.SharedKeyDerivation +import com.machankura.bennu.compose.nostr.subgroup.tags.GuardianTag /** * What a birth certificate is allowed to convince a member of. @@ -350,6 +352,29 @@ class SubgroupBirthCertificateEventTest { * way to test that both are checked. [signature] replaces the real one * outright, for the cases where what arrives is not a signature at all. */ + @Test + fun `guardian keys ride on a certificate without touching what it certifies`() { + val parentKey = parentMaterial.thresholdPublicKey.value.toHex() + val guardians = GuardianDerivation.grant(parentKey, parentChatRoomId, emptyList(), subgroupChatRoomId) + val tags = SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = subgroupChatRoomId, + parentChatRoomId = parentChatRoomId, + thresholdPublicKey = childKey, + adminPublicKeys = admins, + name = name, + path = path, + guardians = guardians, + ) + + assertTrue(SubgroupBirthCertificateEvent.certifies(certificate(tags = tags), subgroupChatRoomId, parentChatRoomId)) + assertEquals(guardians, SubgroupBirthCertificateEvent.parseGuardians(tags)) + assertEquals(emptyList(), SubgroupBirthCertificateEvent.parseGuardians(certificate().tags)) + + // One unreadable entry makes the list unreadable, rather than shorter. + val broken = tags.map { if (it[0] == GuardianTag.TAG_NAME) it.copyOf().also { tag -> tag[2] = "04" + tag[2].drop(2) } else it } + assertNull(SubgroupBirthCertificateEvent.parseGuardians(broken.toTypedArray())) + } + private fun certificate( content: String = subgroupChatRoomId, tags: Array> = SubgroupBirthCertificateEvent.assembleTags( diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt new file mode 100644 index 00000000..c8418a88 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt @@ -0,0 +1,190 @@ +package com.machankura.bennu.compose.managers + +import androidx.room3.Room +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.builder.getRoomDatabase +import com.machankura.bennu.compose.database.model.ChatRoom +import com.machankura.bennu.compose.database.model.DkgParticipantMessage +import com.machankura.bennu.compose.database.model.DkgSession +import com.machankura.bennu.compose.database.model.MarmotInnerEvent +import com.machankura.bennu.compose.database.model.NostrEvent +import com.machankura.bennu.compose.database.model.Profile +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.database.model.types.DkgRitualStage +import com.machankura.bennu.compose.database.model.types.FrostSigningStage +import com.machankura.bennu.compose.extensions.toHex +import com.machankura.bennu.compose.nostr.dkg.DkgRitualEvents +import com.machankura.bennu.compose.nostr.frost.FrostSigningEvents +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.crypto.frost.Frost +import fr.acinq.bitcoin.crypto.frost.KeyMaterial +import kotlinx.coroutines.runBlocking +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.time.Instant + +/** + * A group's guardian keys through the real signing manager, between two of its + * devices, with the wire held by hand -- the harness `GroupSpendSigningJvmTest` + * uses. + * + * The group here is the *ancestor*. What is under test is what its members' + * devices agree to: a certificate is only signed when the guardian keys in it + * are the ones the group grants, whoever proposed it. + */ +class GuardianSigningJvmTest { + private val participants = 3 + private val threshold = 2 + + private val keyMaterial: KeyMaterial = Frost.trustedDealerKeygen( + thresholdSecretKey = PrivateKey(ByteVector32("6a2d1a".padEnd(62, '0') + "a1")), + nParticipants = participants, + threshold = threshold, + ) + private val thresholdPublicKey = keyMaterial.thresholdPublicKey.value.toHex() + private val ceremonyId = "ceremony".padEnd(64, '0') + private val roomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) + private val members = listOf("a", "b", "c").map { it.repeat(64) } + private val hostKeys = listOf("2a", "2b", "2c").map { it.padEnd(66, '0') } + + private val childKey = PrivateKey(ByteVector32(ByteArray(32) { 0x3c })).publicKey().toString() + private val childRoomId = SharedKeyDerivation.marmotGroupId(childKey) + + private val devices = mutableListOf() + + @AfterTest + fun closeDatabases() = devices.forEach { it.db.close() } + + private inner class Device(val publicKey: HexKey, val db: BennuDatabase, val room: LocalChatRoom) { + val received = mutableSetOf() + + suspend fun store(queued: Queued) = db.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = queued.id, publicKey = queued.publicKey, kind = queued.kind, createdAt = queued.createdAt, + tags = queued.tags, content = queued.content, chatRoomId = roomId, + ) + ) + + suspend fun session(id: String) = db.frostSigningSessionDao().getSessionById(id) + } + + private suspend fun device(publicKey: HexKey, signerIndex: Int): Device { + val db = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + members.forEach { member -> + val nostrEventId = "e$member".take(64) + db.nostrEventDao().upsert(NostrEvent(id = nostrEventId, pubKey = member, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + db.profileDao().upsert(Profile(publicKey = member, nostrEventId = nostrEventId)) + } + val chatRoom = ChatRoom( + id = roomId, userPublicKey = publicKey, subject = "Council", + description = SharedKeyDerivation.describe("Council."), mlsGroupState = "00", + ) + db.chatRoomDao().upsert(chatRoom) + db.dkgSessionDao().upsert( + DkgSession( + id = ceremonyId, chatRoomId = roomId, coordinatorPublicKey = members.first(), userPublicKey = publicKey, + threshold = threshold, participantCount = participants, stage = DkgRitualStage.COMPLETE, + hostPublicKey = hostKeys[signerIndex], round1Random = "1".repeat(64), round2AuxRandom = "2".repeat(64), + thresholdPublicKey = thresholdPublicKey, + secretShare = keyMaterial.secretShares[signerIndex].value.toHex(), + publicShares = keyMaterial.publicShares.joinToString(",") { it.value.toHex() }, + ) + ) + members.forEachIndexed { index, member -> + db.dkgSessionDao().upsert( + DkgParticipantMessage(sessionId = ceremonyId, participantPublicKey = member, kind = DkgRitualEvents.HOST_KEY, payload = hostKeys[index]) + ) + } + val localChatRoom = db.chatRoomDao().findChatRoomById(roomId) ?: LocalChatRoom(chatRoom = chatRoom) + return Device(publicKey, db, localChatRoom).also { devices += it } + } + + private data class Queued( + val id: HexKey, val publicKey: HexKey, val kind: Int, + val tags: Array>, val content: String, val createdAt: Instant, + ) { + fun toEvent() = Event(id, publicKey, createdAt.epochSeconds, kind, tags, content, "") + } + + private suspend fun outbox(device: Device): List = + device.db.marmotInnerEventDao() + .getByChatRoomAndKinds(chatRoomId = roomId, kinds = FrostSigningEvents.ALL.toList()) + .map { Queued(it.id, it.publicKey, it.kind, it.tags, it.content, it.createdAt) } + .filter { it.publicKey == device.publicKey } + .sortedWith(compareBy({ it.createdAt }, { it.kind })) + + private suspend fun deliver(to: Device, queued: Queued) { + if (!to.received.add(queued.id)) return + to.store(queued) + FrostSigningManager.processSigningPayload(to.db, to.room, queued.toEvent(), to.publicKey) + } + + private suspend fun pump(vararg between: Device) { + var moved = true + while (moved) { + moved = false + for (from in between) for (to in between) { + if (from === to) continue + outbox(from).forEach { queued -> + if (queued.id !in to.received) moved = true + deliver(to, queued) + } + } + } + } + + private fun certificateTags(guardians: List) = SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = childRoomId, + parentChatRoomId = roomId, + thresholdPublicKey = childKey, + adminPublicKeys = members, + name = "Translation team", + guardians = guardians, + ) + + private suspend fun proposeCertificate(proposer: Device, guardians: List) = + FrostSigningManager.proposeSigning( + proposer.db, proposer.room, proposer.publicKey, SubgroupBirthCertificateEvent.KIND, certificateTags(guardians), childRoomId, + ) + + // ---- The certificate's guardian keys -------------------------------- + + @Test + fun `a certificate granting the group's own key is signed, and carries it`() = runBlocking { + val proposer = device(members[0], signerIndex = 0) + val other = device(members[1], signerIndex = 1) + val granted = GuardianDerivation.grant(thresholdPublicKey, roomId, emptyList(), childRoomId) + + val session = proposeCertificate(proposer, granted) + pump(proposer, other) + assertNotNull(other.session(session.id), "the other member is asked") + FrostSigningManager.approve(other.db, other.room, session.id) + pump(proposer, other) + + listOf(proposer, other).forEach { device -> + assertEquals(FrostSigningStage.COMPLETE, device.session(session.id)?.stage) + val certificate = assertNotNull(SubgroupManager.certificateFor(device.db, childRoomId, roomId)).toEvent() + assertEquals(granted, SubgroupBirthCertificateEvent.parseGuardians(certificate.tags)) + } + } + + @Test + fun `a certificate granting any other key is never put to the member`() = runBlocking { + val proposer = device(members[0], signerIndex = 0) + val other = device(members[1], signerIndex = 1) + val coordinators = PrivateKey(ByteVector32(ByteArray(32) { 0x66 })).publicKey().toString() + + // The coordinator's own key dressed as the group's guardian key. + val session = proposeCertificate(proposer, GuardianDerivation.grant(coordinators, roomId, emptyList(), childRoomId)) + pump(proposer, other) + + assertNull(other.session(session.id), "refused at acceptance, so nothing of the member's is ever published for it") + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/SubgroupManagerJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/SubgroupManagerJvmTest.kt index 2caaa42f..d132f92e 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/SubgroupManagerJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/SubgroupManagerJvmTest.kt @@ -34,7 +34,9 @@ import com.machankura.bennu.compose.database.model.ChatRoom import com.machankura.bennu.compose.database.model.DkgParticipantMessage import com.machankura.bennu.compose.database.model.DkgSession import com.machankura.bennu.compose.database.model.types.DkgRitualStage +import com.machankura.bennu.compose.database.model.GroupKeyState import com.machankura.bennu.compose.database.model.GroupSignedEvent +import com.machankura.bennu.compose.nostr.subgroup.tags.GuardianTag import com.machankura.bennu.compose.database.model.NostrEvent import com.machankura.bennu.compose.database.model.Participant import com.machankura.bennu.compose.database.model.Profile @@ -494,8 +496,117 @@ class SubgroupManagerJvmTest { } } + @Test + fun `a certificate grants the child the parent's guardian key`(): Unit = runBlocking { + val parentRoom = parentWith(listOf(alice, bob)) + + val proposed = proposedCertificate(parentRoom) + + // A parent with no parent of its own grants one key: its own, one step on. + assertEquals( + GuardianDerivation.grant(parentMaterial.thresholdPublicKey.value.toHex(), parentRoomId, emptyList(), childRoomId), + SubgroupBirthCertificateEvent.parseGuardians(proposed.tags) + ) + assertNull(SubgroupManager.refuseGrant(db, parentRoomId, parentMaterial.thresholdPublicKey.value.toHex(), proposed)) + } + + @Test + fun `a subgroup passes on the keys its own parent granted it, one step further`(): Unit = runBlocking { + val parentRoom = parentWith(listOf(alice, bob)) + // The parent is itself a subgroup of a grandparent, whose key reached it + // through the parent's own certificate. + val grandparentKey = strangerMaterial.thresholdPublicKey.value.toHex() + val grandparentRoomId = roomOf(strangerMaterial) + val inherited = GuardianDerivation.grant(grandparentKey, grandparentRoomId, emptyList(), parentRoomId) + fileParentage(inherited) + + val granted = assertNotNull(SubgroupBirthCertificateEvent.parseGuardians(proposedCertificate(parentRoom).tags)) + + assertEquals(listOf(parentRoomId, grandparentRoomId), granted.map { it.chatRoomId }) + assertEquals(inherited[0].grantedTo(childRoomId), granted[1]) + assertEquals( + GuardianDerivation.root(grandparentKey).extendedPublicKey + .derivePublicKey(GuardianDerivation.childIndex(parentRoomId)) + .derivePublicKey(GuardianDerivation.childIndex(childRoomId)) + .publicKey, + granted[1].publicKey, + "the grandparent's key in the grandchild is R / i(parent) / i(child)" + ) + } + + @Test + fun `a signer refuses guardian keys the group does not grant`(): Unit = runBlocking { + val parentRoom = parentWith(listOf(alice, bob)) + val parentKey = parentMaterial.thresholdPublicKey.value.toHex() + val proposed = proposedCertificate(parentRoom) + val granted = assertNotNull(SubgroupBirthCertificateEvent.parseGuardians(proposed.tags)) + val coordinators = GuardianDerivation.grant(strangerMaterial.thresholdPublicKey.value.toHex(), parentRoomId, emptyList(), childRoomId) + + fun withGuardians(guardians: List) = certificate( + tags = proposed.tags.filterNot { it[0] == GuardianTag.TAG_NAME }.toTypedArray() + + guardians.map(GuardianTag::assemble) + ) + + val refusals = mapOf( + "a key of the coordinator's own" to withGuardians(coordinators), + "an extra ancestor" to withGuardians(granted + coordinators), + "the key not stepped for this child" to withGuardians(listOf(granted[0].copy(publicKey = GuardianDerivation.root(parentKey).publicKey))), + "a shorter delay" to withGuardians(listOf(granted[0].copy(delay = 1))), + ) + refusals.forEach { (name, certificate) -> + assertNotNull(SubgroupManager.refuseGrant(db, parentRoomId, parentKey, certificate), name) + } + + // An older proposer's certificate carries none, and grants nothing. + assertNull(SubgroupManager.refuseGrant(db, parentRoomId, parentKey, certificate())) + } + // ---- fixtures ---------------------------------------------------------- + /** The certificate [parentRoom] is asked to sign for the child, as the session holds it. */ + private suspend fun proposedCertificate(parentRoom: LocalChatRoom): Event { + val session = SubgroupManager.proposeBirthCertificate( + database = db, + parentRoom = parentRoom, + userPublicKey = user, + key = completedChildCeremony(), + adminPublicKeys = listOf(user, alice, bob), + name = "Translation team", + ) + return Event.fromJson(assertNotNull(db.frostSigningSessionDao().getItems(session.id).firstOrNull()).unsignedEventJson) + } + + /** + * The parent's own key state, naming a grandparent through a certificate + * that grants [guardians]. Filed as `stateFrom` would leave it; nothing here + * re-checks the certificate, which is what having passed `stateFrom` means. + */ + private suspend fun fileParentage(guardians: List) { + val grandparentRoomId = roomOf(strangerMaterial) + val tags = SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = parentRoomId, + parentChatRoomId = grandparentRoomId, + thresholdPublicKey = parentMaterial.thresholdPublicKey.value.toHex(), + adminPublicKeys = listOf(user, alice, bob), + name = "Ekklesia", + path = path, + guardians = guardians, + ) + val parentCertificate = certificate(subgroupMaterial = parentMaterial, tags = tags, author = strangerMaterial) + db.groupKeyStateDao().upsert( + GroupKeyState( + chatRoomId = parentRoomId, + dkgSessionId = "parent-ceremony", + thresholdPublicKey = parentMaterial.thresholdPublicKey.value.toHex(), + derivationPath = SharedKeyDerivation.formatPath(path), + announcedBy = parentRoomId, + announcedAt = Instant.fromEpochSeconds(1_700_000_000), + parentChatRoomId = grandparentRoomId, + birthCertificateJson = parentCertificate.toJson(), + ) + ) + } + /** * The NIP-17 room a ceremony runs in, stood up the way the picker does it -- * room first, because `DkgSession.chatRoomId` is a foreign key onto it. From 606b4bb12fc98a58de8855c0c9119e18e5665f47 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 15:15:37 +0200 Subject: [PATCH 05/15] feat(wallet): a guarded wallet statement, and the account it opens (Phase 4) An account knows its guardians and puts a leaf per guardian in every address, internal key unchanged. The statement names them and carries the certificate that granted them, and verifies only when the certificate certifies this room and grants exactly those keys. A guarded statement outranks a plain one for its account, and its first guardians stand. Co-Authored-By: Claude Opus 5.5 --- .../compose/managers/GroupWalletDerivation.kt | 82 +++++++++++--- .../bennu/compose/nostr/wallet/GroupWallet.kt | 23 +++- .../nostr/wallet/GroupWalletStatementEvent.kt | 68 +++++++++++- .../wallet/GroupWalletStatementEventTest.kt | 100 +++++++++++++++++- 4 files changed, 247 insertions(+), 26 deletions(-) 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 548a1b91..a843c700 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 @@ -13,6 +13,7 @@ import fr.acinq.bitcoin.KeyPath import fr.acinq.bitcoin.PrivateKey import fr.acinq.bitcoin.PublicKey import fr.acinq.bitcoin.Script +import fr.acinq.bitcoin.ScriptTree import fr.acinq.bitcoin.XonlyPublicKey import fr.acinq.bitcoin.crypto.Pack import fr.acinq.bitcoin.crypto.frost.TweakCache @@ -54,6 +55,15 @@ import fr.acinq.bitcoin.utils.Either * key for any address recovers the group's threshold key -- the room, every * address of every account, and every event the group can sign. Nothing here or * anywhere else reconstructs one. The only export is the account xpub. + * + * ### A guarded account + * + * An account opened with guardians -- the keys a subgroup's birth certificate + * grants it, see `GuardianDerivation` -- is the same account with one change at + * the very end: each address commits to a tree of one leaf per guardian, so the + * last tweak is BIP341's script-path tweak over that tree rather than BIP86's + * empty one. The internal key, and so the group's own key-path spend, is + * untouched. `docs/group-wallet-guardians.md` says why. */ object GroupWalletDerivation { /** BIP44's external chain: addresses handed out to be paid. */ @@ -86,7 +96,16 @@ object GroupWalletDerivation { val extendedPublicKey: DeterministicWallet.ExtendedPublicKey, /** The threshold key tweaked to [extendedPublicKey]'s key: what the account's sessions start from. */ internal val cache: TweakCache, + /** + * The ancestors that can spend from every address of this account, nearest + * first -- empty for an account nobody guards, which is every account a + * group that is nobody's subgroup opens. + */ + val guardians: List = emptyList(), ) { + /** Whether its addresses carry guardian leaves. */ + val isGuarded: Boolean get() = guardians.isNotEmpty() + /** The account key's own fingerprint, as a descriptor's key origin and a PSBT's derivation name it. */ val fingerprint: Long get() = extendedPublicKey.fingerprint() @@ -109,14 +128,20 @@ object GroupWalletDerivation { val changeDescriptor: String get() = descriptor(CHANGE) private fun descriptor(change: Long): String { - val body = "tr([$fingerprintHex]$xpub/$change/*)" + val tree = if (isGuarded) "," + GuardianDerivation.descriptorTree(guardians, chain, account, change) else "" + val body = "tr([$fingerprintHex]$xpub/$change/*$tree)" return "$body#${Descriptor.checksum(body)}" } - override fun equals(other: Any?): Boolean = - other is Account && chain == other.chain && account == other.account && extendedPublicKey == other.extendedPublicKey + /** The same account with [guardians] in every address. */ + fun guardedBy(guardians: List): Account = + Account(chain, account, extendedPublicKey, cache, guardians) - override fun hashCode(): Int = extendedPublicKey.hashCode() + override fun equals(other: Any?): Boolean = + other is Account && chain == other.chain && account == other.account && + extendedPublicKey == other.extendedPublicKey && guardians == other.guardians + + override fun hashCode(): Int = extendedPublicKey.hashCode() * 31 + guardians.hashCode() } /** @@ -134,12 +159,22 @@ object GroupWalletDerivation { /** BIP86's output key `Q`: the key in the output script, and the key a spend's signature verifies against. */ val outputKey: XonlyPublicKey, val cache: TweakCache, + /** The guardian leaves this address commits to, or null for BIP86's empty tree. */ + val tree: ScriptTree? = null, ) { + /** The tweak from [internalKey] to [outputKey]: over [tree] when there is one, BIP86's otherwise. */ + val taprootTweak: Crypto.TaprootTweak + get() = tree?.let { Crypto.TaprootTweak.ScriptPathTweak(it.hash()) } ?: Crypto.TaprootTweak.KeyPathTweak + /** `OP_1 `. */ val pubkeyScript: ByteVector - get() = ByteVector(Script.write(Script.pay2tr(internalKey, Crypto.TaprootTweak.KeyPathTweak))) + get() = ByteVector(Script.write(Script.pay2tr(internalKey, taprootTweak))) - fun address(chain: Chain): String = Bitcoin.computeBIP86Address(internalKey, chain.chainHash) + fun address(chain: Chain): String = when (tree) { + null -> Bitcoin.computeBIP86Address(internalKey, chain.chainHash) + else -> Bitcoin.addressFromPublicKeyScript(chain.chainHash, pubkeyScript.toByteArray()).right + ?: throw IllegalStateException("a taproot output always has an address") + } /** The path below the account, as a PSBT's `tap_bip32_derivation` carries it. */ val keyPath: KeyPath get() = KeyPath(listOf(change, index)) @@ -153,7 +188,12 @@ object GroupWalletDerivation { * or the HMAC lands on an invalid scalar -- around 2^-127, and BIP32 throws at * the same place. */ - fun account(thresholdPublicKey: HexKey, chain: Chain, account: Long = 0L): Account { + fun account( + thresholdPublicKey: HexKey, + chain: Chain, + account: Long = 0L, + guardians: List = emptyList(), + ): Account { require(account in 0L..MAX_INDEX) { "account $account is not an unhardened index" } val root = PublicKey(ByteVector(thresholdPublicKey.hexToByteArray())) @@ -185,6 +225,7 @@ object GroupWalletDerivation { parent = 0L, ), cache = cache, + guardians = guardians, ) } @@ -197,19 +238,27 @@ object GroupWalletDerivation { * a parity mistake in the cache and a wallet whose signatures do not verify. */ fun derive(account: Account, change: Long, index: Long): Derived = - deriveBelow(account.extendedPublicKey, account.cache, change, index) + deriveBelow( + account.extendedPublicKey, + account.cache, + change, + index, + tree = GuardianDerivation.treeAt(account.guardians, account.chain, account.account, change, index), + ) /** - * The tail on its own: BIP32 public derivation and the BIP341 key-path tweak, - * from any account-level key and the cache that signs as it. Split out so the - * tail can be tested against BIP86's published vectors, which start from a - * seed's account key rather than from a threshold key. + * The tail on its own: BIP32 public derivation and the BIP341 tweak -- over + * [tree] when there is one, BIP86's key-path tweak otherwise -- from any + * account-level key and the cache that signs as it. Split out so the tail can + * be tested against BIP86's published vectors, which start from a seed's + * account key rather than from a threshold key. */ internal fun deriveBelow( accountKey: DeterministicWallet.ExtendedPublicKey, accountCache: TweakCache, change: Long, index: Long, + tree: ScriptTree? = null, ): Derived { require(change == RECEIVE || change == CHANGE) { "change must be $RECEIVE or $CHANGE, not $change" } require(index in 0L..MAX_INDEX) { "index $index is not an unhardened index" } @@ -224,15 +273,16 @@ object GroupWalletDerivation { val internalKey = childKey.publicKey.xOnly() require(cache.tweakedPublicKey == internalKey) { "the cache does not reach the internal key at $change/$index" } - cache = when (val tweaked = cache.tweak(internalKey.tweak(Crypto.TaprootTweak.KeyPathTweak), isXonly = true)) { - is Either.Left -> throw IllegalArgumentException("Could not apply the key-path tweak at $change/$index", tweaked.value) + val taprootTweak = tree?.let { Crypto.TaprootTweak.ScriptPathTweak(it.hash()) } ?: Crypto.TaprootTweak.KeyPathTweak + cache = when (val tweaked = cache.tweak(internalKey.tweak(taprootTweak), isXonly = true)) { + is Either.Left -> throw IllegalArgumentException("Could not apply the taproot tweak at $change/$index", tweaked.value) is Either.Right -> tweaked.value.first } - val outputKey = internalKey.outputKey(Crypto.TaprootTweak.KeyPathTweak).first + val outputKey = internalKey.outputKey(taprootTweak).first require(cache.tweakedPublicKey == outputKey) { "the cache does not reach the output key at $change/$index" } - return Derived(change = change, index = index, internalKey = internalKey, outputKey = outputKey, cache = cache) + return Derived(change = change, index = index, internalKey = internalKey, outputKey = outputKey, cache = cache, tree = tree) } /** BIP32's `I_L` for one unhardened step: the scalar CKDpub adds, which a FROST cache takes as a plain tweak. */ diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWallet.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWallet.kt index 1587e43a..a72e7c4d 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWallet.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWallet.kt @@ -54,17 +54,32 @@ data class GroupWallet( * Newest by the group's own timestamp with the id breaking a tie, for the * reason `GroupRelayList.newestAmong` gives: two devices reading the same * events in different orders have to agree. + * + * Two rules first, for a guarded account, each of which keeps a later + * statement from moving every address of one already holding coins: + * + * 1. a guarded statement outranks a plain one -- an account opened guarded + * stays guarded, whatever a client that predates guardians signs later; + * 2. among guarded ones the earliest decides the guardians, and a later one + * naming others is ignored. Changing who guards a wallet is another + * account. */ fun newestAmong( signedEvents: List, thresholdPublicKey: HexKey, chain: Chain, account: Long = 0L, - ): GroupWallet? = - signedEvents - .asSequence() + ): GroupWallet? { + val order = compareBy({ it.openedAt }, { it.signedEvent.id }) + val opened = signedEvents .mapNotNull { of(it, thresholdPublicKey) } .filter { it.chain == chain && it.account.account == account } - .maxWithOrNull(compareBy({ it.openedAt }, { it.signedEvent.id })) + + val guarded = opened.filter { it.account.isGuarded } + val first = guarded.minWithOrNull(order) + ?: return opened.maxWithOrNull(order) + + return guarded.filter { it.account.guardians == first.account.guardians }.maxWithOrNull(order) + } } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEvent.kt index c00421d0..aa3d5705 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEvent.kt @@ -1,6 +1,12 @@ package com.machankura.bennu.compose.nostr.wallet import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.managers.SharedKeyDerivation +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.machankura.bennu.compose.nostr.subgroup.tags.GuardianTag +import com.machankura.bennu.compose.nostr.subgroup.tags.SubgroupBirthCertificateTag +import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.core.Kind import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate @@ -33,6 +39,16 @@ import kotlin.time.Clock * statement naming any xpub but the rederived one is not the group's wallet, * whoever signed it. * + * ### A guarded statement + * + * A subgroup whose birth certificate grants it guardian keys may open its wallet + * *guarded*: every address carries a leaf per ancestor, and the statement is the + * child's quorum agreeing to that. It carries the guardians as [GuardianTag]s + * and the certificate itself, whole, so that a member who holds no key state -- + * one welcomed in after the founding -- can still check every address, and so + * that an ancestor it is forwarded to can check where its own key came from. + * See `docs/group-wallet-guardians.md`. + * * ### Never on a relay * * The xpub is every address and the whole balance, to whoever has it. Like the @@ -70,13 +86,24 @@ object GroupWalletStatementEvent { val xpub: String, val receiveDescriptor: String, val changeDescriptor: String, + /** The guardians it names, nearest first; empty for a plain statement. */ + val guardians: List = emptyList(), + /** The birth certificate a guarded statement carries, unverified. */ + val certificate: Event? = null, ) { /** * The account this statement describes, if [thresholdPublicKey] rederives * every value it carries; null otherwise. + * + * For a guarded one, also: the certificate certifies the room the key + * makes, it names that key, and its guardian keys are exactly the ones + * the statement names -- the guardians come from the parent's signature + * and the child's agreement together, or the statement opens nothing. */ fun verifiedAgainst(thresholdPublicKey: HexKey): GroupWalletDerivation.Account? { - val account = runCatching { GroupWalletDerivation.account(thresholdPublicKey, chain, account) } + if (guardians.isNotEmpty() && !guardiansCheckOut(thresholdPublicKey)) return null + + val account = runCatching { GroupWalletDerivation.account(thresholdPublicKey, chain, account, guardians) } .getOrNull() ?: return null @@ -86,6 +113,16 @@ object GroupWalletStatementEvent { it.changeDescriptor == changeDescriptor } } + + private fun guardiansCheckOut(thresholdPublicKey: HexKey): Boolean = runCatching { + val certificate = certificate ?: return false + val chatRoomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) + val parentChatRoomId = SubgroupBirthCertificateEvent.parseParentChatRoomId(certificate.tags) ?: return false + + SubgroupBirthCertificateEvent.certifies(certificate, chatRoomId, parentChatRoomId) && + SubgroupBirthCertificateEvent.parseThresholdPublicKey(certificate.tags).equals(thresholdPublicKey, ignoreCase = true) && + SubgroupBirthCertificateEvent.parseGuardians(certificate.tags) == guardians + }.getOrDefault(false) } /** @@ -94,8 +131,24 @@ object GroupWalletStatementEvent { */ fun identifier(chain: Chain, account: Long): String = "${chainName(chain)}:$account" - fun template(account: GroupWalletDerivation.Account, createdAt: Long = Clock.System.now().epochSeconds): EventTemplate<*> = - EventTemplate( + /** + * The statement opening [account]. A guarded account needs the [certificate] + * its guardians were granted in, which the statement carries whole. + */ + fun template( + account: GroupWalletDerivation.Account, + certificate: Event? = null, + createdAt: Long = Clock.System.now().epochSeconds, + ): EventTemplate<*> { + require(!account.isGuarded || certificate != null) { "a guarded wallet's statement carries the certificate that granted its guardians" } + + val guarded = if (account.isGuarded) { + account.guardians.map(GuardianTag::assemble) + listOf(SubgroupBirthCertificateTag.assemble(certificate!!)) + } else { + emptyList() + } + + return EventTemplate( createdAt = createdAt, kind = KIND, tags = arrayOf( @@ -104,9 +157,10 @@ object GroupWalletStatementEvent { arrayOf(ACCOUNT_TAG, account.account.toString()), arrayOf(DESCRIPTOR_TAG, account.receiveDescriptor, RECEIVE_MARKER), arrayOf(DESCRIPTOR_TAG, account.changeDescriptor, CHANGE_MARKER), - ), + ) + guarded, content = account.xpub, ) + } /** The statement's fields, or null when any is missing or unreadable. Nothing is verified here. */ fun read(tags: Array>, content: String): Reading? { @@ -123,7 +177,11 @@ object GroupWalletStatementEvent { // account both stand; reading it back here keeps "newest per account" one rule. if (value(D_TAG) != identifier(chain, account)) return null - return Reading(chain, account, content, receive, change) + // Guardians that do not all read are not a shorter list of guardians. + val guardians = GuardianTag.parseAll(tags) ?: return null + val certificate = tags.firstNotNullOfOrNull(SubgroupBirthCertificateTag::parse)?.certificate + + return Reading(chain, account, content, receive, change, guardians, certificate) } /** diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEventTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEventTest.kt index f707eb15..e088e616 100644 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEventTest.kt +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEventTest.kt @@ -2,6 +2,10 @@ package com.machankura.bennu.compose.nostr.wallet import com.machankura.bennu.compose.database.model.GroupSignedEvent import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.managers.SharedKeyDerivation +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.machankura.bennu.compose.nostr.subgroup.tags.GuardianTag import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher import fr.acinq.bitcoin.ByteVector32 @@ -13,6 +17,7 @@ import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull +import kotlin.test.assertTrue /** * A wallet statement, read and believed. @@ -47,7 +52,7 @@ class GroupWalletStatementEventTest { } private fun statement(account: GroupWalletDerivation.Account, createdAt: Long = 1_700_000_000): GroupSignedEvent { - val template = GroupWalletStatementEvent.template(account, createdAt) + val template = GroupWalletStatementEvent.template(account, createdAt = createdAt) return signed(template.tags, template.content, createdAt) } @@ -120,6 +125,99 @@ class GroupWalletStatementEventTest { assertNull(GroupWallet.newestAmong(listOf(older, newer), thresholdKey, Chain.Signet)) } + // ---- A guarded statement --------------------------------------------- + + /** + * The parent, as a key whose secret the test holds: `certifies` asks only + * that the room the certificate names as parent signed it. + */ + private val parentKey = PrivateKey(ByteVector32(Hex.decode("0b".repeat(32)))) + private val parentRoomId = parentKey.publicKey().xOnly().value.toString() + private val childRoomId = SharedKeyDerivation.marmotGroupId(thresholdKey) + private val grant = GuardianDerivation.grant(key(0x9a4e47), parentRoomId, emptyList(), childRoomId) + + private fun certificate(guardians: List = grant, childKey: String = thresholdKey): Event { + val tags = SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = SharedKeyDerivation.marmotGroupId(childKey), + parentChatRoomId = parentRoomId, + thresholdPublicKey = childKey, + adminPublicKeys = listOf("a".repeat(64)), + name = "Translation team", + guardians = guardians, + ) + val content = SharedKeyDerivation.marmotGroupId(childKey) + val id = EventHasher.hashId(parentRoomId, 1_700_000_000, SubgroupBirthCertificateEvent.KIND, tags, content) + val sig = Crypto.signSchnorr(ByteVector32(id), parentKey, null).toString() + return Event(id, parentRoomId, 1_700_000_000, SubgroupBirthCertificateEvent.KIND, tags, content, sig) + } + + private val guarded = GroupWalletDerivation.account(thresholdKey, Chain.Mainnet, guardians = grant) + + private fun guardedStatement( + account: GroupWalletDerivation.Account = guarded, + certificate: Event = certificate(), + createdAt: Long = 1_700_000_000, + ): GroupSignedEvent { + val template = GroupWalletStatementEvent.template(account, certificate, createdAt) + return signed(template.tags, template.content, createdAt) + } + + @Test + fun `a guarded statement reads back as the guarded account, tree and all`() { + val wallet = assertNotNull(GroupWallet.of(guardedStatement(), thresholdKey)) + + assertEquals(guarded, wallet.account) + assertEquals(grant, wallet.account.guardians) + assertTrue(wallet.account.receiveDescriptor.contains("and_v(v:pk("), wallet.account.receiveDescriptor) + // Same internal key as the plain account, different address: only the tree differs. + val plainAddress = GroupWalletDerivation.derive(mainnet, 0, 0) + val guardedAddress = GroupWalletDerivation.derive(guarded, 0, 0) + assertEquals(plainAddress.internalKey, guardedAddress.internalKey) + assertTrue(plainAddress.address(Chain.Mainnet) != guardedAddress.address(Chain.Mainnet)) + assertTrue(guardedAddress.address(Chain.Mainnet).startsWith("bc1p")) + assertEquals(guardedAddress.outputKey, guardedAddress.cache.tweakedPublicKey, "the cache signs the key path of the guarded address") + } + + @Test + fun `guardians the certificate does not grant open nothing`() { + val stranger = GuardianDerivation.grant(key(0x5), parentRoomId, emptyList(), childRoomId) + val wrongGuardians = GroupWalletDerivation.account(thresholdKey, Chain.Mainnet, guardians = stranger) + + assertNull(GroupWallet.of(guardedStatement(account = wrongGuardians), thresholdKey), "guardians the parent never granted") + assertNull(GroupWallet.of(guardedStatement(certificate = certificate(childKey = otherThresholdKey)), thresholdKey), "a certificate for another child") + } + + @Test + fun `a guarded statement with its guardians stripped is no wallet at all`() { + // What a client that predates guardians sees: descriptors with a tree it + // does not build. It refuses rather than hand out plain addresses under + // the guarded account's name. + val template = GroupWalletStatementEvent.template(guarded, certificate()) + val stripped = template.tags.filterNot { it[0] == GuardianTag.TAG_NAME }.toTypedArray() + + assertNull(GroupWallet.of(signed(stripped, template.content), thresholdKey)) + } + + @Test + fun `an account opened guarded stays guarded, under its first guardians`() { + val firstGuarded = guardedStatement(createdAt = 1_700_000_000) + val laterPlain = statement(mainnet, createdAt = 1_700_000_200) + val laterOtherGuardians = run { + // The parent re-certified with other keys; a later statement adopting + // them would move every address, so it is ignored. + val other = GuardianDerivation.grant(key(0x77), parentRoomId, emptyList(), childRoomId) + guardedStatement( + account = GroupWalletDerivation.account(thresholdKey, Chain.Mainnet, guardians = other), + certificate = certificate(other), + createdAt = 1_700_000_300, + ) + } + + val wallet = assertNotNull(GroupWallet.newestAmong(listOf(laterPlain, firstGuarded, laterOtherGuardians), thresholdKey, Chain.Mainnet)) + assertEquals(firstGuarded.id, wallet.signedEvent.id) + assertEquals(laterPlain.id, GroupWallet.newestAmong(listOf(laterPlain), thresholdKey, Chain.Mainnet)?.signedEvent?.id) + } + @Test fun `every network name round trips`() { listOf(Chain.Mainnet, Chain.Testnet3, Chain.Testnet4, Chain.Signet, Chain.Regtest).forEach { From cbe5330cac8da6a6d486dea32d7564791bee6cb6 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 15:17:24 +0200 Subject: [PATCH 06/15] feat(wallet): a subgroup opens a guarded wallet, and spends from it as before (Phase 5) A room whose certificate grants guardian keys is offered a guarded wallet, with a plain one beside it, on test networks; mainnet waits behind GroupWalletRollout.GUARDIANS_ON_MAINNET. A spend's account is the one the statement opened, so its own spends sign the guarded addresses' key path, and wallets are watched per descriptor rather than per xpub. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 4 + .../repository/DatabaseChatRepository.kt | 7 ++ .../compose/managers/FrostSigningManager.kt | 6 +- .../compose/managers/GroupWalletManager.kt | 36 +++++++++ .../compose/repository/ChatRepository.kt | 13 ++++ .../ui/composable/GroupWalletScreen.kt | 55 ++++++++++++-- .../ui/view/model/GroupWalletViewModel.kt | 20 ++++- .../ui/view/state/GroupWalletUIState.kt | 6 ++ .../compose/wallet/GroupOnchainWallets.kt | 9 ++- .../compose/wallet/GroupWalletRollout.kt | 12 +++ .../managers/GroupSpendSigningJvmTest.kt | 74 +++++++++++++++++++ .../view/model/GroupWalletViewModelJvmTest.kt | 54 +++++++++++++- 12 files changed, 281 insertions(+), 15 deletions(-) diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 7dd87438..c1ac4a99 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -616,6 +616,10 @@ Opening a wallet asks the group to agree that it keeps coins here. Any quorum of members can then spend them together, and nobody can spend them alone. Each member's share of the group's key is stored unencrypted on their device. Anyone with an unlocked device, or a copy of its data, holds that member's share. Couldn't ask the group to open a wallet. + The groups above this one have agreed to guard its wallet. In a guarded wallet each of them can spend any coin once it has %1$d confirmations, without this group agreeing. + Open a guarded wallet + Open without guardians + Guarded: the groups above this one can spend any coin here once it has %1$d confirmations. Balance %1$s sats %1$s sats on the way diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt index 67f0128e..3db6572a 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt @@ -201,6 +201,13 @@ class DatabaseChatRepository( null } + override suspend fun groupWalletGuardedOpening(chatRoomId: String, chain: Chain): GroupWalletManager.GuardedOpening? = try { + GroupWalletManager.guardedAccountFor(database, chatRoomId, chain) + } catch (e: Throwable) { + logger.e("Error deriving the guarded wallet account of $chatRoomId", e) + null + } + override suspend fun groupSignedEvent(chatRoomId: String, id: HexKey): GroupSignedEvent? = try { database.groupSignedEventDao().getById(id)?.takeIf { it.chatRoomId == chatRoomId } } catch (e: Throwable) { diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt index e469a04a..8771db08 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt @@ -852,7 +852,11 @@ object FrostSigningManager { ): Pair? { val transaction = database.groupTransactionDao().getBySessionId(session.id) ?: return null val chain = GroupWalletStatementEvent.chainNamed(transaction.chain) ?: return null - return transaction to GroupWalletDerivation.account(thresholdPublicKey, chain, transaction.account) + // The account as the room's statement opened it: a guarded one's + // addresses carry its guardians' leaves, and the bare derivation would be + // a plain account at the same key, whose addresses none of these coins are at. + val opened = GroupWalletManager.walletFor(database, transaction.chatRoomId, thresholdPublicKey, chain, transaction.account) + return transaction to (opened?.account ?: GroupWalletDerivation.account(thresholdPublicKey, chain, transaction.account)) } /** diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletManager.kt index 37c35462..7660df06 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletManager.kt @@ -3,6 +3,8 @@ package com.machankura.bennu.compose.managers import com.machankura.bennu.compose.database.BennuDatabase import com.machankura.bennu.compose.nostr.wallet.GroupWallet import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import fr.acinq.bitcoin.Chain @@ -35,6 +37,40 @@ object GroupWalletManager { ): GroupWalletDerivation.Account? = thresholdKeyFor(database, chatRoomId)?.let { GroupWalletDerivation.account(it, chain, account) } + /** A guarded account a room could open, and the certificate that granted its guardians, which the statement carries. */ + data class GuardedOpening( + val account: GroupWalletDerivation.Account, + val certificate: Event, + ) + + /** + * The guarded account [chatRoomId] would open on [chain], or null for a room + * whose certificate grants it no guardian keys -- a room nobody's subgroup, + * or one certified before certificates carried them. + * + * Off the verified key state, the one place a certificate this device + * believes is kept. A member who holds no key state cannot open one; that + * member cannot sign, either. + */ + suspend fun guardedAccountFor( + database: BennuDatabase, + chatRoomId: String, + chain: Chain, + account: Long = 0L, + ): GuardedOpening? { + val thresholdPublicKey = thresholdKeyFor(database, chatRoomId) ?: return null + val certificate = GroupKeyStateManager.keyStateFor(database, chatRoomId) + ?.takeIf { it.verifies() } + ?.birthCertificateJson + ?.let { Event.fromJsonOrNull(it) } + ?: return null + val guardians = SubgroupBirthCertificateEvent.parseGuardians(certificate.tags) + ?.takeIf { it.isNotEmpty() } + ?: return null + + return GuardedOpening(GroupWalletDerivation.account(thresholdPublicKey, chain, account, guardians), certificate) + } + /** * The wallet [chatRoomId] has opened on [chain] under [thresholdPublicKey], or * null when the room signed no statement that key rederives. diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt index 5e2d8aaa..1351e00d 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt @@ -2,6 +2,7 @@ package com.machankura.bennu.compose.repository import fr.acinq.bitcoin.Chain import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.managers.GroupWalletManager import com.machankura.bennu.compose.nostr.wallet.GroupWallet import com.machankura.bennu.compose.database.model.ChatRoom import com.machankura.bennu.compose.database.model.GiftWrapPayload @@ -119,6 +120,13 @@ interface ChatRepository { */ suspend fun groupWalletAccount(chatRoomId: String, chain: Chain): GroupWalletDerivation.Account? + /** + * The guarded account this group could open on [chain] instead, and the + * certificate granting its guardians -- or null for a group whose birth + * certificate grants it none. + */ + suspend fun groupWalletGuardedOpening(chatRoomId: String, chain: Chain): GroupWalletManager.GuardedOpening? + /** * The kind:1s this group signed, newest first. * @@ -378,6 +386,11 @@ interface ChatRepository { chain: Chain ): GroupWalletDerivation.Account? = null + override suspend fun groupWalletGuardedOpening( + chatRoomId: String, + chain: Chain + ): GroupWalletManager.GuardedOpening? = null + override suspend fun groupPosts(chatRoomId: String): List = emptyList() override suspend fun groupSignedEvent( diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt index fd1ea3d8..a2e00a82 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt @@ -36,6 +36,7 @@ import androidx.compose.material.icons.filled.ContentCopy import androidx.compose.material.icons.filled.FormatListNumbered import androidx.compose.material.icons.filled.Visibility import androidx.compose.material3.Button +import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Card import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon @@ -72,6 +73,11 @@ import bennu.composeapp.generated.resources.finding_the_group_s_coins import bennu.composeapp.generated.resources.group_wallet import bennu.composeapp.generated.resources.nothing_has_been_sent_to_this_wallet_yet import bennu.composeapp.generated.resources.open_a_group_wallet +import bennu.composeapp.generated.resources.open_a_guarded_wallet +import bennu.composeapp.generated.resources.open_without_guardians +import bennu.composeapp.generated.resources.the_groups_above_this_one_have_agreed_to_guard_it +import bennu.composeapp.generated.resources.guarded_the_groups_above_this_one_can_spend +import com.machankura.bennu.compose.managers.GuardianDerivation import bennu.composeapp.generated.resources.opening_a_wallet_asks_the_group_to_agree import bennu.composeapp.generated.resources.receive_address import bennu.composeapp.generated.resources.received @@ -205,8 +211,10 @@ fun GroupWalletScreen( { OpenWalletAction( isPending = groupWalletViewModel.isActionPending.value, - onOpen = { + guardedOffered = state.guarded != null, + onOpen = { guarded -> groupWalletViewModel.openWallet( + guarded = guarded, onSuccess = { sessionId -> // Onto the session: the wallet does // not exist until a quorum signs. @@ -275,7 +283,7 @@ fun GroupWalletScreen( * an unencrypted share on a member's device means once there are coins behind it. */ @Composable -private fun OpenWalletAction(isPending: Boolean, onOpen: () -> Unit) { +private fun OpenWalletAction(isPending: Boolean, guardedOffered: Boolean, onOpen: (guarded: Boolean) -> Unit) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) @@ -289,10 +297,32 @@ private fun OpenWalletAction(isPending: Boolean, onOpen: () -> Unit) { style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, ) - Button(onClick = onOpen, enabled = !isPending) { - Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.open_a_group_wallet)) + if (guardedOffered) { + // The default for a subgroup whose parent agreed to guard it, and the + // plain wallet beside it rather than hidden: being guarded is the + // group's own choice, and its quorum signing the statement is it + // making that choice. + Text( + text = stringResource( + Res.string.the_groups_above_this_one_have_agreed_to_guard_it, + GuardianDerivation.ANCESTOR_DELAY.toInt() + ), + style = MaterialTheme.typography.bodyMedium, + ) + Button(onClick = { onOpen(true) }, enabled = !isPending) { + Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.open_a_guarded_wallet)) + } + OutlinedButton(onClick = { onOpen(false) }, enabled = !isPending) { + Text(stringResource(Res.string.open_without_guardians)) + } + } else { + Button(onClick = { onOpen(false) }, enabled = !isPending) { + Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.open_a_group_wallet)) + } } } } @@ -320,6 +350,19 @@ private fun OpenWallet( ) { item { BalanceCard(walletState) } + if (state.wallet.account.isGuarded) { + item { + Text( + text = stringResource( + Res.string.guarded_the_groups_above_this_one_can_spend, + GuardianDerivation.ANCESTOR_DELAY.toInt() + ), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + onSend?.let { send -> item { Button(onClick = send) { diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt index a2638dbd..7c09ed3f 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt @@ -6,6 +6,7 @@ import com.machankura.bennu.compose.ui.view.state.SpendStatus import com.machankura.bennu.compose.wallet.GroupSpend import com.machankura.bennu.compose.wallet.GroupSpendBuilder import com.machankura.bennu.compose.wallet.GroupTransactionWatcher +import com.machankura.bennu.compose.wallet.GroupWalletRollout import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.flowOf import androidx.compose.runtime.MutableState @@ -76,6 +77,9 @@ class GroupWalletViewModel( localChatRoom = localChatRoom, account = chatRepository.groupWalletAccount(chatRoomId, chain), canSign = canSign, + guarded = if (GroupWalletRollout.offersGuardiansOn(chain)) { + chatRepository.groupWalletGuardedOpening(chatRoomId, chain) + } else null, ) return@launch } @@ -159,17 +163,25 @@ class GroupWalletViewModel( * Never batched with anything, for the reason `GroupWalletStatementEvent` * gives -- every spend is opened against this, and it should never be as * available as its worst co-passenger. + * + * [guarded] opens the guarded account the room's certificate grants instead + * of the plain one: the statement then names the guardians and carries the + * certificate, and the group's quorum signing it is the group agreeing to be + * guarded. */ - fun openWallet(onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) { + fun openWallet(guarded: Boolean = false, onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) { val state = groupWalletUIState as? GroupWalletUIState.NotOpened ?: return - val account = state.account ?: return + val template = if (guarded) { + val opening = state.guarded ?: return + GroupWalletStatementEvent.template(opening.account, opening.certificate) + } else { + GroupWalletStatementEvent.template(state.account ?: return) + } // A second statement for the same account is harmless -- the same values // under the same `d` tag -- but it is a second quorum asked for nothing. if (isActionPending.value) return isActionPending.value = true - val template = GroupWalletStatementEvent.template(account) - viewModelScope.launch(Dispatchers.IO) { val session = runCatching { frostSigningRepository.proposeSigning( diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletUIState.kt index 6fa85a52..d8379218 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletUIState.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletUIState.kt @@ -2,6 +2,7 @@ package com.machankura.bennu.compose.ui.view.state import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.managers.GroupWalletManager import com.machankura.bennu.compose.nostr.wallet.GroupWallet import com.machankura.bennu.compose.wallet.GroupWalletState import com.machankura.bennu.compose.wallet.GroupSpend @@ -16,11 +17,16 @@ sealed interface GroupWalletUIState { * at all -- there is nothing to open then. [canSign] gates the way in, for * the reason every proposing screen gives: `proposeSigning` throws for a * device holding no share. + * + * [guarded] is the guarded account a subgroup could open instead, when its + * birth certificate grants it guardian keys and guarded wallets are offered + * on this network -- see `docs/group-wallet-guardians.md`. */ data class NotOpened( val localChatRoom: LocalChatRoom, val account: GroupWalletDerivation.Account?, val canSign: Boolean, + val guarded: GroupWalletManager.GuardedOpening? = null, ): GroupWalletUIState /** diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallets.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallets.kt index e1347ffb..bad97e3b 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallets.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallets.kt @@ -24,9 +24,14 @@ class GroupOnchainWallets( private val mutex = Mutex() private val wallets = mutableMapOf() - /** The wallet watching [account], made the first time it is asked for. Keyed by xpub, which names one account of one group on one network. */ + /** + * The wallet watching [account], made the first time it is asked for. Keyed + * by its receive descriptor, which names one account of one group on one + * network *and* the guardians in its addresses -- an xpub alone would hand a + * guarded account the plain one's addresses. + */ suspend fun walletFor(account: GroupWalletDerivation.Account): GroupOnchainWallet = mutex.withLock { - wallets.getOrPut(account.xpub) { GroupOnchainWallet(account, electrum, scope) } + wallets.getOrPut(account.receiveDescriptor) { GroupOnchainWallet(account, electrum, scope) } } /** diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupWalletRollout.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupWalletRollout.kt index 94020bed..335946b8 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupWalletRollout.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupWalletRollout.kt @@ -29,4 +29,16 @@ object GroupWalletRollout { val MAINNET_CAP: Satoshi = Satoshi(100_000) fun capFor(chain: Chain): Satoshi? = MAINNET_CAP.takeIf { chain.isMainnet() } + + /** + * Whether a subgroup is offered a guarded wallet on mainnet -- + * `docs/group-wallet-guardians.md`. Test networks are offered one from the + * start. Lifts when a guardian spend has been made on signet by a real + * three-level hierarchy, and every member of a mainnet group runs a build + * that reads guarded statements: an older client sees no wallet, and can open + * a plain one whose addresses the rest do not watch. + */ + const val GUARDIANS_ON_MAINNET: Boolean = false + + fun offersGuardiansOn(chain: Chain): Boolean = GUARDIANS_ON_MAINNET || !chain.isMainnet() } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupSpendSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupSpendSigningJvmTest.kt index 0edb4897..805632b8 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupSpendSigningJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupSpendSigningJvmTest.kt @@ -452,4 +452,78 @@ class GroupSpendSigningJvmTest { val confirmedLine = lines.single { it.messageType == ChatMessage.TYPE_GROUP_TRANSACTION_CONFIRMED } assertEquals("The group's transaction confirmed: 30000 sats sent.", confirmedLine.content) } + + // ---- A guarded wallet ----------------------------------------------- + + /** + * Files the room's key state as a subgroup's, under a certificate granting + * one guardian -- signed by a parent whose key the test holds, since + * `certifies` asks only that the room it names as parent signed it. + */ + private suspend fun fileGuardedParentage(device: Device): GroupWalletManager.GuardedOpening { + val parentKey = PrivateKey(ByteVector32(ByteArray(32) { 0x0b })) + val parentRoomId = parentKey.publicKey().xOnly().value.toString() + val guardians = GuardianDerivation.grant( + PrivateKey(ByteVector32(ByteArray(32) { 0x0c })).publicKey().toString(), parentRoomId, emptyList(), roomId, + ) + val tags = com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = roomId, parentChatRoomId = parentRoomId, thresholdPublicKey = thresholdPublicKey, + adminPublicKeys = members, name = "Treasury", guardians = guardians, + ) + val id = EventHasher.hashId(parentRoomId, 1_700_000_000, 30329, tags, roomId) + val certificate = Event(id, parentRoomId, 1_700_000_000, 30329, tags, roomId, + fr.acinq.bitcoin.Crypto.signSchnorr(ByteVector32(id), parentKey, null).toString()) + + device.db.groupKeyStateDao().upsert( + com.machankura.bennu.compose.database.model.GroupKeyState( + chatRoomId = roomId, dkgSessionId = ceremonyId, thresholdPublicKey = thresholdPublicKey, + derivationPath = SharedKeyDerivation.formatPath(), announcedBy = roomId, + announcedAt = Instant.fromEpochSeconds(1_700_000_000), + parentChatRoomId = parentRoomId, birthCertificateJson = certificate.toJson(), + ) + ) + return assertNotNull(GroupWalletManager.guardedAccountFor(device.db, roomId, chain)) + } + + @Test + fun `a guarded wallet is opened by its quorum, and its own spends stay on the key path`() = runBlocking { + val proposer = device(members[0], signerIndex = 0) + val other = device(members[1], signerIndex = 1) + val opening = fileGuardedParentage(proposer) + fileGuardedParentage(other) + + val template = GroupWalletStatementEvent.template(opening.account, opening.certificate) + val statement = FrostSigningManager.proposeSigning(proposer.db, proposer.room, proposer.publicKey, template.kind, template.tags, template.content) + pump(proposer, other) + FrostSigningManager.approve(other.db, other.room, statement.id) + pump(proposer, other) + + val guarded = assertNotNull(GroupWalletManager.walletFor(other.db, roomId, chain)).account + assertTrue(guarded.isGuarded) + assertEquals(opening.account, guarded) + + val first = GroupWalletDerivation.derive(guarded, GroupWalletDerivation.RECEIVE, 0) + val change = GroupWalletDerivation.derive(guarded, GroupWalletDerivation.CHANGE, 0) + val funding = Transaction(2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 0x47 })), 0), ByteVector.empty, 0xffffffffL)), + listOf(TxOut(Satoshi(60_000), first.pubkeyScript)), 0) + val tx = Transaction(2, listOf(TxIn(OutPoint(funding, 0), ByteVector.empty, 0xfffffffdL)), + listOf(TxOut(Satoshi(40_000), elsewhere), TxOut(Satoshi(19_000), change.pubkeyScript)), 0) + val psbt = GroupSpend.psbtOf(tx, listOf(funding.txOut[0] to first), mapOf(1 to change), guarded) + + // The plain account's check refuses the guarded coin: same internal key, another output. + assertIs(GroupSpend.check(psbt, account)) + + val session = FrostSigningManager.proposeSpend(proposer.db, proposer.room, proposer.publicKey, psbt, chain) + pump(proposer, other) + assertEquals(listOf(false, true), assertNotNull(FrostSigningManager.checkedSpend(other.db, session.id)).outputs.map { it.isChange }) + FrostSigningManager.approve(other.db, other.room, session.id) + pump(proposer, other) + + listOf(proposer, other).forEach { device -> + assertEquals(FrostSigningStage.COMPLETE, device.session(session.id)?.stage) + val signed = Transaction.read(assertNotNull(device.transaction(session.id)?.signedTransaction)) + signed.correctlySpends(mapOf(OutPoint(funding, 0) to funding.txOut[0]), ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) + assertEquals(1, signed.txIn[0].witness.stack.size, "a key-path spend: one signature, no script, no control block") + } + } } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModelJvmTest.kt index cd416648..a5526afd 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModelJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModelJvmTest.kt @@ -106,11 +106,11 @@ class GroupWalletViewModelJvmTest { } } - private fun viewModel(chat: ChatRepository, signing: FrostSigningRepository = RecordingSigning()) = + private fun viewModel(chat: ChatRepository, signing: FrostSigningRepository = RecordingSigning(), chain: Chain = Chain.Mainnet) = GroupWalletViewModel( activeUserPublicKey = me, chatRoomId = chatRoomId, - chain = Chain.Mainnet, + chain = chain, initialGroupWalletUIState = GroupWalletUIState.Loading, chatRepository = chat, frostSigningRepository = signing, @@ -169,6 +169,56 @@ class GroupWalletViewModelJvmTest { runBlocking { withTimeout(5_000) { while (!failed) delay(10) } } } + // ---- a guarded wallet --------------------------------------------------- + + /** What the repository would hand a subgroup whose certificate grants it guardians; the checks behind it are `GroupWalletStatementEventTest`'s. */ + private val certificate = com.vitorpamplona.quartz.nip01Core.core.Event( + "c".repeat(64), "b".repeat(64), 1_700_000_000, 30329, emptyArray(), chatRoomId, "f".repeat(128) + ) + private val guardians = com.machankura.bennu.compose.managers.GuardianDerivation.grant( + PrivateKey(ByteVector32(Hex.decode("9a4e47".padStart(64, '0')))).publicKey().toString(), + "b".repeat(64), emptyList(), chatRoomId, + ) + + private fun guardedRepository(chain: Chain) = object : ChatRepository by repository(opened = null) { + override suspend fun groupWalletGuardedOpening(chatRoomId: String, chain: Chain) = + com.machankura.bennu.compose.managers.GroupWalletManager.GuardedOpening( + GroupWalletDerivation.account( + PrivateKey(ByteVector32(Hex.decode("1c0ffee".padStart(64, '0')))).publicKey().toString(), + chain, guardians = guardians, + ), + certificate, + ) + } + + @Test + fun `a subgroup is offered a guarded wallet on a test network, and not yet on mainnet`() { + val regtest = assertIs( + viewModel(guardedRepository(Chain.Regtest), chain = Chain.Regtest).apply { initiate() }.settled() + ) + assertEquals(guardians, regtest.guarded?.account?.guardians) + + val mainnet = assertIs( + viewModel(guardedRepository(Chain.Mainnet)).apply { initiate() }.settled() + ) + assertNull(mainnet.guarded, "behind GroupWalletRollout.GUARDIANS_ON_MAINNET") + } + + @Test + fun `opening a guarded wallet proposes a statement naming the guardians and carrying the certificate`() { + val signing = RecordingSigning() + val model = viewModel(guardedRepository(Chain.Regtest), signing, chain = Chain.Regtest).apply { initiate() } + model.settled() + + model.openWallet(guarded = true, onSuccess = {}, onFailure = {}) + runBlocking { withTimeout(5_000) { while (signing.proposed == null || model.isActionPending.value) delay(10) } } + + val (_, tags, content) = assertNotNull(signing.proposed) + val reading = assertNotNull(GroupWalletStatementEvent.read(tags, content)) + assertEquals(guardians, reading.guardians) + assertEquals(certificate.id, reading.certificate?.id) + } + // ---- spends ------------------------------------------------------------ private val coinTx = fr.acinq.bitcoin.Transaction( From e7a1ad260f00829a36c946bb023399a8926b8ad9 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 15:26:19 +0200 Subject: [PATCH 07/15] feat(wallet): a guarded wallet is told to the groups above, and they watch it (Phase 6) A member in both rooms carries a descendant's signed guarded statement into an ancestor's MLS room as a 30333 notice, and can pass one on a generation further. Every ancestor device believes it only when its own guardian root reaches the key the statement names for it. The wallet screen lists the guarded wallets below the group with what is within its reach, and the statements this device can still carry up. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 8 + .../compose/database/model/ChatMessage.kt | 31 +++ .../repository/DatabaseChatRepository.kt | 22 ++ .../bennu/compose/managers/GuardianManager.kt | 242 ++++++++++++++++++ .../nostr/wallet/GuardedWalletNoticeEvent.kt | 46 ++++ .../compose/repository/ChatRepository.kt | 22 ++ .../ui/composable/GroupWalletScreen.kt | 108 +++++++- .../ui/view/model/GroupWalletViewModel.kt | 74 +++++- .../ui/view/state/GroupWalletUIState.kt | 28 ++ .../managers/GuardianSigningJvmTest.kt | 167 ++++++++++++ 10 files changed, 737 insertions(+), 11 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianManager.kt create mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GuardedWalletNoticeEvent.kt diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index c1ac4a99..d313760a 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -619,6 +619,14 @@ The groups above this one have agreed to guard its wallet. In a guarded wallet each of them can spend any coin once it has %1$d confirmations, without this group agreeing. Open a guarded wallet Open without guardians + Guarded wallets + Wallets of groups below this one. This group can spend a coin in them once it has %1$d confirmations. + %1$s sats within this group's reach + Tell the groups above + Not yet shared with the groups above that you're in + Share + Shared with the groups above + Couldn't share the wallet Guarded: the groups above this one can spend any coin here once it has %1$d confirmations. Balance %1$s sats diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt index dcfc8dac..e6a2c8be 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt @@ -14,6 +14,7 @@ import com.machankura.bennu.compose.exceptions.MarmotUnprocessableInnerEventExce import com.machankura.bennu.compose.managers.ChronicleManager import com.machankura.bennu.compose.managers.GroupKeyStateManager import com.machankura.bennu.compose.managers.GroupWalletManager +import com.machankura.bennu.compose.managers.GuardianManager import com.machankura.bennu.compose.managers.SubgroupManager import com.machankura.bennu.compose.extensions.toHex import com.vitorpamplona.quartz.marmot.GroupEventResult @@ -33,6 +34,7 @@ import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent import com.machankura.bennu.compose.nostr.wallet.GroupWallet import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.machankura.bennu.compose.nostr.wallet.GuardedWalletNoticeEvent import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent import com.machankura.bennu.compose.nostr.nip30303.ArtifactVersionEvent import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent @@ -497,6 +499,14 @@ data class ChatMessage( */ const val TYPE_GROUP_TRANSACTION_CONFIRMED = "groupTransactionConfirmed" + /** + * A member told this group about a descendant's guarded wallet -- a + * `GuardedWalletNoticeEvent` this device checked and believes. Written + * from the notice, attributed to the member who forwarded it. See + * `docs/group-wallet-guardians.md`. + */ + const val TYPE_GUARDED_WALLET_SHARED = "guardedWalletShared" + val GROUP_IDENTITY_TYPES = setOf( TYPE_GROUP_PROFILE_SIGNED, TYPE_GROUP_RELAYS_SIGNED, @@ -505,6 +515,7 @@ data class ChatMessage( TYPE_LEGACY_GROUP_ENTRY_CURATED, TYPE_GROUP_WALLET_OPENED, TYPE_GROUP_TRANSACTION_CONFIRMED, + TYPE_GUARDED_WALLET_SHARED, ) /** @@ -963,6 +974,26 @@ data class ChatMessage( return null } + // A descendant's guarded wallet, carried up by a member who is in + // both rooms. The row above is the whole record of it -- there is + // no table -- so all that is left is the line, and only for a + // notice this room can actually believe. + if (event.kind == GuardedWalletNoticeEvent.KIND) { + val content = GuardianManager.describeNotice(database, groupEventResult.groupId, event) + ?: return null + return ChatMessage( + giftWrapPayloadId = null, + messageType = TYPE_GUARDED_WALLET_SHARED, + marmotGroupEventId = groupEvent.id, + marmotInnerEventId = event.id, + senderPublicKey = senderIdentity ?: event.pubKey, + isUserMessage = senderIdentity == activeKeyPair.pubKey.toHex(), + chatRoomId = groupEventResult.groupId, + createdAt = Instant.fromEpochSeconds(event.createdAt), + content = content, + ) + } + // Somebody in the room holds none of its signed work and is // asking. Any member may answer and none is elected to: a // duplicate answer costs bandwidth and nothing else, since diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt index 3db6572a..afbbe830 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt @@ -2,6 +2,7 @@ package com.machankura.bennu.compose.database.repository import fr.acinq.bitcoin.Chain import com.machankura.bennu.compose.managers.GroupWalletManager +import com.machankura.bennu.compose.managers.GuardianManager import com.machankura.bennu.compose.managers.GroupWalletDerivation import com.machankura.bennu.compose.nostr.wallet.GroupWallet import com.machankura.bennu.compose.database.GENESIS_AT @@ -208,6 +209,27 @@ class DatabaseChatRepository( null } + override suspend fun guardedWallets(chatRoomId: String): List = try { + GuardianManager.guardedWalletsOf(database, chatRoomId) + } catch (e: Throwable) { + logger.e("Error reading the guarded wallets $chatRoomId was told about", e) + emptyList() + } + + override suspend fun shareableGuardedWallets(chatRoomId: String, chain: Chain): List = try { + GuardianManager.shareableFrom(database, chatRoomId, chain) + } catch (e: Throwable) { + logger.e("Error reading what $chatRoomId can tell the groups above it", e) + emptyList() + } + + override suspend fun shareGuardedWallet(shareable: GuardianManager.Shareable, userPublicKey: HexKey): Int = try { + GuardianManager.share(database, shareable.statement, shareable.rooms, userPublicKey) + } catch (e: Throwable) { + logger.e("Error telling the groups above about ${shareable.statement.pubKey}'s guarded wallet", e) + 0 + } + override suspend fun groupSignedEvent(chatRoomId: String, id: HexKey): GroupSignedEvent? = try { database.groupSignedEventDao().getById(id)?.takeIf { it.chatRoomId == chatRoomId } } catch (e: Throwable) { diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianManager.kt new file mode 100644 index 00000000..1f242e4b --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianManager.kt @@ -0,0 +1,242 @@ +package com.machankura.bennu.compose.managers + +import co.touchlab.kermit.Logger +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.model.MarmotInnerEvent +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.machankura.bennu.compose.nostr.wallet.GuardedWalletNoticeEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import fr.acinq.bitcoin.Chain +import kotlin.time.Clock +import kotlin.time.Instant + +/** + * What an ancestor group knows of the guarded wallets beneath it, and how it + * comes to know. + * + * A descendant opens a guarded wallet in its own room. Its ancestors are not in + * that room, so a member who sits in both carries the signed statement across + * as a [GuardedWalletNoticeEvent]; every device in the ancestor's room checks it + * for itself, and from then on watches the wallet and can propose spending from + * it through its own leaf. See `docs/group-wallet-guardians.md`, "How an + * ancestor finds the coins". + * + * A notice forwarded into a middle group can be forwarded again from there, so + * a root needs a member in common with each generation, not with the grandchild. + */ +object GuardianManager { + private const val TAG = "GuardianManager" + + private val logger = Logger.withTag(TAG) + + /** A descendant's guarded wallet, as one of its ancestors holds it. */ + data class GuardedWallet( + /** The ancestor holding it: the room it was told to. */ + val ancestorChatRoomId: String, + val descendantChatRoomId: String, + /** The descendant's signed statement, whole. */ + val statement: Event, + /** The account the statement opens, rederived from the descendant's key. */ + val account: GroupWalletDerivation.Account, + /** The descendant's birth certificate, carried in the statement. */ + val certificate: Event, + /** The rooms the ancestor walks from its own child down to the descendant -- `GuardianDerivation.lineage`. */ + val lineage: List, + ) { + /** What the descendant's parent certified it as. The founding name: a rename does not reach it. */ + val name: String? get() = SubgroupBirthCertificateEvent.parseName(certificate.tags) + + val chain: Chain get() = account.chain + + val openedAt: Instant get() = Instant.fromEpochSeconds(statement.createdAt) + } + + /** + * [statement] as a guarded wallet [ancestorChatRoomId] guards, or null when + * it is not one -- believed on its own merits, never on the word of whoever + * forwarded it: + * + * 1. it is a wallet statement, and the room it is authored by signed it; + * 2. it is guarded, and carries the certificate its guardians came from; + * 3. the certificate's key makes that room, and the statement's xpub, tree + * and descriptors all rederive from it -- `Reading.verifiedAgainst`, which + * also checks the certificate certifies the room and grants exactly those + * guardians; + * 4. the ancestor is among the guardians, and the key the statement names + * for it is the key [ancestorThresholdPublicKey]'s guardian root reaches + * down the line of descent the guardians name. A key it does not reach is + * a leaf this group cannot sign, whatever the statement calls it. + */ + fun verify(statement: Event, ancestorChatRoomId: String, ancestorThresholdPublicKey: HexKey): GuardedWallet? = runCatching { + if (statement.kind != GroupWalletStatementEvent.KIND) return null + val descendantChatRoomId = statement.pubKey + if (!GroupKeyStateEvent.isSignedByRoom(statement, descendantChatRoomId)) return null + + val reading = GroupWalletStatementEvent.read(statement.tags, statement.content) ?: return null + if (reading.guardians.isEmpty()) return null + val certificate = reading.certificate ?: return null + + val descendantKey = SubgroupBirthCertificateEvent.parseThresholdPublicKey(certificate.tags) ?: return null + if (!SharedKeyDerivation.marmotGroupId(descendantKey).equals(descendantChatRoomId, ignoreCase = true)) return null + val account = reading.verifiedAgainst(descendantKey) ?: return null + + val lineage = GuardianDerivation.lineage(account.guardians, descendantChatRoomId, ancestorChatRoomId) ?: return null + val named = account.guardians.first { it.chatRoomId.equals(ancestorChatRoomId, ignoreCase = true) } + val walked = GuardianDerivation.root(ancestorThresholdPublicKey).extendedPublicKey + .derivePublicKey(lineage.map(GuardianDerivation::childIndex)) + if (walked.publicKey != named.publicKey || walked.chaincode != named.chainCode) return null + + GuardedWallet( + ancestorChatRoomId = ancestorChatRoomId, + descendantChatRoomId = descendantChatRoomId, + statement = statement, + account = account, + certificate = certificate, + lineage = lineage, + ) + }.getOrNull() + + /** + * Every guarded wallet [ancestorChatRoomId] has been told about and can sign + * for, one per descendant account on each network. + * + * Read off the notices the room's inbound path filed, checked again each + * time. Where two statements describe one account, the rules + * `GroupWallet.newestAmong` applies to the descendant's own copy apply here: + * the earliest decides the guardians and a later one naming others is + * ignored, so a forwarder cannot move the addresses an ancestor watches. + */ + suspend fun guardedWalletsOf(database: BennuDatabase, ancestorChatRoomId: String): List { + val thresholdPublicKey = GroupWalletManager.thresholdKeyFor(database, ancestorChatRoomId) ?: return emptyList() + val order = compareBy({ it.openedAt }, { it.statement.id }) + + return database.marmotInnerEventDao() + .getByChatRoomAndKinds(ancestorChatRoomId, listOf(GuardedWalletNoticeEvent.KIND)) + .mapNotNull { row -> Event.fromJsonOrNull(row.content) } + .mapNotNull { verify(it, ancestorChatRoomId, thresholdPublicKey) } + .groupBy { Triple(it.descendantChatRoomId, it.chain, it.account.account) } + .mapNotNull { (_, statements) -> + val first = statements.minWithOrNull(order) ?: return@mapNotNull null + statements.filter { it.account.guardians == first.account.guardians }.maxWithOrNull(order) + } + .sortedBy { it.name ?: it.descendantChatRoomId } + } + + /** The guarded wallet [ancestorChatRoomId] holds for [descendantChatRoomId] on [chain] at [account], or null. */ + suspend fun guardedWalletFor( + database: BennuDatabase, + ancestorChatRoomId: String, + descendantChatRoomId: String, + chain: Chain, + account: Long, + ): GuardedWallet? = guardedWalletsOf(database, ancestorChatRoomId).firstOrNull { + it.descendantChatRoomId.equals(descendantChatRoomId, ignoreCase = true) && it.chain == chain && it.account.account == account + } + + /** A guarded statement this device can carry upward, and the rooms it can carry it into. */ + data class Shareable( + val statement: Event, + /** What the statement's room was certified as, for the screen. */ + val name: String?, + val rooms: List, + ) + + /** + * The guarded statements this device can tell to groups above [chatRoomId]: + * the room's own guarded wallet, and every one the room was itself told + * about -- passed on a generation further. Each with the guardian rooms this + * device is a member of and has not told yet. + */ + suspend fun shareableFrom(database: BennuDatabase, chatRoomId: String, chain: Chain): List { + val own = GroupWalletManager.walletFor(database, chatRoomId, chain) + ?.takeIf { it.account.isGuarded } + ?.let { wallet -> + val statement = wallet.signedEvent.toEvent() + val certificate = GroupWalletStatementEvent.read(statement.tags, statement.content)?.certificate + statement to (certificate?.let { SubgroupBirthCertificateEvent.parseName(it.tags) }) + } + val passedOn = guardedWalletsOf(database, chatRoomId) + .filter { it.chain == chain } + .map { it.statement to it.name } + + return (listOfNotNull(own) + passedOn).mapNotNull { (statement, name) -> + val rooms = targetsFor(database, statement, excluding = chatRoomId) + rooms.takeIf { it.isNotEmpty() }?.let { Shareable(statement, name, it) } + } + } + + /** + * The guardian rooms of [statement] this device can post into and has not + * told it yet. Only Marmot rooms: a guardian is a group with a key, and a + * group with a key has an MLS room. + */ + private suspend fun targetsFor(database: BennuDatabase, statement: Event, excluding: String): List { + val guardians = GroupWalletStatementEvent.read(statement.tags, statement.content)?.guardians.orEmpty() + + return guardians + .map { it.chatRoomId } + .filterNot { it.equals(excluding, ignoreCase = true) } + .mapNotNull { database.chatRoomDao().findChatRoomById(it) } + .filter { it.chatRoom.mlsGroupState != null } + .filterNot { room -> alreadyTold(database, room.chatRoom.id, statement.id) } + } + + private suspend fun alreadyTold(database: BennuDatabase, chatRoomId: String, statementId: HexKey): Boolean = + database.marmotInnerEventDao() + .getByChatRoomAndKinds(chatRoomId, listOf(GuardedWalletNoticeEvent.KIND)) + .any { Event.fromJsonOrNull(it.content)?.id == statementId } + + /** + * Tells every room in [rooms] about [statement], as [userPublicKey]: one + * notice each, queued for the outbound pipeline the way every inner event + * is. Returns how many were queued. + */ + suspend fun share( + database: BennuDatabase, + statement: Event, + rooms: List, + userPublicKey: HexKey, + createdAt: Long = Clock.System.now().epochSeconds, + ): Int { + val content = statement.toJson() + val tags = emptyArray>() + + rooms.forEach { room -> + val id = EventHasher.hashId(userPublicKey, createdAt, GuardedWalletNoticeEvent.KIND, tags, content) + database.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = id, + publicKey = userPublicKey, + kind = GuardedWalletNoticeEvent.KIND, + createdAt = Instant.fromEpochSeconds(createdAt), + tags = tags, + content = content, + chatRoomId = room.chatRoom.id, + ) + ) + logger.i("Told ${room.chatRoom.id} about ${statement.pubKey}'s guarded wallet") + } + + return rooms.size + } + + /** + * What a notice that arrived in [chatRoomId] says, for its transcript line -- + * or null when it is not one this room can believe, which gets no line: a + * line saying a wallet was shared would read as the group being told + * something it was not. + */ + suspend fun describeNotice(database: BennuDatabase, chatRoomId: String, notice: Event): String? { + val statement = GuardedWalletNoticeEvent.statementOf(notice) ?: return null + val thresholdPublicKey = GroupWalletManager.thresholdKeyFor(database, chatRoomId) ?: return null + val wallet = verify(statement, chatRoomId, thresholdPublicKey) ?: return null + + return wallet.name?.let { "Shared the guarded wallet of $it with this group." } + ?: "Shared a subgroup's guarded wallet with this group." + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GuardedWalletNoticeEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GuardedWalletNoticeEvent.kt new file mode 100644 index 00000000..8826113b --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GuardedWalletNoticeEvent.kt @@ -0,0 +1,46 @@ +package com.machankura.bennu.compose.nostr.wallet + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.Kind + +/** + * A member telling an ancestor group about a descendant's guarded wallet. + * + * The descendant's quorum signed a guarded `GroupWalletStatementEvent` in its + * own room, and the ancestors whose keys are in it are not in that room. A + * member who sits in both carries the statement across, whole, as the content of + * one of these in the ancestor's MLS room: + * + * ``` + * descendant's room every member holds the signed 30331 "we keep a guarded wallet" + * member in both --[ 30333 carrying it ]-> the ancestor's room + * every ancestor device checks it on its own, and watches the wallet + * ``` + * + * The forwarder vouches for nothing. A device believes the statement inside for + * the same reasons a descendant member does -- the descendant's room signed it, + * a certificate it carries certifies that room, the xpub rederives from the key + * the certificate names -- plus one of its own: its own guardian key in the + * statement is the key its group's walk reaches. See `GuardianManager.verify`. + * + * No table: the row the inbound path files for every inner event is the record, + * and each read checks it again. + * + * ### Never on a relay + * + * The statement inside is an xpub, which is every address and the whole + * balance. Like the statement, this only ever lives inside an encryption a relay + * cannot open: it is an MLS application message and nothing else. + * + * ### Why 30333 + * + * The first free number past the transaction proposal (30332), beside the + * statement it carries. + */ +object GuardedWalletNoticeEvent { + val KIND: Kind = 30333 + + /** The statement a notice carries, or null when its content is not an event. Nothing is verified here. */ + fun statementOf(notice: Event): Event? = + notice.takeIf { it.kind == KIND }?.let { Event.fromJsonOrNull(it.content) } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt index 1351e00d..6f4a9cae 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt @@ -3,6 +3,7 @@ package com.machankura.bennu.compose.repository import fr.acinq.bitcoin.Chain import com.machankura.bennu.compose.managers.GroupWalletDerivation import com.machankura.bennu.compose.managers.GroupWalletManager +import com.machankura.bennu.compose.managers.GuardianManager import com.machankura.bennu.compose.nostr.wallet.GroupWallet import com.machankura.bennu.compose.database.model.ChatRoom import com.machankura.bennu.compose.database.model.GiftWrapPayload @@ -127,6 +128,15 @@ interface ChatRepository { */ suspend fun groupWalletGuardedOpening(chatRoomId: String, chain: Chain): GroupWalletManager.GuardedOpening? + /** The guarded wallets of groups below this one that it has been told about and can sign for. */ + suspend fun guardedWallets(chatRoomId: String): List + + /** The guarded statements this device can carry from this group to the groups above it, with where to. */ + suspend fun shareableGuardedWallets(chatRoomId: String, chain: Chain): List + + /** Tells the groups in [shareable] about its statement, as [userPublicKey]. Returns how many were told. */ + suspend fun shareGuardedWallet(shareable: GuardianManager.Shareable, userPublicKey: HexKey): Int + /** * The kind:1s this group signed, newest first. * @@ -391,6 +401,18 @@ interface ChatRepository { chain: Chain ): GroupWalletManager.GuardedOpening? = null + override suspend fun guardedWallets(chatRoomId: String): List = emptyList() + + override suspend fun shareableGuardedWallets( + chatRoomId: String, + chain: Chain + ): List = emptyList() + + override suspend fun shareGuardedWallet( + shareable: GuardianManager.Shareable, + userPublicKey: HexKey + ): Int = 0 + override suspend fun groupPosts(chatRoomId: String): List = emptyList() override suspend fun groupSignedEvent( diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt index a2e00a82..b648c2d1 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt @@ -74,6 +74,18 @@ import bennu.composeapp.generated.resources.group_wallet import bennu.composeapp.generated.resources.nothing_has_been_sent_to_this_wallet_yet import bennu.composeapp.generated.resources.open_a_group_wallet import bennu.composeapp.generated.resources.open_a_guarded_wallet +import bennu.composeapp.generated.resources.a_subgroup +import bennu.composeapp.generated.resources.couldn_t_share_the_wallet +import bennu.composeapp.generated.resources.guarded_wallets +import bennu.composeapp.generated.resources.not_yet_shared_with_the_groups_above +import bennu.composeapp.generated.resources.s_sats_within_this_group_s_reach +import bennu.composeapp.generated.resources.share +import bennu.composeapp.generated.resources.shared_with_the_groups_above +import bennu.composeapp.generated.resources.tell_the_groups_above +import bennu.composeapp.generated.resources.wallets_of_groups_below_this_one +import com.machankura.bennu.compose.managers.GuardianManager +import com.machankura.bennu.compose.ui.view.state.GuardedWalletRow +import androidx.compose.foundation.lazy.LazyListScope import bennu.composeapp.generated.resources.open_without_guardians import bennu.composeapp.generated.resources.the_groups_above_this_one_have_agreed_to_guard_it import bennu.composeapp.generated.resources.guarded_the_groups_above_this_one_can_spend @@ -165,6 +177,11 @@ fun GroupWalletScreen( val couldNotOpen = stringResource(Res.string.couldn_t_ask_the_group_to_open_a_wallet) val sentAgain = stringResource(Res.string.sent_again) val couldNotBump = stringResource(Res.string.couldn_t_bump_the_fee) + val shared = stringResource(Res.string.shared_with_the_groups_above) + val couldNotShare = stringResource(Res.string.couldn_t_share_the_wallet) + val onShare = { shareable: GuardianManager.Shareable -> + groupWalletViewModel.share(shareable, onShared = { notify(shared) }, onFailure = { notify(couldNotShare) }) + } val toSession = { sessionId: String -> onNavigateToRoute(FrostSigningRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, sessionId = sessionId)) } @@ -200,8 +217,8 @@ fun GroupWalletScreen( } is GroupWalletUIState.NotOpened -> { - EmptyState( - modifier = Modifier.padding(padding).readableContent(), + val notOpened = @Composable { modifier: Modifier -> EmptyState( + modifier = modifier, message = stringResource(Res.string.this_group_has_not_opened_a_wallet), icon = Icons.Default.AccountBalanceWallet, // Hidden rather than disabled, the way every gated way in @@ -232,7 +249,27 @@ fun GroupWalletScreen( ) } } else null - ) + ) } + + if (state.guardedWallets.isEmpty() && state.shareable.isEmpty()) { + notOpened(Modifier.padding(padding).readableContent()) + } else { + // A group with no wallet of its own can still guard others', + // and still carry a descendant's upward. + LazyColumn( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) + ) { + item { notOpened(Modifier) } + guardianItems( + guardedWallets = state.guardedWallets, + shareable = state.shareable, + isPending = groupWalletViewModel.isActionPending.value, + onShare = onShare, + ) + } + } } is GroupWalletUIState.Loaded -> { @@ -270,6 +307,8 @@ fun GroupWalletScreen( groupWalletViewModel.bumpFee(sessionId, onSuccess = toSession, onFailure = { notify(couldNotBump) }) } } else null, + isPending = groupWalletViewModel.isActionPending.value, + onShare = onShare, ) } } @@ -337,6 +376,8 @@ private fun OpenWallet( onOpenSpend: (sessionId: String) -> Unit, onSendAgain: ((sessionId: String) -> Unit)?, onBump: ((sessionId: String) -> Unit)?, + isPending: Boolean, + onShare: (GuardianManager.Shareable) -> Unit, ) { val clipboardManager = LocalClipboardManager.current val addressCopied = stringResource(Res.string.address_copied) @@ -495,6 +536,13 @@ private fun OpenWallet( ) } } + + guardianItems( + guardedWallets = state.guardedWallets, + shareable = state.shareable, + isPending = isPending, + onShare = onShare, + ) } } @@ -540,6 +588,60 @@ private fun SpendStatus.label() = when (this) { } /** Confirmed and on-the-way said apart: only the first can be spent by a send-all. */ +/** + * The guarded wallets of groups below this one, and the guarded statements this + * device can still carry to the groups above. Both under the room's own wallet, + * or in place of it for a group that has none. + */ +private fun LazyListScope.guardianItems( + guardedWallets: List, + shareable: List, + isPending: Boolean, + onShare: (GuardianManager.Shareable) -> Unit, +) { + if (guardedWallets.isNotEmpty()) { + item { + Text(text = stringResource(Res.string.guarded_wallets), style = MaterialTheme.typography.titleMedium) + } + item { + Text( + text = stringResource(Res.string.wallets_of_groups_below_this_one, GuardianDerivation.ANCESTOR_DELAY.toInt()), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + items(guardedWallets, key = { "guarded-" + it.wallet.statement.id }) { row -> + ListItem( + leadingContent = { Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) }, + headlineContent = { Text(row.wallet.name ?: stringResource(Res.string.a_subgroup), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + supportingContent = { + Text( + row.withinReach?.let { stringResource(Res.string.s_sats_within_this_group_s_reach, it.grouped()) } + ?: stringResource(Res.string.balance_not_known_yet) + ) + }, + ) + } + } + + if (shareable.isNotEmpty()) { + item { + Text(text = stringResource(Res.string.tell_the_groups_above), style = MaterialTheme.typography.titleMedium) + } + items(shareable, key = { "shareable-" + it.statement.id }) { candidate -> + ListItem( + headlineContent = { Text(candidate.name ?: stringResource(Res.string.a_subgroup), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + supportingContent = { Text(stringResource(Res.string.not_yet_shared_with_the_groups_above)) }, + trailingContent = { + TextButton(onClick = { onShare(candidate) }, enabled = !isPending) { + Text(stringResource(Res.string.share)) + } + }, + ) + } + } +} + @Composable private fun BalanceCard(walletState: GroupWalletState?) { Card(modifier = Modifier.fillMaxWidth()) { diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt index 7c09ed3f..5f9d8439 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt @@ -7,8 +7,12 @@ import com.machankura.bennu.compose.wallet.GroupSpend import com.machankura.bennu.compose.wallet.GroupSpendBuilder import com.machankura.bennu.compose.wallet.GroupTransactionWatcher import com.machankura.bennu.compose.wallet.GroupWalletRollout +import com.machankura.bennu.compose.managers.GuardianManager +import com.machankura.bennu.compose.ui.view.state.GuardedWalletRow +import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.map import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -71,16 +75,29 @@ class GroupWalletViewModel( val canSign = localChatRoom.chatRoom.mlsGroupState != null && chatRepository.canSign(chatRoomId) val wallet = chatRepository.groupWallet(chatRoomId, chain) + val guarded = chatRepository.guardedWallets(chatRoomId).filter { it.chain == chain } + val shareable = chatRepository.shareableGuardedWallets(chatRoomId, chain) + val guardedRows = guarded.map { GuardedWalletRow(it, walletState = null) } + + watching?.cancel() if (wallet == null) { - groupWalletUIState = GroupWalletUIState.NotOpened( + val notOpened = GroupWalletUIState.NotOpened( localChatRoom = localChatRoom, account = chatRepository.groupWalletAccount(chatRoomId, chain), canSign = canSign, guarded = if (GroupWalletRollout.offersGuardiansOn(chain)) { chatRepository.groupWalletGuardedOpening(chatRoomId, chain) } else null, + guardedWallets = guardedRows, + shareable = shareable, ) + groupWalletUIState = notOpened + if (guarded.isNotEmpty()) { + watching = viewModelScope.launch(Dispatchers.IO) { + guardedStates(guarded).collect { rows -> groupWalletUIState = notOpened.copy(guardedWallets = rows) } + } + } return@launch } @@ -90,23 +107,64 @@ class GroupWalletViewModel( walletState = null, canWatch = wallets != null, canSign = canSign, + guardedWallets = guardedRows, + shareable = shareable, ) groupWalletUIState = loaded - // The chain and the room's spends, as one state: either changing - // redraws the screen, and neither may overwrite the other. + // The chain, the room's spends and the wallets it guards, as one + // state: any of them changing redraws the screen, and none may + // overwrite another. val chainState = wallets?.walletFor(wallet.account)?.state ?: flowOf(null) - watching?.cancel() watching = viewModelScope.launch(Dispatchers.IO) { - combine(chainState, frostSigningRepository.observeGroupTransactions(chatRoomId)) { state, transactions -> - state to transactions.map { rowOf(it) } - }.collect { (state, rows) -> - groupWalletUIState = loaded.copy(walletState = state, spends = rows) + combine( + chainState, + frostSigningRepository.observeGroupTransactions(chatRoomId), + guardedStates(guarded), + ) { state, transactions, guardedWallets -> + Triple(state, transactions.map { rowOf(it) }, guardedWallets) + }.collect { (state, rows, guardedWallets) -> + groupWalletUIState = loaded.copy(walletState = state, spends = rows, guardedWallets = guardedWallets) } } } } + /** + * Each guarded wallet with what the chain says of it, on the identity's own + * Electrum client -- or with nothing, for a profile that cannot watch. + */ + private suspend fun guardedStates(guarded: List): Flow> { + val wallets = wallets + if (wallets == null || guarded.isEmpty()) return flowOf(guarded.map { GuardedWalletRow(it, walletState = null) }) + + val states = guarded.map { wallet -> wallets.walletFor(wallet.account).state.map { GuardedWalletRow(wallet, it) } } + return combine(states) { it.toList() } + } + + /** + * Tells the groups above about [shareable]'s guarded wallet: one notice into + * each of their rooms this device is in. What is told stays told, so the + * row goes from the screen once it is sent. + */ + fun share(shareable: GuardianManager.Shareable, onShared: () -> Unit, onFailure: () -> Unit) { + if (isActionPending.value) return + isActionPending.value = true + + viewModelScope.launch(Dispatchers.IO) { + val told = chatRepository.shareGuardedWallet(shareable, activeUserPublicKey) + if (told > 0) { + groupWalletUIState = when (val state = groupWalletUIState) { + is GroupWalletUIState.Loaded -> state.copy(shareable = state.shareable - shareable) + is GroupWalletUIState.NotOpened -> state.copy(shareable = state.shareable - shareable) + else -> state + } + } + withContext(Dispatchers.Main) { if (told > 0) onShared() else onFailure() } + isActionPending.value = false + } + } + /** Checked once per session: the PSBT is write-once, so what it says cannot change. */ private val checkedSpends = mutableMapOf() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletUIState.kt index d8379218..12691e90 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletUIState.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletUIState.kt @@ -3,6 +3,10 @@ package com.machankura.bennu.compose.ui.view.state import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom import com.machankura.bennu.compose.managers.GroupWalletDerivation import com.machankura.bennu.compose.managers.GroupWalletManager +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.managers.GuardianManager +import fr.acinq.bitcoin.Satoshi +import fr.acinq.lightning.utils.sum import com.machankura.bennu.compose.nostr.wallet.GroupWallet import com.machankura.bennu.compose.wallet.GroupWalletState import com.machankura.bennu.compose.wallet.GroupSpend @@ -27,6 +31,10 @@ sealed interface GroupWalletUIState { val account: GroupWalletDerivation.Account?, val canSign: Boolean, val guarded: GroupWalletManager.GuardedOpening? = null, + /** Guarded wallets of groups below this one. A group with no wallet of its own can still guard others'. */ + val guardedWallets: List = emptyList(), + /** Guarded statements this device can carry to the groups above. */ + val shareable: List = emptyList(), ): GroupWalletUIState /** @@ -44,6 +52,10 @@ sealed interface GroupWalletUIState { val canSign: Boolean, /** The room's spends, newest first. */ val spends: List = emptyList(), + /** Guarded wallets of groups below this one. */ + val guardedWallets: List = emptyList(), + /** Guarded statements this device can carry to the groups above. */ + val shareable: List = emptyList(), ): GroupWalletUIState data class Error( @@ -53,6 +65,22 @@ sealed interface GroupWalletUIState { data object Loading: GroupWalletUIState } +/** A descendant's guarded wallet, as an ancestor's wallet screen lists it. */ +data class GuardedWalletRow( + val wallet: GuardianManager.GuardedWallet, + /** Null before Electrum's first answer, and for a profile that cannot watch the chain. */ + val walletState: GroupWalletState?, +) { + /** + * What this group could spend now: coins confirmed at least as deep as its + * leaf's lock. Null while the chain is not known. + */ + val withinReach: Satoshi? + get() = walletState?.let { state -> + state.utxos.filter { state.confirmations(it) >= GuardianDerivation.ANCESTOR_DELAY }.map { it.amount }.sum() + } +} + /** Where one of the room's spends has got to, as one fact a member reads. */ enum class SpendStatus { WAITING_FOR_SIGNATURES, diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt index c8418a88..cf275df8 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt @@ -29,6 +29,17 @@ import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.time.Instant +import com.machankura.bennu.compose.database.model.GroupSignedEvent +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.machankura.bennu.compose.nostr.wallet.GuardedWalletNoticeEvent +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.crypto.frost.IndividualNonce +import fr.acinq.bitcoin.crypto.frost.SecretNonce +import fr.acinq.bitcoin.crypto.frost.Session +import kotlin.test.assertTrue /** * A group's guardian keys through the real signing manager, between two of its @@ -187,4 +198,160 @@ class GuardianSigningJvmTest { assertNull(other.session(session.id), "refused at acceptance, so nothing of the member's is ever published for it") } + + // ---- Telling an ancestor about a guarded wallet ----------------------- + + /** The child as a group of its own, so its room can sign its statement. */ + private val childMaterial: KeyMaterial = Frost.trustedDealerKeygen( + thresholdSecretKey = PrivateKey(ByteVector32("c41d".padEnd(62, '0') + "b2")), + nParticipants = participants, + threshold = threshold, + ) + private val guardedChildKey = childMaterial.thresholdPublicKey.value.toHex() + private val guardedChildRoomId = SharedKeyDerivation.marmotGroupId(guardedChildKey) + + /** [material]'s room signing [id], as a quorum of its trusted-dealer shares. */ + private fun roomSignature(material: KeyMaterial, id: String): String { + val cache = SharedKeyDerivation.derive(material.thresholdPublicKey.value.toHex()).cache + val message = ByteVector(id.hexToByteArray()) + val signerIds = listOf(0, 1) + val nonces = signerIds.map { signerId -> + SecretNonce.generate( + sessionRandom = ByteVector32("b".repeat(63) + "${signerId + 1}"), + secretShare = material.secretShares[signerId], + publicShare = material.publicShares[signerId], + tweakedThresholdPublicKey = cache.tweakedPublicKey, + message = message, + extraInput = null, + ) + } + val session = Session.create( + aggregatedNonce = IndividualNonce.aggregate(nonces.map { it.second }).right!!, + signerIds = signerIds.map { it.toUInt() }, + signerPublicShares = signerIds.map { material.publicShares[it] }, + nParticipants = participants, + threshold = threshold, + tweakCache = cache, + message = message, + ) + val partials = signerIds.mapIndexed { position, signerId -> + session.sign(nonces[position].first, material.secretShares[signerId], signerId.toUInt()).right!! + } + return session.aggregateSigs(partials).right!!.toByteArray().toHex() + } + + private fun signedBy(material: KeyMaterial, kind: Int, tags: Array>, content: String, createdAt: Long = 1_700_000_000): Event { + val author = SharedKeyDerivation.marmotGroupId(material.thresholdPublicKey.value.toHex()) + val id = EventHasher.hashId(author, createdAt, kind, tags, content) + return Event(id, author, createdAt, kind, tags, content, roomSignature(material, id)) + } + + /** The ancestor certifies the child with [guardians], and the child signs a guarded statement under them. */ + private fun guardedStatement( + guardians: List = GuardianDerivation.grant(thresholdPublicKey, roomId, emptyList(), guardedChildRoomId), + createdAt: Long = 1_700_000_000, + ): Event { + val certificate = signedBy( + keyMaterial, SubgroupBirthCertificateEvent.KIND, + SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = guardedChildRoomId, parentChatRoomId = roomId, thresholdPublicKey = guardedChildKey, + adminPublicKeys = members, name = "Translation team", guardians = guardians, + ), + guardedChildRoomId, + ) + val account = GroupWalletDerivation.account(guardedChildKey, Chain.Regtest, guardians = guardians) + val template = GroupWalletStatementEvent.template(account, certificate, createdAt) + return signedBy(childMaterial, template.kind, template.tags, template.content, createdAt) + } + + private suspend fun tell(device: Device, statement: Event, from: HexKey = members[2], createdAt: Long = 1_700_000_100) { + val content = statement.toJson() + device.db.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = EventHasher.hashId(from, createdAt, GuardedWalletNoticeEvent.KIND, emptyArray(), content), + publicKey = from, kind = GuardedWalletNoticeEvent.KIND, createdAt = Instant.fromEpochSeconds(createdAt), + tags = emptyArray(), content = content, chatRoomId = roomId, + ) + ) + } + + @Test + fun `an ancestor believes a statement naming a key its own walk reaches, and nothing else`() { + val statement = guardedStatement() + + val wallet = assertNotNull(GuardianManager.verify(statement, roomId, thresholdPublicKey)) + assertEquals(guardedChildRoomId, wallet.descendantChatRoomId) + assertEquals(listOf(guardedChildRoomId), wallet.lineage) + assertEquals("Translation team", wallet.name) + assertTrue(wallet.account.isGuarded) + + val strangerKey = PrivateKey(ByteVector32(ByteArray(32) { 0x55 })).publicKey().toString() + val refusals = mapOf( + "a group that is not among its guardians" to GuardianManager.verify(statement, guardedChildRoomId, guardedChildKey), + "a key the ancestor's walk does not reach" to GuardianManager.verify( + guardedStatement(GuardianDerivation.grant(strangerKey, roomId, emptyList(), guardedChildRoomId)), roomId, thresholdPublicKey, + ), + "a statement the child's room did not sign" to GuardianManager.verify(Event(statement.id, statement.pubKey, statement.createdAt, statement.kind, statement.tags, statement.content, "0".repeat(128)), roomId, thresholdPublicKey), + "a plain statement" to run { + val plain = GroupWalletStatementEvent.template(GroupWalletDerivation.account(guardedChildKey, Chain.Regtest)) + GuardianManager.verify(signedBy(childMaterial, plain.kind, plain.tags, plain.content), roomId, thresholdPublicKey) + }, + ) + refusals.forEach { (name, verified) -> assertNull(verified, name) } + } + + @Test + fun `a notice in the ancestor's room is a guarded wallet it holds, under its first guardians`() = runBlocking { + val ancestor = device(members[0], signerIndex = 0) + val first = guardedStatement(createdAt = 1_700_000_000) + tell(ancestor, first) + // A later statement for the same account, naming other guardians, cannot + // move what the ancestor watches -- the earliest decides. + val second = guardedStatement( + GuardianDerivation.grant(thresholdPublicKey, roomId, emptyList(), guardedChildRoomId).map { it.copy(delay = 13) }, + createdAt = 1_700_000_500, + ) + tell(ancestor, second, createdAt = 1_700_000_600) + // And nonsense is read past, not believed. + ancestor.db.marmotInnerEventDao().upsert( + MarmotInnerEvent(id = "f".repeat(64), publicKey = members[2], kind = GuardedWalletNoticeEvent.KIND, + createdAt = Instant.fromEpochSeconds(1), tags = emptyArray(), content = "not an event", chatRoomId = roomId) + ) + + val held = GuardianManager.guardedWalletsOf(ancestor.db, roomId) + assertEquals(listOf(first.id), held.map { it.statement.id }) + assertEquals( + "Shared the guarded wallet of Translation team with this group.", + GuardianManager.describeNotice(ancestor.db, roomId, Event("1".repeat(64), members[2], 1, GuardedWalletNoticeEvent.KIND, emptyArray(), first.toJson(), "")) + ) + } + + @Test + fun `a member in both rooms carries the child's statement up, once`() = runBlocking { + val member = device(members[0], signerIndex = 0) + // This device is also in the child's room, and holds its signed statement there. + member.db.chatRoomDao().upsert(ChatRoom(id = guardedChildRoomId, userPublicKey = member.publicKey, subject = "Translation team", description = null, mlsGroupState = "00")) + member.db.groupKeyStateDao().upsert( + com.machankura.bennu.compose.database.model.GroupKeyState( + chatRoomId = guardedChildRoomId, dkgSessionId = "child-ceremony", thresholdPublicKey = guardedChildKey, + derivationPath = SharedKeyDerivation.formatPath(), announcedBy = guardedChildRoomId, + announcedAt = Instant.fromEpochSeconds(1_700_000_000), + ) + ) + val statement = guardedStatement() + member.db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(statement, chatRoomId = guardedChildRoomId)) + + val shareable = GuardianManager.shareableFrom(member.db, guardedChildRoomId, Chain.Regtest).single() + assertEquals(statement.id, shareable.statement.id) + assertEquals(listOf(roomId), shareable.rooms.map { it.chatRoom.id }) + + assertEquals(1, GuardianManager.share(member.db, shareable.statement, shareable.rooms, member.publicKey)) + val queued = member.db.marmotInnerEventDao().getByChatRoomAndKinds(roomId, listOf(GuardedWalletNoticeEvent.KIND)).single() + assertEquals(member.publicKey, queued.publicKey) + assertNull(queued.marmotGroupEventId, "queued for the outbound pipeline, not yet sent") + + // Told is told: nothing left to share, and the ancestor's own device reads it back. + assertEquals(emptyList(), GuardianManager.shareableFrom(member.db, guardedChildRoomId, Chain.Regtest)) + assertEquals(listOf(statement.id), GuardianManager.guardedWalletsOf(member.db, roomId).map { it.statement.id }) + } } From 634f51f915ed80e55e59bb82f29dc15eae9e01a3 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 15:34:30 +0200 Subject: [PATCH 08/15] fix(wallet): read a PSBT's key fingerprint as unsigned bitcoin-kmp reads a taproot derivation's fingerprint back from a serialised PSBT as a signed int, so for any account whose fingerprint has its top bit set -- half of them -- every member but the proposer refused every spend as not the wallet's own. Compare the fingerprint as an unsigned 32-bit value. Co-Authored-By: Claude Opus 5.5 --- .../bennu/compose/wallet/GroupSpend.kt | 18 +++++- .../wallet/GroupSpendFingerprintTest.kt | 61 +++++++++++++++++++ 2 files changed, 76 insertions(+), 3 deletions(-) create mode 100644 composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/wallet/GroupSpendFingerprintTest.kt diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpend.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpend.kt index f27490c5..4dcb5cdb 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpend.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpend.kt @@ -169,7 +169,7 @@ object GroupSpend { // 5. Change is change only if it derives. val outputs = psbt.outputs.mapIndexed { index, output -> val txOut = tx.txOut[index] - val ours = output.taprootDerivationPaths.values.filter { it.masterKeyFingerprint == account.fingerprint } + val ours = output.taprootDerivationPaths.values.filter { isOurs(it, account) } val change = if (ours.isEmpty()) { null } else { @@ -204,7 +204,7 @@ object GroupSpend { fun claimedChangeIndices(psbt: Psbt, account: GroupWalletDerivation.Account): Set = psbt.outputs .flatMap { it.taprootDerivationPaths.values } - .filter { it.masterKeyFingerprint == account.fingerprint } + .filter { isOurs(it, account) } .mapNotNull { path -> path.keyPath.path.takeIf { it.size == 2 && it[0] == GroupWalletDerivation.CHANGE }?.get(1) } .toSet() @@ -219,7 +219,7 @@ object GroupSpend { paths: Map, account: GroupWalletDerivation.Account, ): GroupWalletDerivation.Derived? { - val (internalKey, path) = paths.entries.singleOrNull { it.value.masterKeyFingerprint == account.fingerprint } + val (internalKey, path) = paths.entries.singleOrNull { isOurs(it.value, account) } ?.toPair() ?: return null if (path.leaves.isNotEmpty()) return null @@ -230,6 +230,18 @@ object GroupSpend { return GroupWalletDerivation.derive(account, change, index).takeIf { it.internalKey == internalKey } } + /** + * Whether [path] names [account] as its master key. + * + * Compared as an unsigned 32-bit value. bitcoin-kmp reads a taproot + * derivation's fingerprint back from a serialised PSBT as a *signed* int, so + * an account whose fingerprint has its top bit set -- half of them -- would + * write `3578966523` and read back `-716000773`, and every member but the + * proposer would refuse every spend from that wallet as not its own. + */ + private fun isOurs(path: TaprootBip32DerivationPath, account: GroupWalletDerivation.Account): Boolean = + (path.masterKeyFingerprint and 0xFFFFFFFFL) == account.fingerprint + /** * The PSBT a proposer sends: [tx] with every input's spent output and * derivation, and every change output's derivation, so that a signer is diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/wallet/GroupSpendFingerprintTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/wallet/GroupSpendFingerprintTest.kt new file mode 100644 index 00000000..9ad95515 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/wallet/GroupSpendFingerprintTest.kt @@ -0,0 +1,61 @@ +package com.machankura.bennu.compose.wallet + +import com.machankura.bennu.compose.managers.GroupWalletDerivation +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.OutPoint +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.Satoshi +import fr.acinq.bitcoin.Script +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxId +import fr.acinq.bitcoin.TxIn +import fr.acinq.bitcoin.TxOut +import fr.acinq.secp256k1.Hex +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertTrue + +/** + * A spend checked the way every member but the proposer checks it: after the + * PSBT has been through the wire. + * + * Half of all accounts have a fingerprint with its top bit set, and bitcoin-kmp + * reads a taproot derivation's fingerprint back from a serialised PSBT as a + * signed int. Compared as written, every such wallet's spends were refused by + * every member who did not build them. + */ +class GroupSpendFingerprintTest { + /** The first account, counting up from a fixed seed, whose fingerprint has its top bit set. */ + private val account: GroupWalletDerivation.Account = generateSequence(1) { it + 1 } + .map { seed -> + val key = PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))).publicKey().toString() + GroupWalletDerivation.account(key, Chain.Regtest) + } + .first { it.fingerprint >= 0x80000000L } + + @Test + fun `a spend from a wallet with a high fingerprint checks out after the wire`() { + val coin = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, 0) + val change = GroupWalletDerivation.derive(account, GroupWalletDerivation.CHANGE, 0) + val funding = Transaction( + 2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 0x51 })), 0), ByteVector.empty, 0xffffffffL)), + listOf(TxOut(Satoshi(50_000), coin.pubkeyScript)), 0, + ) + val elsewhere = ByteVector(Script.write(Script.pay2wpkh(PrivateKey(ByteVector32(ByteArray(32) { 9 })).publicKey()))) + val tx = Transaction( + 2, listOf(TxIn(OutPoint(funding, 0), ByteVector.empty, GroupSpend.MAX_SEQUENCE)), + listOf(TxOut(Satoshi(30_000), elsewhere), TxOut(Satoshi(19_000), change.pubkeyScript)), 0, + ) + val proposed = GroupSpend.psbtOf(tx, listOf(funding.txOut[0] to coin), mapOf(1 to change), account) + + assertTrue(account.fingerprint >= 0x80000000L) + val received = GroupSpend.decode(GroupSpend.encode(proposed))!! + + val checked = assertIs(GroupSpend.check(received, account)).checked + assertEquals(listOf(false, true), checked.outputs.map { it.isChange }) + assertEquals(setOf(0L), GroupSpend.claimedChangeIndices(received, account)) + } +} From 00df58c1f31a8aca17f83a5bf4987fad0bf4d6e4 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 15:37:21 +0200 Subject: [PATCH 09/15] feat(wallet): an ancestor's quorum spends a descendant's coins through its leaf (Phase 7) GroupSpend checks a spend as a guardian would sign it: every input under the descendant's account, locked by the leaf's 12 blocks, signed over the script-path sighash as the key the ancestor's walk reaches, and witnessed with the leaf and its control block. The builder waits out the lock and weighs the leaf; the signing manager proposes, accepts, signs and completes it, and every signer reads the descendant's wallet from its own copy of the statement. A guarded wallet row on the ancestor's wallet screen opens the send form for it. Schema v27 adds GroupTransaction.guardedChatRoomId. Co-Authored-By: Claude Opus 5.5 --- .../27.json | 5975 +++++++++++++++++ .../composeResources/values/strings.xml | 2 + .../bennu/compose/database/BennuDatabase.kt | 7 +- .../database/model/GroupTransaction.kt | 7 + .../DatabaseFrostSigningRepository.kt | 17 + .../compose/managers/FrostSigningManager.kt | 179 +- .../bennu/compose/managers/GuardianManager.kt | 8 + .../compose/nostr/frost/FrostSigningEvents.kt | 15 + .../repository/FrostSigningRepository.kt | 21 + .../bennu/compose/text/ProposedSpend.kt | 7 +- .../compose/ui/composable/GroupSendScreen.kt | 11 +- .../ui/composable/GroupWalletScreen.kt | 25 + .../ui/composable/navigation/BennuNavHost.kt | 1 + .../navigation/routes/GroupSendRoute.kt | 9 +- .../ui/view/model/GroupSendViewModel.kt | 49 +- .../ui/view/model/GroupWalletViewModel.kt | 8 +- .../compose/ui/view/state/GroupSendUIState.kt | 7 + .../bennu/compose/wallet/GroupSpend.kt | 131 +- .../bennu/compose/wallet/GroupSpendBuilder.kt | 88 +- .../managers/GuardianSigningJvmTest.kt | 123 +- 20 files changed, 6617 insertions(+), 73 deletions(-) create mode 100644 composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/27.json diff --git a/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/27.json b/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/27.json new file mode 100644 index 00000000..1cda00e0 --- /dev/null +++ b/composeApp/schemas/com.machankura.bennu.compose.database.BennuDatabase/27.json @@ -0,0 +1,5975 @@ +{ + "formatVersion": 1, + "database": { + "version": 27, + "identityHash": "2fe774344e85e188dd6793623347bf91", + "entities": [ + { + "tableName": "BroadcastNostrEventReceipt", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `nostrEventId` TEXT NOT NULL, `unsignedNostrEventId` INTEGER, `isAccepted` INTEGER NOT NULL, `isSync` INTEGER NOT NULL, `relayURL` TEXT NOT NULL, `messages` TEXT, FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`unsignedNostrEventId`) REFERENCES `UnsignedNostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "isAccepted", + "columnName": "isAccepted", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isSync", + "columnName": "isSync", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "messages", + "columnName": "messages", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_BroadcastNostrEventReceipt_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventReceipt_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_BroadcastNostrEventReceipt_isAccepted", + "unique": false, + "columnNames": [ + "isAccepted" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventReceipt_isAccepted` ON `${TABLE_NAME}` (`isAccepted`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "UnsignedNostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "unsignedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "BroadcastNostrEventRequest", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `nostrEventId` TEXT NOT NULL, `unsignedNostrEventId` INTEGER, `status` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`unsignedNostrEventId`) REFERENCES `UnsignedNostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_BroadcastNostrEventRequest_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventRequest_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_BroadcastNostrEventRequest_status", + "unique": false, + "columnNames": [ + "status" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_BroadcastNostrEventRequest_status` ON `${TABLE_NAME}` (`status`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "UnsignedNostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "unsignedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Connection", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sourcePublicKey` TEXT NOT NULL, `destinationPublicKey` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`sourcePublicKey`, `destinationPublicKey`), FOREIGN KEY(`sourcePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`destinationPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sourcePublicKey", + "columnName": "sourcePublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "destinationPublicKey", + "columnName": "destinationPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sourcePublicKey", + "destinationPublicKey" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sourcePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "destinationPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + } + ] + }, + { + "tableName": "ChatMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `senderPublicKey` TEXT NOT NULL, `isUserMessage` INTEGER NOT NULL, `giftWrapPayloadId` TEXT, `marmotGroupEventId` TEXT, `marmotInnerEventId` TEXT, `chatRoomId` TEXT NOT NULL, `replyToMessageId` INTEGER, `quotedMessageId` INTEGER, `content` TEXT NOT NULL, `messageType` TEXT NOT NULL, `directMessageRecipientPublicKey` TEXT, `frostSigningSessionId` TEXT, `dkgSessionId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`giftWrapPayloadId`) REFERENCES `GiftWrapPayload`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`marmotGroupEventId`) REFERENCES `MarmotGroupEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`marmotInnerEventId`) REFERENCES `MarmotInnerEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isUserMessage", + "columnName": "isUserMessage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "giftWrapPayloadId", + "columnName": "giftWrapPayloadId", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotGroupEventId", + "columnName": "marmotGroupEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotInnerEventId", + "columnName": "marmotInnerEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "replyToMessageId", + "columnName": "replyToMessageId", + "affinity": "INTEGER" + }, + { + "fieldPath": "quotedMessageId", + "columnName": "quotedMessageId", + "affinity": "INTEGER" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "messageType", + "columnName": "messageType", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "directMessageRecipientPublicKey", + "columnName": "directMessageRecipientPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "frostSigningSessionId", + "columnName": "frostSigningSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_ChatMessage_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ChatMessage_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "GiftWrapPayload", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "giftWrapPayloadId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "MarmotGroupEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "marmotGroupEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "MarmotInnerEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "marmotInnerEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatMessageBroadcastNostrEventRequestRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `chatMessageId` INTEGER NOT NULL, `broadcastNostrEventRequestId` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, FOREIGN KEY(`chatMessageId`) REFERENCES `ChatMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`broadcastNostrEventRequestId`) REFERENCES `BroadcastNostrEventRequest`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "chatMessageId", + "columnName": "chatMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "broadcastNostrEventRequestId", + "columnName": "broadcastNostrEventRequestId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "ChatMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatMessageId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "BroadcastNostrEventRequest", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "broadcastNostrEventRequestId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatMessageBroadcastNostrEventReceiptRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `chatMessageId` INTEGER NOT NULL, `broadcastNostrEventReceiptId` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, FOREIGN KEY(`chatMessageId`) REFERENCES `ChatMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`broadcastNostrEventReceiptId`) REFERENCES `BroadcastNostrEventReceipt`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "chatMessageId", + "columnName": "chatMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "broadcastNostrEventReceiptId", + "columnName": "broadcastNostrEventReceiptId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "ChatMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatMessageId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "BroadcastNostrEventReceipt", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "broadcastNostrEventReceiptId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatMessageNostrEventRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `chatMessageId` INTEGER NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, FOREIGN KEY(`chatMessageId`) REFERENCES `ChatMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "chatMessageId", + "columnName": "chatMessageId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "ChatMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatMessageId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ChatRoom", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `subject` TEXT, `description` TEXT, `mlsGroupState` TEXT, `initialGiftWrapPayloadId` TEXT, `leftGroupAt` INTEGER, `joinedGroupAt` INTEGER, `chronicleRequestedAt` INTEGER, `parentChatRoomId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`userPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`initialGiftWrapPayloadId`) REFERENCES `GiftWrapPayload`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT" + }, + { + "fieldPath": "description", + "columnName": "description", + "affinity": "TEXT" + }, + { + "fieldPath": "mlsGroupState", + "columnName": "mlsGroupState", + "affinity": "TEXT" + }, + { + "fieldPath": "initialGiftWrapPayloadId", + "columnName": "initialGiftWrapPayloadId", + "affinity": "TEXT" + }, + { + "fieldPath": "leftGroupAt", + "columnName": "leftGroupAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "joinedGroupAt", + "columnName": "joinedGroupAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "chronicleRequestedAt", + "columnName": "chronicleRequestedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "parentChatRoomId", + "columnName": "parentChatRoomId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "userPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "GiftWrapPayload", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "initialGiftWrapPayloadId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "DkgParticipantMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `participantPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `participantPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `DkgSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "participantPublicKey", + "columnName": "participantPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "participantPublicKey", + "kind" + ] + }, + "indices": [ + { + "name": "index_DkgParticipantMessage_sessionId", + "unique": false, + "columnNames": [ + "sessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_DkgParticipantMessage_sessionId` ON `${TABLE_NAME}` (`sessionId`)" + } + ], + "foreignKeys": [ + { + "table": "DkgSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "DkgSession", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `threshold` INTEGER NOT NULL, `participantCount` INTEGER NOT NULL, `participantPublicKeys` TEXT, `subject` TEXT, `stage` TEXT NOT NULL, `hostPublicKey` TEXT NOT NULL, `round1Random` TEXT NOT NULL, `round2AuxRandom` TEXT NOT NULL, `coordinatorRound1` TEXT, `certificate` TEXT, `thresholdPublicKey` TEXT, `secretShare` TEXT, `publicShares` TEXT, `recoveryData` TEXT, `failureReason` TEXT, `hostKeyApprovedAt` INTEGER, `round1ApprovedAt` INTEGER, `round2ApprovedAt` INTEGER, `approvalRequestedThrough` TEXT, `parentChatRoomId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorPublicKey", + "columnName": "coordinatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "threshold", + "columnName": "threshold", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantCount", + "columnName": "participantCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantPublicKeys", + "columnName": "participantPublicKeys", + "affinity": "TEXT" + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT" + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "hostPublicKey", + "columnName": "hostPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "round1Random", + "columnName": "round1Random", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "round2AuxRandom", + "columnName": "round2AuxRandom", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorRound1", + "columnName": "coordinatorRound1", + "affinity": "TEXT" + }, + { + "fieldPath": "certificate", + "columnName": "certificate", + "affinity": "TEXT" + }, + { + "fieldPath": "thresholdPublicKey", + "columnName": "thresholdPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "secretShare", + "columnName": "secretShare", + "affinity": "TEXT" + }, + { + "fieldPath": "publicShares", + "columnName": "publicShares", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryData", + "columnName": "recoveryData", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "hostKeyApprovedAt", + "columnName": "hostKeyApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "round1ApprovedAt", + "columnName": "round1ApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "round2ApprovedAt", + "columnName": "round2ApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequestedThrough", + "columnName": "approvalRequestedThrough", + "affinity": "TEXT" + }, + { + "fieldPath": "parentChatRoomId", + "columnName": "parentChatRoomId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_DkgSession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_DkgSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "FrostSignerMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `signerPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `payload` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `signerPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signerPublicKey", + "columnName": "signerPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "signerPublicKey", + "kind" + ] + }, + "indices": [ + { + "name": "index_FrostSignerMessage_sessionId", + "unique": false, + "columnNames": [ + "sessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSignerMessage_sessionId` ON `${TABLE_NAME}` (`sessionId`)" + } + ], + "foreignKeys": [ + { + "table": "FrostSigningSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "FrostSigningItem", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `itemIndex` INTEGER NOT NULL, `unsignedEventJson` TEXT NOT NULL, `eventId` TEXT NOT NULL, `nonceRandom` TEXT NOT NULL, `aggregatedNonce` TEXT, `signature` TEXT, `inputIndex` INTEGER, PRIMARY KEY(`sessionId`, `itemIndex`), FOREIGN KEY(`sessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "itemIndex", + "columnName": "itemIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "unsignedEventJson", + "columnName": "unsignedEventJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "eventId", + "columnName": "eventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nonceRandom", + "columnName": "nonceRandom", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "aggregatedNonce", + "columnName": "aggregatedNonce", + "affinity": "TEXT" + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT" + }, + { + "fieldPath": "inputIndex", + "columnName": "inputIndex", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "itemIndex" + ] + }, + "indices": [ + { + "name": "index_FrostSigningItem_sessionId", + "unique": false, + "columnNames": [ + "sessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSigningItem_sessionId` ON `${TABLE_NAME}` (`sessionId`)" + } + ], + "foreignKeys": [ + { + "table": "FrostSigningSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "FrostSigningSession", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `threshold` INTEGER NOT NULL, `participantCount` INTEGER NOT NULL, `signerId` INTEGER NOT NULL, `derivationPath` TEXT, `stage` TEXT NOT NULL, `signerIds` TEXT, `failureReason` TEXT, `signApprovedAt` INTEGER, `signDeclinedAt` INTEGER, `approvalRequestedAt` INTEGER, `resentAt` INTEGER, `subject` TEXT NOT NULL DEFAULT 'EVENTS', `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorPublicKey", + "columnName": "coordinatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "threshold", + "columnName": "threshold", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantCount", + "columnName": "participantCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "signerId", + "columnName": "signerId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "derivationPath", + "columnName": "derivationPath", + "affinity": "TEXT" + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signerIds", + "columnName": "signerIds", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "affinity": "TEXT" + }, + { + "fieldPath": "signApprovedAt", + "columnName": "signApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "signDeclinedAt", + "columnName": "signDeclinedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequestedAt", + "columnName": "approvalRequestedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "resentAt", + "columnName": "resentAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "'EVENTS'" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_FrostSigningSession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSigningSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_FrostSigningSession_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_FrostSigningSession_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GiftWrapMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `receiverPublicKey` TEXT NOT NULL, `receiverRelayHit` TEXT, `content` TEXT NOT NULL, `signature` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "receiverPublicKey", + "columnName": "receiverPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receiverRelayHit", + "columnName": "receiverRelayHit", + "affinity": "TEXT" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GiftWrapSeal", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `signature` TEXT NOT NULL, `giftWrapMessageId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`giftWrapMessageId`) REFERENCES `GiftWrapMessage`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "giftWrapMessageId", + "columnName": "giftWrapMessageId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "GiftWrapMessage", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "giftWrapMessageId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GiftWrapPayload", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `quotedEventId` TEXT, `giftWrapSealId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`giftWrapSealId`) REFERENCES `GiftWrapSeal`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedEventId", + "columnName": "quotedEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "giftWrapSealId", + "columnName": "giftWrapSealId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "GiftWrapSeal", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "giftWrapSealId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupKeyState", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `thresholdPublicKey` TEXT NOT NULL, `derivationPath` TEXT NOT NULL, `announcedBy` TEXT NOT NULL, `announcedAt` INTEGER NOT NULL, `parentChatRoomId` TEXT, `birthCertificateJson` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`chatRoomId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "thresholdPublicKey", + "columnName": "thresholdPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "derivationPath", + "columnName": "derivationPath", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "announcedBy", + "columnName": "announcedBy", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "announcedAt", + "columnName": "announcedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "parentChatRoomId", + "columnName": "parentChatRoomId", + "affinity": "TEXT" + }, + { + "fieldPath": "birthCertificateJson", + "columnName": "birthCertificateJson", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId" + ] + }, + "indices": [ + { + "name": "index_GroupKeyState_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupKeyState_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupSignedEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `signature` TEXT NOT NULL, `derivationPath` TEXT, `frostSigningSessionId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "derivationPath", + "columnName": "derivationPath", + "affinity": "TEXT" + }, + { + "fieldPath": "frostSigningSessionId", + "columnName": "frostSigningSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_GroupSignedEvent_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupSignedEvent_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupSignedEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupSignedEvent_kind` ON `${TABLE_NAME}` (`kind`)" + }, + { + "name": "index_GroupSignedEvent_frostSigningSessionId", + "unique": false, + "columnNames": [ + "frostSigningSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupSignedEvent_frostSigningSessionId` ON `${TABLE_NAME}` (`frostSigningSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "GroupTransaction", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`frostSigningSessionId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `chain` TEXT NOT NULL, `account` INTEGER NOT NULL, `guardedChatRoomId` TEXT, `psbt` TEXT NOT NULL, `txid` TEXT NOT NULL, `signedTransaction` TEXT, `broadcastAt` INTEGER, `seenAt` INTEGER, `confirmedAt` INTEGER, `replacedByTxid` TEXT, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`frostSigningSessionId`), FOREIGN KEY(`frostSigningSessionId`) REFERENCES `FrostSigningSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "frostSigningSessionId", + "columnName": "frostSigningSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chain", + "columnName": "chain", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "account", + "columnName": "account", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "guardedChatRoomId", + "columnName": "guardedChatRoomId", + "affinity": "TEXT" + }, + { + "fieldPath": "psbt", + "columnName": "psbt", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "txid", + "columnName": "txid", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signedTransaction", + "columnName": "signedTransaction", + "affinity": "TEXT" + }, + { + "fieldPath": "broadcastAt", + "columnName": "broadcastAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "seenAt", + "columnName": "seenAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "confirmedAt", + "columnName": "confirmedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "replacedByTxid", + "columnName": "replacedByTxid", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "frostSigningSessionId" + ] + }, + "indices": [ + { + "name": "index_GroupTransaction_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupTransaction_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_GroupTransaction_txid", + "unique": false, + "columnNames": [ + "txid" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_GroupTransaction_txid` ON `${TABLE_NAME}` (`txid`)" + } + ], + "foreignKeys": [ + { + "table": "FrostSigningSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "frostSigningSessionId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "InReplyToRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`replyingNostrEventId` TEXT NOT NULL, `inReplyToNostrEventId` TEXT NOT NULL, `inReplyToProfilePublicKey` TEXT, `inReplyToRootNostrEventId` TEXT, `inReplyToRootProfilePublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`replyingNostrEventId`, `inReplyToNostrEventId`), FOREIGN KEY(`inReplyToProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`inReplyToRootProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`replyingNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`inReplyToNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`inReplyToRootNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "replyingNostrEventId", + "columnName": "replyingNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "inReplyToNostrEventId", + "columnName": "inReplyToNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "inReplyToProfilePublicKey", + "columnName": "inReplyToProfilePublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToRootNostrEventId", + "columnName": "inReplyToRootNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToRootProfilePublicKey", + "columnName": "inReplyToRootProfilePublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "replyingNostrEventId", + "inReplyToNostrEventId" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "inReplyToProfilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "inReplyToRootProfilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "replyingNostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "inReplyToNostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "inReplyToRootNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MantraArtifact", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `name` TEXT NOT NULL, `url` TEXT NOT NULL, `visibility` TEXT NOT NULL, `dialectId` TEXT NOT NULL, `license` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `signature` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`dialectId`) REFERENCES `MantraDialect`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "url", + "columnName": "url", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "visibility", + "columnName": "visibility", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dialectId", + "columnName": "dialectId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "license", + "columnName": "license", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayHint", + "columnName": "relayHint", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotGroupEventId", + "columnName": "marmotGroupEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "groupSignedEventId", + "columnName": "groupSignedEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "MantraDialect", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "dialectId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MantraArtifactVersion", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `artifactId` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `versionLabel` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`artifactId`) REFERENCES `MantraArtifact`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "artifactId", + "columnName": "artifactId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "versionLabel", + "columnName": "versionLabel", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayHint", + "columnName": "relayHint", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotGroupEventId", + "columnName": "marmotGroupEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "groupSignedEventId", + "columnName": "groupSignedEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "MantraArtifact", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "artifactId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MantraChapter", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `artifactVersionId` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `name` TEXT NOT NULL, `originalText` TEXT NOT NULL, `index` INTEGER NOT NULL, `wordCount` INTEGER NOT NULL, `characterCount` INTEGER NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`artifactVersionId`) REFERENCES `MantraArtifactVersion`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "artifactVersionId", + "columnName": "artifactVersionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "originalText", + "columnName": "originalText", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "index", + "columnName": "index", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "wordCount", + "columnName": "wordCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "characterCount", + "columnName": "characterCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayHint", + "columnName": "relayHint", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotGroupEventId", + "columnName": "marmotGroupEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "groupSignedEventId", + "columnName": "groupSignedEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "MantraArtifactVersion", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "artifactVersionId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MantraChunk", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chapterId` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `text` TEXT NOT NULL, `index` INTEGER NOT NULL, `wordCount` INTEGER NOT NULL, `characterCount` INTEGER NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chapterId`) REFERENCES `MantraChapter`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chapterId", + "columnName": "chapterId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "text", + "columnName": "text", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "index", + "columnName": "index", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "wordCount", + "columnName": "wordCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "characterCount", + "columnName": "characterCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayHint", + "columnName": "relayHint", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotGroupEventId", + "columnName": "marmotGroupEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "groupSignedEventId", + "columnName": "groupSignedEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "MantraChapter", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chapterId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MantraDialect", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `name` TEXT NOT NULL, `country` TEXT NOT NULL, `language` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "country", + "columnName": "country", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "language", + "columnName": "language", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayHint", + "columnName": "relayHint", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotGroupEventId", + "columnName": "marmotGroupEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "groupSignedEventId", + "columnName": "groupSignedEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MantraTranslation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `translationChunkId` TEXT NOT NULL, `translationArtifactVersionId` TEXT NOT NULL, `text` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`translationChunkId`) REFERENCES `MantraTranslationChunk`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`translationArtifactVersionId`) REFERENCES `MantraTranslationArtifactVersion`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "translationChunkId", + "columnName": "translationChunkId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "translationArtifactVersionId", + "columnName": "translationArtifactVersionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "text", + "columnName": "text", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayHint", + "columnName": "relayHint", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotGroupEventId", + "columnName": "marmotGroupEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "groupSignedEventId", + "columnName": "groupSignedEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "MantraTranslationChunk", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "translationChunkId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "MantraTranslationArtifactVersion", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "translationArtifactVersionId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MantraTranslationArtifactVersion", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `artifactVersionId` TEXT NOT NULL, `dialectId` TEXT NOT NULL, `name` TEXT NOT NULL, `visibility` TEXT NOT NULL, `license` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`artifactVersionId`) REFERENCES `MantraArtifactVersion`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`dialectId`) REFERENCES `MantraDialect`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "artifactVersionId", + "columnName": "artifactVersionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dialectId", + "columnName": "dialectId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "visibility", + "columnName": "visibility", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "license", + "columnName": "license", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayHint", + "columnName": "relayHint", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotGroupEventId", + "columnName": "marmotGroupEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "groupSignedEventId", + "columnName": "groupSignedEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "MantraArtifactVersion", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "artifactVersionId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "MantraDialect", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "dialectId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MantraTranslationArtifactVersionContributor", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `translationArtifactVersionId` TEXT NOT NULL, `editorPublicKey` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`translationArtifactVersionId`) REFERENCES `MantraTranslationArtifactVersionContributor`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "translationArtifactVersionId", + "columnName": "translationArtifactVersionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "editorPublicKey", + "columnName": "editorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayHint", + "columnName": "relayHint", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotGroupEventId", + "columnName": "marmotGroupEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "groupSignedEventId", + "columnName": "groupSignedEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "MantraTranslationArtifactVersionContributor", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "translationArtifactVersionId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MantraTranslationChapter", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chapterId` TEXT NOT NULL, `translationArtifactVersionId` TEXT NOT NULL, `index` INTEGER NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`translationArtifactVersionId`) REFERENCES `MantraTranslationArtifactVersion`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chapterId`) REFERENCES `MantraChapter`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chapterId", + "columnName": "chapterId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "translationArtifactVersionId", + "columnName": "translationArtifactVersionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "index", + "columnName": "index", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayHint", + "columnName": "relayHint", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotGroupEventId", + "columnName": "marmotGroupEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "groupSignedEventId", + "columnName": "groupSignedEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "MantraTranslationArtifactVersion", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "translationArtifactVersionId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "MantraChapter", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chapterId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MantraTranslationChapterContributor", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `translationChapterId` TEXT NOT NULL, `translatorPublicKey` TEXT NOT NULL, `role` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`translationChapterId`) REFERENCES `MantraTranslationChapter`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "translationChapterId", + "columnName": "translationChapterId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "translatorPublicKey", + "columnName": "translatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "role", + "columnName": "role", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayHint", + "columnName": "relayHint", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotGroupEventId", + "columnName": "marmotGroupEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "groupSignedEventId", + "columnName": "groupSignedEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "MantraTranslationChapter", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "translationChapterId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MantraTranslationChunk", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chunkId` TEXT NOT NULL, `translationChapterId` TEXT NOT NULL, `text` TEXT NOT NULL, `index` INTEGER NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`chunkId`) REFERENCES `MantraChunk`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`translationChapterId`) REFERENCES `MantraTranslationChapter`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chunkId", + "columnName": "chunkId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "translationChapterId", + "columnName": "translationChapterId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "text", + "columnName": "text", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "index", + "columnName": "index", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayHint", + "columnName": "relayHint", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotGroupEventId", + "columnName": "marmotGroupEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "groupSignedEventId", + "columnName": "groupSignedEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "MantraChunk", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chunkId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "MantraTranslationChapter", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "translationChapterId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MantraTranslationContributor", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `dTag` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `translationId` TEXT NOT NULL, `translatorPublicKey` TEXT NOT NULL, `signature` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `marmotGroupEventId` TEXT, `groupSignedEventId` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`translationId`) REFERENCES `MantraTranslation`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dTag", + "columnName": "dTag", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "translationId", + "columnName": "translationId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "translatorPublicKey", + "columnName": "translatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayHint", + "columnName": "relayHint", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotGroupEventId", + "columnName": "marmotGroupEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "groupSignedEventId", + "columnName": "groupSignedEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "MantraTranslation", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "translationId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MarmotCommitResult", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `peerKeyPackageEventId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `isOneMemberInitialGroupCreation` INTEGER NOT NULL, `commitBytes` BLOB NOT NULL, `welcomeBytes` BLOB, `groupInfoBytes` BLOB, `framedCommitBytes` BLOB NOT NULL, `preCommitExporterSecret` BLOB NOT NULL, `obligationId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "peerKeyPackageEventId", + "columnName": "peerKeyPackageEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isOneMemberInitialGroupCreation", + "columnName": "isOneMemberInitialGroupCreation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "commitBytes", + "columnName": "commitBytes", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "welcomeBytes", + "columnName": "welcomeBytes", + "affinity": "BLOB" + }, + { + "fieldPath": "groupInfoBytes", + "columnName": "groupInfoBytes", + "affinity": "BLOB" + }, + { + "fieldPath": "framedCommitBytes", + "columnName": "framedCommitBytes", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "preCommitExporterSecret", + "columnName": "preCommitExporterSecret", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "obligationId", + "columnName": "obligationId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + } + }, + { + "tableName": "MarmotGroupEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `signature` TEXT NOT NULL, `encryptedContent` TEXT NOT NULL, `expiresAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`id`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signature", + "columnName": "signature", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "encryptedContent", + "columnName": "encryptedContent", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "expiresAt", + "columnName": "expiresAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "id" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MarmotInnerEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `quotedEventId` TEXT, `payloadEventId` TEXT, `marmotGroupEventId` TEXT, `directMessageRecipientPublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`marmotGroupEventId`) REFERENCES `MarmotGroupEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedEventId", + "columnName": "quotedEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "payloadEventId", + "columnName": "payloadEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "marmotGroupEventId", + "columnName": "marmotGroupEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "directMessageRecipientPublicKey", + "columnName": "directMessageRecipientPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "MarmotGroupEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "marmotGroupEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MarmotKeyPackage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `tlsEncodedMarmotKeyPackage` BLOB NOT NULL, `profile` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`publicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "tlsEncodedMarmotKeyPackage", + "columnName": "tlsEncodedMarmotKeyPackage", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "profile", + "columnName": "profile", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "publicKey" + ], + "referencedColumns": [ + "publicKey" + ] + } + ] + }, + { + "tableName": "MarmotKeyPackageBundle", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `tlsEncodedMarmotKeyPackage` BLOB NOT NULL, `ncryptsecInitPrivateKey` TEXT NOT NULL, `ncryptsecEncryptionPrivateKey` TEXT NOT NULL, `ncryptsecSignaturePrivateKey` TEXT NOT NULL, `consumed` INTEGER NOT NULL, `rotated` INTEGER NOT NULL, `profile` TEXT, `dTag` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "tlsEncodedMarmotKeyPackage", + "columnName": "tlsEncodedMarmotKeyPackage", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "ncryptsecInitPrivateKey", + "columnName": "ncryptsecInitPrivateKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ncryptsecEncryptionPrivateKey", + "columnName": "ncryptsecEncryptionPrivateKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ncryptsecSignaturePrivateKey", + "columnName": "ncryptsecSignaturePrivateKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "consumed", + "columnName": "consumed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "rotated", + "columnName": "rotated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "profile", + "columnName": "profile", + "affinity": "TEXT" + }, + { + "fieldPath": "dTag", + "columnName": "dTag", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_MarmotKeyPackageBundle_publicKey", + "unique": false, + "columnNames": [ + "publicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_MarmotKeyPackageBundle_publicKey` ON `${TABLE_NAME}` (`publicKey`)" + } + ] + }, + { + "tableName": "MarmotRouting", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`routingId` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `activeFromEpoch` INTEGER NOT NULL, `retiredAtEpoch` INTEGER, PRIMARY KEY(`routingId`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "routingId", + "columnName": "routingId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "activeFromEpoch", + "columnName": "activeFromEpoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "retiredAtEpoch", + "columnName": "retiredAtEpoch", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "routingId" + ] + }, + "indices": [ + { + "name": "index_MarmotRouting_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_MarmotRouting_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "MarmotPublishObligation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`obligationId` TEXT NOT NULL, `bytes` BLOB NOT NULL, PRIMARY KEY(`obligationId`))", + "fields": [ + { + "fieldPath": "obligationId", + "columnName": "obligationId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "bytes", + "columnName": "bytes", + "affinity": "BLOB", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "obligationId" + ] + } + }, + { + "tableName": "MarmotOutboundGate", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`groupId` TEXT NOT NULL, `gate` TEXT NOT NULL, PRIMARY KEY(`groupId`))", + "fields": [ + { + "fieldPath": "groupId", + "columnName": "groupId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "gate", + "columnName": "gate", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "groupId" + ] + } + }, + { + "tableName": "MarmotRetainedEpochSecret", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `epoch` INTEGER NOT NULL, `senderDataSecret` BLOB NOT NULL, `encryptionSecret` BLOB NOT NULL, `leafCount` INTEGER NOT NULL, `exporterSecret` BLOB NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`chatRoomId`, `epoch`), FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "epoch", + "columnName": "epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "senderDataSecret", + "columnName": "senderDataSecret", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "encryptionSecret", + "columnName": "encryptionSecret", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "leafCount", + "columnName": "leafCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "exporterSecret", + "columnName": "exporterSecret", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId", + "epoch" + ] + }, + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Mention", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `mentionedPublicKey` TEXT NOT NULL, `mentioningNostrEventId` TEXT, `relayUrl` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, FOREIGN KEY(`mentionedPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`mentioningNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mentionedPublicKey", + "columnName": "mentionedPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "mentioningNostrEventId", + "columnName": "mentioningNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "relayUrl", + "columnName": "relayUrl", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "mentionedPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "mentioningNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "NegentropySynchronizeRequest", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `uuid` TEXT NOT NULL, `purpose` TEXT NOT NULL, `status` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `isRecommendedRelay` INTEGER NOT NULL, `level` INTEGER NOT NULL, `synchronizationFilter` TEXT NOT NULL, `ownerPublicKey` TEXT, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "uuid", + "columnName": "uuid", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "purpose", + "columnName": "purpose", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isRecommendedRelay", + "columnName": "isRecommendedRelay", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "level", + "columnName": "level", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "synchronizationFilter", + "columnName": "synchronizationFilter", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ownerPublicKey", + "columnName": "ownerPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_NegentropySynchronizeRequest_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NegentropySynchronizeRequest_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_NegentropySynchronizeRequest_status", + "unique": false, + "columnNames": [ + "status" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NegentropySynchronizeRequest_status` ON `${TABLE_NAME}` (`status`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "NegentropySynchronizeResult", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `status` TEXT NOT NULL, `negentropySynchronizeRequestId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`negentropySynchronizeRequestId`) REFERENCES `SynchronizeNostrEventResult`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "negentropySynchronizeRequestId", + "columnName": "negentropySynchronizeRequestId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "SynchronizeNostrEventResult", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "negentropySynchronizeRequestId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "NostrEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `pubKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `content` TEXT NOT NULL, `sig` TEXT NOT NULL, `relayUrl` TEXT, `quotedNostrEventId` TEXT, `quotedAuthorPublicKey` TEXT, `inReplyToNostrEventId` TEXT, `inReplyToAuthorPublicKey` TEXT, `inReplyToRootNostrEventId` TEXT, `inReplyToRootAuthorPublicKey` TEXT, `repostedNostrEventId` TEXT, `repostedAuthorPublicKey` TEXT, `unsignedNostrEventId` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "pubKey", + "columnName": "pubKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sig", + "columnName": "sig", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayUrl", + "columnName": "relayUrl", + "affinity": "TEXT" + }, + { + "fieldPath": "quotedNostrEventId", + "columnName": "quotedNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "quotedAuthorPublicKey", + "columnName": "quotedAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToNostrEventId", + "columnName": "inReplyToNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToAuthorPublicKey", + "columnName": "inReplyToAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToRootNostrEventId", + "columnName": "inReplyToRootNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "inReplyToRootAuthorPublicKey", + "columnName": "inReplyToRootAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "repostedNostrEventId", + "columnName": "repostedNostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "repostedAuthorPublicKey", + "columnName": "repostedAuthorPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_NostrEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_kind` ON `${TABLE_NAME}` (`kind`)" + }, + { + "name": "index_NostrEvent_pubKey", + "unique": false, + "columnNames": [ + "pubKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_pubKey` ON `${TABLE_NAME}` (`pubKey`)" + }, + { + "name": "index_NostrEvent_quotedNostrEventId", + "unique": false, + "columnNames": [ + "quotedNostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_quotedNostrEventId` ON `${TABLE_NAME}` (`quotedNostrEventId`)" + }, + { + "name": "index_NostrEvent_inReplyToNostrEventId", + "unique": false, + "columnNames": [ + "inReplyToNostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_inReplyToNostrEventId` ON `${TABLE_NAME}` (`inReplyToNostrEventId`)" + }, + { + "name": "index_NostrEvent_inReplyToRootNostrEventId", + "unique": false, + "columnNames": [ + "inReplyToRootNostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEvent_inReplyToRootNostrEventId` ON `${TABLE_NAME}` (`inReplyToRootNostrEventId`)" + } + ] + }, + { + "tableName": "NostrEventRelay", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`relayURL` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`nostrEventId`, `relayURL`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "nostrEventId", + "relayURL" + ] + }, + "indices": [ + { + "name": "index_NostrEventRelay_relayURL", + "unique": false, + "columnNames": [ + "relayURL" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_NostrEventRelay_relayURL` ON `${TABLE_NAME}` (`relayURL`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Participant", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `participantPublicKey` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `relayHint` TEXT, `adminAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER, FOREIGN KEY(`participantPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`chatRoomId`) REFERENCES `ChatRoom`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantPublicKey", + "columnName": "participantPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "chatRoomId", + "columnName": "chatRoomId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayHint", + "columnName": "relayHint", + "affinity": "TEXT" + }, + { + "fieldPath": "adminAt", + "columnName": "adminAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "participantPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Post", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `repostId` TEXT, `quote` TEXT, `content` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `replyToId` TEXT, `profilePublicKey` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`profilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`replyToId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`repostId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "repostId", + "columnName": "repostId", + "affinity": "TEXT" + }, + { + "fieldPath": "quote", + "columnName": "quote", + "affinity": "TEXT" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "replyToId", + "columnName": "replyToId", + "affinity": "TEXT" + }, + { + "fieldPath": "profilePublicKey", + "columnName": "profilePublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Post_profilePublicKey", + "unique": false, + "columnNames": [ + "profilePublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_profilePublicKey` ON `${TABLE_NAME}` (`profilePublicKey`)" + }, + { + "name": "index_Post_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_Post_replyToId", + "unique": false, + "columnNames": [ + "replyToId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_replyToId` ON `${TABLE_NAME}` (`replyToId`)" + }, + { + "name": "index_Post_repostId", + "unique": false, + "columnNames": [ + "repostId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Post_repostId` ON `${TABLE_NAME}` (`repostId`)" + } + ], + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "profilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "replyToId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Profile", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`publicKey` TEXT NOT NULL, `userName` TEXT, `displayName` TEXT, `picture` TEXT, `banner` TEXT, `website` TEXT, `about` TEXT, `bot` INTEGER, `pronouns` TEXT, `nip05` TEXT, `domain` TEXT, `lud06` TEXT, `lud16` TEXT, `twitter` TEXT, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`publicKey`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userName", + "columnName": "userName", + "affinity": "TEXT" + }, + { + "fieldPath": "displayName", + "columnName": "displayName", + "affinity": "TEXT" + }, + { + "fieldPath": "picture", + "columnName": "picture", + "affinity": "TEXT" + }, + { + "fieldPath": "banner", + "columnName": "banner", + "affinity": "TEXT" + }, + { + "fieldPath": "website", + "columnName": "website", + "affinity": "TEXT" + }, + { + "fieldPath": "about", + "columnName": "about", + "affinity": "TEXT" + }, + { + "fieldPath": "bot", + "columnName": "bot", + "affinity": "INTEGER" + }, + { + "fieldPath": "pronouns", + "columnName": "pronouns", + "affinity": "TEXT" + }, + { + "fieldPath": "nip05", + "columnName": "nip05", + "affinity": "TEXT" + }, + { + "fieldPath": "domain", + "columnName": "domain", + "affinity": "TEXT" + }, + { + "fieldPath": "lud06", + "columnName": "lud06", + "affinity": "TEXT" + }, + { + "fieldPath": "lud16", + "columnName": "lud16", + "affinity": "TEXT" + }, + { + "fieldPath": "twitter", + "columnName": "twitter", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "publicKey" + ] + }, + "indices": [ + { + "name": "index_Profile_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Profile_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "QuotedRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`quotingNostrEventId` TEXT NOT NULL, `quotedNostrEventId` TEXT NOT NULL, `quotedProfilePublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`quotingNostrEventId`, `quotedNostrEventId`), FOREIGN KEY(`quotedProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`quotingNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`quotedNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "quotingNostrEventId", + "columnName": "quotingNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedNostrEventId", + "columnName": "quotedNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quotedProfilePublicKey", + "columnName": "quotedProfilePublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "quotingNostrEventId", + "quotedNostrEventId" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "quotedProfilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "quotingNostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "quotedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "Reaction", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `content` TEXT NOT NULL, `nostrEventId` TEXT NOT NULL, `replyToId` TEXT NOT NULL, `profilePublicKey` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`profilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`replyToId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "replyToId", + "columnName": "replyToId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "profilePublicKey", + "columnName": "profilePublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Reaction_profilePublicKey", + "unique": false, + "columnNames": [ + "profilePublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Reaction_profilePublicKey` ON `${TABLE_NAME}` (`profilePublicKey`)" + }, + { + "name": "index_Reaction_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Reaction_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_Reaction_replyToId", + "unique": false, + "columnNames": [ + "replyToId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Reaction_replyToId` ON `${TABLE_NAME}` (`replyToId`)" + } + ], + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "profilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "replyToId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "RecentSearch", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`query` TEXT NOT NULL, `synchronizationFilters` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`query`))", + "fields": [ + { + "fieldPath": "query", + "columnName": "query", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "synchronizationFilters", + "columnName": "synchronizationFilters", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "query" + ] + } + }, + { + "tableName": "Relay", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`publicKey` TEXT NOT NULL, `type` TEXT NOT NULL, `url` TEXT NOT NULL, `read` INTEGER NOT NULL, `write` INTEGER NOT NULL, PRIMARY KEY(`publicKey`, `type`, `url`))", + "fields": [ + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "url", + "columnName": "url", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "read", + "columnName": "read", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "write", + "columnName": "write", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "publicKey", + "type", + "url" + ] + } + }, + { + "tableName": "RepostedRelation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`repostingNostrEventId` TEXT NOT NULL, `repostedNostrEventId` TEXT NOT NULL, `repostedProfilePublicKey` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`repostingNostrEventId`, `repostedNostrEventId`), FOREIGN KEY(`repostedProfilePublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`repostedNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`repostingNostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "repostingNostrEventId", + "columnName": "repostingNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "repostedNostrEventId", + "columnName": "repostedNostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "repostedProfilePublicKey", + "columnName": "repostedProfilePublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "repostingNostrEventId", + "repostedNostrEventId" + ] + }, + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostedProfilePublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "repostingNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "SynchronizeNostrEventRequest", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `purpose` TEXT NOT NULL, `status` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `isRecommendedRelay` INTEGER NOT NULL, `level` INTEGER NOT NULL, `synchronizationFilters` TEXT NOT NULL, `ownerPublicKey` TEXT, `nostrEventId` TEXT, `unsignedNostrEventId` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`unsignedNostrEventId`) REFERENCES `UnsignedNostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "purpose", + "columnName": "purpose", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isRecommendedRelay", + "columnName": "isRecommendedRelay", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "level", + "columnName": "level", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "synchronizationFilters", + "columnName": "synchronizationFilters", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ownerPublicKey", + "columnName": "ownerPublicKey", + "affinity": "TEXT" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "unsignedNostrEventId", + "columnName": "unsignedNostrEventId", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_SynchronizeNostrEventRequest_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_SynchronizeNostrEventRequest_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_SynchronizeNostrEventRequest_status", + "unique": false, + "columnNames": [ + "status" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_SynchronizeNostrEventRequest_status` ON `${TABLE_NAME}` (`status`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "UnsignedNostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "unsignedNostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "SynchronizeNostrEventResult", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `relayURL` TEXT NOT NULL, `nostrEventId` TEXT, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relayURL", + "columnName": "relayURL", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_SynchronizeNostrEventResult_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_SynchronizeNostrEventResult_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + } + ], + "foreignKeys": [ + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "UnsignedNostrEvent", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `pubKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `tags` TEXT NOT NULL, `privateTags` TEXT, `content` TEXT NOT NULL, `signedAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `deletedAt` INTEGER, `broadcastedAt` INTEGER)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "pubKey", + "columnName": "pubKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tags", + "columnName": "tags", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "privateTags", + "columnName": "privateTags", + "affinity": "TEXT" + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "signedAt", + "columnName": "signedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_UnsignedNostrEvent_pubKey", + "unique": false, + "columnNames": [ + "pubKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_UnsignedNostrEvent_pubKey` ON `${TABLE_NAME}` (`pubKey`)" + }, + { + "name": "index_UnsignedNostrEvent_kind", + "unique": false, + "columnNames": [ + "kind" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_UnsignedNostrEvent_kind` ON `${TABLE_NAME}` (`kind`)" + } + ] + }, + { + "tableName": "Zap", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `postId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `receiverPublicKey` TEXT NOT NULL, `message` TEXT, `invoice` TEXT, `amountInMillisatoshis` INTEGER, `nostrEventId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, `viewedAt` INTEGER, `deletedAt` INTEGER, `broadcastedAt` INTEGER, PRIMARY KEY(`id`), FOREIGN KEY(`senderPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`receiverPublicKey`) REFERENCES `Profile`(`publicKey`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`nostrEventId`) REFERENCES `NostrEvent`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`postId`) REFERENCES `Post`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "postId", + "columnName": "postId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "receiverPublicKey", + "columnName": "receiverPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "message", + "columnName": "message", + "affinity": "TEXT" + }, + { + "fieldPath": "invoice", + "columnName": "invoice", + "affinity": "TEXT" + }, + { + "fieldPath": "amountInMillisatoshis", + "columnName": "amountInMillisatoshis", + "affinity": "INTEGER" + }, + { + "fieldPath": "nostrEventId", + "columnName": "nostrEventId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewedAt", + "columnName": "viewedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "broadcastedAt", + "columnName": "broadcastedAt", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Zap_senderPublicKey", + "unique": false, + "columnNames": [ + "senderPublicKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Zap_senderPublicKey` ON `${TABLE_NAME}` (`senderPublicKey`)" + }, + { + "name": "index_Zap_nostrEventId", + "unique": false, + "columnNames": [ + "nostrEventId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Zap_nostrEventId` ON `${TABLE_NAME}` (`nostrEventId`)" + }, + { + "name": "index_Zap_postId", + "unique": false, + "columnNames": [ + "postId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_Zap_postId` ON `${TABLE_NAME}` (`postId`)" + } + ], + "foreignKeys": [ + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "senderPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "Profile", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "receiverPublicKey" + ], + "referencedColumns": [ + "publicKey" + ] + }, + { + "table": "NostrEvent", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "nostrEventId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "Post", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "postId" + ], + "referencedColumns": [ + "id" + ] + } + ] + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '2fe774344e85e188dd6793623347bf91')" + ] + } +} \ No newline at end of file diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index d313760a..67e99aac 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -620,6 +620,8 @@ Open a guarded wallet Open without guardians Guarded wallets + Spend + Spend from %1$s's guarded wallet Wallets of groups below this one. This group can spend a coin in them once it has %1$d confirmations. %1$s sats within this group's reach Tell the groups above diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/BennuDatabase.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/BennuDatabase.kt index 812bc2ff..bb51dac4 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/BennuDatabase.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/BennuDatabase.kt @@ -190,7 +190,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) UnsignedNostrEvent::class, Zap::class ], - version = 26, + version = 27, autoMigrations = [ // v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can // generate the migration itself — nothing existing changes shape. @@ -378,6 +378,11 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) // nothing is rebuilt; a rebuild of either signing table would fire the // cascades from FrostSigningSession, see docs/frost-batch-signing.md. AutoMigration(from = 25, to = 26), + // v27 adds the nullable GroupTransaction.guardedChatRoomId: the descendant + // whose guarded wallet a guardian's spend draws from + // (docs/group-wallet-guardians.md, Phase 7). Every spend before it was the + // room's own, which is what null means. + AutoMigration(from = 26, to = 27), ] ) @ConstructedBy(BennuDatabaseConstructor::class) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/GroupTransaction.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/GroupTransaction.kt index b0960854..f0ed7081 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/GroupTransaction.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/GroupTransaction.kt @@ -48,6 +48,13 @@ data class GroupTransaction( /** The wallet account the inputs are under. From the room's statement, never from the proposal. */ val account: Long, + /** + * The descendant whose guarded wallet this spend draws from, through this + * room's guardian leaf -- or null for a spend from the room's own wallet. + * [account] is then the descendant's, from the statement this room was told. + */ + val guardedChatRoomId: String? = null, + /** * The PSBT as proposed, base64. Write-once: it is what every item's sighash * was computed from, and a second proposal under the same session id that diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseFrostSigningRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseFrostSigningRepository.kt index d469f05b..1308606a 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseFrostSigningRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseFrostSigningRepository.kt @@ -148,6 +148,23 @@ class DatabaseFrostSigningRepository( ) } + override suspend fun proposeGuardianSpend( + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + psbt: Psbt, + descendantChatRoomId: String, + chain: Chain, + ): FrostSigningSession? = proposing(localChatRoom) { + FrostSigningManager.proposeGuardianSpend( + database = database, + localChatRoom = localChatRoom, + userPublicKey = userPublicKey, + psbt = psbt, + descendantChatRoomId = descendantChatRoomId, + chain = chain, + ) + } + override suspend fun checkedSpend(sessionId: String): GroupSpend.Checked? = try { FrostSigningManager.checkedSpend(database, sessionId) } catch (e: Throwable) { diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt index 8771db08..f6586e03 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt @@ -680,6 +680,82 @@ object FrostSigningManager { return session } + /** + * Opens a session over one transaction from a *descendant's* guarded wallet, + * signed through this room's guardian leaf -- `docs/group-wallet-guardians.md`. + * + * The same session as [proposeSpend] in every way but three: the wallet is + * the one this room was told about rather than its own, every input is + * signed over BIP342's script-path sighash as the key this group's walk + * reaches, and the proposal names the descendant so every signer reads the + * same wallet from its own copy of the statement. + * + * @throws IllegalArgumentException when the spend fails a check, with the reason + * @throws IllegalStateException when the room has no key, this device holds no + * share of it, or the room holds no guarded wallet of [descendantChatRoomId] on + * [chain] at [account] + */ + suspend fun proposeGuardianSpend( + database: BennuDatabase, + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + psbt: Psbt, + descendantChatRoomId: String, + chain: Chain, + account: Long = 0L, + ): FrostSigningSession { + val chatRoomId = localChatRoom.chatRoom.id + val ceremony = completedKey(database, chatRoomId) + ?: throw IllegalStateException("This group has no shared key to sign with") + val thresholdPublicKey = ceremony.thresholdPublicKey + ?: throw IllegalStateException("Ceremony ${ceremony.id} holds no threshold key") + val signerId = signerIdOf(database, ceremony, userPublicKey) + ?: throw IllegalStateException("This device is not a participant in ceremony ${ceremony.id}") + val guarded = GuardianManager.guardedWalletFor(database, chatRoomId, descendantChatRoomId, chain, account) + ?: throw IllegalStateException("This group guards no wallet of $descendantChatRoomId on ${GroupWalletStatementEvent.chainName(chain)}") + + val checked = when (val result = GroupSpend.check(psbt, guarded.account, guarded.spender(thresholdPublicKey))) { + is GroupSpend.Result.Ok -> result.checked + is GroupSpend.Result.Refused -> throw IllegalArgumentException("This spend ${result.reason}") + } + + val session = FrostSigningSession( + id = RandomInstance.bytes(32).toHex(), + chatRoomId = chatRoomId, + coordinatorPublicKey = userPublicKey, + userPublicKey = userPublicKey, + dkgSessionId = ceremony.id, + threshold = ceremony.threshold, + participantCount = ceremony.participantCount, + signerId = signerId, + derivationPath = null, + subject = FrostSigningSubject.TRANSACTION, + signApprovedAt = Clock.System.now() + ) + writeSpend(database, session, checked, chain, account, guardedChatRoomId = descendantChatRoomId) + announceStarted(database, session) + + logger.i( + "Proposing guardian spend ${session.id} from $descendantChatRoomId: ${checked.inputs.size} input(s), " + + "${checked.amountSent.sat} sats out, ${checked.fee.sat} sats fee, txid ${checked.tx.txid}" + ) + + broadcast( + database = database, + localChatRoom = localChatRoom, + session = session, + kind = FrostSigningEvents.TRANSACTION_PROPOSAL, + content = GroupSpend.encode(psbt), + includeKey = true, + extraTags = FrostSigningEvents.walletTags(GroupWalletStatementEvent.chainName(chain), account) + + FrostSigningEvents.guardedTags(descendantChatRoomId) + ) + + advance(database, localChatRoom, session.id) + + return session + } + /** * Records a proposed spend, after every check [GroupSpend.check] makes. * Returns the session, whether it was just created or already known. @@ -742,14 +818,33 @@ object FrostSigningManager { return null } - // 1. There is a wallet, and it is the room's. - val wallet = GroupWalletManager.walletFor(database, localChatRoom.chatRoom.id, thresholdPublicKey, chain, account) - if (wallet == null) { - logger.w("Spend proposal $sessionId spends from a wallet the group has not opened on $chainName; dropping") - return null + // 1. There is a wallet, and it is the room's -- or, for a guardian's + // spend, a descendant's this room was told about and holds a leaf in. + // Either way read from this device's own copy of the statement. + val guardedChatRoomId = FrostSigningEvents.parseGuarded(innerEvent.tags) + val (walletAccount, spender) = if (guardedChatRoomId == null) { + val wallet = GroupWalletManager.walletFor(database, localChatRoom.chatRoom.id, thresholdPublicKey, chain, account) + if (wallet == null) { + logger.w("Spend proposal $sessionId spends from a wallet the group has not opened on $chainName; dropping") + return null + } + wallet.account to GroupSpend.Spender.Owner + } else { + // The leaf is the room's, so the key signing it has to be the room's + // own -- not a subgroup ceremony held in this room. + if (GroupWalletManager.thresholdKeyFor(database, localChatRoom.chatRoom.id) != thresholdPublicKey) { + logger.w("Guardian spend proposal $sessionId names a key that is not this room's; dropping") + return null + } + val guarded = GuardianManager.guardedWalletFor(database, localChatRoom.chatRoom.id, guardedChatRoomId, chain, account) + if (guarded == null) { + logger.w("Guardian spend proposal $sessionId spends from a wallet this room guards none of; dropping") + return null + } + guarded.account to guarded.spender(thresholdPublicKey) } - val checked = when (val result = GroupSpend.check(psbt, wallet.account)) { + val checked = when (val result = GroupSpend.check(psbt, walletAccount, spender)) { is GroupSpend.Result.Ok -> result.checked is GroupSpend.Result.Refused -> { logger.w("Spend proposal $sessionId ${result.reason}; dropping") @@ -769,7 +864,7 @@ object FrostSigningManager { derivationPath = null, subject = FrostSigningSubject.TRANSACTION, ) - writeSpend(database, session, checked, chain, account) + writeSpend(database, session, checked, chain, account, guardedChatRoomId) announceStarted(database, session) logger.i( @@ -793,6 +888,7 @@ object FrostSigningManager { checked: GroupSpend.Checked, chain: Chain, account: Long, + guardedChatRoomId: String? = null, ) { database.frostSigningSessionDao().upsert(session) database.frostSigningSessionDao().upsertItems( @@ -814,6 +910,7 @@ object FrostSigningManager { chatRoomId = session.chatRoomId, chain = GroupWalletStatementEvent.chainName(chain), account = account, + guardedChatRoomId = guardedChatRoomId, psbt = GroupSpend.encode(checked.psbt), txid = checked.tx.txid.toString(), ) @@ -831,6 +928,26 @@ object FrostSigningManager { * rebuilt on every pass from the ceremony's key and the transaction row -- * the same rule as a room's path: stored inputs, rederived, never cached. */ + /** + * One cache per input: the address's key path for the room's own spend, read + * off the items as always; the guardian's leaf for a spend through it, read + * off the spend checked again -- the leaf, the walk and the sighash are one + * computation, and a cache taken apart from it could sign for another leaf. + */ + private suspend fun spendCaches( + database: BennuDatabase, + session: FrostSigningSession, + thresholdPublicKey: HexKey, + items: List, + ): List? { + val transaction = database.groupTransactionDao().getBySessionId(session.id) ?: return null + if (transaction.guardedChatRoomId == null) { + return spendDerivations(database, session, thresholdPublicKey, items)?.map { it.cache } + } + val checked = checkedSpend(database, session.id) ?: return null + return checked.inputs.map { it.cache }.takeIf { it.size == items.size } + } + private suspend fun spendDerivations( database: BennuDatabase, session: FrostSigningSession, @@ -845,6 +962,30 @@ object FrostSigningManager { } } + /** What a spend session signs under: its transaction row, the account its coins are in, and who signs them. */ + private data class SpendContext( + val transaction: GroupTransaction, + val account: GroupWalletDerivation.Account, + val spender: GroupSpend.Spender, + ) + + /** + * [spendAccount], and for a guardian's spend the descendant's guarded wallet + * as this room holds it, with this group as the spender. + */ + private suspend fun spendContext( + database: BennuDatabase, + session: FrostSigningSession, + thresholdPublicKey: HexKey, + ): SpendContext? { + val transaction = database.groupTransactionDao().getBySessionId(session.id) ?: return null + val guardedChatRoomId = transaction.guardedChatRoomId + ?: return spendAccount(database, session, thresholdPublicKey)?.let { (row, account) -> SpendContext(row, account, GroupSpend.Spender.Owner) } + val chain = GroupWalletStatementEvent.chainNamed(transaction.chain) ?: return null + val guarded = GuardianManager.guardedWalletFor(database, transaction.chatRoomId, guardedChatRoomId, chain, transaction.account) ?: return null + return SpendContext(transaction, guarded.account, guarded.spender(thresholdPublicKey)) + } + private suspend fun spendAccount( database: BennuDatabase, session: FrostSigningSession, @@ -873,9 +1014,9 @@ object FrostSigningManager { if (session.subject != FrostSigningSubject.TRANSACTION) return null val thresholdPublicKey = database.dkgSessionDao().getSessionById(session.dkgSessionId)?.thresholdPublicKey ?: return null - val (transaction, account) = spendAccount(database, session, thresholdPublicKey) ?: return null - val psbt = GroupSpend.decode(transaction.psbt) ?: return null - return (GroupSpend.check(psbt, account) as? GroupSpend.Result.Ok)?.checked + val context = spendContext(database, session, thresholdPublicKey) ?: return null + val psbt = GroupSpend.decode(context.transaction.psbt) ?: return null + return (GroupSpend.check(psbt, context.account, context.spender) as? GroupSpend.Result.Ok)?.checked } /** @@ -988,11 +1129,11 @@ object FrostSigningManager { val key = database.dkgSessionDao().getSessionById(session.dkgSessionId) val thresholdPublicKey = key?.thresholdPublicKey ?: throw IllegalStateException("The ceremony this spend signs under is gone") - val (transaction, account) = spendAccount(database, session, thresholdPublicKey) + val (transaction, account, spender) = spendContext(database, session, thresholdPublicKey) ?: throw IllegalStateException("This spend has no transaction on file") val psbt = GroupSpend.decode(transaction.psbt) ?: throw IllegalStateException("This spend's PSBT can no longer be read") - val checked = when (val result = GroupSpend.check(psbt, account)) { + val checked = when (val result = GroupSpend.check(psbt, account, spender)) { is GroupSpend.Result.Ok -> result.checked is GroupSpend.Result.Refused -> throw IllegalStateException("This spend ${result.reason}") } @@ -1000,13 +1141,13 @@ object FrostSigningManager { val signatures = items.mapIndexed { index, item -> val input = checked.inputs[index] val signature = ByteVector64(item.signature!!) - if (!Crypto.verifySignatureSchnorr(input.sighash, signature, input.derivation.outputKey)) { + if (!Crypto.verifySignatureSchnorr(input.sighash, signature, input.signingKey)) { throw IllegalStateException("The aggregated signature for input $index does not verify against its coin") } signature } - val signed = GroupSpend.witnessed(checked.tx, signatures) + val signed = checked.witnessed(signatures) signed.correctlySpends( checked.inputs.associate { it.outPoint to it.txOut }, ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS @@ -1029,8 +1170,11 @@ object FrostSigningManager { database = database, session = session, messageType = ChatMessage.TYPE_FROST_COMPLETE, - content = "The group signed a transaction sending ${checked.amountSent.sat} sats, " + - "with ${checked.fee.sat} sats in fees. It took ${session.threshold} of " + + content = when (val guardian = checked.spender as? GroupSpend.Spender.Guardian) { + null -> "The group signed a transaction sending ${checked.amountSent.sat} sats, " + else -> "The group signed a transaction sending ${checked.amountSent.sat} sats from " + + "${guardian.name ?: "a subgroup"}'s guarded wallet, " + } + "with ${checked.fee.sat} sats in fees. It took ${session.threshold} of " + "${session.participantCount} members.", actor = session.coordinatorPublicKey ) @@ -1384,8 +1528,7 @@ object FrostSigningManager { .cache .let { cache -> List(items.size) { cache } } - FrostSigningSubject.TRANSACTION -> spendDerivations(database, session, thresholdPublicKey, items) - ?.map { it.cache } + FrostSigningSubject.TRANSACTION -> spendCaches(database, session, thresholdPublicKey, items) ?: throw IllegalStateException("The coins this transaction spends no longer derive under the group's wallet") } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianManager.kt index 1f242e4b..a2ae3e63 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianManager.kt @@ -8,6 +8,7 @@ import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent import com.machankura.bennu.compose.nostr.wallet.GuardedWalletNoticeEvent +import com.machankura.bennu.compose.wallet.GroupSpend import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher @@ -54,6 +55,13 @@ object GuardianManager { val chain: Chain get() = account.chain val openedAt: Instant get() = Instant.fromEpochSeconds(statement.createdAt) + + /** Where the ancestor sits among the guardians: whose leaf, in every address, is its. */ + val position: Int get() = account.guardians.indexOfFirst { it.chatRoomId.equals(ancestorChatRoomId, ignoreCase = true) } + + /** The ancestor as the spender of a spend from this wallet, signing as [thresholdPublicKey] -- null to only build one. */ + fun spender(thresholdPublicKey: HexKey? = null): GroupSpend.Spender.Guardian = + GroupSpend.Spender.Guardian(position = position, lineage = lineage, thresholdPublicKey = thresholdPublicKey, name = name) } /** diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/frost/FrostSigningEvents.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/frost/FrostSigningEvents.kt index 28db33d5..82963ec9 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/frost/FrostSigningEvents.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/frost/FrostSigningEvents.kt @@ -175,6 +175,21 @@ object FrostSigningEvents { return chain to account } + private const val GUARDED_TAG = "guarded" + + /** + * On a [TRANSACTION_PROPOSAL] from an ancestor's room: the descendant whose + * guarded wallet it spends from, through the room's guardian leaf. Absent + * for a spend from the room's own wallet. Which wallet it is is all this + * says; every signer then reads that wallet from the statement its own room + * was told, never from the proposal. + */ + fun guardedTags(descendantChatRoomId: String): Array> = arrayOf(arrayOf(GUARDED_TAG, descendantChatRoomId)) + + /** The descendant a guardian's [TRANSACTION_PROPOSAL] names, or null for the room's own wallet. */ + fun parseGuarded(tags: Array>): String? = + tags.firstOrNull { it.size >= 2 && it[0] == GUARDED_TAG }?.get(1)?.takeIf { it.isNotBlank() } + fun parseSessionId(tags: Array>): String? = tags.firstNotNullOfOrNull(FrostSessionIdTag::parse)?.sessionId diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/FrostSigningRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/FrostSigningRepository.kt index 34f0b0ef..6c7bcdd9 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/FrostSigningRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/FrostSigningRepository.kt @@ -241,6 +241,19 @@ interface FrostSigningRepository { chain: Chain, ): FrostSigningSession? + /** + * Opens a session over one transaction from [descendantChatRoomId]'s guarded + * wallet, signed through this room's guardian leaf, or null when it could not + * be proposed. See `FrostSigningManager.proposeGuardianSpend`. + */ + suspend fun proposeGuardianSpend( + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + psbt: Psbt, + descendantChatRoomId: String, + chain: Chain, + ): FrostSigningSession? + /** The spend a transaction session signs, checked again; null for anything else. */ suspend fun checkedSpend(sessionId: String): GroupSpend.Checked? @@ -327,6 +340,14 @@ interface FrostSigningRepository { chain: Chain, ): FrostSigningSession? = null + override suspend fun proposeGuardianSpend( + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + psbt: Psbt, + descendantChatRoomId: String, + chain: Chain, + ): FrostSigningSession? = null + override suspend fun checkedSpend(sessionId: String): GroupSpend.Checked? = null override suspend fun reservedOutPoints(chatRoomId: String): Set = emptySet() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedSpend.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedSpend.kt index a465b636..a95f079b 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedSpend.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedSpend.kt @@ -13,7 +13,12 @@ import fr.acinq.bitcoin.Chain object ProposedSpend { fun summarize(spend: GroupSpend.Checked, chain: Chain): ProposedEvent.Summary = ProposedEvent.Summary( - label = "Spend from the group's wallet", + // A guardian's spend takes a descendant's coins, so whose they are + // is the first thing a signer reads. + label = when (val guardian = spend.spender as? GroupSpend.Spender.Guardian) { + null -> "Spend from the group's wallet" + else -> "Spend from ${guardian.name ?: "a subgroup"}'s guarded wallet" + }, detail = when (val payment = spend.payments.singleOrNull()) { null -> "Send ${spend.amountSent.grouped()} sats to ${spend.payments.size} addresses" else -> "Send ${payment.txOut.amount.grouped()} sats to ${addressOf(payment.txOut.publicKeyScript, chain)}" diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupSendScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupSendScreen.kt index 7ea771b3..4df3ce63 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupSendScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupSendScreen.kt @@ -88,6 +88,9 @@ import com.machankura.bennu.compose.wallet.GroupSpendBuilder import com.vitorpamplona.quartz.nip01Core.core.HexKey import fr.acinq.bitcoin.Chain import org.jetbrains.compose.resources.stringResource +import bennu.composeapp.generated.resources.spend_from_s_s_guarded_wallet +import bennu.composeapp.generated.resources.a_subgroup +import com.machankura.bennu.compose.wallet.GroupSpend /** * A spend from the group's wallet, proposed. @@ -108,6 +111,7 @@ fun GroupSendScreen( chatRepository: ChatRepository, frostSigningRepository: FrostSigningRepository, wallets: GroupOnchainWallets?, + guardedChatRoomId: String? = null, onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, onNavigateBack: () -> Unit, ) { @@ -120,6 +124,7 @@ fun GroupSendScreen( chatRepository = chatRepository, frostSigningRepository = frostSigningRepository, wallets = wallets, + guardedChatRoomId = guardedChatRoomId, ) ) @@ -135,8 +140,12 @@ fun GroupSendScreen( topBar = { TopAppBar( title = { + // Whose wallet is in the title: a guardian's spend takes a + // descendant's coins, and nothing else on the form says so. + val guardian = ((groupSendViewModel.groupSendUIState as? GroupSendUIState.Ready)?.spender as? GroupSpend.Spender.Guardian) Text( - text = stringResource(Res.string.send_from_the_group_s_wallet), + text = if (guardian == null) stringResource(Res.string.send_from_the_group_s_wallet) + else stringResource(Res.string.spend_from_s_s_guarded_wallet, guardian.name ?: stringResource(Res.string.a_subgroup)), maxLines = 1, overflow = TextOverflow.Ellipsis ) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt index b648c2d1..ac7b0b4d 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt @@ -80,6 +80,7 @@ import bennu.composeapp.generated.resources.guarded_wallets import bennu.composeapp.generated.resources.not_yet_shared_with_the_groups_above import bennu.composeapp.generated.resources.s_sats_within_this_group_s_reach import bennu.composeapp.generated.resources.share +import bennu.composeapp.generated.resources.spend import bennu.composeapp.generated.resources.shared_with_the_groups_above import bennu.composeapp.generated.resources.tell_the_groups_above import bennu.composeapp.generated.resources.wallets_of_groups_below_this_one @@ -179,6 +180,18 @@ fun GroupWalletScreen( val couldNotBump = stringResource(Res.string.couldn_t_bump_the_fee) val shared = stringResource(Res.string.shared_with_the_groups_above) val couldNotShare = stringResource(Res.string.couldn_t_share_the_wallet) + // Behind the same two gates as the room's own send: a share to propose + // with, and a node to see the descendant's coins with. + val toGuardianSpend = { row: GuardedWalletRow -> + onNavigateToRoute( + GroupSendRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + relayHint = null, + guardedChatRoomId = row.wallet.descendantChatRoomId, + ) + ) + } val onShare = { shareable: GuardianManager.Shareable -> groupWalletViewModel.share(shareable, onShared = { notify(shared) }, onFailure = { notify(couldNotShare) }) } @@ -267,6 +280,7 @@ fun GroupWalletScreen( shareable = state.shareable, isPending = groupWalletViewModel.isActionPending.value, onShare = onShare, + onSpend = if (state.canSign && wallets != null) toGuardianSpend else null, ) } } @@ -309,6 +323,7 @@ fun GroupWalletScreen( } else null, isPending = groupWalletViewModel.isActionPending.value, onShare = onShare, + onSpend = if (state.canSign && state.canWatch) toGuardianSpend else null, ) } } @@ -378,6 +393,7 @@ private fun OpenWallet( onBump: ((sessionId: String) -> Unit)?, isPending: Boolean, onShare: (GuardianManager.Shareable) -> Unit, + onSpend: ((GuardedWalletRow) -> Unit)?, ) { val clipboardManager = LocalClipboardManager.current val addressCopied = stringResource(Res.string.address_copied) @@ -542,6 +558,7 @@ private fun OpenWallet( shareable = state.shareable, isPending = isPending, onShare = onShare, + onSpend = onSpend, ) } } @@ -598,6 +615,7 @@ private fun LazyListScope.guardianItems( shareable: List, isPending: Boolean, onShare: (GuardianManager.Shareable) -> Unit, + onSpend: ((GuardedWalletRow) -> Unit)?, ) { if (guardedWallets.isNotEmpty()) { item { @@ -620,6 +638,13 @@ private fun LazyListScope.guardianItems( ?: stringResource(Res.string.balance_not_known_yet) ) }, + trailingContent = onSpend?.let { spend -> + { + TextButton(onClick = { spend(row) }) { + Text(stringResource(Res.string.spend)) + } + } + }, ) } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt index 5342fe5d..b1601927 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt @@ -1275,6 +1275,7 @@ fun BennuNavHost( chatRepository = databaseChatRepository, frostSigningRepository = databaseFrostSigningRepository, wallets = groupOnchainWallets, + guardedChatRoomId = route.guardedChatRoomId, onNavigateToRouteAndPopUpInclusive = { signingRoute -> // Replace the form so back returns to the wallet rather // than to a spend that has already been proposed. diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupSendRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupSendRoute.kt index 52db5baa..b18b67d2 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupSendRoute.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupSendRoute.kt @@ -2,10 +2,15 @@ package com.machankura.bennu.compose.ui.composable.navigation.routes import kotlinx.serialization.Serializable -/** The form a member proposes a spend from the group's wallet with. */ +/** + * The form a member proposes a spend from the group's wallet with -- or, with + * [guardedChatRoomId], from that descendant's guarded wallet, through the + * group's guardian leaf. + */ @Serializable data class GroupSendRoute( val activeUserPublicKey: String, val chatRoomId: String, - val relayHint: String? + val relayHint: String?, + val guardedChatRoomId: String? = null, ): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupSendViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupSendViewModel.kt index 6168caa8..e3eb9088 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupSendViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupSendViewModel.kt @@ -1,6 +1,9 @@ package com.machankura.bennu.compose.ui.view.model import com.machankura.bennu.compose.wallet.GroupWalletRollout +import com.machankura.bennu.compose.wallet.GroupSpend +import com.machankura.bennu.compose.nostr.wallet.GroupWallet +import com.machankura.bennu.compose.database.model.GroupSignedEvent import androidx.compose.foundation.text.input.TextFieldState import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd import androidx.compose.runtime.MutableState @@ -49,6 +52,8 @@ class GroupSendViewModel( val chatRepository: ChatRepository, val frostSigningRepository: FrostSigningRepository, private val wallets: GroupOnchainWallets?, + /** The descendant whose guarded wallet this form spends from, or null for the room's own. */ + val guardedChatRoomId: String? = null, ): ViewModel() { private val logger = Logger.withTag(TAG) @@ -72,7 +77,18 @@ class GroupSendViewModel( return@launch } - val wallet = chatRepository.groupWallet(chatRoomId, chain) + // A descendant's guarded wallet, as this room was told it, with the + // group as its guardian -- or the room's own wallet. + val guarded = guardedChatRoomId?.let { descendant -> + chatRepository.guardedWallets(chatRoomId).firstOrNull { + it.descendantChatRoomId.equals(descendant, ignoreCase = true) && it.chain == chain + } + } + val wallet = when { + guardedChatRoomId == null -> chatRepository.groupWallet(chatRoomId, chain) + guarded == null -> null + else -> GroupWallet(GroupSignedEvent.fromEvent(guarded.statement, chatRoomId = guarded.descendantChatRoomId), guarded.account) + } val canSign = localChatRoom.chatRoom.mlsGroupState != null && chatRepository.canSign(chatRoomId) if (wallet == null || !canSign || wallets == null) { groupSendUIState = GroupSendUIState.Unavailable @@ -85,6 +101,7 @@ class GroupSendViewModel( walletState = null, reserved = frostSigningRepository.reservedOutPoints(chatRoomId), reservedChange = frostSigningRepository.reservedChangeIndices(chatRoomId, wallet.account), + spender = guarded?.spender() ?: GroupSpend.Spender.Owner, ) groupSendUIState = ready @@ -131,7 +148,7 @@ class GroupSendViewModel( /** The confirmed coins no open spend holds, summed, or null before Electrum has answered. */ fun spendable(): Satoshi? { val state = groupSendUIState as? GroupSendUIState.Ready ?: return null - return state.walletState?.let { GroupSpendBuilder.spendableBalance(it, state.reserved) } + return state.walletState?.let { GroupSpendBuilder.spendableBalance(it, state.reserved, state.spender) } } /** @@ -171,9 +188,9 @@ class GroupSendViewModel( val address = addressField.text.toString().trim().takeIf { it.isNotEmpty() } ?: return null val built = if (amount == null) { - GroupSpendBuilder.sendAll(walletState, address, feerate, state.reserved) + GroupSpendBuilder.sendAll(walletState, address, feerate, state.reserved, state.spender) } else { - GroupSpendBuilder.send(walletState, address, amount, feerate, state.reserved, state.reservedChange) + GroupSpendBuilder.send(walletState, address, amount, feerate, state.reserved, state.reservedChange, state.spender) } return GroupSpendBuilder.capped(built, GroupWalletRollout.capFor(chain)) } @@ -186,12 +203,21 @@ class GroupSendViewModel( viewModelScope.launch(Dispatchers.IO) { val session = runCatching { - frostSigningRepository.proposeSpend( - localChatRoom = state.localChatRoom, - userPublicKey = activeUserPublicKey, - psbt = built.psbt, - chain = chain, - ) + when (val descendant = guardedChatRoomId.takeIf { state.spender is GroupSpend.Spender.Guardian }) { + null -> frostSigningRepository.proposeSpend( + localChatRoom = state.localChatRoom, + userPublicKey = activeUserPublicKey, + psbt = built.psbt, + chain = chain, + ) + else -> frostSigningRepository.proposeGuardianSpend( + localChatRoom = state.localChatRoom, + userPublicKey = activeUserPublicKey, + psbt = built.psbt, + descendantChatRoomId = descendant, + chain = chain, + ) + } }.onFailure { logger.e("Failed to propose a spend from $chatRoomId", it) }.getOrNull() withContext(Dispatchers.Main) { @@ -212,11 +238,12 @@ class GroupSendViewModel( chatRepository: ChatRepository, frostSigningRepository: FrostSigningRepository, wallets: GroupOnchainWallets?, + guardedChatRoomId: String? = null, ): ViewModelProvider.Factory = viewModelFactory { initializer { GroupSendViewModel( activeUserPublicKey, chatRoomId, chain, initialGroupSendUIState, - chatRepository, frostSigningRepository, wallets, + chatRepository, frostSigningRepository, wallets, guardedChatRoomId, ) } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt index 5f9d8439..53aa94a9 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt @@ -203,9 +203,15 @@ class GroupWalletViewModel( } isActionPending.value = true + // A guardian's spend is bumped as one: the same leaf, the same descendant. + val guardedChatRoomId = state.spends.first { it.transaction.frostSigningSessionId == sessionId }.transaction.guardedChatRoomId + viewModelScope.launch(Dispatchers.IO) { val session = runCatching { - frostSigningRepository.proposeSpend(state.localChatRoom, activeUserPublicKey, built.psbt, chain) + when (guardedChatRoomId) { + null -> frostSigningRepository.proposeSpend(state.localChatRoom, activeUserPublicKey, built.psbt, chain) + else -> frostSigningRepository.proposeGuardianSpend(state.localChatRoom, activeUserPublicKey, built.psbt, guardedChatRoomId, chain) + } }.onFailure { logger.e("Failed to bump $sessionId", it) }.getOrNull() withContext(Dispatchers.Main) { diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupSendUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupSendUIState.kt index 6b2fef1a..b5b0969e 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupSendUIState.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupSendUIState.kt @@ -2,6 +2,7 @@ package com.machankura.bennu.compose.ui.view.state import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom import com.machankura.bennu.compose.nostr.wallet.GroupWallet +import com.machankura.bennu.compose.wallet.GroupSpend import com.machankura.bennu.compose.wallet.GroupWalletState import fr.acinq.bitcoin.OutPoint @@ -18,6 +19,12 @@ sealed interface GroupSendUIState { val reserved: Set, /** The change indices open spends already pay back to, which a new one pays past. */ val reservedChange: Set = emptySet(), + /** + * Who would sign: the room's own group, or -- spending from a descendant's + * guarded wallet -- the group as that wallet's guardian. [wallet] is then + * the descendant's. + */ + val spender: GroupSpend.Spender = GroupSpend.Spender.Owner, ): GroupSendUIState /** A room this device cannot propose from -- no wallet, no share, or no node. */ diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpend.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpend.kt index 4dcb5cdb..22204027 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpend.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpend.kt @@ -2,15 +2,22 @@ package com.machankura.bennu.compose.wallet import com.machankura.bennu.compose.managers.FrostSigningManager import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.ByteVector import fr.acinq.bitcoin.ByteVector32 import fr.acinq.bitcoin.ByteVector64 import fr.acinq.bitcoin.KeyPath import fr.acinq.bitcoin.OutPoint import fr.acinq.bitcoin.Satoshi import fr.acinq.bitcoin.Script +import fr.acinq.bitcoin.ScriptTree +import fr.acinq.bitcoin.ScriptWitness import fr.acinq.bitcoin.SigHash import fr.acinq.bitcoin.Transaction import fr.acinq.bitcoin.TxOut +import fr.acinq.bitcoin.XonlyPublicKey +import fr.acinq.bitcoin.crypto.frost.TweakCache import fr.acinq.bitcoin.psbt.Input import fr.acinq.bitcoin.psbt.Psbt import fr.acinq.bitcoin.psbt.TaprootBip32DerivationPath @@ -38,6 +45,16 @@ import kotlin.io.encoding.Base64 * is what lets a member with no node of their own, and so no way to look a coin * up, still sign safely: the worst a lying proposer gets is a transaction nobody * can mine. + * + * ### Two ways to sign a coin + * + * The wallet's own group signs each input on its address's key path. An + * ancestor of a guarded wallet signs through its leaf instead -- a [Spender.Guardian] + * -- and then every input's sighash is BIP342's over that leaf, its sequence is + * the leaf's lock, its signature verifies against the leaf key, and its witness + * is the leaf and its control block. Everything else above holds unchanged: the + * coins are still the descendant's, at places under its account, and each claim + * is still rederived rather than believed. See `docs/group-wallet-guardians.md`. */ object GroupSpend { /** @@ -65,6 +82,28 @@ object GroupSpend { */ const val MAX_FEERATE_SAT_PER_VBYTE: Long = 2_000L + /** Who signs a spend's inputs. */ + sealed interface Spender { + /** The wallet's own group, on each address's key path. */ + data object Owner : Spender + + /** + * An ancestor of a guarded wallet, through its leaf: the guardian at + * [position] in the account's guardians, whose key is [thresholdPublicKey] + * walked down [lineage] -- `GuardianDerivation.signingCache`. + * + * [thresholdPublicKey] is null for a builder, which needs the leaf and + * never the key that signs it; [check] refuses without it. + */ + data class Guardian( + val position: Int, + val lineage: List, + val thresholdPublicKey: HexKey? = null, + /** The guarded wallet's founding name, for the words a spend is shown in. */ + val name: String? = null, + ) : Spender + } + /** One input, and what its signature has to be over and verify against. */ data class SpentInput( val index: Int, @@ -72,7 +111,19 @@ object GroupSpend { val txOut: TxOut, val derivation: GroupWalletDerivation.Derived, val sighash: ByteVector32, - ) + /** The leaf a guardian signs through, or null for a key-path input. */ + val leaf: ScriptTree.Leaf? = null, + /** The key the input's signature verifies against: the address's output key, or the leaf key. */ + val signingKey: XonlyPublicKey = derivation.outputKey, + /** The cache a session signs this input with. */ + val cache: TweakCache = derivation.cache, + ) { + /** The input's witness around [signature]. */ + fun witness(signature: ByteVector64): ScriptWitness = when (leaf) { + null -> Script.witnessKeyPathPay2tr(signature) + else -> Script.witnessScriptPathPay2tr(derivation.internalKey, leaf, ScriptWitness(listOf(signature)), derivation.tree!!) + } + } /** One output, and -- when its claim to be the wallet's own derives -- where under the account it is. */ data class CheckedOutput( @@ -91,8 +142,13 @@ object GroupSpend { val outputs: List, /** `Σ inputs − Σ outputs`, believable for the reason the object's kdoc gives. */ val fee: Satoshi, - /** The finished transaction's weight. Exact before signing: a default-sighash key-path witness is always 64 bytes. */ + /** + * The finished transaction's weight. Exact before signing: a default-sighash + * signature is always 64 bytes, and a guardian's leaf and control block are + * known before it signs. + */ val weight: Int, + val spender: Spender = Spender.Owner, ) { val tx: Transaction get() = psbt.global.tx @@ -106,6 +162,10 @@ object GroupSpend { /** Every spent output, in input order: what every sighash and `correctlySpends` take. */ val spentOutputs: List get() = inputs.map { it.txOut } + + /** [tx] with each input's witness around its signature, in input order. */ + fun witnessed(signatures: List): Transaction = + signatures.foldIndexed(tx) { index, partial, signature -> partial.updateWitness(index, inputs[index].witness(signature)) } } sealed interface Result { @@ -116,11 +176,17 @@ object GroupSpend { /** * The checks a member makes before signing, in the order `docs/group-chain-wallet.md` * numbers them, against [account] -- which comes from the room's verified - * statement and never from the proposal. + * statement and never from the proposal -- as [spender] would sign it. */ - fun check(psbt: Psbt, account: GroupWalletDerivation.Account): Result { + fun check(psbt: Psbt, account: GroupWalletDerivation.Account, spender: Spender = Spender.Owner): Result { val tx = psbt.global.tx + // A guardian's leaf, and what it locks: every one of its inputs carries + // exactly that lock, and it signs as the key its walk reaches. + val guardian = spender as? Spender.Guardian + val delay = guardian?.let { account.guardians.getOrNull(it.position)?.delay ?: return Result.Refused("names a guardian this wallet does not have") } + if (guardian != null && guardian.thresholdPublicKey == null) return Result.Refused("has no key to sign a guardian's leaf with") + // 4. Bounded, before any per-input work. if (tx.txIn.isEmpty()) return Result.Refused("spends nothing") if (tx.txIn.size > MAX_INPUTS) return Result.Refused("spends ${tx.txIn.size} coins, more than the $MAX_INPUTS one spend may sign") @@ -128,6 +194,7 @@ object GroupSpend { if (tx.version != 2L) return Result.Refused("is version ${tx.version}, not 2") if (tx.lockTime != 0L) return Result.Refused("has a lock time") if (tx.txIn.any { it.sequence > MAX_SEQUENCE }) return Result.Refused("cannot be replaced: a sequence is above ${MAX_SEQUENCE}") + if (delay != null && tx.txIn.any { it.sequence != delay }) return Result.Refused("has an input whose sequence is not its leaf's lock of $delay blocks") if (tx.txIn.map { it.outPoint }.toSet().size != tx.txIn.size) return Result.Refused("spends one coin twice") // 2 and 3. Every input is the group's, at a key path, under the default sighash. @@ -157,13 +224,36 @@ object GroupSpend { val spentOutputs = claimed.map { it.second } val inputs = claimed.map { (index, txOut, derivation) -> - SpentInput( - index = index, - outPoint = tx.txIn[index].outPoint, - txOut = txOut, - derivation = derivation, - sighash = tx.hashForSigningTaprootKeyPath(index, spentOutputs, SigHash.SIGHASH_DEFAULT), - ) + if (guardian == null) { + SpentInput( + index = index, + outPoint = tx.txIn[index].outPoint, + txOut = txOut, + derivation = derivation, + sighash = tx.hashForSigningTaprootKeyPath(index, spentOutputs, SigHash.SIGHASH_DEFAULT), + ) + } else { + val leaf = GuardianDerivation.leaves(account.guardians, account.chain, account.account, derivation.change, derivation.index)[guardian.position] + val signing = GuardianDerivation.signingCache( + guardian.thresholdPublicKey!!, guardian.lineage, account.chain, account.account, derivation.change, derivation.index, + ) + // The leaf in the descendant's address, and the key this group's + // walk reaches, have to be one key -- or this group would sign for + // a leaf it cannot spend. + if (leaf.script != ByteVector(Script.write(GuardianDerivation.leafScript(signing.leafKey, delay!!)))) { + return Result.Refused("input $index's leaf is not this group's to sign") + } + SpentInput( + index = index, + outPoint = tx.txIn[index].outPoint, + txOut = txOut, + derivation = derivation, + sighash = tx.hashForSigningTaprootScriptPath(index, spentOutputs, SigHash.SIGHASH_DEFAULT, leaf.hash()), + leaf = leaf, + signingKey = signing.leafKey, + cache = signing.cache, + ) + } } // 5. Change is change only if it derives. @@ -186,12 +276,12 @@ object GroupSpend { // 6. A sane fee. val fee = spentOutputs.map { it.amount }.sum() - tx.txOut.map { it.amount }.sum() if (fee.sat <= 0) return Result.Refused("pays out more than it spends") - val weight = witnessed(tx, List(tx.txIn.size) { ByteVector64.Zeroes }).weight() + val weight = inputs.fold(tx) { partial, input -> partial.updateWitness(input.index, input.witness(ByteVector64.Zeroes)) }.weight() if (fee.sat > MAX_FEERATE_SAT_PER_VBYTE * vbytes(weight)) { return Result.Refused("pays a fee of ${fee.sat} sats, over $MAX_FEERATE_SAT_PER_VBYTE sats per byte") } - return Result.Ok(Checked(account = account, psbt = psbt, inputs = inputs, outputs = outputs, fee = fee, weight = weight)) + return Result.Ok(Checked(account = account, psbt = psbt, inputs = inputs, outputs = outputs, fee = fee, weight = weight, spender = spender)) } /** @@ -286,6 +376,21 @@ object GroupSpend { partial.updateWitness(index, Script.witnessKeyPathPay2tr(signature)) } + /** + * The witness a guardian puts on [derivation]'s coin around [signature]: its + * leaf in that address, and the control block that proves the leaf is there. + * What a builder weighs a guardian spend by, before anybody signs. + */ + fun guardianWitness( + account: GroupWalletDerivation.Account, + derivation: GroupWalletDerivation.Derived, + position: Int, + signature: ByteVector64 = ByteVector64.Zeroes, + ): ScriptWitness { + val leaf = GuardianDerivation.leaves(account.guardians, account.chain, account.account, derivation.change, derivation.index)[position] + return Script.witnessScriptPathPay2tr(derivation.internalKey, leaf, ScriptWitness(listOf(signature)), derivation.tree!!) + } + fun encode(psbt: Psbt): String = Base64.Default.encode(Psbt.write(psbt).toByteArray()) fun decode(content: String): Psbt? = diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpendBuilder.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpendBuilder.kt index 8024178f..b4725d19 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpendBuilder.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpendBuilder.kt @@ -22,6 +22,11 @@ import fr.acinq.lightning.utils.sum * proposal is already spending. Two proposals over one coin are not dangerous -- * only one can confirm, and each has its own nonces -- but the second is a quorum * asked for nothing. + * + * A guardian building a spend from a descendant's guarded wallet -- a + * [GroupSpend.Spender.Guardian] -- takes only coins its leaf's lock has already + * let go of, puts that lock on every input, and weighs each input by its leaf + * and control block. Its change, if any, goes back to the descendant. */ object GroupSpendBuilder { /** Phoenix's floor, kept: an output below it is one no node will relay. */ @@ -61,16 +66,22 @@ object GroupSpendBuilder { if (cap != null && result is Result.Built && result.amount > cap) Result.OverCap(cap) else result /** Every confirmed, unreserved coin, to [address], less the fee. */ - fun sendAll(state: GroupWalletState, address: String, feeratePerVbyte: Long, reserved: Set): Result { + fun sendAll( + state: GroupWalletState, + address: String, + feeratePerVbyte: Long, + reserved: Set, + spender: GroupSpend.Spender = GroupSpend.Spender.Owner, + ): Result { val script = scriptOf(state, address) ?: return Result.NotAnAddress - val coins = spendable(state, reserved).ifEmpty { return Result.NothingToSpend } + val coins = spendable(state, reserved, spender).ifEmpty { return Result.NothingToSpend } val total = coins.map { it.amount }.sum() - val fee = feeOf(coins, listOf(script), feeratePerVbyte) + val fee = feeOf(state, coins, listOf(script), feeratePerVbyte, spender) val amount = total - fee if (amount < DUST) return Result.BelowDust - val tx = transaction(coins, listOf(TxOut(amount, script))) + val tx = transaction(state, coins, listOf(TxOut(amount, script)), spender) return Result.Built(psbtOf(state, tx, coins, change = emptyMap()), amount, fee, change = null) } @@ -86,10 +97,11 @@ object GroupSpendBuilder { feeratePerVbyte: Long, reserved: Set, reservedChange: Set = emptySet(), + spender: GroupSpend.Spender = GroupSpend.Spender.Owner, ): Result { val script = scriptOf(state, address) ?: return Result.NotAnAddress if (amount < DUST) return Result.BelowDust - val coins = spendable(state, reserved).sortedByDescending { it.amount.sat }.ifEmpty { return Result.NothingToSpend } + val coins = spendable(state, reserved, spender).sortedByDescending { it.amount.sat }.ifEmpty { return Result.NothingToSpend } if (!state.changeKnown) return Result.FindingChange val changeIndex = state.nextChangeIndex(reservedChange) ?: return Result.TooManyOpen @@ -99,18 +111,18 @@ object GroupSpendBuilder { for (coin in coins) { chosen += coin val total = chosen.map { it.amount }.sum() - val withChange = feeOf(chosen, listOf(script, change.pubkeyScript), feeratePerVbyte) + val withChange = feeOf(state, chosen, listOf(script, change.pubkeyScript), feeratePerVbyte, spender) val leftover = total - amount - withChange if (leftover >= DUST) { - val tx = transaction(chosen, listOf(TxOut(amount, script), TxOut(leftover, change.pubkeyScript))) + val tx = transaction(state, chosen, listOf(TxOut(amount, script), TxOut(leftover, change.pubkeyScript)), spender) return Result.Built(psbtOf(state, tx, chosen, mapOf(1 to change)), amount, withChange, leftover) } // Enough to pay without change: the remainder, under dust, goes to fees. - val withoutChange = feeOf(chosen, listOf(script), feeratePerVbyte) + val withoutChange = feeOf(state, chosen, listOf(script), feeratePerVbyte, spender) if (total - amount >= withoutChange) { - val tx = transaction(chosen, listOf(TxOut(amount, script))) + val tx = transaction(state, chosen, listOf(TxOut(amount, script)), spender) return Result.Built( psbtOf(state, tx, chosen, emptyMap()), amount, total - amount, change = null, absorbed = total - amount - withoutChange, @@ -150,33 +162,67 @@ object GroupSpendBuilder { ) } - /** The coins a new spend may use: confirmed, and held by no open spend. */ - fun spendable(state: GroupWalletState, reserved: Set): List = - state.utxos.filter { it.isConfirmed && it.utxo.outPoint !in reserved } + /** + * The coins a new spend may use: confirmed -- for a guardian, as deep as its + * leaf's lock -- and held by no open spend. + */ + fun spendable( + state: GroupWalletState, + reserved: Set, + spender: GroupSpend.Spender = GroupSpend.Spender.Owner, + ): List { + val lock = lockOf(state, spender) + return state.utxos.filter { + it.isConfirmed && (lock == null || state.confirmations(it) >= lock) && it.utxo.outPoint !in reserved + } + } /** * What [spendable] adds up to: the most a form can offer, before the fee. * Less than the wallet's confirmed balance by whatever open spends hold. */ - fun spendableBalance(state: GroupWalletState, reserved: Set): Satoshi = - spendable(state, reserved).map { it.amount }.sum() + fun spendableBalance( + state: GroupWalletState, + reserved: Set, + spender: GroupSpend.Spender = GroupSpend.Spender.Owner, + ): Satoshi = spendable(state, reserved, spender).map { it.amount }.sum() + + /** The relative lock a guardian's inputs carry, or null for the wallet's own group. */ + private fun lockOf(state: GroupWalletState, spender: GroupSpend.Spender): Long? = + (spender as? GroupSpend.Spender.Guardian)?.let { state.account.guardians[it.position].delay } private fun scriptOf(state: GroupWalletState, address: String): ByteVector? = Bitcoin.addressToPublicKeyScript(state.account.chain.chainHash, address.trim()).right ?.let { ByteVector(Script.write(it)) } - private fun transaction(coins: List, outputs: List) = Transaction( + private fun transaction(state: GroupWalletState, coins: List, outputs: List, spender: GroupSpend.Spender) = Transaction( version = 2, - // Replaceable, so a stuck spend can be bumped by a new proposal. - txIn = coins.map { TxIn(it.utxo.outPoint, ByteVector.empty, GroupSpend.MAX_SEQUENCE) }, + // Replaceable, so a stuck spend can be bumped by a new proposal -- and a + // guardian's lock is far below the replaceable ceiling, so its is too. + txIn = coins.map { TxIn(it.utxo.outPoint, ByteVector.empty, lockOf(state, spender) ?: GroupSpend.MAX_SEQUENCE) }, txOut = outputs, lockTime = 0, ) - /** The fee at [feeratePerVbyte] for spending [coins] to [scripts]: exact, because every witness is 64 bytes. */ - private fun feeOf(coins: List, scripts: List, feeratePerVbyte: Long): Satoshi { - val tx = transaction(coins, scripts.map { TxOut(Satoshi(0), it) }) - val weight = GroupSpend.witnessed(tx, List(coins.size) { ByteVector64.Zeroes }).weight() + /** + * The fee at [feeratePerVbyte] for spending [coins] to [scripts]: exact, + * because every signature is 64 bytes and a guardian's leaf and control + * block are known before anybody signs. + */ + private fun feeOf( + state: GroupWalletState, + coins: List, + scripts: List, + feeratePerVbyte: Long, + spender: GroupSpend.Spender, + ): Satoshi { + val tx = transaction(state, coins, scripts.map { TxOut(Satoshi(0), it) }, spender) + val weight = when (spender) { + GroupSpend.Spender.Owner -> GroupSpend.witnessed(tx, List(coins.size) { ByteVector64.Zeroes }) + is GroupSpend.Spender.Guardian -> coins.foldIndexed(tx) { index, partial, coin -> + partial.updateWitness(index, GroupSpend.guardianWitness(state.account, coin.derivation, spender.position)) + } + }.weight() return Satoshi(feeratePerVbyte * ((weight + 3) / 4)) } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt index cf275df8..d26f6c1d 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt @@ -40,6 +40,20 @@ import fr.acinq.bitcoin.crypto.frost.IndividualNonce import fr.acinq.bitcoin.crypto.frost.SecretNonce import fr.acinq.bitcoin.crypto.frost.Session import kotlin.test.assertTrue +import com.machankura.bennu.compose.wallet.GroupSpend +import com.machankura.bennu.compose.wallet.GroupSpendBuilder +import com.machankura.bennu.compose.wallet.GroupWalletState +import com.machankura.bennu.compose.database.model.types.FrostSigningSubject +import fr.acinq.bitcoin.OutPoint +import fr.acinq.bitcoin.Satoshi +import fr.acinq.bitcoin.Script +import fr.acinq.bitcoin.ScriptFlags +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxId +import fr.acinq.bitcoin.TxIn +import fr.acinq.bitcoin.TxOut +import fr.acinq.lightning.blockchain.electrum.WalletState +import kotlin.test.assertIs /** * A group's guardian keys through the real signing manager, between two of its @@ -168,7 +182,7 @@ class GuardianSigningJvmTest { // ---- The certificate's guardian keys -------------------------------- @Test - fun `a certificate granting the group's own key is signed, and carries it`() = runBlocking { + fun `a certificate granting the group's own key is signed, and carries it`(): Unit = runBlocking { val proposer = device(members[0], signerIndex = 0) val other = device(members[1], signerIndex = 1) val granted = GuardianDerivation.grant(thresholdPublicKey, roomId, emptyList(), childRoomId) @@ -187,7 +201,7 @@ class GuardianSigningJvmTest { } @Test - fun `a certificate granting any other key is never put to the member`() = runBlocking { + fun `a certificate granting any other key is never put to the member`(): Unit = runBlocking { val proposer = device(members[0], signerIndex = 0) val other = device(members[1], signerIndex = 1) val coordinators = PrivateKey(ByteVector32(ByteArray(32) { 0x66 })).publicKey().toString() @@ -301,7 +315,7 @@ class GuardianSigningJvmTest { } @Test - fun `a notice in the ancestor's room is a guarded wallet it holds, under its first guardians`() = runBlocking { + fun `a notice in the ancestor's room is a guarded wallet it holds, under its first guardians`(): Unit = runBlocking { val ancestor = device(members[0], signerIndex = 0) val first = guardedStatement(createdAt = 1_700_000_000) tell(ancestor, first) @@ -327,7 +341,7 @@ class GuardianSigningJvmTest { } @Test - fun `a member in both rooms carries the child's statement up, once`() = runBlocking { + fun `a member in both rooms carries the child's statement up, once`(): Unit = runBlocking { val member = device(members[0], signerIndex = 0) // This device is also in the child's room, and holds its signed statement there. member.db.chatRoomDao().upsert(ChatRoom(id = guardedChildRoomId, userPublicKey = member.publicKey, subject = "Translation team", description = null, mlsGroupState = "00")) @@ -354,4 +368,105 @@ class GuardianSigningJvmTest { assertEquals(emptyList(), GuardianManager.shareableFrom(member.db, guardedChildRoomId, Chain.Regtest)) assertEquals(listOf(statement.id), GuardianManager.guardedWalletsOf(member.db, roomId).map { it.statement.id }) } + + // ---- Spending from a guarded wallet ------------------------------------ + + private val chain = Chain.Regtest + private val elsewhere = ByteVector(Script.write(Script.pay2wpkh(PrivateKey(ByteVector32(ByteArray(32) { 9 })).publicKey()))) + + /** Somebody else's money paying the child's first guarded receive address. */ + private fun fundingOf(guarded: GroupWalletDerivation.Account) = Transaction( + 2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 0x61 })), 0), ByteVector.empty, 0xffffffffL)), + listOf(TxOut(Satoshi(50_000), GroupWalletDerivation.derive(guarded, GroupWalletDerivation.RECEIVE, 0).pubkeyScript)), 0, + ) + + /** The child's wallet as Electrum would report it holding [funding], confirmed at [height], with the tip at [tip]. */ + private fun fundedState(guarded: GroupWalletDerivation.Account, funding: Transaction, height: Int, tip: Int): GroupWalletState { + val meta = WalletState.AddressMeta.Derived(0) + val address = GroupWalletDerivation.derive(guarded, GroupWalletDerivation.RECEIVE, 0).address(chain) + val receive = WalletState(mapOf(address to WalletState.AddressState(meta, alreadyUsed = true, utxos = listOf(WalletState.Utxo(funding.txid, 0, height.toLong(), funding, meta))))) + val change = WalletState((0 until 3).associate { index -> + GroupWalletDerivation.derive(guarded, GroupWalletDerivation.CHANGE, index.toLong()).address(chain) to + WalletState.AddressState(WalletState.AddressMeta.Derived(index), alreadyUsed = false, utxos = emptyList()) + }) + return GroupWalletState(guarded, receive, change, tipHeight = tip) + } + + @Test + fun `the builder waits out the leaf's lock, and puts it on every input`() { + val guarded = assertNotNull(GuardianManager.verify(guardedStatement(), roomId, thresholdPublicKey)) + val funding = fundingOf(guarded.account) + val address = fr.acinq.bitcoin.Bitcoin.addressFromPublicKeyScript(chain.chainHash, elsewhere.toByteArray()).right!! + + // Eleven confirmations: the owner could spend it, the guardian cannot yet. + val young = fundedState(guarded.account, funding, height = 100, tip = 110) + assertIs(GroupSpendBuilder.sendAll(young, address, 2, emptySet())) + assertEquals(GroupSpendBuilder.Result.NothingToSpend, GroupSpendBuilder.sendAll(young, address, 2, emptySet(), guarded.spender())) + + val old = fundedState(guarded.account, funding, height = 100, tip = 111) + val built = assertIs(GroupSpendBuilder.sendAll(old, address, 2, emptySet(), guarded.spender())) + assertEquals(listOf(12L), built.psbt.global.tx.txIn.map { it.sequence }) + + // What the builder charged for is what a signer weighs it at. + val checked = assertIs(GroupSpend.check(built.psbt, guarded.account, guarded.spender(thresholdPublicKey))).checked + assertEquals(built.fee.sat, 2 * ((checked.weight + 3) / 4).toLong()) + } + + @Test + fun `an ancestor's quorum spends a descendant's coin through its leaf, on every device`(): Unit = runBlocking { + val proposer = device(members[0], signerIndex = 0) + val other = device(members[1], signerIndex = 1) + val statement = guardedStatement() + tell(proposer, statement) + tell(other, statement) + + val guarded = assertNotNull(GuardianManager.guardedWalletFor(proposer.db, roomId, guardedChildRoomId, chain, 0)) + val funding = fundingOf(guarded.account) + val built = assertIs( + GroupSpendBuilder.send(fundedState(guarded.account, funding, 100, 200), fr.acinq.bitcoin.Bitcoin.addressFromPublicKeyScript(chain.chainHash, elsewhere.toByteArray()).right!!, + Satoshi(30_000), 2, emptySet(), emptySet(), guarded.spender()) + ) + + val session = FrostSigningManager.proposeGuardianSpend(proposer.db, proposer.room, proposer.publicKey, built.psbt, guardedChildRoomId, chain) + pump(proposer, other) + assertEquals(FrostSigningSubject.TRANSACTION, other.session(session.id)?.subject) + val seen = assertNotNull(FrostSigningManager.checkedSpend(other.db, session.id)) + assertIs(seen.spender) + assertEquals(listOf(false, true), seen.outputs.map { it.isChange }, "the change goes back to the child") + + FrostSigningManager.approve(other.db, other.room, session.id) + pump(proposer, other) + + listOf(proposer, other).forEach { device -> + assertEquals(FrostSigningStage.COMPLETE, device.session(session.id)?.stage) + val row = assertNotNull(device.db.groupTransactionDao().getBySessionId(session.id)) + assertEquals(guardedChildRoomId, row.guardedChatRoomId) + val signed = Transaction.read(assertNotNull(row.signedTransaction)) + signed.correctlySpends(mapOf(OutPoint(funding, 0) to funding.txOut[0]), ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) + assertEquals(3, signed.txIn[0].witness.stack.size, "a signature, the leaf, and its control block") + } + } + + @Test + fun `a guardian's spend is refused for a wallet the room was not told about, or without the lock`(): Unit = runBlocking { + val proposer = device(members[0], signerIndex = 0) + val other = device(members[1], signerIndex = 1) + val statement = guardedStatement() + tell(proposer, statement) + // The other device was never told: it has no wallet to check the spend against. + + val guarded = assertNotNull(GuardianManager.guardedWalletFor(proposer.db, roomId, guardedChildRoomId, chain, 0)) + val funding = fundingOf(guarded.account) + val built = assertIs( + GroupSpendBuilder.sendAll(fundedState(guarded.account, funding, 100, 200), fr.acinq.bitcoin.Bitcoin.addressFromPublicKeyScript(chain.chainHash, elsewhere.toByteArray()).right!!, 2, emptySet(), guarded.spender()) + ) + val session = FrostSigningManager.proposeGuardianSpend(proposer.db, proposer.room, proposer.publicKey, built.psbt, guardedChildRoomId, chain) + pump(proposer, other) + assertNull(other.session(session.id), "a device not told about the wallet has nothing to sign it against") + + // And the proposer's own device will not propose one that skips the lock. + val unlocked = built.psbt.global.tx.let { tx -> tx.copy(txIn = tx.txIn.map { it.copy(sequence = GroupSpend.MAX_SEQUENCE) }) } + val psbt = GroupSpend.psbtOf(unlocked, listOf(funding.txOut[0] to GroupWalletDerivation.derive(guarded.account, 0, 0)), emptyMap(), guarded.account) + assertIs(GroupSpend.check(psbt, guarded.account, guarded.spender(thresholdPublicKey))) + } } From 2b44ebcbbc21a7b7e019477af009ec6de84dac8b Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 15:40:43 +0200 Subject: [PATCH 10/15] feat(wallet): a subgroup's transcript names the guardian that spent from it (Phase 8) Whenever a guarded wallet's coins change, the wallet screen reads every used address's history off Electrum, recognises a guardian's leaf in the witness that spent a coin, and writes one transcript line per transaction saying which group above took how much -- the child's only notice, since nobody in its room signed it. Co-Authored-By: Claude Opus 5.5 --- .../compose/database/model/ChatMessage.kt | 8 ++ .../repository/DatabaseChatRepository.kt | 7 ++ .../bennu/compose/managers/GuardianManager.kt | 80 ++++++++++++++++ .../compose/repository/ChatRepository.kt | 8 ++ .../ui/view/model/GroupWalletViewModel.kt | 23 +++++ .../compose/wallet/GroupOnchainWallets.kt | 48 ++++++++++ .../managers/GuardianSigningJvmTest.kt | 38 ++++++++ .../bennu/compose/wallet/FakeElectrum.kt | 18 +++- .../wallet/GuardianSpendNoticeJvmTest.kt | 91 +++++++++++++++++++ 9 files changed, 320 insertions(+), 1 deletion(-) create mode 100644 composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GuardianSpendNoticeJvmTest.kt diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt index e6a2c8be..8d442022 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt @@ -507,6 +507,13 @@ data class ChatMessage( */ const val TYPE_GUARDED_WALLET_SHARED = "guardedWalletShared" + /** + * One of this group's guardians spent from its guarded wallet through its + * leaf. Read off the chain by `GuardianManager.takenIn`, and the child's + * only notice of it: nobody in this room signed it. + */ + const val TYPE_GUARDIAN_SPEND = "guardianSpend" + val GROUP_IDENTITY_TYPES = setOf( TYPE_GROUP_PROFILE_SIGNED, TYPE_GROUP_RELAYS_SIGNED, @@ -516,6 +523,7 @@ data class ChatMessage( TYPE_GROUP_WALLET_OPENED, TYPE_GROUP_TRANSACTION_CONFIRMED, TYPE_GUARDED_WALLET_SHARED, + TYPE_GUARDIAN_SPEND, ) /** diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt index afbbe830..041a248c 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt @@ -230,6 +230,13 @@ class DatabaseChatRepository( 0 } + override suspend fun recordGuardianSpends(chatRoomId: String, taken: List): Int = try { + GuardianManager.recordTaken(database, chatRoomId, taken) + } catch (e: Throwable) { + logger.e("Error recording guardian spends from $chatRoomId's wallet", e) + 0 + } + override suspend fun groupSignedEvent(chatRoomId: String, id: HexKey): GroupSignedEvent? = try { database.groupSignedEventDao().getById(id)?.takeIf { it.chatRoomId == chatRoomId } } catch (e: Throwable) { diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianManager.kt index a2ae3e63..fdd64988 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GuardianManager.kt @@ -2,6 +2,7 @@ package com.machankura.bennu.compose.managers import co.touchlab.kermit.Logger import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.model.ChatMessage import com.machankura.bennu.compose.database.model.MarmotInnerEvent import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent @@ -13,6 +14,12 @@ import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.OutPoint +import fr.acinq.bitcoin.Satoshi +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxId +import fr.acinq.bitcoin.TxOut +import fr.acinq.lightning.utils.sum import kotlin.time.Clock import kotlin.time.Instant @@ -233,6 +240,79 @@ object GuardianManager { return rooms.size } + /** Coins of a guarded wallet one of its guardians took, in one transaction. */ + data class Taken( + val txid: TxId, + val guardian: GuardianDerivation.Guardian, + val amount: Satoshi, + ) + + /** + * Which guardians of [account] took which of [coins] in [spending] -- one + * entry per guardian -- read off the witnesses alone. + * + * A guardian's input carries three things: a signature, a leaf, and the + * control block proving the leaf is in the address. The leaf is matched + * against the guardian leaves of the address the coin was at, so a leaf is + * named only by a guardian whose key it is; anything else -- the wallet's own + * key-path spend, a witness of another shape -- names nobody. + */ + fun takenIn( + spending: Transaction, + account: GroupWalletDerivation.Account, + coins: Map>, + ): List { + if (!account.isGuarded) return emptyList() + + return spending.txIn.mapNotNull { input -> + val (txOut, derivation) = coins[input.outPoint] ?: return@mapNotNull null + val stack = input.witness.stack.takeIf { it.size == 3 } ?: return@mapNotNull null + val leaves = GuardianDerivation.leaves(account.guardians, account.chain, account.account, derivation.change, derivation.index) + val position = leaves.indexOfFirst { it.script == stack[1] }.takeIf { it >= 0 } ?: return@mapNotNull null + account.guardians[position] to txOut.amount + } + .groupBy({ it.first }, { it.second }) + .map { (guardian, amounts) -> Taken(spending.txid, guardian, amounts.sum()) } + } + + /** + * Writes a transcript line in [chatRoomId] for each of [taken] it has no line + * for yet. Returns how many it wrote. + * + * The whole of the child's notice that an ancestor spent from its wallet -- + * there is no channel from the ancestor's room into this one -- so it is + * written by whichever device reads the chain first, and every device that + * reads it afterwards finds it already there. + */ + suspend fun recordTaken(database: BennuDatabase, chatRoomId: String, taken: List): Int { + val written = database.chatMessageDao().getChatMessagesByChatRoomId(chatRoomId) + .map { it.chatMessage } + .filter { it.messageType == ChatMessage.TYPE_GUARDIAN_SPEND } + .map { it.content } + + val fresh = taken.filter { spend -> written.none { it.contains(spend.txid.toString()) } } + fresh.forEach { spend -> + val name = database.chatRoomDao().findChatRoomById(spend.guardian.chatRoomId)?.chatRoom?.subject + ?.takeIf { it.isNotBlank() } + ?: "A group above this one" + database.chatMessageDao().upsert( + ChatMessage( + senderPublicKey = spend.guardian.chatRoomId, + isUserMessage = false, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = chatRoomId, + content = "$name took ${spend.amount.sat} sats from this wallet through its guardian leaf, " + + "in transaction ${spend.txid}.", + messageType = ChatMessage.TYPE_GUARDIAN_SPEND, + ) + ) + logger.i("${spend.guardian.chatRoomId} took ${spend.amount.sat} sats from $chatRoomId's guarded wallet in ${spend.txid}") + } + return fresh.size + } + /** * What a notice that arrived in [chatRoomId] says, for its transcript line -- * or null when it is not one this room can believe, which gets no line: a diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt index 6f4a9cae..8892ed81 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt @@ -137,6 +137,9 @@ interface ChatRepository { /** Tells the groups in [shareable] about its statement, as [userPublicKey]. Returns how many were told. */ suspend fun shareGuardedWallet(shareable: GuardianManager.Shareable, userPublicKey: HexKey): Int + /** Writes a transcript line for each guardian spend from this group's wallet it has none for yet. */ + suspend fun recordGuardianSpends(chatRoomId: String, taken: List): Int + /** * The kind:1s this group signed, newest first. * @@ -413,6 +416,11 @@ interface ChatRepository { userPublicKey: HexKey ): Int = 0 + override suspend fun recordGuardianSpends( + chatRoomId: String, + taken: List + ): Int = 0 + override suspend fun groupPosts(chatRoomId: String): List = emptyList() override suspend fun groupSignedEvent( diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt index 53aa94a9..8ead9bb5 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt @@ -13,6 +13,8 @@ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.distinctUntilChangedBy +import com.machankura.bennu.compose.managers.GroupWalletDerivation import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -116,6 +118,7 @@ class GroupWalletViewModel( // state: any of them changing redraws the screen, and none may // overwrite another. val chainState = wallets?.walletFor(wallet.account)?.state ?: flowOf(null) + noticeGuardianSpends(wallet.account) watching = viewModelScope.launch(Dispatchers.IO) { combine( chainState, @@ -142,6 +145,26 @@ class GroupWalletViewModel( return combine(states) { it.toList() } } + private var noticing: Job? = null + + /** + * For a guarded wallet: each time its coins change, reads the chain for + * spends a guardian made from it and writes the transcript line for any that + * has none -- the group's only notice, since nobody in it signed them. + */ + private suspend fun noticeGuardianSpends(account: GroupWalletDerivation.Account) { + val wallets = wallets ?: return + if (!account.isGuarded) return + val onchain = wallets.walletFor(account) + + noticing?.cancel() + noticing = viewModelScope.launch(Dispatchers.IO) { + onchain.state + .distinctUntilChangedBy { state -> state.utxos.map { it.utxo.outPoint }.toSet() } + .collect { state -> chatRepository.recordGuardianSpends(chatRoomId, wallets.guardianSpends(state)) } + } + } + /** * Tells the groups above about [shareable]'s guarded wallet: one notice into * each of their rooms this device is in. What is told stays told, so the diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallets.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallets.kt index bad97e3b..0e34b15e 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallets.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallets.kt @@ -1,6 +1,12 @@ package com.machankura.bennu.compose.wallet import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.managers.GuardianManager +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.OutPoint +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxId +import fr.acinq.bitcoin.byteVector32 import fr.acinq.lightning.blockchain.electrum.IElectrumClient import fr.acinq.lightning.blockchain.fee.FeeratePerByte import kotlinx.coroutines.CoroutineScope @@ -42,6 +48,48 @@ class GroupOnchainWallets( suspend fun suggestedFeeratePerVbyte(): Long? = electrum.estimateFees(6)?.let { FeeratePerByte(it).feerate.sat }?.coerceAtLeast(1) + /** Transactions fetched for [guardianSpends], which never change once mined or seen. */ + private val transactions = mutableMapOf() + + /** + * Every spend a guardian of [state]'s account made from it, read off the + * history of each address the wallet has used. Empty for an unguarded + * account, and for whatever Electrum cannot answer right now -- the next look + * asks again. + * + * History rather than a watch on coins disappearing: a device asleep when the + * coin moved still finds it, since the chain keeps the record and nothing + * here has to have been running at the time. + */ + suspend fun guardianSpends(state: GroupWalletState): List { + val account = state.account + if (!account.isGuarded) return emptyList() + + val used = listOf(GroupWalletDerivation.RECEIVE to state.receive, GroupWalletDerivation.CHANGE to state.change) + .flatMap { (branch, wallet) -> + wallet.addresses.values.filter { it.alreadyUsed }.mapNotNull { address -> + address.meta.indexOrNull?.let { GroupWalletDerivation.derive(account, branch, it.toLong()) } + } + } + val ours = used.associateBy { it.pubkeyScript } + + val history = used.flatMap { derived -> + runCatching { electrum.getScriptHashHistory(Crypto.sha256(derived.pubkeyScript).byteVector32().reversed()) } + .getOrDefault(emptyList()) + .map { it.txid } + }.distinct().mapNotNull { txid -> transactionOf(txid) } + + val coins = history.flatMap { tx -> + tx.txOut.mapIndexedNotNull { index, out -> ours[out.publicKeyScript]?.let { OutPoint(tx, index.toLong()) to (out to it) } } + }.toMap() + + return history.flatMap { GuardianManager.takenIn(it, account, coins) } + } + + private suspend fun transactionOf(txid: TxId): Transaction? = + mutex.withLock { transactions[txid] } + ?: runCatching { electrum.getTx(txid) }.getOrNull()?.also { tx -> mutex.withLock { transactions[txid] = tx } } + suspend fun stop() = mutex.withLock { wallets.values.forEach { it.stop() } wallets.clear() diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt index d26f6c1d..bffa294e 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt @@ -447,6 +447,44 @@ class GuardianSigningJvmTest { } } + @Test + fun `the child reads off the chain which guardian took its coins, and says so once`(): Unit = runBlocking { + val proposer = device(members[0], signerIndex = 0) + val other = device(members[1], signerIndex = 1) + val statement = guardedStatement() + tell(proposer, statement) + tell(other, statement) + + val guarded = assertNotNull(GuardianManager.guardedWalletFor(proposer.db, roomId, guardedChildRoomId, chain, 0)) + val funding = fundingOf(guarded.account) + val built = assertIs( + GroupSpendBuilder.sendAll(fundedState(guarded.account, funding, 100, 200), fr.acinq.bitcoin.Bitcoin.addressFromPublicKeyScript(chain.chainHash, elsewhere.toByteArray()).right!!, 2, emptySet(), guarded.spender()) + ) + val session = FrostSigningManager.proposeGuardianSpend(proposer.db, proposer.room, proposer.publicKey, built.psbt, guardedChildRoomId, chain) + pump(proposer, other) + FrostSigningManager.approve(other.db, other.room, session.id) + pump(proposer, other) + val signed = Transaction.read(assertNotNull(proposer.db.groupTransactionDao().getBySessionId(session.id)?.signedTransaction)) + + // What the child's device knows: its own coin, and the transaction that spent it. + val coins = mapOf(OutPoint(funding, 0) to (funding.txOut[0] to GroupWalletDerivation.derive(guarded.account, 0, 0))) + val taken = GuardianManager.takenIn(signed, guarded.account, coins) + assertEquals(listOf(GuardianManager.Taken(signed.txid, guarded.account.guardians[0], Satoshi(50_000))), taken) + + // The child's own key-path spend names nobody. + val ownSpend = signed.updateWitness(0, fr.acinq.bitcoin.ScriptWitness(listOf(ByteVector(ByteArray(64))))) + assertEquals(emptyList(), GuardianManager.takenIn(ownSpend, guarded.account, coins)) + + // The line, written once, in the child's room -- the ancestor's name from + // this device's own copy of its room. + proposer.db.chatRoomDao().upsert(ChatRoom(id = guardedChildRoomId, userPublicKey = proposer.publicKey, subject = "Translation team", description = null, mlsGroupState = "00")) + assertEquals(1, GuardianManager.recordTaken(proposer.db, guardedChildRoomId, taken)) + assertEquals(0, GuardianManager.recordTaken(proposer.db, guardedChildRoomId, taken), "a second reading of the chain writes nothing") + val line = proposer.db.chatMessageDao().getChatMessagesByChatRoomId(guardedChildRoomId).map { it.chatMessage } + .single { it.messageType == com.machankura.bennu.compose.database.model.ChatMessage.TYPE_GUARDIAN_SPEND } + assertTrue(line.content.startsWith("Council took 50000 sats from this wallet through its guardian leaf"), line.content) + } + @Test fun `a guardian's spend is refused for a wallet the room was not told about, or without the lock`(): Unit = runBlocking { val proposer = device(members[0], signerIndex = 0) diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/FakeElectrum.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/FakeElectrum.kt index f2d51fbe..83558bbc 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/FakeElectrum.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/FakeElectrum.kt @@ -41,6 +41,9 @@ internal class FakeElectrum : IElectrumClient { /** How many transactions have touched each script: Electrum's status is over the history, not the unspents. */ private val history = mutableMapOf() + /** The transactions that touched each script, in order: what `get_history` answers. */ + private val historyTxs = mutableMapOf>() + private fun status(scriptHash: ByteVector32): String? = history[scriptHash]?.let { "used:$it" } /** Pays [script] in a fresh transaction, confirmed at [height] (0 for the mempool), and tells the wallet. */ @@ -55,6 +58,7 @@ internal class FakeElectrum : IElectrumClient { val hash = scriptHash(script) unspents[hash] = unspents[hash].orEmpty() + UnspentItem(tx.txid, 0, amount.sat, height) history[hash] = (history[hash] ?: 0) + 1 + historyTxs[hash] = historyTxs[hash].orEmpty() + tx.txid notifications.emit(ScriptHashSubscriptionResponse(hash, status(hash))) } @@ -66,6 +70,17 @@ internal class FakeElectrum : IElectrumClient { notifications.emit(ScriptHashSubscriptionResponse(hash, status(hash))) } + /** The transaction paying [script] most recently, as [pay] made it. */ + fun fundingOf(script: ByteVector): Transaction = txs.getValue(historyTxs.getValue(scriptHash(script)).last()) + + /** Spends what [script] holds with [tx] itself, which joins its history as a real spend would. */ + suspend fun spendWith(script: ByteVector, tx: Transaction) { + val hash = scriptHash(script) + txs[tx.txid] = tx + historyTxs[hash] = historyTxs[hash].orEmpty() + tx.txid + spend(script) + } + override suspend fun startScriptHashSubscription(scriptHash: ByteVector32): ScriptHashSubscriptionResponse { subscribed += scriptHash return ScriptHashSubscriptionResponse(scriptHash, status(scriptHash)) @@ -76,7 +91,8 @@ internal class FakeElectrum : IElectrumClient { override suspend fun getHeader(blockHeight: Int): BlockHeader? = null override suspend fun getHeaders(startHeight: Int, count: Int): List = emptyList() override suspend fun getMerkle(txId: TxId, blockHeight: Int, contextOpt: Transaction?): GetMerkleResponse? = null - override suspend fun getScriptHashHistory(scriptHash: ByteVector32): List = emptyList() + override suspend fun getScriptHashHistory(scriptHash: ByteVector32): List = + historyTxs[scriptHash].orEmpty().map { TransactionHistoryItem(100, it) } override suspend fun broadcastTransaction(tx: Transaction): TxId = tx.txid override suspend fun estimateFees(confirmations: Int): FeeratePerKw? = null override suspend fun startHeaderSubscription() = HeaderSubscriptionResponse(0, Block.RegtestGenesisBlock.header) diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GuardianSpendNoticeJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GuardianSpendNoticeJvmTest.kt new file mode 100644 index 00000000..6ef16c35 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GuardianSpendNoticeJvmTest.kt @@ -0,0 +1,91 @@ +package com.machankura.bennu.compose.wallet + +import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.managers.GuardianManager +import com.machankura.bennu.compose.managers.SharedKeyDerivation +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.OutPoint +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.Satoshi +import fr.acinq.bitcoin.Script +import fr.acinq.bitcoin.ScriptWitness +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxIn +import fr.acinq.bitcoin.TxOut +import fr.acinq.lightning.blockchain.electrum.WalletState +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.runBlocking +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * A guarded wallet reading its own history for spends its guardians made -- + * the child's only notice of one, since nobody in its room signed it. + * + * The witnesses here are the right shape and carry no valid signature: what is + * under test is which leaf a spend used, which the chain records whether or not + * anybody checks the signature again. `GuardianSigningJvmTest` spends for real. + */ +class GuardianSpendNoticeJvmTest { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + @AfterTest + fun stop() = scope.cancel() + + private fun key(seed: Int): String = PrivateKey(ByteVector32(ByteArray(32) { seed.toByte() })).publicKey().toString() + + private val chain = Chain.Regtest + private val parentRoom = SharedKeyDerivation.marmotGroupId(key(1)) + private val childKey = key(2) + private val childRoom = SharedKeyDerivation.marmotGroupId(childKey) + private val grant = GuardianDerivation.grant(key(1), parentRoom, emptyList(), childRoom) + private val account = GroupWalletDerivation.account(childKey, chain, guardians = grant) + private val coin = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, 0) + private val elsewhere = ByteVector(Script.write(Script.pay2wpkh(PrivateKey(ByteVector32(ByteArray(32) { 9 })).publicKey()))) + + /** The wallet after its one coin has been spent: the address used, nothing left on it. */ + private val spentState = GroupWalletState( + account, + WalletState(mapOf(coin.address(chain) to WalletState.AddressState(WalletState.AddressMeta.Derived(0), alreadyUsed = true, utxos = emptyList()))), + WalletState(emptyMap()), + tipHeight = 200, + ) + + private fun spending(funding: Transaction, witness: ScriptWitness) = Transaction( + 2, listOf(TxIn(OutPoint(funding, 0), ByteVector.empty, GuardianDerivation.ANCESTOR_DELAY, witness)), + listOf(TxOut(Satoshi(49_000), elsewhere)), 0, + ) + + @Test + fun `a spend through the parent's leaf is read off the address's history`(): Unit = runBlocking { + val electrum = FakeElectrum() + electrum.pay(coin.pubkeyScript, Satoshi(50_000)) + val funding = electrum.fundingOf(coin.pubkeyScript) + val leaf = GuardianDerivation.leaves(grant, chain, 0, coin.change, coin.index)[0] + val taken = spending(funding, Script.witnessScriptPathPay2tr(coin.internalKey, leaf, ScriptWitness(listOf(ByteVector(ByteArray(64)))), coin.tree!!)) + electrum.spendWith(coin.pubkeyScript, taken) + + val wallets = GroupOnchainWallets(electrum, scope) + assertEquals( + listOf(GuardianManager.Taken(taken.txid, grant[0], Satoshi(50_000))), + wallets.guardianSpends(spentState), + ) + } + + @Test + fun `the group's own key-path spend names no guardian`(): Unit = runBlocking { + val electrum = FakeElectrum() + electrum.pay(coin.pubkeyScript, Satoshi(50_000)) + val own = spending(electrum.fundingOf(coin.pubkeyScript), Script.witnessKeyPathPay2tr(fr.acinq.bitcoin.ByteVector64.Zeroes)) + electrum.spendWith(coin.pubkeyScript, own) + + assertEquals(emptyList(), GroupOnchainWallets(electrum, scope).guardianSpends(spentState)) + } +} From f9e2d45ec4ed2a79d29d2a5b97b17b03fcc13489 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 15:40:43 +0200 Subject: [PATCH 11/15] docs(wallet): guardian leaves built, and where the build differed (Phase 9) The guardians note records what was built against the plan, what is left to do by hand before the mainnet gate lifts, and the conflicting-spend gap. The subgroups and wallet notes each change the one sentence the plan said they would. Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 2 +- docs/group-chain-wallet.md | 6 ++++++ docs/group-wallet-guardians.md | 38 +++++++++++++++++++++++++++++----- docs/subgroups.md | 7 +++++-- 4 files changed, 45 insertions(+), 8 deletions(-) diff --git a/docs/README.md b/docs/README.md index 5fc4c619..4c3d5500 100644 --- a/docs/README.md +++ b/docs/README.md @@ -48,7 +48,7 @@ The group-wallet-addresses note is a phased plan that has been built, and is the group-chain-wallet note's Phase 5 taken one screen further: read that note's Phases 4 and 5 first, and its own table of where the build chose differently before the code. -The group-wallet-guardians note is a phased plan; it assumes the subgroups and group-chain-wallet notes, and changes one sentence in +The group-wallet-guardians note is a phased plan that has been built; it assumes the subgroups and group-chain-wallet notes, and changes one sentence in each. The Material Design note is a phased plan that has not been built, and is the only one about what the app looks like rather than what it does; read the diff --git a/docs/group-chain-wallet.md b/docs/group-chain-wallet.md index c0ee5df7..293e83da 100644 --- a/docs/group-chain-wallet.md +++ b/docs/group-chain-wallet.md @@ -236,6 +236,12 @@ address with a hidden script path is an address no member's device recognises which is the whole defence, and why the app never displays, accepts or signs for an address it did not derive. +A subgroup's *guarded* wallet does have a tree -- one leaf per ancestor, see +[group-wallet-guardians.md](./group-wallet-guardians.md) -- and the defence is the +same with one word changed: every member derives every address, tree included, +from the child's key and a certificate every member verifies, and compares it byte +for byte. The tree is computed, never proposed. + ### The rule this inherits, made more expensive Every tweak above is publicly computable from `K`. So the derivation note's rule diff --git a/docs/group-wallet-guardians.md b/docs/group-wallet-guardians.md index b1032c08..59cc79a8 100644 --- a/docs/group-wallet-guardians.md +++ b/docs/group-wallet-guardians.md @@ -10,8 +10,26 @@ Read [subgroups.md](./subgroups.md) and [group-chain-wallet.md](./group-chain-wa first. This builds on the birth certificate from the first and the account derivation from the second, and it changes one sentence in each. -**A phased plan**, written against the code as it stood at `409be6db`, with the -`lightning-kmp-app` submodule at `e0d2b82`. +**Built**, phases 1-9, one commit each, written against the code as it stood at +`409be6db` with the `lightning-kmp-app` submodule at `e0d2b82`. `GuardianDerivation`, +`GuardianManager` and `FrostSigningManager.proposeGuardianSpend` are the entry +points, and `GroupWalletRollout.GUARDIANS_ON_MAINNET` is the gate. The phases +below are kept as written; where the build chose differently the table says so. + +| what the plan said | what it turned out to be | +|---|---| +| Phase 4 is the statement, Phase 5 the addresses | Phase 4 did both: a statement cannot be verified without rebuilding the descriptors it carries, so `Account` learned its guardians and `deriveBelow` its tree in the same commit | +| Phase 9 adds the rollout gate | the gate came with Phase 5, because that is where a guarded wallet is first offered; a way in shipped before its gate would have been offered on mainnet for four commits. Phase 9 is this table | +| forwarded statements are stored for the ancestor to watch | no table: the 30333 notice is the `MarmotInnerEvent` row the inbound path files for every inner event, and `GuardianManager.guardedWalletsOf` checks each one again on every read -- the economy `GroupWallet` already has | +| the proposal carries `["input", …]` tags | it carries one tag, `["guarded", ]`. Each input's `tap_bip32_derivation` already names its place under the descendant's account, exactly as the child's own spend does, so a second place to say it would be a second thing to disagree | +| `check` asks the proposer's device whether a coin has 12 confirmations | the builder does: it only offers a guardian coins its lock has already let go of. `check` cannot ask, because a signer with no node has no tip, and a coin spent too early is a transaction nobody can mine rather than a loss | +| `GroupTransactionWatcher` notices a guardian's spend | the wallet screen's view model does, each time the guarded wallet's coins change, by reading every used address's history off Electrum -- so a device asleep when the coin moved still finds it, and whichever device reads first writes the one line. A device that never opens the wallet screen writes nothing | +| schema unchanged | v27: `GroupTransaction.guardedChatRoomId`, the descendant a guardian's spend draws from. A spend's account is otherwise read from the statement, and a guardian's is the descendant's statement, not the room's | +| nothing outside the plan | a bug older than it: bitcoin-kmp reads a taproot derivation's fingerprint back from a PSBT as a signed int, so for half of all accounts every member but the proposer refused every spend as not the wallet's own. Fixed on its own, in `fix(wallet): read a PSBT's key fingerprint as unsigned`, because it reaches every plain wallet too | + +Still to do by hand, and the condition the mainnet gate lifts on: a guardian +spend made on signet by a real three-level hierarchy, every member's device +watching, and the grandchild's transcript naming the root. The headline: **the parent puts a guardian key for the child into the child's birth certificate, beside the keys its own ancestors gave it, each derived one @@ -327,9 +345,10 @@ spent too early is a transaction nobody can mine, never a loss. ### What the child sees -Nothing until it happens. `GroupTransactionWatcher` on a child's device sees one -of its coins spent by a transaction it has no row for, reads the witness, finds -a leaf it can name, and writes a transcript line saying which ancestor took it. +Nothing until it happens. A child's device reads the history of every address +its guarded wallet has used, finds a transaction whose witness carries one of +its guardians' leaves for the coin it spent, and writes a transcript line saying +which ancestor took how much -- `GuardianManager.takenIn` and `recordTaken`. ### What it costs onchain @@ -396,6 +415,15 @@ threshold key, so to the shares of the ceremony that made it, including the shares of members who have since left. This is the wallet note's *removal from the group does not un-know a key*, inherited one level down. +**It does not settle a spend that lost its coins to the other side.** The +wallet note settles conflicting spends when one of the group's own confirms, +because "only the group can spend its coins". A guarded wallet's coins have +other spenders now. A child's open spend whose coin a guardian took, or a +guardian's whose coin the child moved first, is never marked replaced: it sits +as signed, rebroadcast every ten minutes, until somebody abandons it. The fix is +for `GroupTransactionWatcher` to ask whether an unconfirmed spend's inputs are +still unspent, and it is a follow-up rather than a line here. + **It does not tell the child before it happens**, and it does not constrain where the coins go. "Only back into the child, at a new address" is a covenant, and there is none on mainnet to write it with (`OP_CHECKTEMPLATEVERIFY`, diff --git a/docs/subgroups.md b/docs/subgroups.md index c8fc3193..78605899 100644 --- a/docs/subgroups.md +++ b/docs/subgroups.md @@ -1021,8 +1021,11 @@ is wanted, is the button. **A subgroup cannot sign for its parent, and the parent cannot sign for it.** Two independent keys, two independent quorums. The certificate is a claim about lineage, not a delegation of authority, and nothing in this design lets one group -act as the other. If delegation is ever wanted it is a different mechanism and it -should not be built on top of this one silently. +act as the other. Delegation is a different mechanism, and it was built as one: +[group-wallet-guardians.md](./group-wallet-guardians.md) lets a parent guard a +child's wallet, but only when the parent's quorum signs guardian keys into the +certificate *and* the child's quorum opens a guarded wallet naming them. The +certificate on its own still delegates nothing. **A member added to the parent later sees no subgroups, and a member added to the subgroup later cannot verify its parent.** One cause, two faces, and both are the From 29328b4c5f6fb40df6ae26eda8fce33394a53a3f Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 16:12:48 +0200 Subject: [PATCH 12/15] fix(wallet): settle a spend whose coins another room's transaction took A guarded wallet's coins have a spender outside the room: a guardian can take a coin the child's open spend wants, and the child can move one a guardian's wants. Neither winner is a row in the loser's room, so the loser sat signed and rebroadcast forever. The watcher now asks the chain, for a signed spend Electrum has not heard of, which transaction took each coin; once that one confirms, recordReplaced marks the spend replaced and settles every other spend of the coin, as recordConfirmed does for the room's own. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 2 +- .../compose/managers/FrostSigningManager.kt | 84 ++++++++++++++----- .../compose/wallet/GroupTransactionWatcher.kt | 48 ++++++++++- .../wallet/GroupTransactionWatcherJvmTest.kt | 76 ++++++++++++++++- docs/group-wallet-guardians.md | 10 +-- 5 files changed, 183 insertions(+), 37 deletions(-) diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 67e99aac..31cca5d0 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -694,7 +694,7 @@ Signed, sending it to the network Sent, waiting for a confirmation Confirmed - Replaced by a later spend + Replaced by another spend of the same coins Send again Bump the fee Sent again diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt index f6586e03..627147f7 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt @@ -1072,28 +1072,7 @@ object FrostSigningManager { database.groupTransactionDao().upsert(confirmed.copy(confirmedAt = at, seenAt = confirmed.seenAt ?: at)) - val coins = coinsOf(confirmed) - database.groupTransactionDao().getByChatRoomId(confirmed.chatRoomId) - .filter { it.frostSigningSessionId != sessionId && (coinsOf(it) intersect coins).isNotEmpty() } - .forEach { other -> - val otherSession = database.frostSigningSessionDao().getSessionById(other.frostSigningSessionId) - ?: return@forEach - when (otherSession.stage) { - FrostSigningStage.COMPLETE -> if (other.confirmedAt == null && other.replacedByTxid == null) { - database.groupTransactionDao().upsert(other.copy(replacedByTxid = confirmed.txid)) - } - - FrostSigningStage.FAILED -> Unit - - else -> fail( - database = database, - session = otherSession, - reason = "Spent by another transaction", - content = "abandoned a spend: another of the group's transactions spent its coins first. " + - "Nothing was signed." - ) - } - } + settleSpendsOf(database, confirmed.chatRoomId, coinsOf(confirmed), byTxid = confirmed.txid, except = sessionId) val sent = checkedSpend(database, sessionId)?.amountSent announce( @@ -1106,6 +1085,67 @@ object FrostSigningManager { ) } + /** + * A spend whose coins a transaction the room never proposed has taken, as + * [conflictTxid] confirmed: marked replaced, and every other spend of the same + * coins settled with it. + * + * A guarded wallet's coins have two kinds of spender. The child's own spend + * can lose a coin to a guardian's, and a guardian's to the child's, and the + * winner is never a row in the loser's room -- so [recordConfirmed] cannot be + * what settles the loser. The watcher is: it asks the chain whether a signed + * spend's coins are still there, and calls this when one was taken by a + * confirmed transaction. Once per spend, by the read of `replacedByTxid`. + */ + suspend fun recordReplaced(database: BennuDatabase, sessionId: String, conflictTxid: String) { + val lost = database.groupTransactionDao().getBySessionId(sessionId) ?: return + if (lost.confirmedAt != null || lost.replacedByTxid != null) return + + database.groupTransactionDao().upsert(lost.copy(replacedByTxid = conflictTxid)) + settleSpendsOf(database, lost.chatRoomId, coinsOf(lost), byTxid = conflictTxid, except = sessionId) + logger.i("Spend $sessionId lost its coins to $conflictTxid") + } + + /** + * Every spend in [chatRoomId] other than [except] that wants any of [coins], + * settled by [byTxid] having taken them: only one spend of a coin can ever + * confirm, so the rest are over whatever stage they are in. One still + * collecting is abandoned -- its signatures, if it ever got them, would be + * over a transaction nobody can mine. One already signed is a transaction + * [byTxid] replaced, a fee bump or a race, and is marked so rather than + * failed: it was signed, and saying otherwise would misreport what the group + * did. + */ + private suspend fun settleSpendsOf( + database: BennuDatabase, + chatRoomId: String, + coins: Set, + byTxid: String, + except: String, + ) { + database.groupTransactionDao().getByChatRoomId(chatRoomId) + .filter { it.frostSigningSessionId != except && (coinsOf(it) intersect coins).isNotEmpty() } + .forEach { other -> + val otherSession = database.frostSigningSessionDao().getSessionById(other.frostSigningSessionId) + ?: return@forEach + when (otherSession.stage) { + FrostSigningStage.COMPLETE -> if (other.confirmedAt == null && other.replacedByTxid == null) { + database.groupTransactionDao().upsert(other.copy(replacedByTxid = byTxid)) + } + + FrostSigningStage.FAILED -> Unit + + else -> fail( + database = database, + session = otherSession, + reason = "Spent by another transaction", + content = "abandoned a spend: another transaction spent its coins first. " + + "Nothing was signed." + ) + } + } + } + private fun coinsOf(transaction: GroupTransaction): Set = GroupSpend.decode(transaction.psbt)?.global?.tx?.txIn?.map { it.outPoint }?.toSet().orEmpty() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcher.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcher.kt index 75cc0f13..9faaf536 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcher.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcher.kt @@ -4,7 +4,10 @@ import co.touchlab.kermit.Logger import com.machankura.bennu.compose.database.BennuDatabase import com.machankura.bennu.compose.database.model.GroupTransaction import com.machankura.bennu.compose.managers.FrostSigningManager +import fr.acinq.bitcoin.Crypto import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxId +import fr.acinq.bitcoin.byteVector32 import fr.acinq.lightning.blockchain.electrum.IElectrumClient import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope @@ -34,6 +37,15 @@ import kotlin.time.Instant * sent again every [REBROADCAST_AFTER], which is what `IElectrumClient` asks of * its callers. A confirmation goes through [FrostSigningManager.recordConfirmed], * which settles every other spend of the same coins. + * + * A spend Electrum has not heard of may have lost its coins. Only the group can + * spend a plain wallet's coins, so there the loser is always another of the + * room's own spends and the winner's confirmation settles it. A guarded wallet's + * coins have a second spender, in another room: so an unseen spend asks the + * chain whether its coins are still there, and one taken by a *confirmed* + * transaction it is not goes through [FrostSigningManager.recordReplaced]. A + * conflict still in the mempool settles nothing -- ours may yet be the one that + * confirms. */ class GroupTransactionWatcher( private val database: BennuDatabase, @@ -100,8 +112,12 @@ class GroupTransactionWatcher( database.groupTransactionDao().upsert(row) } - // Null while disconnected, or while Electrum has not heard of it. - val confirmations = electrum.getConfirmations(signed) ?: return + // Null while disconnected, or while Electrum has not heard of it -- which + // is also what a spend whose coins somebody else took looks like. + val confirmations = electrum.getConfirmations(signed) ?: run { + conflictOf(row, signed)?.let { FrostSigningManager.recordReplaced(database, row.frostSigningSessionId, it.toString()) } + return + } if (row.seenAt == null) { row = row.copy(seenAt = now()) database.groupTransactionDao().upsert(row) @@ -111,6 +127,34 @@ class GroupTransactionWatcher( } } + /** + * A confirmed transaction other than [signed] that spent one of its coins, or + * null when every coin is still unspent, or was only taken by something + * unconfirmed, or the chain cannot be asked right now. + * + * Read per coin off the address it is at: is it still unspent there, and if + * not, which transaction in that address's history spent it. The address is + * the spent output's script, which the proposed PSBT carries for every input. + */ + private suspend fun conflictOf(transaction: GroupTransaction, signed: Transaction): TxId? { + val psbt = GroupSpend.decode(transaction.psbt) ?: return null + + signed.txIn.forEachIndexed { index, input -> + val txOut = (psbt.inputs.getOrNull(index) as? fr.acinq.bitcoin.psbt.Input.WitnessInput)?.txOut ?: return@forEachIndexed + val scriptHash = Crypto.sha256(txOut.publicKeyScript).byteVector32().reversed() + + val unspent = electrum.getScriptHashUnspents(scriptHash) + .any { it.txid == input.outPoint.txid && it.outputIndex.toLong() == input.outPoint.index } + if (unspent) return@forEachIndexed + + electrum.getScriptHashHistory(scriptHash) + .filter { it.blockHeight > 0 && it.txid != signed.txid } + .firstOrNull { item -> electrum.getTx(item.txid)?.txIn?.any { it.outPoint == input.outPoint } == true } + ?.let { return it.txid } + } + return null + } + companion object { val POLL: Duration = 30.seconds val REBROADCAST_AFTER: Duration = 10.minutes diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcherJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcherJvmTest.kt index 97a16184..615300dc 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcherJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupTransactionWatcherJvmTest.kt @@ -59,17 +59,21 @@ class GroupTransactionWatcherJvmTest { val broadcasts = mutableListOf() /** Confirmations by txid; absent is "Electrum has not heard of it". */ val confirmations = mutableMapOf() + /** What each script hash still holds, has seen, and the transactions behind both. */ + val unspents = mutableMapOf>() + val histories = mutableMapOf>() + val txs = mutableMapOf() override val notifications = MutableSharedFlow() override val connectionStatus: StateFlow = MutableStateFlow(ElectrumConnectionStatus.Closed(null)) override suspend fun broadcastTransaction(tx: Transaction): TxId = tx.txid.also { broadcasts += it } override suspend fun getConfirmations(tx: Transaction): Int? = confirmations[tx.txid] - override suspend fun getTx(txId: TxId): Transaction? = null + override suspend fun getTx(txId: TxId): Transaction? = txs[txId] override suspend fun getHeader(blockHeight: Int): BlockHeader? = null override suspend fun getHeaders(startHeight: Int, count: Int): List = emptyList() override suspend fun getMerkle(txId: TxId, blockHeight: Int, contextOpt: Transaction?): GetMerkleResponse? = null - override suspend fun getScriptHashHistory(scriptHash: ByteVector32): List = emptyList() - override suspend fun getScriptHashUnspents(scriptHash: ByteVector32): List = emptyList() + override suspend fun getScriptHashHistory(scriptHash: ByteVector32): List = histories[scriptHash].orEmpty() + override suspend fun getScriptHashUnspents(scriptHash: ByteVector32): List = unspents[scriptHash].orEmpty() override suspend fun estimateFees(confirmations: Int): FeeratePerKw? = null override suspend fun startScriptHashSubscription(scriptHash: ByteVector32) = ScriptHashSubscriptionResponse(scriptHash, null) override suspend fun startHeaderSubscription() = HeaderSubscriptionResponse(0, Block.RegtestGenesisBlock.header) @@ -173,4 +177,70 @@ class GroupTransactionWatcherJvmTest { assertEquals(1, lines.size) assertTrue(db.groupTransactionDao().getUnsettled().isEmpty(), "neither signed spend is still on its way") } + + // ---- Coins another room's transaction took ------------------------------ + + /** The script the guarded coin sits at, and its Electrum script hash. */ + private val coinScript = ByteVector("5120" + "ab".repeat(32)) + private val coinHash = ByteVector32(fr.acinq.bitcoin.Crypto.sha256(coinScript.toByteArray()).reversedArray()) + + /** A signed spend of [coin] whose PSBT names the output it spends, as every real proposal's does. */ + private suspend fun signedSpendOfCoin(id: String, tx: Transaction) { + db.frostSigningSessionDao().upsert( + FrostSigningSession( + id = id, chatRoomId = room, coordinatorPublicKey = user, userPublicKey = user, dkgSessionId = "dkg", + threshold = 2, participantCount = 3, signerId = 0, stage = FrostSigningStage.COMPLETE, subject = FrostSigningSubject.TRANSACTION, + ) + ) + val psbt = Psbt(tx).updateWitnessInput(coin, TxOut(Satoshi(10_000), coinScript)).right!! + db.groupTransactionDao().insertIfAbsent( + GroupTransaction( + frostSigningSessionId = id, chatRoomId = room, chain = "regtest", account = 0, + psbt = GroupSpend.encode(psbt), txid = tx.txid.toString(), signedTransaction = Hex.encode(Transaction.write(tx)), + ) + ) + } + + /** Somebody else -- a guardian, or the guarded group itself -- spends [coin], at [height] (0 for the mempool). */ + private fun takenElsewhere(height: Int): Transaction { + val theirs = spending(coin, pay = 7_000).copy(txOut = listOf(TxOut(Satoshi(7_000), ByteVector("0014" + "11".repeat(20))))) + electrum.txs[theirs.txid] = theirs + electrum.histories[coinHash] = listOf(TransactionHistoryItem(90, coin.txid), TransactionHistoryItem(height, theirs.txid)) + return theirs + } + + @Test + fun `a spend whose coin another transaction took is replaced once that transaction confirms`(): Unit = runBlocking { + seed() + val ours = spending(coin, pay = 9_000) + signedSpendOfCoin("ours", ours) + // Another of this room's spends of the same coin, still collecting. + spend("collecting", spending(coin, OutPoint(TxId(ByteVector32(ByteArray(32) { 6 })), 0), pay = 12_000), FrostSigningStage.COLLECTING_NONCES, signed = false) + + val theirs = takenElsewhere(height = 101) + watcher.pass() + + assertEquals(theirs.txid.toString(), db.groupTransactionDao().getBySessionId("ours")?.replacedByTxid) + assertEquals(FrostSigningStage.COMPLETE, db.frostSigningSessionDao().getSessionById("ours")?.stage, "it was signed, and stays so") + assertEquals(FrostSigningStage.FAILED, db.frostSigningSessionDao().getSessionById("collecting")?.stage) + assertTrue(db.groupTransactionDao().getUnsettled().isEmpty(), "nothing is left being sent again every ten minutes") + } + + @Test + fun `a coin taken only in the mempool, or not taken at all, settles nothing`(): Unit = runBlocking { + seed() + signedSpendOfCoin("ours", spending(coin, pay = 9_000)) + + // Still unspent where it sits. + electrum.unspents[coinHash] = listOf(UnspentItem(coin.txid, coin.index.toInt(), 10_000, 90)) + electrum.histories[coinHash] = listOf(TransactionHistoryItem(90, coin.txid)) + watcher.pass() + assertNull(db.groupTransactionDao().getBySessionId("ours")?.replacedByTxid) + + // Spent by something unconfirmed: ours may yet be the one that confirms. + electrum.unspents.remove(coinHash) + takenElsewhere(height = 0) + watcher.pass() + assertNull(db.groupTransactionDao().getBySessionId("ours")?.replacedByTxid) + } } diff --git a/docs/group-wallet-guardians.md b/docs/group-wallet-guardians.md index 59cc79a8..07772ee1 100644 --- a/docs/group-wallet-guardians.md +++ b/docs/group-wallet-guardians.md @@ -25,6 +25,7 @@ below are kept as written; where the build chose differently the table says so. | `check` asks the proposer's device whether a coin has 12 confirmations | the builder does: it only offers a guardian coins its lock has already let go of. `check` cannot ask, because a signer with no node has no tip, and a coin spent too early is a transaction nobody can mine rather than a loss | | `GroupTransactionWatcher` notices a guardian's spend | the wallet screen's view model does, each time the guarded wallet's coins change, by reading every used address's history off Electrum -- so a device asleep when the coin moved still finds it, and whichever device reads first writes the one line. A device that never opens the wallet screen writes nothing | | schema unchanged | v27: `GroupTransaction.guardedChatRoomId`, the descendant a guardian's spend draws from. A spend's account is otherwise read from the statement, and a guardian's is the descendant's statement, not the room's | +| a spend that lost its coins to the other side is never settled -- this note's own *What this does not do*, as first written | settled. `GroupTransactionWatcher` asks the chain, for a signed spend Electrum has not heard of, whether each coin is still unspent at its address and, if not, which transaction in that address's history took it; once that transaction is confirmed, `FrostSigningManager.recordReplaced` marks the spend replaced and settles every other spend of the coin, as `recordConfirmed` does for the room's own. A conflict still in the mempool settles nothing | | nothing outside the plan | a bug older than it: bitcoin-kmp reads a taproot derivation's fingerprint back from a PSBT as a signed int, so for half of all accounts every member but the proposer refused every spend as not the wallet's own. Fixed on its own, in `fix(wallet): read a PSBT's key fingerprint as unsigned`, because it reaches every plain wallet too | Still to do by hand, and the condition the mainnet gate lifts on: a guardian @@ -415,15 +416,6 @@ threshold key, so to the shares of the ceremony that made it, including the shares of members who have since left. This is the wallet note's *removal from the group does not un-know a key*, inherited one level down. -**It does not settle a spend that lost its coins to the other side.** The -wallet note settles conflicting spends when one of the group's own confirms, -because "only the group can spend its coins". A guarded wallet's coins have -other spenders now. A child's open spend whose coin a guardian took, or a -guardian's whose coin the child moved first, is never marked replaced: it sits -as signed, rebroadcast every ten minutes, until somebody abandons it. The fix is -for `GroupTransactionWatcher` to ask whether an unconfirmed spend's inputs are -still unspent, and it is a follow-up rather than a line here. - **It does not tell the child before it happens**, and it does not constrain where the coins go. "Only back into the child, at a new address" is a covenant, and there is none on mainnet to write it with (`OP_CHECKTEMPLATEVERIFY`, From af4304aaae883df1ce9def1c0d90cf9ab45e8a27 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 17:59:34 +0200 Subject: [PATCH 13/15] fix(dkg): a parent's second subgroup is not shown its first one's signing sessions A subgroup's ceremony runs in its parent's room, so that room holds a certificate and a key-state signing session for every subgroup made under it. The ceremony screen took the newest of each kind regardless of which subgroup it was for, so a parent's second subgroup opened on the first one's finished certificate, with "Ask the parent group to certify" already disabled. Each session is now matched on what its event names: the certificate on the subgroup's threshold key, the key state on the ceremony. The newest match still wins, so a failed request can be asked for again. Co-Authored-By: Claude Opus 5.5 --- .../ui/view/model/DkgRitualViewModel.kt | 61 +++++++--- .../view/model/DkgRitualViewModelJvmTest.kt | 114 ++++++++++++++++++ 2 files changed, 159 insertions(+), 16 deletions(-) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/DkgRitualViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/DkgRitualViewModel.kt index 0b0e07ef..8d14e090 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/DkgRitualViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/DkgRitualViewModel.kt @@ -135,20 +135,25 @@ class DkgRitualViewModel( val sessions = dkgRepository.observeSessionById(dkgSessionId) // The session in which the group agrees what its admin room will sign - // with. The room a ceremony runs in signs nothing else, so the newest - // session in it is the key state's -- but it is matched on the kind it - // carries anyway, so a room that one day signs something else does not - // confuse the two. + // with. Matched on the ceremony the state names, not on being the newest + // key state in the room: a subgroup's ceremony runs in its parent's room, + // and so does every other subgroup's, so the newest one there is as + // likely a sibling's as this one's. val keyStateSession = dkgRepository.observeSigningSessions(chatRoomId) - .map { it.firstCarrying(GroupKeyStateEvent.KIND) } + .map { sessions -> + sessions.firstCarrying(GroupKeyStateEvent.KIND) { + GroupKeyStateEvent.parseDkgSessionId(it.tags) == dkgSessionId + } + } - // Everything about one ceremony, re-pointed when the ceremony or its - // purpose changes -- which for a member arriving cold is once -- and not - // on every change to the session row. + // Everything about one ceremony, re-pointed when the ceremony, its + // purpose or its key changes -- which for a member arriving cold is at + // most twice, the key arriving as the ceremony finishes -- and not on + // every change to the session row. val parts = sessions - .map { it?.id to it?.parentChatRoomId } + .map { Triple(it?.id, it?.parentChatRoomId, it?.thresholdPublicKey) } .distinctUntilChanged() - .flatMapLatest { (sessionId, parent) -> ceremonyParts(sessionId, parent) } + .flatMapLatest { (sessionId, parent, key) -> ceremonyParts(sessionId, parent, key) } return combine( sessions, @@ -200,8 +205,19 @@ class DkgRitualViewModel( * rather than this room's: it is made where the parent's key can sign it, * which is never the ceremony's room. An ordinary ceremony passes no parent * and gets nothing watched there, which is exactly right. + * + * The parent's room holds a certificate session for every subgroup it has + * been asked about, so the one shown is the one naming [thresholdPublicKey]. + * Taking the newest regardless is how a parent's second subgroup opened on + * its first one's finished certificate, with the button to ask for its own + * already disabled. Before the ceremony has a key there is nothing to have + * certified, and no session is this one's. */ - private fun ceremonyParts(sessionId: String?, parentChatRoomId: HexKey?): Flow { + private fun ceremonyParts( + sessionId: String?, + parentChatRoomId: HexKey?, + thresholdPublicKey: HexKey?, + ): Flow { if (sessionId == null) return flowOf(CeremonyParts(sessionId = null)) val certified = parentChatRoomId @@ -209,9 +225,14 @@ class DkgRitualViewModel( ?: flowOf(false) val certificateSession = parentChatRoomId + ?.takeIf { thresholdPublicKey != null } ?.let { parent -> - dkgRepository.observeSigningSessions(parent) - .map { it.firstCarrying(SubgroupBirthCertificateEvent.KIND) } + dkgRepository.observeSigningSessions(parent).map { sessions -> + sessions.firstCarrying(SubgroupBirthCertificateEvent.KIND) { + SubgroupBirthCertificateEvent.parseThresholdPublicKey(it.tags) + .equals(thresholdPublicKey, ignoreCase = true) + } + } } ?: flowOf(null) @@ -240,11 +261,19 @@ class DkgRitualViewModel( } } - /** The signing session carrying an event of [kind], if there is one. */ - private fun List.firstCarrying(kind: Kind): FrostSigningSession? = + /** + * The newest signing session carrying an event of [kind] that is [about] + * this ceremony, if there is one. + */ + private fun List.firstCarrying( + kind: Kind, + about: (Event) -> Boolean, + ): FrostSigningSession? = firstOrNull { local -> local.items.any { item -> - runCatching { Event.fromJson(item.unsignedEventJson).kind }.getOrNull() == kind + runCatching { Event.fromJson(item.unsignedEventJson) } + .getOrNull() + ?.let { it.kind == kind && about(it) } == true } }?.session diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/DkgRitualViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/DkgRitualViewModelJvmTest.kt index d7b4692d..e30bc072 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/DkgRitualViewModelJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/DkgRitualViewModelJvmTest.kt @@ -1,7 +1,10 @@ package com.machankura.bennu.compose.ui.view.model import androidx.datastore.preferences.core.PreferenceDataStoreFactory +import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync import fr.acinq.bitcoin.ByteVector32 import fr.acinq.bitcoin.PrivateKey import fr.acinq.phoenix.utils.preferences.InternalPrefs @@ -27,13 +30,19 @@ import org.junit.rules.TemporaryFolder import com.machankura.bennu.compose.database.model.ChatRoom import com.machankura.bennu.compose.database.model.DkgParticipantMessage import com.machankura.bennu.compose.database.model.DkgSession +import com.machankura.bennu.compose.database.model.FrostSigningItem +import com.machankura.bennu.compose.database.model.FrostSigningSession import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.database.model.intermdiate.LocalFrostSigningSession import com.machankura.bennu.compose.database.model.types.DkgApprovalStep import com.machankura.bennu.compose.database.model.types.DkgRitualStage +import com.machankura.bennu.compose.database.model.types.FrostSigningStage import com.machankura.bennu.compose.identity.Identity import com.machankura.bennu.compose.identity.IdentityKind import com.machankura.bennu.compose.identity.toWalletId import com.machankura.bennu.compose.nostr.dkg.DkgRitualEvents +import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent import com.machankura.bennu.compose.repository.ChatRepository import com.machankura.bennu.compose.repository.DkgRepository import com.machankura.bennu.compose.ui.composable.navigation.routes.CreateSharedKeyRoute @@ -46,6 +55,7 @@ import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertIs +import kotlin.test.assertNull import kotlin.test.assertTrue /** @@ -112,6 +122,7 @@ class DkgRitualViewModelJvmTest { private val sessionRow = MutableStateFlow(session()) private val messages = MutableStateFlow>(emptyList()) + private val signingSessions = MutableStateFlow>(emptyList()) /** How many times the screen started watching its ceremony. */ private var sessionSubscriptions = 0 @@ -126,6 +137,9 @@ class DkgRitualViewModelJvmTest { override fun observeMessages(sessionId: String): Flow> = messages + override fun observeSigningSessions(chatRoomId: String): Flow> = + signingSessions + // A deliberately slow answer, so a read-modify-write around it would have // the widest possible window to lose somebody else's write in. override suspend fun pendingApproval(session: DkgSession): DkgApprovalStep? { @@ -309,4 +323,104 @@ class DkgRitualViewModelJvmTest { assertEquals(listOf(DkgApprovalStep.HOST_KEY), approved) assertFalse(viewModel.isActionPending.value) } + + /** A signing session in this room over one event of [kind]. */ + private fun signing( + id: String, + kind: Int, + tags: Array>, + content: String, + stage: FrostSigningStage = FrostSigningStage.COMPLETE, + ): LocalFrostSigningSession { + val event = NostrSignerSync(KeyPair()).sign( + createdAt = 1_700_000_000L, + kind = kind, + tags = tags, + content = content, + ) + return LocalFrostSigningSession( + session = FrostSigningSession( + id = id, + chatRoomId = chatRoomId, + coordinatorPublicKey = bob, + userPublicKey = ada, + dkgSessionId = sessionId, + threshold = 2, + participantCount = 3, + signerId = 1, + stage = stage, + ), + unorderedItems = listOf( + FrostSigningItem( + sessionId = id, + itemIndex = 0, + unsignedEventJson = event.toJson(), + eventId = event.id, + nonceRandom = "cc".repeat(32), + ) + ), + ) + } + + @Test + fun `a parent's second subgroup is not shown its first one's signing sessions`(): Unit = runBlocking { + // The ceremony is held in the parent's room, so this room is the parent's + // -- and it already holds the first subgroup's finished certificate and + // key state, newest first, as the store returns them. + val firstKey = "02" + "1f".repeat(32) + val secondKey = "02" + "2f".repeat(32) + sessionRow.value = session(DkgRitualStage.COMPLETE).copy( + parentChatRoomId = chatRoomId, + thresholdPublicKey = secondKey, + ) + signingSessions.value = listOf( + signing( + id = "first-key-state", + kind = GroupKeyStateEvent.KIND, + tags = GroupKeyStateEvent.assembleTags(chatRoomId = "f1".repeat(32), dkgSessionId = "f1"), + content = firstKey, + ), + signing( + id = "first-certificate", + kind = SubgroupBirthCertificateEvent.KIND, + tags = SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = "f1".repeat(32), + parentChatRoomId = chatRoomId, + thresholdPublicKey = firstKey, + adminPublicKeys = listOf(ada, bob), + name = "First", + ), + content = "f1".repeat(32), + ), + ) + + val viewModel = viewModel() + viewModel.initiate() + + val before = viewModel.awaitLoaded() + assertNull(before.certificateSession, "the first subgroup's certificate is not this one's") + assertNull(before.keyStateSession, "nor is its key state") + + // Its own, once asked for, is the one shown. + signingSessions.value = listOf( + signing( + id = "second-certificate", + kind = SubgroupBirthCertificateEvent.KIND, + tags = SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = "f2".repeat(32), + parentChatRoomId = chatRoomId, + thresholdPublicKey = secondKey, + adminPublicKeys = listOf(ada, bob), + name = "Second", + ), + content = "f2".repeat(32), + stage = FrostSigningStage.COLLECTING_NONCES, + ), + ) + signingSessions.value + + assertEquals( + "second-certificate", + viewModel.awaitLoaded { it.certificateSession != null }.certificateSession?.id, + ) + } } From 7746f3d17f1e1adabc5705f1f1bd04270e2f82a1 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 18:06:19 +0200 Subject: [PATCH 14/15] feat(wallet): offer guarded wallets on mainnet GroupWalletRollout.GUARDIANS_ON_MAINNET is on, lifted by decision ahead of the signet run its condition named. The mixed-version risk stays open and is said so in the gate and the guardians note; guardian spends on mainnet are held to MAINNET_CAP like every other spend. Co-Authored-By: Claude Opus 5.5 --- .../bennu/compose/wallet/GroupWalletRollout.kt | 14 ++++++++------ .../ui/view/model/GroupWalletViewModelJvmTest.kt | 7 +++++-- docs/group-wallet-guardians.md | 13 +++++++++---- 3 files changed, 22 insertions(+), 12 deletions(-) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupWalletRollout.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupWalletRollout.kt index 335946b8..3970edca 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupWalletRollout.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupWalletRollout.kt @@ -32,13 +32,15 @@ object GroupWalletRollout { /** * Whether a subgroup is offered a guarded wallet on mainnet -- - * `docs/group-wallet-guardians.md`. Test networks are offered one from the - * start. Lifts when a guardian spend has been made on signet by a real - * three-level hierarchy, and every member of a mainnet group runs a build - * that reads guarded statements: an older client sees no wallet, and can open - * a plain one whose addresses the rest do not watch. + * `docs/group-wallet-guardians.md`. Test networks were offered one from the + * start. On: lifted by decision, ahead of the signet run its own condition + * named -- a guardian spend made by a real three-level hierarchy. What it + * still leaves open is the mixed-version risk: a member on a build that + * predates guarded statements sees no wallet, and can open a plain one whose + * addresses the rest do not watch. Every guardian spend on mainnet is held to + * [MAINNET_CAP] like any other. */ - const val GUARDIANS_ON_MAINNET: Boolean = false + const val GUARDIANS_ON_MAINNET: Boolean = true fun offersGuardiansOn(chain: Chain): Boolean = GUARDIANS_ON_MAINNET || !chain.isMainnet() } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModelJvmTest.kt index a5526afd..09d3df5a 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModelJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModelJvmTest.kt @@ -11,6 +11,7 @@ import com.machankura.bennu.compose.repository.ChatRepository import com.machankura.bennu.compose.repository.FrostSigningRepository import com.machankura.bennu.compose.ui.view.state.GroupWalletUIState import com.machankura.bennu.compose.ui.view.state.SpendStatus +import com.machankura.bennu.compose.wallet.GroupWalletRollout import com.machankura.bennu.compose.database.model.types.FrostSigningStage import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.core.Kind @@ -192,16 +193,18 @@ class GroupWalletViewModelJvmTest { } @Test - fun `a subgroup is offered a guarded wallet on a test network, and not yet on mainnet`() { + fun `a subgroup is offered a guarded wallet on a test network and on mainnet`() { val regtest = assertIs( viewModel(guardedRepository(Chain.Regtest), chain = Chain.Regtest).apply { initiate() }.settled() ) assertEquals(guardians, regtest.guarded?.account?.guardians) + // Mainnet follows GroupWalletRollout.GUARDIANS_ON_MAINNET, which is on. val mainnet = assertIs( viewModel(guardedRepository(Chain.Mainnet)).apply { initiate() }.settled() ) - assertNull(mainnet.guarded, "behind GroupWalletRollout.GUARDIANS_ON_MAINNET") + assertEquals(GroupWalletRollout.GUARDIANS_ON_MAINNET, mainnet.guarded != null) + assertEquals(guardians, mainnet.guarded?.account?.guardians) } @Test diff --git a/docs/group-wallet-guardians.md b/docs/group-wallet-guardians.md index 53c3ed84..59ae109c 100644 --- a/docs/group-wallet-guardians.md +++ b/docs/group-wallet-guardians.md @@ -28,9 +28,13 @@ below are kept as written; where the build chose differently the table says so. | a spend that lost its coins to the other side is never settled -- this note's own *What this does not do*, as first written | settled. `GroupTransactionWatcher` asks the chain, for a signed spend Electrum has not heard of, whether each coin is still unspent at its address and, if not, which transaction in that address's history took it; once that transaction is confirmed, `FrostSigningManager.recordReplaced` marks the spend replaced and settles every other spend of the coin, as `recordConfirmed` does for the room's own. A conflict still in the mempool settles nothing | | nothing outside the plan | a bug older than it: bitcoin-kmp reads a taproot derivation's fingerprint back from a PSBT as a signed int, so for half of all accounts every member but the proposer refused every spend as not the wallet's own. Fixed on its own, in `fix(wallet): read a PSBT's key fingerprint as unsigned`, because it reaches every plain wallet too | -Still to do by hand, and the condition the mainnet gate lifts on: a guardian -spend made on signet by a real three-level hierarchy, every member's device -watching, and the grandchild's transcript naming the root. +**The mainnet gate is open.** It was to lift on a guardian spend made on signet +by a real three-level hierarchy, every member's device watching, and the +grandchild's transcript naming the root; it was lifted by decision before that +run. The run is still worth making, and the mixed-version risk below is still +open: a group whose members are not all on a build that reads guarded statements +should not open one. Guardian spends on mainnet are held to the same per-spend +cap as every other spend, `GroupWalletRollout.MAINNET_CAP`. The headline: **the parent puts a guardian key for the child into the child's birth certificate, beside the keys its own ancestors gave it, each derived one @@ -276,7 +280,8 @@ Three rules, each closing a way to lose coins: What an old client can still do is see no wallet and open a plain one. Rule 1 keeps every new client on the guarded addresses, but the old client then hands out plain ones that new clients do not watch. That is a mixed-version risk, and -it is why the guarded wallet ships behind a gate that stays shut on mainnet. +it is why the guarded wallet first shipped behind a gate shut on mainnet -- since +opened, so the risk is now the group's to manage. ### The rule from the wallet note, restated From 044929396375ab828da59f4169e78784af212eff Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 18:13:02 +0200 Subject: [PATCH 15/15] fix(marmot): a direct message's envelope is opened, not taken for a signing decline FrostSigningEvents.DECLINE and MarmotDirectMessage.ENVELOPE_KIND are both 30330. Recognising protocol kinds first (ceremony-creation Phase 6) returned before the direct-message branch, so every direct message in a current-profile room was dropped unopened. A 30330 that holds a gift wrap is an envelope; only one that does not is a decline. ProtocolKindDispatchJvmTest now opens an envelope through fromGroupEventResult, which no test did before. Co-Authored-By: Claude Opus 5.5 --- .../compose/database/model/ChatMessage.kt | 12 +++- .../model/ProtocolKindDispatchJvmTest.kt | 60 +++++++++++++++---- docs/ceremony-creation.md | 8 +++ 3 files changed, 66 insertions(+), 14 deletions(-) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt index 0ad56b00..1a7ca4a3 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt @@ -888,8 +888,16 @@ data class ChatMessage( // before its proposal; acted on by the managers // `NostrDao.fileGroupEventResult` dispatches to, which write // their own transcript lines. - val isProtocolMessage = event.kind in DkgRitualEvents.ALL || - event.kind in FrostSigningEvents.ALL + // + // Except a direct message's envelope. It shares 30330 with a + // signing session's decline, and is told apart by what it + // carries: an envelope holds a gift wrap, a decline does not. + // Treating every 30330 as a decline dropped every direct + // message in a current-profile room. + val isDirectMessageEnvelope = MarmotDirectMessage.wrapInside(event) != null + val isProtocolMessage = !isDirectMessageEnvelope && ( + event.kind in DkgRitualEvents.ALL || event.kind in FrostSigningEvents.ALL + ) database.marmotInnerEventDao().upsert( MarmotInnerEvent( diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/model/ProtocolKindDispatchJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/model/ProtocolKindDispatchJvmTest.kt index a501b23b..339a2ba6 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/model/ProtocolKindDispatchJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/database/model/ProtocolKindDispatchJvmTest.kt @@ -8,6 +8,11 @@ import com.vitorpamplona.quartz.nip01Core.core.Kind import com.vitorpamplona.quartz.nip01Core.core.toHexKey import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair import kotlinx.coroutines.runBlocking +import kotlin.test.assertNotNull +import com.machankura.bennu.compose.nostr.MarmotDirectMessage +import com.vitorpamplona.quartz.nip17Dm.messages.ChatMessageEvent +import com.vitorpamplona.quartz.nip01Core.tags.people.PTag +import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync import kotlin.test.AfterTest import kotlin.test.Test import kotlin.test.assertEquals @@ -36,13 +41,27 @@ class ProtocolKindDispatchJvmTest { fun closeDb() = database.close() private val self = KeyPair() - private val sender = KeyPair().pubKey.toHexKey() + private val senderSigner = NostrSignerSync(KeyPair()) + private val sender = senderSigner.pubKey private val chatRoomId = "639f".repeat(16) private var next = 0 /** A kind:445 this device has stored, carrying one inner event of [kind]. */ - private suspend fun arrive(kind: Kind, content: String): Pair { + private suspend fun arrive(kind: Kind, content: String): Pair = arrive( + Event( + id = "%064x".format(2000 + next), + pubKey = sender, + createdAt = 1, + kind = kind, + tags = DkgRitualEvents.assembleTags(sessionId = "5e55".repeat(16)), + content = content, + sig = "", + ) + ) + + /** A kind:445 this device has stored, carrying [inner]. */ + private suspend fun arrive(inner: Event): Pair { val n = next++ val groupEventId = "%064x".format(1000 + n) @@ -77,16 +96,6 @@ class ProtocolKindDispatchJvmTest { content = "ciphertext", sig = "0".repeat(128), ) - val inner = Event( - id = "%064x".format(2000 + n), - pubKey = sender, - createdAt = 1, - kind = kind, - tags = DkgRitualEvents.assembleTags(sessionId = "5e55".repeat(16)), - content = content, - sig = "", - ) - val line = ChatMessage.fromGroupEventResult( database = database, activeKeyPair = self, @@ -129,6 +138,33 @@ class ProtocolKindDispatchJvmTest { ) } + /** + * A direct message's envelope shares 30330 with a signing session's decline. + * + * Treating every 30330 as a decline -- which is what recognising protocol + * kinds first did at first -- dropped every direct message in a + * current-profile room before it was opened. What tells the two apart is + * what the event carries. + */ + @Test + fun `a direct message envelope is opened, not taken for a decline`(): Unit = runBlocking { + val wrap = MarmotDirectMessage.wrap( + signer = senderSigner, + recipientPublicKey = self.pubKey.toHexKey(), + kind = ChatMessageEvent.KIND, + createdAt = 1, + tags = arrayOf(PTag.assemble(self.pubKey.toHexKey(), null)), + content = "the vote is at six", + ) + val envelope = MarmotDirectMessage.envelope(sender, self.pubKey.toHexKey(), wrap, createdAt = 1) + assertEquals(FrostSigningEvents.DECLINE, envelope.kind, "the collision this test exists for") + + val (_, line) = arrive(Event.fromJson(envelope.toJson())) + + val opened = assertNotNull(line, "the envelope must reach the direct-message path") + assertTrue(opened.content.contains("the vote is at six"), "and be opened: ${opened.content}") + } + @Test fun `a signing message writes no chat line`(): Unit = runBlocking { FrostSigningEvents.ALL.forEach { kind -> diff --git a/docs/ceremony-creation.md b/docs/ceremony-creation.md index 9f208e7e..b4e8db37 100644 --- a/docs/ceremony-creation.md +++ b/docs/ceremony-creation.md @@ -45,6 +45,14 @@ key** handed over to its finished ceremony, and back returned to its details. Not exercised on a device: the certificate and key state after Tapscript, and starting a ceremony from `CreateSharedKeyScreen` in a group without a key. +**A regression Phase 6 shipped, and its fix.** `FrostSigningEvents.DECLINE` and +`MarmotDirectMessage.ENVELOPE_KIND` are both 30330. Phase 6 returned early for +every protocol kind before the direct-message branch, so every direct message in +a current-profile room was dropped unopened. Found while mapping this fix onto +Curare. An event of kind 30330 that holds a gift wrap is now an envelope, never a +decline -- the test `MarmotDirectMessage.wrapInside` already made -- and +`ProtocolKindDispatchJvmTest` opens one. Any port of Phase 6 has to carry this. + The headline: **a ceremony is started only from a screen that knows what it is for, and the screen that shows a ceremony can never start one.** Today `DkgRitualScreen` does three jobs (showing progress, asking for approvals, and