From 8dd710a156672273df01a9ec6b1737cd9aca05f6 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Thu, 19 Nov 2026 22:32:48 +0200 Subject: [PATCH 01/12] docs: rotating a group's shares without moving its key (plan) Enrollment evaluates the same polynomial, so it cannot rotate a share; a zero-sum refresh can. Thirteen phases from a frost_refresh module in secp256k1-zkp to the cutover, removal, repair and UI in Giza. D1-D8 are decided as recommended. Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 1 + docs/frost-share-refresh.md | 695 ++++++++++++++++++++++++++++++++++++ 2 files changed, 696 insertions(+) create mode 100644 docs/frost-share-refresh.md diff --git a/docs/README.md b/docs/README.md index 2194da9a..b4a6a027 100644 --- a/docs/README.md +++ b/docs/README.md @@ -18,6 +18,7 @@ the [retired](./retired/) notes now. | [ceremony-creation.md](./ceremony-creation.md) | one place to start a key ceremony — how joining a subgroup's ceremony opened a second one for the parent room, the screen that showed a ceremony and offered to start one in the same button, and the removal of the nip30303 documents, whose kinds collided with the ceremony's, leaving the member chronicle with nothing to carry and nothing to say | | [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 | | [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 | +| [frost-share-refresh.md](./frost-share-refresh.md) | giving every member a new share of the same group key, phased and not built — why enrollment cannot rotate a share, the zero-sum refresh that can, what a rotation protects against and the two things it never can, and re-enrollment as the repair that brings back the members a refresh left out | | [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 | | [member-chronicle.md](./member-chronicle.md) | handing a member added after the work was done the group's signed record — why the events are not on the wire at all, and why the room's id is enough to verify them | | [marmot-direct-messages.md](./marmot-direct-messages.md) | a one-to-one message inside a group as a stock NIP-59 gift wrap — what its MIP-03 carve-out costs, why the sender cannot read their own, and the one query that would broadcast it | diff --git a/docs/frost-share-refresh.md b/docs/frost-share-refresh.md new file mode 100644 index 00000000..c157788d --- /dev/null +++ b/docs/frost-share-refresh.md @@ -0,0 +1,695 @@ +# FROST share refresh and re-enrollment + +The goal: give every member of a group a new share of the **same** threshold key, so the group +signs as it always has (same key, same room, same certificates) while the shares it held before +stop being useful. Those old shares may be a lost phone's, a removed member's, or a database a +backup service still holds. + +This is a phased plan, being built. It was written against `d4dd87f2` on 2026-11-19, +right after [submodule-refresh.md](./submodule-refresh.md) carried reduced (v2) FROST enrollment +up to Giza. Read [shared-key-ceremony.md](./shared-key-ceremony.md) and +[shared-key-derivation.md](./shared-key-derivation.md) first. Everything below assumes the +ceremony they describe and the rule that a room's id *is* the key it signs with. + +## The headline: enrollment cannot rotate a share + +The word in the request is *re-enrollment*, and the enrollment module that just arrived looks +like the tool for it. It is not, and the reason is what the rest of the plan rests on. + +A `t`-of-`n` FROST key is a polynomial `f` of degree `t−1` with `f(0) = x`, the group secret. +Member `j` holds `s_j = f(x_j)`. Any `t` points on `f` reconstruct `x`. + +**Enrollment, v1 and v2, and in both its modes, evaluates the *same* `f` somewhere else.** + +- `newId == n` gives a new member `f(x_n)`. +- `newId < n` ("repair") gives back exactly `f(x_k)`. + +`FrostEnrollment`'s own KDoc says it: "every existing share [is] unchanged by an enrollment". So +re-enrolling every member, even at fresh identifiers, hands out new points on the old polynomial. +Every old share stays a valid point on it. A removed member's share plus `t−1` new ones still +signs, and a leaked backup is exactly as dangerous as before. + +**Rotation needs a different `f`.** That is a proactive share refresh (Herzberg et al., 1995): + +1. Every dealer `i` picks a random polynomial `δ_i` with `δ_i(0) = 0`. +2. Each member adds the sum to their share: `s_j' = s_j + Σ_i δ_i(x_j)`. +3. The new shares lie on `f' = f + Σ δ_i`. Because every `δ_i(0) = 0`, `f'(0) = x`, so the key + does not move. +4. A mix of old and new shares interpolates to garbage. Only `t` *old* shares together still + reconstruct `x`, which is why "rotating away" also needs the old ones deleted (see + [What it protects against](#what-a-refresh-protects-against-and-what-it-cannot)). + +Neither secp256k1-zkp, secp256k1-kmp nor bitcoin-kmp has this today: the grep is for `refresh` +and `reshare` across `Secp256k1.kt` and the `frost`/`chill` wrappers. Building it is the first +half of this plan. + +Enrollment still has a job here, and it is the half that earns the word *re-enrollment*: + +- **Refresh** rotates the shares of the members who take part. +- **Repair** (v2 `FrostReducedEnrollment`, `newId < n`) brings in a member who could not take + part: offline, or on a new device. It gives them their point on the **new** polynomial, which + their old device never had. + +A member who was withheld from a refresh and is never repaired is, cryptographically, removed. +So rotation, removal and recovery from a lost device are one protocol plus one repair. + +## Vocabulary + +| term | meaning | +|---|---| +| **key** | a ChillDKG output: threshold public key `X`, identified by its `dkgSessionId`, which is also the `frost_key` tag. Never changes | +| **participant id** | a member's index in the ChillDKG order (the sorted host keys; `FrostSigningManager.signerIds`). Fixed for the life of the key; `n` fixed until an enrollment grows it | +| **generation** `g` | which polynomial the shares are on. `0` is ChillDKG's output; each completed refresh adds one | +| **standing** | per id, per generation: `live` (holds a share of `g`), `stale` (withheld, awaiting repair) or `retired` (withheld for good; never repaired) | +| **recipients** `R` | the ids a refresh delivers to. Every recipient is also a dealer | +| **withheld** `W` | the live ids a refresh delivers nothing to. They come out `stale` or `retired`, as the proposal says | + +## What a refresh protects against, and what it cannot + +This section matters most for the UI copy, because the action sounds stronger than it is. + +**It protects against** an attacker who collects fewer than `t` shares of any one generation: + +- a stolen or lost phone's database; +- `aux.db` in a cloud backup; +- a removed member's share, once the others have deleted theirs. + +After a refresh the attacker needs `t` shares of the *new* generation, and what they hold is of +the old one. + +**It cannot protect against:** + +- **Honest deletion failing.** Two members who keep their generation-`g` shares after a refresh + still hold two points on `f`. If `t` old shares ever meet, the key is gone, refresh or not. The + plan wipes old shares (Phase 8), but a wipe on one device proves nothing to the others. +- **A compromised nsec.** The ChillDKG host key is `sha256("mantra/chilldkg/host-key/v1" || + nostrPriv)`. ChillDKG's `participantRecover(hostSecretKey, recovery)` rebuilds the + generation-0 share from it and the public transcript. So **every member's generation-0 share + can always be rebuilt from their nsec**, whatever is wiped. A refresh moves the group past a + leaked *share*, never past a leaked *identity*. A member whose nsec is compromised has to be + withheld and repaired under a new identity (Phase 10b), not refreshed. +- **An adversary already holding `t` shares of the current generation.** They have the key. A + refresh is not a recovery from that; only a new ceremony is, and it gives a new key and a new + room. +- **The threshold.** A refresh keeps `t` and `n`. Changing `t` is a reshare, which is out of scope + ([what this does not do](#what-this-does-not-do)). + +Two things in the tree today undercut even the protections listed above, and they are +preconditions for the rest (Phase 5): + +- `DkgSession.secretShare` is **plaintext hex** in `aux.db`, under an "encrypted local storage" + assumption (`DkgSession.kt`) that the database does not meet: `BundledSQLiteDriver`, no + SQLCipher, no keystore. `round1Random` and `round2AuxRandom` sit beside it and rebuild the + share on their own. +- `AndroidManifest.xml` has `android:allowBackup="true"` with no `dataExtractionRules`, so + `aux.db` goes to the platform backup. **A share that has been backed up cannot be rotated away + from by anything this app does afterwards**, short of every other member deleting theirs. + +## Decisions this plan asks for + +Each has a recommendation. Decide them before Phase 1; several change the wire. + +**Decided 2026-11-19: all eight as recommended.** Execution began the same day. Part B (Phases 5–6) +runs first because it needs nothing from Part A; Part A's pushes wait on an explicit go-ahead, +since a parent may only pin what the child's remote has. + +| # | question | recommendation | if decided otherwise | +|---|---|---|---| +| D1 | Where does the refresh primitive live? | **In secp256k1-zkp, as a `frost_refresh` module beside `frost_enrollment`**, with bindings up the chain the way enrollment came. It shares the frost module's identifier-to-evaluation-point convention, gets Python vectors, and goes through the same review | In bitcoin-kmp, as Kotlin over `PrivateKey`/`PublicKey` arithmetic (each op calls libsecp256k1). Phases 1–2 collapse into Phase 3 and the chain bump shrinks. The cost: protocol code with no reference implementation and no vectors, in a place no cryptographer reviews | +| D2 | Who has to take part? | **Every recipient.** A refresh cannot finish until all of `R` confirms, the same rule ChillDKG has. Anyone not taking part is withheld and repaired afterwards | Letting a refresh finish without some recipients means a member who later finds their delta inconsistent has no one to complain to. Repair already covers the absent member | +| D3 | How are two concurrent refreshes kept from forking the group? | **Two rules together.** (a) A device confirms at most one refresh per (key, base generation), write-once, like the nonce rules on `FrostSigningSession`. (b) `|R|` must exceed half the ids not yet retired, and must be at least `t`. Any two recipient sets then overlap, so at most one certificate can exist | Without (b), a 2-of-5 group could finish two disjoint refreshes, each with its own generation `g+1`, and sign with neither | +| D4 | Ship gate | **Behind a build flag, off in release, until upstream drops "experimental" from `frost_enrollment` and `frost_refresh` has had independent review.** submodule-refresh.md Phase 6 already says this for enrollment | Shipping earlier means accepting unreviewed key-handling code on the group's only key | +| D5 | Groups with Bennu members | **Refuse a refresh whose recipients include a member whose client has not advertised support.** A Bennu peer cannot take part, so the refresh would withhold them, which removes them from signing | Port the protocol to Bennu first (Giza → Bennu is a cherry-pick, the reverse of [giza-rebrand.md](./giza-rebrand.md) Phase 9) | +| D6 | When is the old share wiped? | **Once the group has signed the generation-`g+1` key state (30326).** That signature is the proof that `t` members can sign with the new shares. Before it, a broken refresh would otherwise leave nothing to sign with | Wiping at the certificate is earlier, but trusts that the new shares work without a signature showing it | +| D7 | Where does a refresh run? | **In the Marmot room whose id the key derives**, p-tagging the recipients, as a subgroup's ceremony does in its parent. A key with no room yet cannot be refreshed. Its holders can just run the ceremony again | The NIP-17 room the ceremony ran in. That room has no record of removals, which is what a refresh is most often for | +| D8 | Does removing a share holder from the room offer a refresh? | **Yes, as a separate, named step after the MLS removal, never folded into it.** Removal is one member's decision; a refresh needs every recipient | Silent: the removed member keeps a working share indefinitely, which is today's behaviour (`MarmotOutboundDao.removeMember` touches MLS only) | + +## The protocol + +This is the shape the primitive should have, written so Phase 1 has a spec to start from and +Phases 7–8 have something to persist. It is EncPedPop and CertEq from ChillDKG with the constant +term removed. Reusing ChillDKG's structure means reusing its review, its blame and its recovery +story. + +### Inputs everyone already holds + +- The threshold key `X`, participant count `n` and threshold `t`. +- The host public keys in ChillDKG order. +- The generation-`g` public-share table `P_0 … P_{n−1}`. +- The recipient set `R`, which the proposal names and which sorts to a canonical order. +- A `refreshId`: 32 fresh bytes chosen by the proposer, bound into every hash the way v2 + enrollment binds `sessionId`. + +**Session parameters hash.** `H(tag ‖ X ‖ n ‖ t ‖ g ‖ hostkeys ‖ R ‖ P-table ‖ refreshId)`. +Every message carries it. As with ChillDKG's ordering, a device that disagrees on any input gets +no refresh rather than a weaker one. + +### Round 1: each recipient deals + +Each recipient `i` in `R` does the following: + +1. Draws `δ_i(x) = a_{i,1}x + … + a_{i,t−1}x^{t−1}`. There is no constant term and so no proof of + possession: there is no secret contribution to prove. +2. Publishes the commitments `A_{i,m} = a_{i,m}·G` for `m = 1…t−1`: `t−1` points. +3. For every `j` in `R`, encrypts `δ_i(x_j)` to `j`'s host key, with a pad derived from ECDH and + bound to the parameters hash, `i` and `j`. This is EncPedPop's construction. + +**Nothing is encrypted to a withheld id.** That is what withholding means. A withheld member +never learns their point on `f'`. + +### Coordinator: aggregate + +The coordinator sums the commitments, `A_m = Σ_i A_{i,m}`, and packages each recipient's +ciphertexts. It is untrusted, as in ChillDKG: it relays and sums, and can neither learn a delta +nor bias one. + +### Round 2: each recipient checks, persists, confirms + +1. Decrypt and sum: `d_j = Σ_i δ_i(x_j)`. +2. Feldman check: `d_j·G == Σ_m A_m · x_j^m`. On failure, blame by investigation, as ChillDKG + does. +3. Compute the new share `s_j' = s_j + d_j`. +4. Compute **every** id's new public share, including withheld ones: + `P_k' = P_k + Σ_m A_m · x_k^m`. This needs only public data. +5. Check `s_j'·G == P_j'` and `frostThresholdInfoValidate(X, P', t)`. +6. **Persist generation `g+1` as `pending`.** +7. Only then sign CertEq over the transcript with the host key. A confirmation means "I have + stored it", so a certificate means everyone has. + +### Certificate + +The coordinator collects every recipient's CertEq signature into a certificate. A device that +verifies it moves `g+1` from `pending` to `active`. + +**Recovery data** for generation `g+1` is the round-1 transcript (commitments and ciphertexts) +plus the certificate: everything public. With the host key it rebuilds `d_j`; on top of +generation `g` it rebuilds `s_j'`. So the chain ChillDKG recovery → refresh 1 → … → refresh `g` +restores any generation from the nsec. That is the same property generation 0 has today, and +the same limit. + +### Repair of a withheld id (re-enrollment) + +Repair uses v2 `FrostReducedEnrollment` with `newId = k < n` and helpers drawn from the live ids +of the current generation (`t ≤ u`). + +The expected public share is `P_k'` from the **group-signed** generation table (Phase 8): never +from the helpers, as submodule-refresh.md Phase 6 requires. + +v2's messages are raw scalars, so they need a confidential, authenticated channel per pair. That +is a gift wrap to one npub in a NIP-17 room, and the MIP-03 one-to-one carve-out in a Marmot room +([marmot-direct-messages.md](./marmot-direct-messages.md)). **Never an MLS application message: +every member of the room can read those.** + +## Phases + +Four parts. + +- **A** (1–4) is library work, below Giza. It follows [submodule-refresh.md](./submodule-refresh.md) + procedurally. +- **B** (5–6) makes Giza ready for a share to change, and changes no behaviour. +- **C** (7–8) is the refresh itself. +- **D** (9–13) is what makes it usable. + +One commit per phase, as the other plans do. + +--- + +### Part A: the primitive + +#### Phase 1: `frost_refresh` in secp256k1-zkp + +On a branch of `frost/secp256k1-zkp` `main`, beside `frost_enrollment`. + +- The spec text first, in the module's README, covering everything in [the protocol](#the-protocol): + - the parameters hash; + - round 1 (dealer); + - coordinator aggregate; + - round 2 (recipient verify and new share); + - public-share table update; + - CertEq; + - recovery; + - participant and coordinator investigate. +- A Python reference in the style of the enrollment generator, emitting frozen vectors. +- C functions, roughly mirroring `chilldkg_*`: + - `frost_refresh_params_hash` + - `frost_refresh_participant_step1` + - `frost_refresh_coordinator_step1` + - `frost_refresh_participant_step2`, which returns the new secret share, the new public-share + table and the CertEq signature + - `frost_refresh_coordinator_finalize` + - `frost_refresh_participant_finalize` + - `frost_refresh_participant_recover` + - `frost_refresh_*_investigate` +- Tests, each one a property worth its own name: + - refresh then sign: the signature verifies under the unchanged `X`; + - `t` new shares sign, and a mix of old and new does not (with overwhelming probability); + - `t` old shares still reconstruct. This is the honest-deletion caveat as a test, so nobody + mistakes it for a bug later; + - `P_k'` for a withheld `k` equals what a repair at `k` produces; + - every malformed and inconsistent input lands on the right blame; + - recovery from host key and transcript equals the share computed live; + - two consecutive refreshes compose. + +**Done when** the vectors, the C tests and the Python reference agree, and the module carries +the same "experimental" warning enrollment does. **Not done** until somebody other than its +author has reviewed it (D4). That does not block Phases 2–9, only release. + +#### Phase 2: secp256k1-kmp bindings + +On `claude/frost-share-refresh` from `threshold`. + +1. Bump zkp to the Phase 1 commit. +2. Add JNI glue, iOS cinterop declarations, and `Secp256k1` functions that return result types + carrying `ChilldkgFault`-style blame. +3. Rebuild the natives from scratch (`native/build/`). A stale `libsecp256k1` shows up as a + missing `secp256k1_frost_refresh_*` symbol at load time. +4. Add JVM tests over the vectors. +5. Run `connectedAndroidTest` if an emulator is to hand. The JNI marshalling is where a mistake + hides. + +**Done when** `:tests:jvmTest` passes with natives built from the Phase 1 commit. + +#### Phase 3: bitcoin-kmp `FrostRefresh` + +`crypto/frost/FrostRefresh.kt`, an object in the shape of `ChillDKG.kt`: + +- opaque `RefreshParticipantState1/2` and `RefreshCoordinatorState`; +- results that carry a fault rather than throw; +- a `RefreshResult(secretShare, publicShares, recovery)`. + +Rules carried over from `FrostReducedEnrollment`: + +- **Messages keyed by participant id, never by position.** A missing or extra sender is + `Either.Left`, a caller error, never a participant at fault. +- **Refresh and enrollment are separate objects with separate message types.** Feeding one into + the other is a type error. + +Tests in `FrostRefreshTestsCommon` cover each Phase 1 property through the wrapper, plus the one +that matters most for Giza: + +- **refresh with `k` withheld, then a `FrostReducedEnrollment` repair at `k`, then sign with `k` + in the signer set.** This is the whole of re-enrollment, end to end, below the app. + +**Done when** those pass and `FrostEnrollmentTestsCommon` and `FrostReducedEnrollmentTestsCommon` +are unchanged. + +#### Phase 4: carry it up the chain + +Follow [submodule-refresh.md](./submodule-refresh.md) exactly: + +- a worktree with its own submodule checkout; +- a branch per level; +- bitcoin-kmp → lightning-kmp → lightning-kmp-app → Giza; +- pushes bottom up; +- fast-forward the tracked branches only once Giza is green. + +If [giza-wallet-removal.md](./giza-wallet-removal.md) Phase 7b has landed by then, the chain is +three levels and this is one bump. + +**Done when** Giza's `compileDebugKotlinAndroid`, `jvmTest` and `check` pass on the bump with no +app change. + +--- + +### Part B: a share that can change + +Parts A and B are independent. B can start the day this plan is accepted. + +#### Phase 5: preconditions, the share at rest + +These are a refresh's preconditions, but each is worth doing on its own; the backup one is a +standing leak. + +1. **Keep `aux.db` out of platform backups.** + - Add `dataExtractionRules` (API 31+) and `fullBackupContent` (below 31) that exclude the + database directory, or set `allowBackup="false"`. + - The identity is already restored from the recovery phrase, and the shares have their own + recovery path (Phase 12), so nothing is lost but a copy of secrets. +2. **Secure delete.** Open the database with `PRAGMA secure_delete = ON` so an overwritten share + is zeroed on disk, not left in a free page. + - A one-time `VACUUM` after the first wipe (Phase 8) clears what earlier writes left behind. + - Not a substitute for encryption at rest, but without it a wipe is a promise the file does + not keep. +3. **Name encryption at rest as the open item it is.** It already has `TODO(security)` notes in + `RoomMlsGroupStateStore` and `DatabaseMarmotRepository`. This plan does not do it, and the UI + copy (Phase 11) must not claim it. + +**Done when** an Android backup taken with `adb backup` / `bmgr` holds no `aux.db`, and a test +writes a share, overwrites it, and finds no copy of the old bytes in the database file. + +#### Phase 6: schema 37 → 38, and generations in signing + +**The schema.** Two new tables, plus generation columns on the signing session and the key state. + +| table / column | holds | +|---|---| +| `KeyShareGeneration` PK (`dkgSessionId`, `generation`) | `secretShare` (nullable: null once wiped, or while `stale`), `publicShares` CSV in id order, `state` (`PENDING`, `ACTIVE`, `RETIRING`, `WIPED`), `refreshSessionId` (null for 0), `recoveryData`, `activatedAt`, `wipedAt` | +| `KeyShareMember` PK (`dkgSessionId`, `generation`, `participantId`) | `memberPublicKey`, `hostPublicKey`, `publicShare`, `standing` (`LIVE`, `STALE`, `RETIRED`) | +| `FrostSigningSession.generation` | nullable `Int`. Null reads as 0, so rows from before the migration mean what they meant | +| `GroupKeyState.generation`, `.publicSharesHash` | nullable. Null is generation 0 | + +**The migration.** + +- The tables come in through an `AutoMigration`. A manual `MIGRATION_37_38` backfills generation + 0 from every `DkgSession` with a `secretShare`: the share and table come from `DkgSession`, and + the members come from the `HOST_KEY` rows sorted exactly as `signerIds()` sorts them. +- `DkgSession.secretShare` stays for now and is nulled at the generation-0 wipe. + +**Reading through one door.** `FrostSigningManager.advance`, `completedKey` and `signerIds` read +the share, the public shares and the ids through one function: +`ShareGenerations.active(dkgSessionId)`. + +**This reverses a decision, so the doc has to say why.** `signerIds` is derived on purpose ("so +signing cannot disagree with the ceremony that made the key"). From generation 1 on, the roster +is a certified fact: the refresh certificate and the group-signed 30326. Generation 0 stays +derived. `ShareGenerationBackfillJvmTest` asserts the backfilled rows equal `signerIds()` and +`publicShareList()` for every fixture in `GroupFixtures`. The day they disagree is the day the +migration is wrong. + +**Generation on the wire.** + +- A `frost_generation` tag on 30320, alongside `frost_key`. No tag means 0, so proposals from + older builds still mean what they meant. +- A receiver whose active generation differs **declines out loud**: a 30330 with a reason, as + `WalletRefusal` does. It never drops the proposal silently, and never signs with a share of + another generation. +- `SecretNonce.generate` already takes the share, so binding the session to a generation also + binds its nonce. Write the test anyway: a session opened under `g` whose device has moved to + `g+1` fails rather than producing a partial signature from the wrong share. + +**Done when** `jvmTest` passes with no behaviour change: every existing signing test, unedited +except fixtures, signs at generation 0. A new `FrostSigningGenerationJvmTest` covers the +mismatch decline. + +--- + +### Part C: the refresh + +#### Phase 7: `ShareRefreshManager` + +A stateless `object` in the image of `ChillDkgRitualManager`: + +- persist each inbound message; +- ask whether the ritual can move; +- recompute every step from stored inputs (`round1Random`, `auxRandom` and the received + messages), so an app killed mid-round resumes on the next message. + +**Kinds.** The proposal is 30340–30345. 30338–30349 are unused, and `RetiredKindsTest` already +asserts 30338 and 30349 are not retired. Check Bennu's kinds before fixing the numbers. + +| kind | from | carries | +|---|---|---| +| 30340 | proposer (coordinator) | proposal: `frost_key`, `frost_generation` (base `g`), `refresh_id`, `p` per recipient, `withheld` per withheld id with `stale` or `retired` | +| 30341 | recipient | round 1: commitments and ciphertexts | +| 30342 | coordinator | aggregate | +| 30343 | recipient | CertEq signature | +| 30344 | coordinator | certificate | +| 30345 | any recipient | failure: abort and blame, or abandon | + +They travel as Marmot inner events in the key's room (D7). The ciphertexts are encrypted to +host keys, so a room-wide message is fine here, which it is **not** for repair (Phase 10). + +**Entities.** + +- `ShareRefreshSession`: id, `dkgSessionId`, `baseGeneration`, coordinator, recipients, withheld + and their standings, stage, `round1Random`, `auxRandom`, approvals, the certificate, the + failure reason. +- `ShareRefreshMessage`, keyed (`sessionId`, `participantPublicKey`, `kind`), which absorbs + redelivery the way `DkgParticipantMessage` does. + +**Refusals at proposal and on arrival.** Each is a value, with a reason the screen can show: + +- the key has no room, or this device is not `live` at the base generation; +- `|R| < t`, or `|R|` is not more than half the non-retired ids (D3b); +- a recipient's client has not advertised refresh support (D5); +- the base generation is not this device's active one; +- **this device has already confirmed a refresh from this base generation (D3a).** This rule is + enforced with a write-once column on `KeyShareGeneration`, set in the same transaction that + stores the `PENDING` row. **It is as important as the nonce rules, and for the same reason: it + is the one way the group splits.** +- an open ChillDKG or refresh for the same key. + +**Approval gates.** Two, mirroring the ceremony's, with `pendingApproval` mirroring `advance` +exactly: + +| step | publishes | why it is its own decision | +|---|---|---| +| `DEAL` | round 1 | joins the refresh and agrees to the withheld list. Withholding someone is a decision about them, so every recipient makes it, not only the proposer | +| `CONFIRM` | CertEq | commits to the new generation. This is what stops a coordinator substituting a table the recipients never dealt | + +The proposer is auto-approved for nothing. Proposing a refresh is not agreeing to withhold +whomever the form defaulted to. + +**Transcript.** System lines in the room, as the ceremony writes them, idempotent by reading the +row before writing: + +- started (naming who is withheld, and whether as stale or retired); +- each member's contribution; +- complete; +- abandoned. + +**Done when** `ShareRefreshRitualTest` (commonTest, real primitive, in-memory multi-device in the +manner of `RobustRoomKeyCeremonyTest`) passes for: + +- n 2..5, t 2..n, with 0, 1 and 2 withheld; +- redelivery of every message; +- a kill between "persist `PENDING`" and "send CertEq"; +- a faulty dealer blamed by id; +- abandon; +- `ShareRefreshForkTest`: two proposals from one base generation, with the majority rule and the + write-once rule each shown to be necessary by a test that drops it and gets two certificates. + +#### Phase 8: cutover, the signed table, and the wipe + +What a device does with a certificate, and when the old share goes. + +1. **Certificate verified** → `g+1` becomes `ACTIVE`, `g` becomes `RETIRING`. + - New signing proposals use `g+1`. + - Sessions already open under `g` may finish while `g` is still `RETIRING`. +2. **The group signs the new key state.** Any recipient proposes a 30326 for the room. It is + unchanged in content and `d`, and carries new tags: + - `frost_generation` = `g+1`; + - `frost_pubshares` = hash of the new public-share table; + - `frost_refresh` = the refresh id; + - `frost_retired` per retired id. + + It is signed under `g+1`, which makes it the first signature the new shares make: the proof + D6 waits for. +3. **`GroupKeyStateManager` changes, and the comment in `GroupKeyStateEvent.kt` (L84–87) gets + answered.** + - The comment expects that rotation would break `verifies()`. It does not: the *key* is + unchanged, so `marmotGroupId(X, path) == chatRoomId` still holds. What changes is that a + state now names a generation. + - `GroupKeyStateDao.replace()` keeps the **highest generation**, then the newest `announcedAt`, + not the newest `announcedAt` alone. `created_at` is chosen by the author, and an older + generation's state is still validly signed by the group. + - `stateFrom` checks `frost_pubshares` against the local `KeyShareGeneration` table. A + mismatch is a refusal with a reason, because it means this device and the group disagree + about who holds what. +4. **On seeing that signed state:** wipe `g`. + - `KeyShareGeneration(g).secretShare` becomes null and the state becomes `WIPED`. + - Every open session under `g` fails, with "this share was rotated". + - **At generation 0, also null `DkgSession.secretShare`, `round1Random` and + `round2AuxRandom`.** The last two rebuild the share on their own, and a wipe that leaves them + wipes nothing. + - Then the one-time `VACUUM` from Phase 5. + - Check first that `ChillDkgRitualManager.advance` returns early for a `COMPLETE` session and + never reaches for the nulled randomness. If it does not, that is the bug this step will find. + +**Done when** `ShareRefreshCutoverJvmTest` covers: + +- a refresh followed by signing at `g+1`; +- a signature attempted at `g` after the wipe, which fails out loud; +- the wiped bytes, absent from the database file; +- a late 30326 at generation `g`, which loses to `g+1` whatever its `created_at`; +- a device that missed the certificate, which comes back from the transcript in its own backlog + replay. + +`GroupKeyStateTest` and `SignedGroupKeyStateTest` must pass unedited for generation 0. + +--- + +### Part D: membership, recovery, UI, rollout + +#### Phase 9: removing a share holder + +`MarmotOutboundDao.removeMember` stays as it is (D8). After it succeeds for a member who is +`live` in the room's key, the members screen offers a second action: "Rotate shares without +them". That opens a refresh proposal withholding their id as `retired`. + +The removal and the rotation are two acts, for three reasons: + +- the removal is one admin's commit; +- the rotation needs every remaining holder; +- a removal that silently started a refresh would leave the group in a ritual no one chose. + +**Refusals.** + +- Withholding would leave fewer than `t` non-retired ids. The copy says the group would no longer + be able to sign at all, and that the way out is a new ceremony. +- The majority rule (D3b) fails. Remove fewer at a time: in a 2-of-5, one at a time always passes. + +A retired id is never reused, and `n` does not shrink. FROST identifiers are positions below `n`, +and `frostSessionInit` takes `nParticipants`, so a gap is fine. Renumbering would invalidate +every public share. + +**Done when** `MemberRemovalRefreshJvmTest` removes a member from a 2-of-3 room, rotates without +them, and shows that: + +- the remaining two sign at `g+1`; +- the removed member's share does not appear in any signer set; +- their share combined with one remaining member's `g+1` share produces no valid signature. + +#### Phase 10: re-enrollment + +The repair path, for the members a refresh left `stale`. It uses `FrostReducedEnrollment` only, +never v1, as submodule-refresh.md decided. + +**10a. Same identity, missed the refresh.** The member was offline or had no build that supported +it. + +1. They (the target) propose a repair with a fresh `sessionId`. +2. `t` or more `live` helpers each approve. Approval is a gate, because a helper's round 1.1 + message spends its share's secrecy on the target's behalf. +3. Round 1.1 shares go helper to larger-id helper, and round 1.2 messages go helper to target, + every one over a pairwise channel (see [the protocol](#repair-of-a-withheld-id-re-enrollment)). +4. The target derives `P_k'` from the group-signed table, runs `generateSecretShare` with it as + `expectedPublicShare`, and persists `g` as `live`. + +Kinds 30346 (request), 30347 (round 1.1) and 30348 (round 1.2). + +**10b. New identity: lost device, compromised nsec.** + +- The member's id `k` is re-bound to a new npub, and so a new host key, by a 30326 the group + signs. The state gains a `frost_member` tag per id that has changed hands, and the + `KeyShareMember` row follows it. Only then can a repair target `k`. +- The order is forced. **A repair to an npub the group has not bound to `k` is a repair to + whoever asked.** +- Withholding the old identity first, by a refresh, is what makes the old device's share + worthless. A repair alone would hand the new device the same point the old one has. + +**10c. A new member (`newId = n`)** is enrollment proper. It belongs in submodule-refresh.md's +Phase 6 document, not here. This plan leaves it one thing: an enrollment is a 30326 that grows +`n` and the table, at the current generation. The schema above already has room for it. + +**Done when** `ReEnrollmentJvmTest` runs 10a and 10b end to end, and shows that: + +- the repaired member signs; +- a repair whose helpers present a table that disagrees with the signed one fails at round 2, + not at signing; +- a 10b repair to an unbound npub is refused before any helper sends anything. + +#### Phase 11: UI + +Under CLAUDE.md's rules: + +- strings in the catalogue, sentence case; +- spacing and colour from the theme; +- `NavigateBackButton` on the pushed screen; +- four states through `ScreenStateTransition`; +- outcomes through `rememberNotifier`. + +**What to build.** + +- **A "Shares" section on the key's screen.** It shows: + - the generation; + - each id's member and standing; + - when the generation became active; + - an action to rotate. + + Standing gets a text label, not only an icon, so the icon gets `Decorative`. +- **The refresh screen.** A progress ladder that names who it waits on, like the ceremony's, + with the two approvals. + - The `DEAL` prompt lists who is withheld, and as what. + - The `CONFIRM` prompt is the ceremony's CertEq prompt in different words. +- **The copy has to tell the truth from [what it protects against](#what-a-refresh-protects-against-and-what-it-cannot).** + - Say "Shares held before today stop working once everyone's device has deleted them." + - Never write "the removed member can no longer sign" without that clause. + - Never write anything implying a compromised account is fixed by a rotation. +- **The repair screen**, and a banner on the key's screen for a `stale` member: "You missed a + share rotation. Ask the group to bring you back in." + +**Done when** `./gradlew :composeApp:m3Audit` and `check` pass at their budgets, and the floors +have not moved down. + +#### Phase 12: restore + +Today nothing calls `ChillDKG.participantRecover`. `DkgSession.recoveryData` is written at the +end of a ceremony and never read. So the line "restorable from that member's wallet backup" in +shared-key-ceremony.md describes a path that is not built. Refresh makes this gap longer, since a +restored device now needs generation 0 *and* every refresh after it. It does not make the gap +wider. + +This phase: + +- makes the refresh transcripts (round 1 messages and certificate) part of what a room's backlog + replay keeps; +- adds `ShareGenerations.recover(dkgSessionId, hostSecretKey)`, which walks ChillDKG recovery + and then each refresh to the active generation; +- tests that it lands on the live share at every generation. + +Wiring that into a restore flow belongs with whoever builds the restore flow. Until then, the +honest copy is that a reinstalled device is repaired (10a), not restored. + +**Done when** the recovery walk is tested to generation 3 against the shares computed live. + +#### Phase 13: rollout + +- **The flag (D4).** `BuildConfig`-style, off in release. The key screen shows no rotate action, + and inbound 30340s are declined out loud with "this build cannot rotate shares". +- **Capability.** The support D5 checks for is a value in the client's key package or profile + tags, so a proposer can refuse before anyone deals. +- **Compatibility.** + - An old build sees a 30340 as an unknown kind and does nothing. That is acceptable only + because D5 has already refused to make it a recipient. + - An old build that sees a 30320 with `frost_generation` ≥ 1 ignores the tag and signs with + generation 0. The partial signature then fails verification, and the coordinator blames it. + That is noisy, not dangerous. D5 keeps it from happening in a group that has refreshed. +- **Checks this tree cannot run.** + - Android install over the current build, then a refresh across three devices. + - A desktop member in the same group. + - iOS on a Mac. + - The `adb backup` check from Phase 5. + + Say so in the PR until done, as submodule-refresh.md does. + +## What this does not do + +- **Change the threshold, or add members.** A reshare with a different `t'` deals each member's + Lagrange-weighted share as a fresh VSS secret. It is a different protocol, with its own + review. Adding a member is enrollment (10c). +- **Encrypt `aux.db`.** Phase 5 shrinks the exposure; it does not close it. +- **Recover from `t` compromised shares.** A refresh is for before that happens. After it, only a + new ceremony helps, and it gives a new key, a new room and new certificates. +- **Prove deletion.** Every member's wipe is on their own device, on trust. +- **Rotate subgroup keys from the parent.** A subgroup refreshes its own key in its own room. The + birth certificate names the child's key, which a refresh does not change, so it stays valid. + +## Appendix: considered and rejected + +| idea | why not | +|---|---| +| Re-enroll every member at fresh ids, then retire the old ids | Same polynomial. Every old share is still a point on it ([the headline](#the-headline-enrollment-cannot-rotate-a-share)) | +| Run ChillDKG again | A new key: a new room id (`marmotGroupId`), every `GroupSignedEvent` author changes, and subgroup birth certificates and the chronicle no longer verify. That is the right tool after `t` shares leak, and the wrong one for a routine rotation | +| Refresh in Kotlin inside Giza | Protocol code in the app, with no vectors and no reviewer. If not zkp, then bitcoin-kmp (D1), never `composeApp` | +| Let the refresh finish without everyone | A recipient who cannot confirm could hold an inconsistent delta and nobody would know. Repair covers the absent member cleanly (D2) | +| Fold the refresh into `removeMember` | A removal is one admin's commit, and a refresh needs every holder. Coupling them makes a removal hang on the slowest phone (D8) | +| Send repair messages as MLS application messages | Every member of the room can read them. The v2 messages are raw additive shares | + +## Summary + +| phase | where | what | done when | +|---|---|---|---| +| 1 | secp256k1-zkp | `frost_refresh`: spec, Python vectors, C, tests | vectors agree; review requested | +| 2 | secp256k1-kmp | bindings, natives | `:tests:jvmTest` | +| 3 | bitcoin-kmp | `FrostRefresh` wrapper; refresh → repair → sign test | wrapper tests; enrollment tests unchanged | +| 4 | chain → Giza | bumps, per submodule-refresh.md | Giza `check` with no app change | +| 5 | Giza | `aux.db` out of backups; `secure_delete` | no `aux.db` in a backup; overwritten bytes gone | +| 6 | Giza | schema 38: generations and roster; `frost_generation` on signing | existing tests unedited; mismatch declines | +| 7 | Giza | `ShareRefreshManager`, kinds 30340–30345, gates, fork rules | ritual and fork tests | +| 8 | Giza | cutover, signed 30326 with generation, wipe | cutover test; old share gone from file | +| 9 | Giza | rotate after removal | removed member's share signs nothing | +| 10 | Giza | repair: same identity, new identity | re-enrollment tests | +| 11 | Giza | Shares section, refresh and repair screens | `m3Audit`, `check` | +| 12 | Giza | recovery walk across generations | recovery equals live to `g = 3` | +| 13 | Giza | flag, capability, device checks | flag off in release; device checks named in PR | From 4040ae7424a3ad59c008a8a2fb16479461011987 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Thu, 19 Nov 2026 22:40:17 +0200 Subject: [PATCH 02/12] fix: a deleted share is gone from aux.db, and aux.db leaves the phone in no backup (frost-share-refresh, Phase 5) Every connection opens with PRAGMA secure_delete = ON (SecureDeleteDriver), and GizaDatabase.scrubFreedPages truncates the write-ahead log, which keeps whole page images of a share after its row is gone. Android backups and device-to-device transfers carry none of the app's data: aux.db holds FROST shares in plaintext, and a share copied somewhere the app cannot reach cannot be rotated away from. SecureDeleteJvmTest reads the database's files byte by byte; its two controls find the share with secure_delete off and before the scrub. jvmTest 1176/1176. Co-Authored-By: Claude Opus 5.5 --- .../src/androidMain/AndroidManifest.xml | 6 +- .../res/xml/data_extraction_rules.xml | 36 ++++ .../giza/compose/database/GizaDatabase.kt | 21 ++ .../builder/PlatformDatabaseBuilder.kt | 4 +- .../database/builder/SecureDeleteDriver.kt | 39 ++++ .../compose/database/SecureDeleteJvmTest.kt | 185 ++++++++++++++++++ docs/frost-share-refresh.md | 13 ++ 7 files changed, 302 insertions(+), 2 deletions(-) create mode 100644 composeApp/src/androidMain/res/xml/data_extraction_rules.xml create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/builder/SecureDeleteDriver.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/SecureDeleteJvmTest.kt diff --git a/composeApp/src/androidMain/AndroidManifest.xml b/composeApp/src/androidMain/AndroidManifest.xml index dc20c74b..30757806 100644 --- a/composeApp/src/androidMain/AndroidManifest.xml +++ b/composeApp/src/androidMain/AndroidManifest.xml @@ -4,9 +4,13 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt index 89908278..43832397 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt @@ -502,6 +502,27 @@ abstract class GizaDatabase: RoomDatabase() { abstract fun unsignedNostrEventDao(): UnsignedNostrEventDao abstract fun zapDao(): ZapDao + /** + * Folds the write-ahead log into the database file and truncates it to nothing. + * + * `secure_delete` (see [mobi.giza.compose.database.builder.SecureDeleteDriver]) zeroes freed + * content in the database's own pages, but in WAL mode every change first goes to `-wal` as a + * whole page image, and those images stay in the file after a checkpoint until a later write + * happens to reuse the space. A share written last week can still be sitting in a frame there + * after its row has been overwritten. A truncating checkpoint is what removes them. + * + * Call it after deleting a secret, never inside a transaction: SQLite refuses to checkpoint + * from one. It is cheap but not free, so it is for the moment a secret is deleted rather than + * for every write. + */ + suspend fun scrubFreedPages() { + useWriterConnection { transactor -> + transactor.usePrepared("PRAGMA wal_checkpoint(TRUNCATE)") { statement -> + while (statement.step()) Unit + } + } + } + suspend fun wipeData() { useWriterConnection { transactor -> transactor.immediateTransaction { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/builder/PlatformDatabaseBuilder.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/builder/PlatformDatabaseBuilder.kt index fe122477..6a08bcf7 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/builder/PlatformDatabaseBuilder.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/builder/PlatformDatabaseBuilder.kt @@ -33,7 +33,9 @@ fun getRoomDatabase( // wallet's own messages left, and 35->36 drops the wallets' tables, // columns, chat lines and signing sessions. .addMigrations(MIGRATION_3_4, MIGRATION_9_10, MIGRATION_13_14, MIGRATION_14_15, MIGRATION_26_27, MIGRATION_32_33, MIGRATION_35_36) - .setDriver(BundledSQLiteDriver()) + // secure_delete on every connection: a share this device deletes has to be gone + // from the file, not only from the query results. See SecureDeleteDriver. + .setDriver(SecureDeleteDriver(BundledSQLiteDriver())) .setQueryCoroutineContext(Dispatchers.IO) .build() } \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/builder/SecureDeleteDriver.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/builder/SecureDeleteDriver.kt new file mode 100644 index 00000000..1004796f --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/builder/SecureDeleteDriver.kt @@ -0,0 +1,39 @@ +package mobi.giza.compose.database.builder + +import androidx.sqlite.SQLiteConnection +import androidx.sqlite.SQLiteDriver +import androidx.sqlite.execSQL + +/** + * Opens every connection with `PRAGMA secure_delete = ON`, so content SQLite frees -- a row + * deleted, a column overwritten with something shorter -- is zeroed in the page rather than left + * there until the space happens to be reused. + * + * The secret this is for is a FROST share. `DkgSession.secretShare` sits in `aux.db` as plaintext + * hex, and rotating a group's shares (docs/frost-share-refresh.md) ends with this device deleting + * the old one. Without this, that delete is a promise the file does not keep: the old share stays + * in a free block of the page, readable by anything that gets the file. + * + * The pragma is per connection, and Room keeps a pool of them, which is why it is set here, where + * every connection is born, rather than once in a `RoomDatabase.Callback`: a callback sees one + * connection, and a delete run on another would not be secure. + * + * It is not encryption at rest, which the database still lacks. It only makes sure that what this + * app deletes is gone from the database file; it says nothing about what was copied out of it + * before. See [mobi.giza.compose.database.GizaDatabase.scrubFreedPages] for the write-ahead log, + * which keeps old page images of its own. + */ +class SecureDeleteDriver(private val delegate: SQLiteDriver) : SQLiteDriver { + override val hasConnectionPool: Boolean get() = delegate.hasConnectionPool + + override fun open(fileName: String): SQLiteConnection { + val connection = delegate.open(fileName) + try { + connection.execSQL("PRAGMA secure_delete = ON") + } catch (t: Throwable) { + connection.close() + throw t + } + return connection + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/SecureDeleteJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/SecureDeleteJvmTest.kt new file mode 100644 index 00000000..fab723ef --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/SecureDeleteJvmTest.kt @@ -0,0 +1,185 @@ +package mobi.giza.compose.database + +import androidx.room3.Room +import androidx.room3.RoomDatabase +import androidx.sqlite.SQLiteConnection +import androidx.sqlite.SQLiteDriver +import androidx.sqlite.driver.bundled.BundledSQLiteDriver +import androidx.sqlite.execSQL +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import androidx.room3.useWriterConnection +import mobi.giza.compose.database.builder.SecureDeleteDriver +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.DkgSession +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.database.model.types.DkgRitualStage +import java.io.File +import java.nio.file.Files +import kotlin.random.Random +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue +import kotlin.time.Instant + +/** + * A share this device deletes has to be gone from `aux.db`, not only from the query results. + * + * Rotating a group's shares (docs/frost-share-refresh.md) ends with each device deleting its old + * one, and the whole value of the rotation rests on that delete. SQLite does not, by default, + * erase what it frees: an overwritten column's old bytes stay in the page, and in WAL mode a whole + * page image of the write that put them there stays in `-wal`. These tests read the database's + * files byte by byte for the old share's hex. + * + * The control matters as much as the claim. Without it, a test that looks for bytes in the wrong + * file, or after the wrong step, would pass for the same reason it passes when the delete works. + */ +class SecureDeleteJvmTest { + + private val directory: File = Files.createTempDirectory("secure-delete").toFile() + + @AfterTest + fun removeDirectory() { + directory.deleteRecursively() + } + + private val user = KeyPair().pubKey.toHexKey() + private val room = "11".repeat(32) + + /** A share no other bytes in the file could happen to equal. */ + private val share = Random.nextBytes(32).toHexKey() + + private fun session(secretShare: String?) = DkgSession( + id = "ceremony", + chatRoomId = room, + coordinatorPublicKey = user, + userPublicKey = user, + threshold = 2, + participantCount = 3, + stage = DkgRitualStage.COMPLETE, + hostPublicKey = user, + round1Random = "aa".repeat(32), + round2AuxRandom = "bb".repeat(32), + thresholdPublicKey = "02" + "cc".repeat(32), + secretShare = secretShare, + createdAt = Instant.fromEpochSeconds(1_000), + ) + + private suspend fun seed(db: GizaDatabase) { + val nostrEventId = "c".repeat(64) + db.nostrEventDao().upsert( + NostrEvent(id = nostrEventId, pubKey = user, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128)) + ) + db.profileDao().upsert(Profile(publicKey = user, userName = "user", nostrEventId = nostrEventId)) + db.chatRoomDao().upsert(ChatRoom(id = room, userPublicKey = user, subject = null, description = null, mlsGroupState = null)) + } + + private fun builder(): RoomDatabase.Builder = + Room.databaseBuilder(name = File(directory, "aux.db").absolutePath) + + /** Every byte SQLite keeps for this database: the file, its write-ahead log and its index. */ + private fun bytesOnDisk(): String = + directory.listFiles().orEmpty() + .filter { it.name.startsWith("aux.db") } + .joinToString("") { it.readBytes().toString(Charsets.ISO_8859_1) } + + /** + * Writes the share, then gets rid of it: by overwriting the column with null, which is what a + * wipe does, or by deleting the row. + * + * Both, because they free different things. An overwrite drops the old cell and writes a + * shorter one, and where SQLite places the new cell decides whether the old share's bytes + * happen to be written over -- in this schema they are, so an overwrite cannot serve as the + * control. A deleted row's cell is freed and nothing is written over it, so without + * secure_delete its bytes stay in the page for certain. + */ + private suspend fun storeThenDelete(db: GizaDatabase, deleteRow: Boolean = false) { + seed(db) + db.dkgSessionDao().upsert(session(secretShare = share)) + assertEquals(share, db.dkgSessionDao().getSessionById("ceremony")?.secretShare) + if (deleteRow) { + db.useWriterConnection { transactor -> + transactor.usePrepared("DELETE FROM DkgSession") { it.step() } + } + } else { + db.dkgSessionDao().upsert(session(secretShare = null)) + } + } + + @Test + fun `a deleted share leaves no bytes in the database files`() = runBlocking { + val db = getRoomDatabase(builder()) + storeThenDelete(db) + db.scrubFreedPages() + + // Read while the database is open, which is how it is on a phone: a close checkpoints + // and removes the log, which would hide exactly what the scrub is for. + assertFalse(share in bytesOnDisk(), "the deleted share is still in the database files") + db.close() + } + + @Test + fun `a deleted row leaves no bytes in the database files`() = runBlocking { + val db = getRoomDatabase(builder()) + storeThenDelete(db, deleteRow = true) + db.scrubFreedPages() + + assertFalse(share in bytesOnDisk(), "the deleted row's share is still in the database files") + db.close() + } + + @Test + fun `secure delete alone leaves the share in the write-ahead log`() = runBlocking { + val db = getRoomDatabase(builder()) + storeThenDelete(db) + + assertTrue(share in bytesOnDisk(), "nothing to scrub, so the scrub above proves nothing") + db.scrubFreedPages() + assertFalse(share in bytesOnDisk()) + db.close() + } + + @Test + fun `with secure delete off, a deleted row leaves the share in the page`() = runBlocking { + val db = builder() + .setDriver(SecureDeleteOff(BundledSQLiteDriver())) + .setQueryCoroutineContext(Dispatchers.IO) + .build() + storeThenDelete(db, deleteRow = true) + db.scrubFreedPages() + + assertTrue(share in bytesOnDisk(), "the control found nothing, so secure_delete is not what the first test shows") + db.close() + } + + /** The control's driver: the same as the app's but for the one pragma, set the other way. */ + private class SecureDeleteOff(private val delegate: SQLiteDriver) : SQLiteDriver { + override val hasConnectionPool: Boolean get() = delegate.hasConnectionPool + override fun open(fileName: String): SQLiteConnection = + delegate.open(fileName).also { it.execSQL("PRAGMA secure_delete = OFF") } + } + + @Test + fun `every connection the driver opens has secure delete on`() { + val driver = SecureDeleteDriver(BundledSQLiteDriver()) + val path = File(directory, "pragma.db").absolutePath + val connections = List(3) { driver.open(path) } + try { + connections.forEach { connection -> + val on = connection.prepare("PRAGMA secure_delete").use { statement -> + statement.step() + statement.getLong(0) + } + assertEquals(1L, on) + } + } finally { + connections.forEach { it.close() } + } + } +} diff --git a/docs/frost-share-refresh.md b/docs/frost-share-refresh.md index c157788d..ade3bfdd 100644 --- a/docs/frost-share-refresh.md +++ b/docs/frost-share-refresh.md @@ -11,6 +11,19 @@ up to Giza. Read [shared-key-ceremony.md](./shared-key-ceremony.md) and [shared-key-derivation.md](./shared-key-derivation.md) first. Everything below assumes the ceremony they describe and the rule that a room's id *is* the key it signs with. +## Where it stands + +| phase | commit | checked | +|---|---|---| +| 5 | Phase 5 | `SecureDeleteJvmTest` (5, two of them controls that fail without the fix); `jvmTest` 1176/1176; `compileDebugKotlinAndroid`, `processDebugResources` | + +Where the build chose differently from the plan: + +| what the plan said | what it turned out to be | +|---|---| +| Phase 5: a test overwrites a share and finds no copy | three. An overwrite in this schema happens to write the new cell over the old share, so it passed with `secure_delete` off too and proved nothing; a deleted row is the control that fails without it. And `secure_delete` alone leaves the share in `-wal` until a truncating checkpoint, so `GizaDatabase.scrubFreedPages` is part of the fix, with its own control | +| Phase 5: `dataExtractionRules` or `allowBackup="false"` | both. From Android 12 `allowBackup="false"` stops cloud backup but not a device-to-device transfer | + ## The headline: enrollment cannot rotate a share The word in the request is *re-enrollment*, and the enrollment module that just arrived looks From fce51e20f6460234b94226d243eb40c077d09ccd Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Thu, 19 Nov 2026 22:48:42 +0200 Subject: [PATCH 03/12] feat: a key's shares have generations, and signing reads the one it names (frost-share-refresh, Phase 6) Schema 38 (AutoMigration): KeyShareGeneration and KeyShareMember for every generation a refresh makes, FrostSigningSession.generation, and GroupKeyState.generation and publicSharesHash. Generation 0 has no row: it stays where ChillDKG wrote it, with ids derived from the host keys as before. ShareGenerations is the one door signing reads a share through. FrostSigningManager fixes a session to the generation the group signs with when it is proposed, carries it as frost_generation from generation 1 (a generation-0 proposal is byte for byte what it was), and a device holding no share of the named generation declines out loud with GENERATION_REFUSAL instead of waiting or signing with the wrong share. ShareGenerationsJvmTest refreshes a 2-of-3 group's shares by hand with a zero-constant polynomial; the new shares sign and the signature verifies as the unchanged room. jvmTest 1183/1183, compileDebugKotlinAndroid, and the M3, brand and wallet audits pass. Co-Authored-By: Claude Opus 5.5 --- .../38.json | 4710 +++++++++++++++++ .../giza/compose/database/GizaDatabase.kt | 15 +- .../compose/database/dao/DkgSessionDao.kt | 12 +- .../giza/compose/database/dao/KeyShareDao.kt | 34 + .../database/model/FrostSigningSession.kt | 15 + .../compose/database/model/GroupKeyState.kt | 14 + .../database/model/KeyShareGeneration.kt | 99 + .../compose/database/model/KeyShareMember.kt | 52 + .../model/types/ShareGenerationState.kt | 30 + .../database/model/types/ShareStanding.kt | 24 + .../compose/managers/FrostSigningManager.kt | 137 +- .../giza/compose/managers/ShareGenerations.kt | 132 + .../compose/nostr/frost/FrostSigningEvents.kt | 18 +- .../nostr/frost/tags/FrostGenerationTag.kt | 36 + .../ShippedProfileUpgradeJvmTest.kt | 15 +- .../managers/ShareGenerationsJvmTest.kt | 372 ++ docs/frost-share-refresh.md | 6 +- 17 files changed, 5674 insertions(+), 47 deletions(-) create mode 100644 composeApp/schemas/mobi.giza.compose.database.GizaDatabase/38.json create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/KeyShareDao.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/KeyShareGeneration.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/KeyShareMember.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareGenerationState.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareStanding.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareGenerations.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/tags/FrostGenerationTag.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareGenerationsJvmTest.kt diff --git a/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/38.json b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/38.json new file mode 100644 index 00000000..aff219cf --- /dev/null +++ b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/38.json @@ -0,0 +1,4710 @@ +{ + "formatVersion": 1, + "database": { + "version": 38, + "identityHash": "07040a5611aaf51ce2719d78e60b7025", + "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, `walletPolicy` 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": "walletPolicy", + "columnName": "walletPolicy", + "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, 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" + } + ], + "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, `generation` INTEGER, `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": "generation", + "columnName": "generation", + "affinity": "INTEGER" + }, + { + "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, `generation` INTEGER, `publicSharesHash` 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": "generation", + "columnName": "generation", + "affinity": "INTEGER" + }, + { + "fieldPath": "publicSharesHash", + "columnName": "publicSharesHash", + "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": "KeyShareGeneration", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`dkgSessionId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `secretShare` TEXT, `publicShares` TEXT NOT NULL, `state` TEXT NOT NULL, `refreshSessionId` TEXT, `recoveryData` TEXT, `activatedAt` INTEGER, `wipedAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`dkgSessionId`, `generation`), FOREIGN KEY(`dkgSessionId`) REFERENCES `DkgSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "secretShare", + "columnName": "secretShare", + "affinity": "TEXT" + }, + { + "fieldPath": "publicShares", + "columnName": "publicShares", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "state", + "columnName": "state", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "refreshSessionId", + "columnName": "refreshSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryData", + "columnName": "recoveryData", + "affinity": "TEXT" + }, + { + "fieldPath": "activatedAt", + "columnName": "activatedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "wipedAt", + "columnName": "wipedAt", + "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 + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "dkgSessionId", + "generation" + ] + }, + "indices": [ + { + "name": "index_KeyShareGeneration_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_KeyShareGeneration_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "DkgSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "dkgSessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "KeyShareMember", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`dkgSessionId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `participantId` INTEGER NOT NULL, `memberPublicKey` TEXT NOT NULL, `hostPublicKey` TEXT NOT NULL, `standing` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`dkgSessionId`, `generation`, `participantId`), FOREIGN KEY(`dkgSessionId`, `generation`) REFERENCES `KeyShareGeneration`(`dkgSessionId`, `generation`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantId", + "columnName": "participantId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "memberPublicKey", + "columnName": "memberPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "hostPublicKey", + "columnName": "hostPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "standing", + "columnName": "standing", + "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": false, + "columnNames": [ + "dkgSessionId", + "generation", + "participantId" + ] + }, + "indices": [ + { + "name": "index_KeyShareMember_dkgSessionId_generation", + "unique": false, + "columnNames": [ + "dkgSessionId", + "generation" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_KeyShareMember_dkgSessionId_generation` ON `${TABLE_NAME}` (`dkgSessionId`, `generation`)" + } + ], + "foreignKeys": [ + { + "table": "KeyShareGeneration", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "dkgSessionId", + "generation" + ], + "referencedColumns": [ + "dkgSessionId", + "generation" + ] + } + ] + }, + { + "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": "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, `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": "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": "MarmotSenderRatchet", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `epoch` INTEGER NOT NULL, `leafIndex` INTEGER NOT NULL, `applicationGeneration` INTEGER NOT NULL, `record` BLOB 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": "epoch", + "columnName": "epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "leafIndex", + "columnName": "leafIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "applicationGeneration", + "columnName": "applicationGeneration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "record", + "columnName": "record", + "affinity": "BLOB", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId" + ] + }, + "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, '07040a5611aaf51ce2719d78e60b7025')" + ] + } +} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt index 43832397..eca9b7a1 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt @@ -24,6 +24,7 @@ import mobi.giza.compose.database.dao.GiftWrapSealDao import mobi.giza.compose.database.dao.GroupKeyStateDao import mobi.giza.compose.database.dao.GroupSignedEventDao import mobi.giza.compose.database.dao.InReplyToRelationDao +import mobi.giza.compose.database.dao.KeyShareDao import mobi.giza.compose.database.dao.MarmotCommitResultDao import mobi.giza.compose.database.dao.MarmotOutboundDao import mobi.giza.compose.database.dao.MarmotGroupEventDao @@ -65,6 +66,8 @@ import mobi.giza.compose.database.model.GiftWrapMessage import mobi.giza.compose.database.model.GiftWrapPayload import mobi.giza.compose.database.model.GiftWrapSeal import mobi.giza.compose.database.model.GroupKeyState +import mobi.giza.compose.database.model.KeyShareGeneration +import mobi.giza.compose.database.model.KeyShareMember import mobi.giza.compose.database.model.GroupSignedEvent import mobi.giza.compose.database.model.InReplyToRelation import mobi.giza.compose.database.model.MarmotCommitResult @@ -124,6 +127,8 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) GiftWrapPayload::class, GroupKeyState::class, GroupSignedEvent::class, + KeyShareGeneration::class, + KeyShareMember::class, InReplyToRelation::class, MarmotCommitResult::class, MarmotGroupEvent::class, @@ -153,7 +158,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) UnsignedNostrEvent::class, Zap::class ], - version = 37, + version = 38, autoMigrations = [ // v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can // generate the migration itself — nothing existing changes shape. @@ -396,6 +401,12 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) // not sent since its last full save" -- true of every one of them at the moment of the // upgrade, because the build before this one saved the whole state on every send. AutoMigration(from = 36, to = 37), + // v38 adds share generations (docs/frost-share-refresh.md, Phase 6): the + // KeyShareGeneration and KeyShareMember tables, FrostSigningSession.generation, + // and GroupKeyState.generation and publicSharesHash. Two new tables and four + // nullable columns, so Room generates it. Nothing is backfilled: generation 0 + // stays where the ceremony put it, and a null generation reads as 0. + AutoMigration(from = 37, to = 38), ] ) @ConstructedBy(GizaDatabaseConstructor::class) @@ -428,6 +439,8 @@ abstract class GizaDatabase: RoomDatabase() { abstract fun groupKeyStateDao(): GroupKeyStateDao + abstract fun keyShareDao(): KeyShareDao + abstract fun groupSignedEventDao(): GroupSignedEventDao diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/DkgSessionDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/DkgSessionDao.kt index 3cffa2c8..997b6045 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/DkgSessionDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/DkgSessionDao.kt @@ -136,8 +136,18 @@ interface DkgSessionDao { * Signing happens in the admin room, whose id is derived from the key * rather than from the room the ceremony ran in, so the key is found by * matching that derivation rather than by a stored room id. + * + * A share of any generation counts (docs/frost-share-refresh.md): once a key + * has been refreshed and its ceremony's share wiped, the share it holds is a + * KeyShareGeneration row. Which generation signs is `ShareGenerations`'s to + * say, not this query's. */ - @Query("SELECT * FROM DkgSession WHERE thresholdPublicKey IS NOT NULL AND secretShare IS NOT NULL ORDER BY createdAt DESC") + @Query( + "SELECT * FROM DkgSession WHERE thresholdPublicKey IS NOT NULL AND (" + + "secretShare IS NOT NULL OR " + + "id IN (SELECT dkgSessionId FROM KeyShareGeneration WHERE secretShare IS NOT NULL)" + + ") ORDER BY createdAt DESC" + ) suspend fun getKeyHoldingSessions(): List /** diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/KeyShareDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/KeyShareDao.kt new file mode 100644 index 00000000..65aef04c --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/KeyShareDao.kt @@ -0,0 +1,34 @@ +package mobi.giza.compose.database.dao + +import androidx.room3.Dao +import androidx.room3.Query +import androidx.room3.Upsert +import mobi.giza.compose.database.model.KeyShareGeneration +import mobi.giza.compose.database.model.KeyShareMember + +/** + * The generations a refresh has made of a key's shares (docs/frost-share-refresh.md). + * Generation 0 is not here; see [KeyShareGeneration]. Read through + * `ShareGenerations`, which puts the two together. + */ +@Dao +interface KeyShareDao { + @Query("SELECT * FROM KeyShareGeneration WHERE dkgSessionId = :dkgSessionId AND generation = :generation") + suspend fun getGeneration(dkgSessionId: String, generation: Int): KeyShareGeneration? + + /** The generation the group signs with, by this device's account, or null while that is still 0. */ + @Query("SELECT * FROM KeyShareGeneration WHERE dkgSessionId = :dkgSessionId AND state = 'ACTIVE' ORDER BY generation DESC LIMIT 1") + suspend fun getActive(dkgSessionId: String): KeyShareGeneration? + + @Query("SELECT * FROM KeyShareGeneration WHERE dkgSessionId = :dkgSessionId ORDER BY generation ASC") + suspend fun getGenerations(dkgSessionId: String): List + + @Query("SELECT * FROM KeyShareMember WHERE dkgSessionId = :dkgSessionId AND generation = :generation ORDER BY participantId ASC") + suspend fun getMembers(dkgSessionId: String, generation: Int): List + + @Upsert + suspend fun upsert(generation: KeyShareGeneration) + + @Upsert + suspend fun upsert(members: List) +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/FrostSigningSession.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/FrostSigningSession.kt index d5415e93..8266d2f0 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/FrostSigningSession.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/FrostSigningSession.kt @@ -117,6 +117,21 @@ data class FrostSigningSession( */ val derivationPath: String? = null, + /** + * Which generation of the key's shares this session signs with + * (docs/frost-share-refresh.md), or null on a session from before shares + * could change -- which signed with generation 0, the ceremony's, and reads + * as that. + * + * Fixed at creation like every other input. A share is an input to the + * nonce, so a session whose device moved to a newer generation halfway + * through would regenerate a different nonce from the same seed; and a + * partial signature made with another generation's share is checked against + * the wrong public share and cannot aggregate. A device that holds no share + * of the generation a proposal names declines it, out loud. + */ + val generation: Int? = null, + val stage: FrostSigningStage = FrostSigningStage.COLLECTING_NONCES, /** The chosen signers' FROST ids in aggregation order, comma separated. Written once. */ diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupKeyState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupKeyState.kt index 3acbe976..0f2199a7 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupKeyState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupKeyState.kt @@ -129,6 +129,20 @@ data class GroupKeyState( */ val birthCertificateJson: String? = null, + /** + * Which generation of the key's shares the group says it signs with, or null + * for a state from before shares could change, which means generation 0. + * docs/frost-share-refresh.md, Phase 8, is what writes it. + */ + val generation: Int? = null, + + /** + * A hash of the public-share table at [generation], as the group signed it. + * What a device checks its own table against, so that it cannot sign at a + * generation the group disagrees with it about. + */ + val publicSharesHash: String? = null, + override val createdAt: Instant = Clock.System.now(), override val updatedAt: Instant = createdAt, override val savedAt: Instant = createdAt, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/KeyShareGeneration.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/KeyShareGeneration.kt new file mode 100644 index 00000000..aaec784c --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/KeyShareGeneration.kt @@ -0,0 +1,99 @@ +package mobi.giza.compose.database.model + +import androidx.room3.Entity +import androidx.room3.ForeignKey +import androidx.room3.Index +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.PublicKey +import kotlin.time.Clock +import kotlin.time.Instant +import mobi.giza.compose.database.model.traits.LocalStoreEntity +import mobi.giza.compose.database.model.traits.TimestampedEntity +import mobi.giza.compose.database.model.types.ShareGenerationState + +/** + * One generation of a key's shares, as this device holds it: every generation a + * refresh made, never the one ChillDKG made. + * + * A refresh (docs/frost-share-refresh.md) gives every member a new share of the + * same threshold key, on a new polynomial, so the old shares stop combining + * with the new. The key does not move -- the room, its id and everything the + * group has signed stay as they are -- but which share signs, and which public + * share it is checked against, now depends on the generation. + * + * **Generation 0 has no row.** It is the ceremony's output and stays where the + * ceremony put it: `DkgSession.secretShare` and `publicShares`, with participant + * ids derived from the ceremony's host keys. That derivation was chosen so that + * signing could never disagree with the ceremony that made the key, and a copy + * of it here would be a second source of truth to keep in step with the first. + * From generation 1 on there is no ceremony to derive from, and the rows are + * the record: certified by the refresh, and named in the group's signed key + * state. `ShareGenerations` reads both through one door. + */ +@Entity( + primaryKeys = ["dkgSessionId", "generation"], + foreignKeys = [ + ForeignKey( + entity = DkgSession::class, + parentColumns = ["id"], + childColumns = ["dkgSessionId"], + onDelete = ForeignKey.CASCADE, + ) + ], + indices = [ + Index("dkgSessionId"), + ], +) +data class KeyShareGeneration( + /** The ceremony that made the key. Its id is the `frost_key` every signing session names. */ + val dkgSessionId: String, + + /** 1 or more. 0 is the ceremony's, and has no row. */ + val generation: Int, + + /** + * Secret: this device's share at this generation, hex. Null once wiped, and + * null throughout for a generation this device was withheld from. + */ + val secretShare: HexKey?, + + /** Every participant's public share at this generation, comma-separated hex, in participant id order. */ + val publicShares: String, + + val state: ShareGenerationState, + + /** The refresh that made this generation, or null while that is not yet recorded. */ + val refreshSessionId: String? = null, + + /** + * What rebuilds this generation from the one before it with the host key: + * the refresh's public transcript. Not secret on its own. + */ + val recoveryData: HexKey? = null, + + /** When the group started signing with it, here. */ + val activatedAt: Instant? = null, + + /** When its secret share was deleted from this device. */ + val wipedAt: Instant? = null, + + override val createdAt: Instant = Clock.System.now(), + override val updatedAt: Instant = createdAt, + override val savedAt: Instant = createdAt, +) : TimestampedEntity, LocalStoreEntity { + init { + require(generation >= 1) { "Generation 0 is the ceremony's and has no row; got $generation" } + } + + fun publicShareList(): List? = publicShares + .split(",") + .mapNotNull { hex -> hex.trim().takeIf { it.isNotEmpty() } } + .map { PublicKey(ByteVector(it.hexToByteArray())) } + .takeIf { it.isNotEmpty() } + + override fun toString(): String = + "KeyShareGeneration(dkgSessionId=$dkgSessionId, generation=$generation, state=$state, " + + "secretShare=${if (secretShare == null) "null" else ""})" +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/KeyShareMember.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/KeyShareMember.kt new file mode 100644 index 00000000..dddcd1bc --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/KeyShareMember.kt @@ -0,0 +1,52 @@ +package mobi.giza.compose.database.model + +import androidx.room3.Entity +import androidx.room3.ForeignKey +import androidx.room3.Index +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlin.time.Clock +import kotlin.time.Instant +import mobi.giza.compose.database.model.traits.LocalStoreEntity +import mobi.giza.compose.database.model.traits.TimestampedEntity +import mobi.giza.compose.database.model.types.ShareStanding + +/** + * Who holds participant id [participantId] at one generation of a key, and + * whether they can sign with it. One row per id per [KeyShareGeneration]. + * + * Ids are fixed for the life of the key: they are the positions ChillDKG gave + * its participants, and FROST places every share by them. What can change is + * who is behind one (a member re-enrolled under a new identity) and whether it + * holds a share of this generation at all ([standing]). + */ +@Entity( + primaryKeys = ["dkgSessionId", "generation", "participantId"], + foreignKeys = [ + ForeignKey( + entity = KeyShareGeneration::class, + parentColumns = ["dkgSessionId", "generation"], + childColumns = ["dkgSessionId", "generation"], + onDelete = ForeignKey.CASCADE, + ) + ], + indices = [ + Index("dkgSessionId", "generation"), + ], +) +data class KeyShareMember( + val dkgSessionId: String, + val generation: Int, + val participantId: Int, + + /** The member's nostr key: who signs as this id. */ + val memberPublicKey: HexKey, + + /** Their ChillDKG host key, which refresh and repair messages are encrypted to. */ + val hostPublicKey: HexKey, + + val standing: ShareStanding, + + override val createdAt: Instant = Clock.System.now(), + override val updatedAt: Instant = createdAt, + override val savedAt: Instant = createdAt, +) : TimestampedEntity, LocalStoreEntity diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareGenerationState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareGenerationState.kt new file mode 100644 index 00000000..44f6ff0c --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareGenerationState.kt @@ -0,0 +1,30 @@ +package mobi.giza.compose.database.model.types + +/** + * Where one generation of a key's shares stands on this device + * (docs/frost-share-refresh.md). + * + * Declaration order is the life of a generation, and nothing goes backwards. + */ +enum class ShareGenerationState { + /** + * Stored, and this device has confirmed it to the group, but the refresh + * that made it has no certificate yet. Never signed with: until every + * recipient has confirmed, the group may yet abandon it, and the previous + * generation is still the one the group signs with. + */ + PENDING, + + /** The generation the group signs with. At most one per key. */ + ACTIVE, + + /** + * Superseded by a newer active generation, and kept only so that sessions + * opened under it can finish. Wiped once the group has signed with its + * successor. + */ + RETIRING, + + /** The secret share is gone from this device. The public table is kept. */ + WIPED, +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareStanding.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareStanding.kt new file mode 100644 index 00000000..519c5d24 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareStanding.kt @@ -0,0 +1,24 @@ +package mobi.giza.compose.database.model.types + +/** + * What one participant id holds at one generation of a key's shares + * (docs/frost-share-refresh.md). + */ +enum class ShareStanding { + /** Holds a share of this generation, and can sign with it. */ + LIVE, + + /** + * Was withheld from the refresh that made this generation, and holds only an + * older share, which signs nothing at this one. A repair (re-enrollment) + * makes them [LIVE] again. + */ + STALE, + + /** + * Withheld for good. Never repaired, never reused: participant ids are FROST + * identifiers, positions below `n`, and renumbering would invalidate every + * public share. + */ + RETIRED, +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt index 4e5d01a3..46ff773a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt @@ -159,6 +159,13 @@ object FrostSigningManager { */ const val MAX_BATCH_SIZE: Int = 64 + /** + * The reason a device gives for declining a session at a generation of the + * key's shares it holds nothing of (docs/frost-share-refresh.md). Read by + * other devices as the reason in a decline, like [WalletRefusal.REASON]. + */ + const val GENERATION_REFUSAL: String = "Holds no share of the generation this signs with" + /** * How many seconds [broadcast] will step forward looking for an unused * outbound row id before giving up and publishing nothing. @@ -308,12 +315,17 @@ object FrostSigningManager { dependents: (lead: Event) -> List>, key: DkgSession? = null ): FrostSigningSession { - val ceremony = key?.takeIf { it.stage == DkgRitualStage.COMPLETE && it.secretShare != null } + val ceremony = key?.takeIf { it.stage == DkgRitualStage.COMPLETE && ShareGenerations.canSign(database, it) } ?: completedKey(database, localChatRoom.chatRoom.id) ?: throw IllegalStateException("This group has no shared key to sign with") - val signerId = signerIdOf(database, ceremony, userPublicKey) - ?: throw IllegalStateException("This device is not a participant in ceremony ${ceremony.id}") + // The generation the group signs with now. Every signer has to sign with + // a share of this one, so the session names it and is fixed to it. + val shares = ShareGenerations.active(database, ceremony) + val signerId = shares.signerIds[userPublicKey] + ?: throw IllegalStateException( + "This device holds no share of generation ${shares.generation} of ceremony ${ceremony.id}" + ) val path = signingPath(database, localChatRoom, ceremony) val unsignedEventOf = { template: EventTemplate<*> -> @@ -346,6 +358,7 @@ object FrostSigningManager { participantCount = ceremony.participantCount, signerId = signerId, derivationPath = path?.let(SharedKeyDerivation::formatPath), + generation = shares.generation, // Proposing a signature is already the act of agreeing to it. signApprovedAt = Clock.System.now() ) @@ -490,7 +503,8 @@ object FrostSigningManager { userPublicKey: HexKey, key: DkgSession, signerId: Int, - path: List? + path: List?, + generation: Int = 0 ) = FrostSigningSession( id = sessionId, chatRoomId = localChatRoom.chatRoom.id, @@ -503,7 +517,8 @@ object FrostSigningManager { threshold = key.threshold, participantCount = key.participantCount, signerId = signerId, - derivationPath = path?.let(SharedKeyDerivation::formatPath) + derivationPath = path?.let(SharedKeyDerivation::formatPath), + generation = generation ) /** @@ -556,6 +571,8 @@ object FrostSigningManager { return null } + val generation = FrostSigningEvents.parseGeneration(innerEvent.tags) + val proposed = FrostSigningEvents.decodeProposal(innerEvent.content) if (proposed == null) { logger.w("Signing proposal $sessionId does not carry any events; dropping") @@ -615,7 +632,29 @@ object FrostSigningManager { // docs/giza-wallet-removal.md, Phase 1. WalletRefusal.of(unsignedEvents)?.let { why -> logger.w("Signing proposal $sessionId $why; declining") - val declined = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path) + val declined = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation ?: 0) + .copy(signDeclinedAt = Clock.System.now()) + database.frostSigningSessionDao().upsert(declined) + database.frostSigningSessionDao().upsertItems(itemsOver(sessionId, unsignedEvents)) + announceStarted(database, declined) + return declined + } + + // A share of the generation the proposal names, or a refusal said out loud. + // Signing with any other generation's share would put a partial signature + // behind the wrong public share -- it cannot aggregate -- and staying + // silent would leave the group waiting on a member who cannot help. + // Withheld from a refresh, or never told of one, this device declines. + // docs/frost-share-refresh.md, Phase 6. + val signable = generation?.let { ShareGenerations.at(database, key, it) } + if (generation == null || signable?.secretShare == null || signable.signerIds[userPublicKey] == null) { + logger.w( + "Signing proposal $sessionId signs with generation ${generation ?: "(unreadable)"} of key " + + "${key.id}, of which this device holds no share; declining" + ) + // An unreadable tag is filed as -1: no generation, so nothing reads it as a + // share this device holds, and the decline says why. + val declined = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation ?: -1) .copy(signDeclinedAt = Clock.System.now()) database.frostSigningSessionDao().upsert(declined) database.frostSigningSessionDao().upsertItems(itemsOver(sessionId, unsignedEvents)) @@ -631,7 +670,7 @@ object FrostSigningManager { } } - val session = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path) + val session = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation) database.frostSigningSessionDao().upsert(session) database.frostSigningSessionDao().upsertItems(itemsOver(sessionId, unsignedEvents)) announceStarted(database, session) @@ -842,7 +881,7 @@ object FrostSigningManager { reason: String ): Boolean { val key = database.dkgSessionDao().getSessionById(session.dkgSessionId) ?: return true - val participants = signerIds(database, key).keys + val participants = participantIds(database, key, session).keys if (member !in participants) { logger.w( @@ -943,8 +982,11 @@ object FrostSigningManager { if (session.stage == FrostSigningStage.COMPLETE || session.stage == FrostSigningStage.FAILED) return val key = database.dkgSessionDao().getSessionById(session.dkgSessionId) ?: return - val secretShare = key.secretShare?.let { PrivateKey(ByteVector32(it)) } ?: return val thresholdPublicKey = key.thresholdPublicKey ?: return + // The generation the session was opened at, never whichever is newest: + // see FrostSigningSession.generation. Null when this device holds nothing + // of it, which only a session it has declined can be. + val shares = ShareGenerations.at(database, key, session.generationOrZero()) try { // A signature the group has already made settles this session whether @@ -983,12 +1025,14 @@ object FrostSigningManager { return } + val secretShare = shares?.secretShare ?: return + // The room's key rather than the group's root key. A signature // aggregates against whatever the cache carries, so the cache and the // author on the event have to be the same derivation -- and the // session stores the path exactly so that every pass rebuilds the // same one. - val publicShares = key.publicShareList() + val publicShares = shares?.publicShares // The events this session signs, in the order the proposal fixed. Every // join below is positional against it. @@ -1464,7 +1508,7 @@ object FrostSigningManager { items: Int ): List>>? { val key = database.dkgSessionDao().getSessionById(session.dkgSessionId) ?: return null - val idByMember = signerIds(database, key) + val idByMember = signerIds(database, key, session) val offered = database.frostSigningSessionDao() .getMessagesByKind(session.id, FrostSigningEvents.NONCE) @@ -1502,7 +1546,7 @@ object FrostSigningManager { items: Int ): List>? { val key = database.dkgSessionDao().getSessionById(session.dkgSessionId) ?: return null - val memberById = signerIds(database, key).entries.associate { (member, id) -> id to member } + val memberById = signerIds(database, key, session).entries.associate { (member, id) -> id to member } val payloadByMember = database.frostSigningSessionDao() .getMessagesByKind(session.id, FrostSigningEvents.PARTIAL_SIGNATURE) @@ -1566,34 +1610,34 @@ object FrostSigningManager { } /** - * Every ceremony participant's FROST id, keyed by their nostr public key. - * - * The id is the member's index in the ceremony's participant order, which is - * the bytewise sort of the host public keys — the same ordering ChillDKG - * hashed into the session identity, and so the same one the public shares - * are in. Deriving it rather than storing it means signing cannot disagree - * with the ceremony that made the key. + * Who can sign in [session], keyed by nostr public key: every member holding a + * share of the generation it signs with. See [ShareGenerations]; at the + * ceremony's own generation this is every ceremony participant, at its index + * in the ceremony's participant order. */ private suspend fun signerIds( database: GizaDatabase, - key: DkgSession - ): Map { - val hostKeys = database.dkgSessionDao() - .getMessagesByKind(key.id, DkgRitualEvents.HOST_KEY) - .associate { it.participantPublicKey to it.payload.lowercase() } + key: DkgSession, + session: FrostSigningSession + ): Map = + ShareGenerations.at(database, key, session.generationOrZero())?.signerIds.orEmpty() - val order = hostKeys.values.sorted() - - return hostKeys.mapNotNull { (member, hostKey) -> - order.indexOf(hostKey).takeIf { it >= 0 }?.let { member to it } - }.toMap() - } + /** Every member with a participant id in [key] at [session]'s generation, whether or not they can sign at it. */ + private suspend fun participantIds( + database: GizaDatabase, + key: DkgSession, + session: FrostSigningSession + ): Map = + ShareGenerations.at(database, key, session.generationOrZero())?.participantIds + ?: ShareGenerations.active(database, key).participantIds private suspend fun signerIdOf( database: GizaDatabase, key: DkgSession, member: HexKey - ): Int? = signerIds(database, key)[member] + ): Int? = ShareGenerations.participantIdOf(database, key, member) + + private fun FrostSigningSession.generationOrZero(): Int = generation ?: 0 /** * The key a room signs with, or null when it has none. @@ -1642,8 +1686,8 @@ object FrostSigningManager { GroupKeyStateManager.keyStateFor(database, chatRoomId)?.let { state -> database.dkgSessionDao().getSessionById(state.dkgSessionId)?.takeIf { key -> key.stage == DkgRitualStage.COMPLETE && - key.secretShare != null && - key.thresholdPublicKey == state.thresholdPublicKey + key.thresholdPublicKey == state.thresholdPublicKey && + ShareGenerations.canSign(database, key) }?.let { return it } } @@ -1651,12 +1695,13 @@ object FrostSigningManager { session.stage == DkgRitualStage.COMPLETE && session.thresholdPublicKey?.let { SharedKeyDerivation.marmotGroupId(it) == chatRoomId - } == true + } == true && + ShareGenerations.canSign(database, session) }?.let { return it } return database.dkgSessionDao() .getLatestOwnSessionForChatRoom(chatRoomId) - ?.takeIf { it.stage == DkgRitualStage.COMPLETE && it.secretShare != null } + ?.takeIf { it.stage == DkgRitualStage.COMPLETE && ShareGenerations.canSign(database, it) } } /** Whether this group can sign at all, read by the UI so it offers nothing that would fail. */ @@ -2277,7 +2322,7 @@ object FrostSigningManager { session: FrostSigningSession ): Set { val key = database.dkgSessionDao().getSessionById(session.dkgSessionId) ?: return emptySet() - val holders = signerIds(database, key) + val holders = signerIds(database, key, session) val collectingPartials = session.stage == FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES val chosen = session.signerIdList()?.toSet() @@ -2413,13 +2458,28 @@ object FrostSigningManager { } } + /** + * Whether this device holds a share of the generation [session] signs with. + * Not holding one is the only refusal that is not a person's: the device + * cannot sign, so it says so rather than leaving the group to wait. + */ + private suspend fun holdsShareFor(database: GizaDatabase, session: FrostSigningSession): Boolean { + val key = database.dkgSessionDao().getSessionById(session.dkgSessionId) ?: return false + val shares = ShareGenerations.at(database, key, session.generationOrZero()) ?: return false + return shares.secretShare != null && shares.signerIds[session.userPublicKey] != null + } + private suspend fun publishDecline( database: GizaDatabase, localChatRoom: LocalChatRoom, session: FrostSigningSession ) { val items = database.frostSigningSessionDao().getItems(session.id) - val reason = if (isWalletSession(session, items)) WalletRefusal.REASON else "Declined to sign" + val reason = when { + isWalletSession(session, items) -> WalletRefusal.REASON + !holdsShareFor(database, session) -> GENERATION_REFUSAL + else -> "Declined to sign" + } broadcast( database = database, @@ -2690,7 +2750,8 @@ object FrostSigningManager { sessionId = session.id, dkgSessionId = if (includeKey) session.dkgSessionId else null, signerIds = signerIds, - silentMembers = silentMembers + silentMembers = silentMembers, + generation = session.generation ) + extraTags // No MLS state is what marks a room NIP-17 -- the same reading diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareGenerations.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareGenerations.kt new file mode 100644 index 00000000..15bf2a79 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareGenerations.kt @@ -0,0 +1,132 @@ +package mobi.giza.compose.managers + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.PublicKey +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.DkgSession +import mobi.giza.compose.database.model.KeyShareGeneration +import mobi.giza.compose.database.model.types.ShareGenerationState +import mobi.giza.compose.database.model.types.ShareStanding +import mobi.giza.compose.nostr.dkg.DkgRitualEvents + +/** + * The one door signing reads a share through (docs/frost-share-refresh.md, + * Phase 6). + * + * A key's shares can be refreshed: every member given a new share of the same + * key, on a new polynomial, so that the old ones stop combining with the new. + * Which share signs, which public shares it is checked against, and who can + * sign at all then depend on the *generation*. Generation 0 is what ChillDKG + * made and lives on [DkgSession]; every later one is a [KeyShareGeneration] + * row. Nothing outside this object should read `DkgSession.secretShare` to + * sign: the day a key has been refreshed, that column is the share the group + * has moved away from, and then nothing at all. + */ +object ShareGenerations { + + /** + * One generation of a key's shares as this device holds it. + * + * [signerIds] is who can sign at this generation -- every participant whose + * share is of it -- keyed by their nostr key. [participantIds] is everyone + * who has an id at all, including a member withheld from the refresh that + * made it: the ids are the ceremony's and do not move. + */ + class Shares( + val generation: Int, + val secretShare: PrivateKey?, + val publicShares: List?, + val signerIds: Map, + val participantIds: Map, + ) { + override fun toString(): String = + "Shares(generation=$generation, secretShare=${if (secretShare == null) "null" else ""}, " + + "signers=${signerIds.size}/${participantIds.size})" + } + + /** + * The generation the group signs with, by this device's account: the newest + * active one, or the ceremony's while there has been no refresh. + * + * A device withheld from the newest refresh gets that generation back with + * no secret share, which is right: the group has moved on, and the share it + * still holds signs nothing the group will aggregate. + */ + suspend fun active(database: GizaDatabase, key: DkgSession): Shares = + database.keyShareDao().getActive(key.id)?.let { row -> fromRow(database, row) } + ?: ceremony(database, key) + + /** + * Generation [generation] of [key], or null when this device knows nothing of + * it -- a refresh it never heard about -- or knows it only as pending, which + * nothing signs with. + */ + suspend fun at(database: GizaDatabase, key: DkgSession, generation: Int): Shares? { + if (generation == 0) return ceremony(database, key) + if (generation < 0) return null + + val row = database.keyShareDao().getGeneration(key.id, generation) ?: return null + if (row.state == ShareGenerationState.PENDING) return null + + return fromRow(database, row) + } + + /** Whether this device can sign with [key] today: it holds a share of the generation the group signs with. */ + suspend fun canSign(database: GizaDatabase, key: DkgSession): Boolean = + active(database, key).secretShare != null + + /** [member]'s participant id in [key], whatever their standing. */ + suspend fun participantIdOf(database: GizaDatabase, key: DkgSession, member: HexKey): Int? = + active(database, key).participantIds[member] ?: ceremonyIds(database, key)[member] + + /** + * Generation 0: the ceremony's own output, read where the ceremony wrote it. + * + * The ids are each member's index in the ceremony's participant order, the + * bytewise sort of the host public keys -- the same ordering ChillDKG hashed + * into the session identity, and so the same one the public shares are in. + * Deriving them rather than storing them means signing cannot disagree with + * the ceremony that made the key. + */ + private suspend fun ceremony(database: GizaDatabase, key: DkgSession): Shares { + val ids = ceremonyIds(database, key) + return Shares( + generation = 0, + secretShare = key.secretShare?.let { PrivateKey(ByteVector32(it)) }, + publicShares = key.publicShareList(), + signerIds = ids, + participantIds = ids, + ) + } + + private suspend fun ceremonyIds(database: GizaDatabase, key: DkgSession): Map { + val hostKeys = database.dkgSessionDao() + .getMessagesByKind(key.id, DkgRitualEvents.HOST_KEY) + .associate { it.participantPublicKey to it.payload.lowercase() } + + val order = hostKeys.values.sorted() + + return hostKeys.mapNotNull { (member, hostKey) -> + order.indexOf(hostKey).takeIf { it >= 0 }?.let { member to it } + }.toMap() + } + + private suspend fun fromRow(database: GizaDatabase, row: KeyShareGeneration): Shares { + val members = database.keyShareDao().getMembers(row.dkgSessionId, row.generation) + return Shares( + generation = row.generation, + secretShare = row.secretShare + ?.takeIf { row.state == ShareGenerationState.ACTIVE || row.state == ShareGenerationState.RETIRING } + ?.let { PrivateKey(ByteVector32(it)) }, + publicShares = row.publicShareList(), + signerIds = members + .filter { it.standing == ShareStanding.LIVE } + .associate { it.memberPublicKey to it.participantId }, + participantIds = members + .filter { it.standing != ShareStanding.RETIRED } + .associate { it.memberPublicKey to it.participantId }, + ) + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/FrostSigningEvents.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/FrostSigningEvents.kt index 5bd8bbe9..b22d7de4 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/FrostSigningEvents.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/FrostSigningEvents.kt @@ -7,6 +7,7 @@ import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.core.Kind import kotlinx.serialization.json.jsonArray import mobi.giza.compose.network.serialization.CommonJson +import mobi.giza.compose.nostr.frost.tags.FrostGenerationTag import mobi.giza.compose.nostr.frost.tags.FrostKeyTag import mobi.giza.compose.nostr.frost.tags.FrostSessionIdTag import mobi.giza.compose.nostr.frost.tags.FrostSignerIdsTag @@ -139,10 +140,13 @@ object FrostSigningEvents { sessionId: String, dkgSessionId: String? = null, signerIds: List? = null, - silentMembers: List? = null + silentMembers: List? = null, + generation: Int? = null ): Array> = buildList { add(FrostSessionIdTag.assemble(sessionId)) dkgSessionId?.let { add(FrostKeyTag.assemble(it)) } + // Only beside the key, and only from generation 1: see FrostGenerationTag. + if (dkgSessionId != null && generation != null && generation > 0) add(FrostGenerationTag.assemble(generation)) signerIds?.let { add(FrostSignerIdsTag.assemble(it)) } silentMembers?.takeIf { it.isNotEmpty() }?.let { add(FrostSilentMembersTag.assemble(it)) } }.toTypedArray() @@ -159,6 +163,18 @@ object FrostSigningEvents { fun parseKey(tags: Array>): String? = tags.firstNotNullOfOrNull(FrostKeyTag::parse)?.dkgSessionId + /** + * The generation of the key's shares a proposal signs with: the tag's, or 0 + * when there is none -- every proposal from before shares could change, and + * every one since at the ceremony's own generation. Null for a tag present + * and unreadable, which is not the same as absent: it names a generation, + * and this device cannot tell which. + */ + fun parseGeneration(tags: Array>): Int? { + val tag = tags.firstOrNull { it.isNotEmpty() && it[0] == FrostGenerationTag.TAG_NAME } ?: return 0 + return FrostGenerationTag.parse(tag)?.generation + } + fun parseSignerIds(tags: Array>): List? = tags.firstNotNullOfOrNull(FrostSignerIdsTag::parse)?.signerIds diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/tags/FrostGenerationTag.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/tags/FrostGenerationTag.kt new file mode 100644 index 00000000..8da3c3dc --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/tags/FrostGenerationTag.kt @@ -0,0 +1,36 @@ +package mobi.giza.compose.nostr.frost.tags + +import com.vitorpamplona.quartz.nip01Core.core.has +import com.vitorpamplona.quartz.utils.ensure + +/** + * Which generation of the key's shares a signing session signs with + * (docs/frost-share-refresh.md). + * + * Rides beside [FrostKeyTag], and only from generation 1: a session at the + * ceremony's own generation carries no tag, so it is byte for byte what it was + * before shares could change, and an older build reads it exactly as it always + * has. An absent tag means 0. + * + * A share of one generation and the public share of another do not match, so a + * partial signature made across them cannot aggregate. A device that holds no + * share of the generation named here declines the session, out loud. + */ +class FrostGenerationTag( + val generation: Int, +) { + companion object { + const val TAG_NAME = "frost_generation" + + fun parse(tag: Array): FrostGenerationTag? { + ensure(tag.has(1)) { return null } + ensure(tag[0] == TAG_NAME) { return null } + val generation = tag[1].toIntOrNull() ?: return null + ensure(generation >= 0) { return null } + + return FrostGenerationTag(generation) + } + + fun assemble(generation: Int): Array = arrayOf(TAG_NAME, generation.toString()) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt index 6a4dd7b8..79db770f 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt @@ -61,8 +61,13 @@ class ShippedProfileUpgradeJvmTest { /** The schema version on `giza`, which is the one every existing install is at. */ private val shipped = 36 - /** The schema version this branch builds. */ - private val current = 37 + /** + * The schema version this branch builds. 38 since share generations + * (docs/frost-share-refresh.md, Phase 6), so the upgrade crosses two + * generated migrations, 36 -> 37 -> 38, and the file has to come out at the + * second. + */ + private val current = 38 private val directory: File = Files.createTempDirectory("giza-shipped-profile").toFile() private val file: File = File(directory, "aux.db") @@ -225,13 +230,13 @@ class ShippedProfileUpgradeJvmTest { // -- what it has to prove -------------------------------------------------------- /** - * Room finds the way from 36 to 37, runs it, and stamps the file with the hash the + * Room finds the way from 36 to the current version, runs it, and stamps the file with the hash the * generated code expects. The hash is the assertion that matters: Room writes it * only after `validateMigration` has compared every table it was handed against the * schema the entities declare. */ @Test - fun `a v36 profile opens at v37, with the table this branch adds`(): Unit = runBlocking { + fun `a v36 profile opens at the current version, with the tables added since`(): Unit = runBlocking { writeShippedProfile() onDisk { connection -> assertEquals(shipped.toLong(), connection.userVersion(), "the fixture is not at the shipped version") @@ -247,7 +252,7 @@ class ShippedProfileUpgradeJvmTest { assertEquals( schema(current)["identityHash"]!!.jsonPrimitive.content, connection.identityHash(), - "Room did not stamp the v37 identity hash, so it did not validate the migrated schema", + "Room did not stamp the current identity hash, so it did not validate the migrated schema", ) val expected = entities(current).associateBy { it.tableName() } assertEquals(expected.keys, connection.tables(), "the migrated file has a different set of tables") diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareGenerationsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareGenerationsJvmTest.kt new file mode 100644 index 00000000..a90bf35e --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareGenerationsJvmTest.kt @@ -0,0 +1,372 @@ +package mobi.giza.compose.managers + +import androidx.room3.Room +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.Nip01Crypto +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.PublicKey +import fr.acinq.bitcoin.crypto.frost.Frost +import fr.acinq.bitcoin.crypto.frost.KeyMaterial +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Instant +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.DkgParticipantMessage +import mobi.giza.compose.database.model.DkgSession +import mobi.giza.compose.database.model.KeyShareGeneration +import mobi.giza.compose.database.model.KeyShareMember +import mobi.giza.compose.database.model.MarmotInnerEvent +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.database.model.types.DkgRitualStage +import mobi.giza.compose.database.model.types.FrostSigningStage +import mobi.giza.compose.database.model.types.ShareGenerationState +import mobi.giza.compose.database.model.types.ShareStanding +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.dkg.DkgRitualEvents +import mobi.giza.compose.nostr.frost.FrostSigningEvents +import mobi.giza.compose.nostr.frost.tags.FrostGenerationTag + +/** + * Signing once a key's shares can change (docs/frost-share-refresh.md, Phase 6). + * + * A refresh gives every member a new share of the same key, on a new + * polynomial. Nothing in the app makes one yet -- that is Phases 1-3 and 7 -- + * so the refresh here is done by hand, the way the protocol will do it: a + * polynomial with a zero constant term, evaluated at each member's point and + * added to their share. If the app's signing reads the generation it should, + * the new shares sign under the unchanged key, the room's id does not move, + * and a member holding only the old share cannot take part. + * + * Three members, 2-of-3, in a Marmot admin room, as [SignedGroupKeyStateTest] + * sets them up: one database each, and nothing shared but what is ferried. + */ +class ShareGenerationsJvmTest { + private val participants = 3 + private val threshold = 2 + + private val keyMaterial: KeyMaterial = Frost.trustedDealerKeygen( + thresholdSecretKey = PrivateKey( + ByteVector32("5ea1ed0000000000000000000000000000000000000000000000000000000ab1") + ), + nParticipants = participants, + threshold = threshold + ) + + private val thresholdPublicKey = keyMaterial.thresholdPublicKey.value.toHex() + private val adminRoomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) + private val ceremonyId = "ceremony".padEnd(64, '0') + + /** Chosen so the bytewise sort of the host keys reads in list order: member i is participant i. */ + private val members = listOf("a", "b", "c").map { it.repeat(64) } + private val hostKeys = listOf("2a", "2b", "2c").map { it.padEnd(66, '0') } + + // ---- The refresh, by hand ------------------------------------------------- + + /** + * delta(x) = a·x: degree t-1 with no constant term, so it moves every share + * and leaves the secret where it is. Participant i sits at x = i + 1, the + * frost module's convention. + */ + private val deltaCoefficient = PrivateKey( + ByteVector32("0de17a0000000000000000000000000000000000000000000000000000000c0e") + ) + + private fun scalar(value: Int): PrivateKey = + PrivateKey(ByteVector32(ByteArray(32).also { it[31] = value.toByte() })) + + private fun delta(participant: Int): PrivateKey = deltaCoefficient * scalar(participant + 1) + + private val refreshedSecretShares: List = + keyMaterial.secretShares.mapIndexed { i, share -> share + delta(i) } + + private val refreshedPublicShares: List = + keyMaterial.publicShares.mapIndexed { i, share -> share + delta(i).publicKey() } + + // ---- Devices --------------------------------------------------------------- + + private val devices = mutableListOf() + + @AfterTest + fun closeDatabases() = devices.forEach { it.db.close() } + + private inner class Device(val publicKey: HexKey, val db: GizaDatabase, val room: LocalChatRoom) { + val received = mutableSetOf() + suspend fun session(id: String) = db.frostSigningSessionDao().getSessionById(id) + suspend fun key() = db.dkgSessionDao().getSessionById(ceremonyId)!! + } + + private suspend fun device(index: Int): Device { + val publicKey = members[index] + 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 = adminRoomId, + userPublicKey = publicKey, + subject = "#Ekklesia", + description = SharedKeyDerivation.describe("Admins of the group."), + mlsGroupState = "00" + ) + db.chatRoomDao().upsert(chatRoom) + + db.dkgSessionDao().upsert( + DkgSession( + id = ceremonyId, + chatRoomId = adminRoomId, + coordinatorPublicKey = members.first(), + userPublicKey = publicKey, + threshold = threshold, + participantCount = participants, + stage = DkgRitualStage.COMPLETE, + hostPublicKey = hostKeys[index], + round1Random = "1".repeat(64), + round2AuxRandom = "2".repeat(64), + thresholdPublicKey = thresholdPublicKey, + secretShare = keyMaterial.secretShares[index].value.toHex(), + publicShares = keyMaterial.publicShares.joinToString(",") { it.value.toHex() } + ) + ) + members.forEachIndexed { i, member -> + db.dkgSessionDao().upsert( + DkgParticipantMessage(sessionId = ceremonyId, participantPublicKey = member, kind = DkgRitualEvents.HOST_KEY, payload = hostKeys[i]) + ) + } + + return Device(publicKey, db, LocalChatRoom(chatRoom = chatRoom)).also { devices += it } + } + + /** + * Files generation 1 on [device] as a finished refresh would: the device's + * new share (none if it was [withheld]), the new public table, and every + * member's standing. + */ + private suspend fun refresh( + device: Device, + withheld: Set = emptySet(), + state: ShareGenerationState = ShareGenerationState.ACTIVE, + ) { + val index = members.indexOf(device.publicKey) + device.db.keyShareDao().upsert( + KeyShareGeneration( + dkgSessionId = ceremonyId, + generation = 1, + secretShare = refreshedSecretShares[index].value.toHex().takeIf { index !in withheld }, + publicShares = refreshedPublicShares.joinToString(",") { it.value.toHex() }, + state = state, + ) + ) + device.db.keyShareDao().upsert( + members.mapIndexed { i, member -> + KeyShareMember( + dkgSessionId = ceremonyId, + generation = 1, + participantId = i, + memberPublicKey = member, + hostPublicKey = hostKeys[i], + standing = if (i in withheld) ShareStanding.STALE else ShareStanding.LIVE, + ) + } + ) + } + + // ---- The wire, as SignedGroupKeyStateTest ferries it ------------------------ + + private suspend fun outbox(device: Device): List = + device.db.marmotInnerEventDao() + .getByChatRoomAndKinds(chatRoomId = adminRoomId, kinds = FrostSigningEvents.ALL.toList()) + .filter { it.publicKey == device.publicKey } + .sortedWith(compareBy({ it.createdAt }, { it.kind })) + + private fun MarmotInnerEvent.toEvent() = + Event(id = id, pubKey = publicKey, createdAt = createdAt.epochSeconds, kind = kind, tags = tags, content = content, sig = "") + + 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 (!to.received.add(queued.id)) return@forEach + moved = true + to.db.marmotInnerEventDao().upsert(queued.copy(chatRoomId = adminRoomId)) + FrostSigningManager.processSigningPayload(to.db, to.room, queued.toEvent(), to.publicKey) + } + } + } + } + + private suspend fun propose(by: Device) = FrostSigningManager.proposeSigning( + database = by.db, + localChatRoom = by.room, + userPublicKey = by.publicKey, + kind = 1, + tags = arrayOf(), + content = "Said with the new shares" + ) + + private suspend fun proposalOf(device: Device, sessionId: String) = outbox(device).single { + it.kind == FrostSigningEvents.PROPOSAL && FrostSigningEvents.parseSessionId(it.tags) == sessionId + } + + // ---- Generation 0 ---------------------------------------------------------- + + /** + * Generation 0 has no row: it is read where the ceremony wrote it, with ids + * derived from the ceremony's host keys exactly as signing always derived + * them. If this ever disagrees with the ceremony, every signer lands in the + * wrong slot -- which is why it is derived and not copied. + */ + @Test + fun `generation 0 is the ceremony's, read where the ceremony wrote it`() = runBlocking { + val alice = device(0) + val shares = ShareGenerations.active(alice.db, alice.key()) + + assertEquals(0, shares.generation) + assertEquals(keyMaterial.secretShares[0], shares.secretShare) + assertEquals(keyMaterial.publicShares, shares.publicShares) + assertEquals(members.withIndex().associate { (i, m) -> m to i }, shares.signerIds) + assertEquals(shares.signerIds, shares.participantIds) + assertTrue(ShareGenerations.canSign(alice.db, alice.key())) + } + + @Test + fun `a proposal at generation 0 carries no generation tag`() = runBlocking { + val alice = device(0) + val session = propose(alice) + + assertEquals(0, session.generation) + val proposal = proposalOf(alice, session.id) + assertNull(proposal.tags.firstOrNull { it[0] == FrostGenerationTag.TAG_NAME }, "an older build must read this as it always has") + assertEquals(0, FrostSigningEvents.parseGeneration(proposal.tags)) + } + + // ---- Generation 1 ---------------------------------------------------------- + + @Test + fun `a pending generation signs nothing`() = runBlocking { + val alice = device(0) + refresh(alice, state = ShareGenerationState.PENDING) + + assertNull(ShareGenerations.at(alice.db, alice.key(), 1)) + assertEquals(0, ShareGenerations.active(alice.db, alice.key()).generation) + } + + /** + * The point of the phase: after a refresh the group signs with the new + * shares, and the signature verifies under the room's id, which did not + * move. If signing still read the ceremony's share, Alice's and Bob's + * partial signatures would be checked against public shares they do not + * match, and nothing would aggregate. + */ + @Test + fun `after a refresh the group signs with the new shares, as the same room`() = runBlocking { + val alice = device(0) + val bob = device(1) + refresh(alice) + refresh(bob) + + val session = propose(alice) + assertEquals(1, session.generation) + assertEquals(1, FrostSigningEvents.parseGeneration(proposalOf(alice, session.id).tags)) + + pump(alice, bob) + assertEquals(1, bob.session(session.id)?.generation) + FrostSigningManager.approve(bob.db, bob.room, session.id) + pump(alice, bob) + + listOf(alice, bob).forEach { device -> + assertEquals(FrostSigningStage.COMPLETE, device.session(session.id)?.stage) + val item = device.db.frostSigningSessionDao().getItems(session.id).single() + assertTrue( + Nip01Crypto.verify( + signature = assertNotNull(item.signature).hexToByteArray(), + hash = item.eventId.hexToByteArray(), + pubKey = adminRoomId.hexToByteArray() + ), + "signed with the new shares, the signature is still the room's" + ) + } + } + + /** + * A device that never heard of the refresh holds only the ceremony's share. + * It cannot help, and it says so: a refusal with a reason, which the group + * counts, rather than silence or a partial signature that cannot aggregate. + */ + @Test + fun `a device without the named generation declines out loud`() = runBlocking { + val alice = device(0) + val bob = device(1) + refresh(alice) + // Bob's device missed the refresh: generation 0 only. + + val session = propose(alice) + pump(alice, bob) + + val onBob = assertNotNull(bob.session(session.id)) + assertNotNull(onBob.signDeclinedAt, "Bob's device must refuse rather than wait for an approval it cannot act on") + val decline = outbox(bob).single { it.kind == FrostSigningEvents.DECLINE } + assertEquals(FrostSigningManager.GENERATION_REFUSAL, decline.content) + assertNotNull( + alice.db.frostSigningSessionDao().getMessage(session.id, FrostSigningEvents.DECLINE, bob.publicKey), + "and Alice's device counts it" + ) + } + + /** + * A member withheld from the refresh is stale at generation 1: they keep an + * id, but they are not a signer, and their own device knows it. + */ + @Test + fun `a withheld member is not a signer at the new generation`() = runBlocking { + val alice = device(0) + val carol = device(2) + refresh(alice, withheld = setOf(2)) + refresh(carol, withheld = setOf(2)) + + val onAlice = ShareGenerations.active(alice.db, alice.key()) + assertEquals(setOf(members[0], members[1]), onAlice.signerIds.keys) + assertEquals(2, onAlice.participantIds[members[2]]) + + val onCarol = ShareGenerations.active(carol.db, carol.key()) + assertEquals(1, onCarol.generation) + assertNull(onCarol.secretShare) + assertEquals(false, ShareGenerations.canSign(carol.db, carol.key())) + assertNull(FrostSigningManager.completedKey(carol.db, adminRoomId), "Carol's device must offer nothing it would fail at") + + val session = propose(alice) + pump(alice, carol) + assertEquals(FrostSigningManager.GENERATION_REFUSAL, outbox(carol).single { it.kind == FrostSigningEvents.DECLINE }.content) + } + + /** The refresh by hand is a refresh: the same key, different shares. */ + @Test + fun `the hand-made refresh keeps the key and moves every share`() { + assertTrue(KeyMaterial(keyMaterial.thresholdPublicKey, refreshedSecretShares, refreshedPublicShares, threshold).isValid()) + refreshedSecretShares.forEachIndexed { i, share -> + assertNotEquals(keyMaterial.secretShares[i], share) + assertEquals(refreshedPublicShares[i], share.publicKey()) + } + } +} diff --git a/docs/frost-share-refresh.md b/docs/frost-share-refresh.md index ade3bfdd..c2dfe9f3 100644 --- a/docs/frost-share-refresh.md +++ b/docs/frost-share-refresh.md @@ -15,13 +15,17 @@ ceremony they describe and the rule that a room's id *is* the key it signs with. | phase | commit | checked | |---|---|---| -| 5 | Phase 5 | `SecureDeleteJvmTest` (5, two of them controls that fail without the fix); `jvmTest` 1176/1176; `compileDebugKotlinAndroid`, `processDebugResources` | +| 5 | `4040ae74` | `SecureDeleteJvmTest` (5, two of them controls that fail without the fix); `jvmTest` 1176/1176; `compileDebugKotlinAndroid`, `processDebugResources` | +| 6 | Phase 6 | `ShareGenerationsJvmTest` (7: a real 2-of-3 signature with hand-refreshed shares verifying as the unchanged room, a decline from a device without the generation, a withheld member who is not a signer); every existing signing test unedited; `jvmTest` 1183/1183; `compileDebugKotlinAndroid`; the M3, brand and wallet audits | Where the build chose differently from the plan: | what the plan said | what it turned out to be | |---|---| | Phase 5: a test overwrites a share and finds no copy | three. An overwrite in this schema happens to write the new cell over the old share, so it passed with `secure_delete` off too and proved nothing; a deleted row is the control that fails without it. And `secure_delete` alone leaves the share in `-wal` until a truncating checkpoint, so `GizaDatabase.scrubFreedPages` is part of the fix, with its own control | +| Phase 6: a manual `MIGRATION_37_38` backfills generation 0 into the new tables | no backfill, and no manual migration. Generation 0 stays where the ceremony wrote it, read by `ShareGenerations` with ids derived from the host keys exactly as `signerIds` derived them; rows exist from generation 1 on. A copy of generation 0 would have been a second source of truth for the one fact signing most needs to agree with the ceremony about, and `ShareGenerationsJvmTest` asserts the derivation instead of a copy. The migration is a Room `AutoMigration` | +| Phase 6: a session at a generation this device lacks declines | so does one whose `frost_generation` is present and unreadable, filed at generation -1 so nothing reads it as a share this device holds. A decline's reason is `FrostSigningManager.GENERATION_REFUSAL` | +| Phase 6: (not in the plan) | `DkgSessionDao.getKeyHoldingSessions` now counts a share of any generation, and `completedKey` asks `ShareGenerations.canSign`, so a refreshed key whose ceremony share is wiped is still found -- and a member withheld from the newest refresh is offered nothing to sign. `ShippedProfileUpgradeJvmTest` pins the built version at 38 | | Phase 5: `dataExtractionRules` or `allowBackup="false"` | both. From Android 12 `allowBackup="false"` stops cloud backup but not a device-to-device transfer | ## The headline: enrollment cannot rotate a share From c8a529a17815f19fc8b2f57cdc76c1547d8904c6 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Thu, 19 Nov 2026 23:15:46 +0200 Subject: [PATCH 04/12] build: lightning-kmp-app with FROST share refresh down the chain (frost-share-refresh, Phase 4) e4779ff..3794eb8, every level on a local claude/frost-share-refresh branch: lightning-kmp-app 3794eb8 (e4779ff + this bump) lightning-kmp 2043f254 (df778bc4 + bump) bitcoin-kmp 3cd82d1 (1982eba + bump + FrostRefresh) secp256k1-kmp 0f5a710 (ce05021 + bump + frostRefresh* bindings + tests) secp256k1-zkp 31ea015c (a04dc1ed + the frost_refresh module) None of it is pushed; the pins are to local commits until it is. Giza does not call the refresh yet (Phase 7). compileDebugKotlinAndroid, jvmTest 1183/1183 and the M3, brand and wallet audits pass. Co-Authored-By: Claude Opus 5.5 --- docs/frost-share-refresh.md | 14 +++++++++++++- lightning-kmp-app | 2 +- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/docs/frost-share-refresh.md b/docs/frost-share-refresh.md index c2dfe9f3..26392f51 100644 --- a/docs/frost-share-refresh.md +++ b/docs/frost-share-refresh.md @@ -15,14 +15,26 @@ ceremony they describe and the rule that a room's id *is* the key it signs with. | phase | commit | checked | |---|---|---| +| 1 | zkp `8477b7c1`, `a7c54598`, `e30c8a16`, `31ea015c` | `tests -t=frost_refresh` (vectors, roundtrip n 2..5, withheld, sequential, recovery, faults, binding, params, lengths); full `tests` suite; `ctime_tests` under valgrind (RelWithDebInfo) clean; autotools build. **Not reviewed** (D4) | +| 2 | secp256k1-kmp `7fd0d34`, `8beb781`, `0f5a710` | `:tests:jvmTest` and `:tests:linuxX64Test` 112/112, the zkp vector byte for byte through both backends | +| 3 | bitcoin-kmp `d2e15b8`, `3cd82d1` | `jvmTest` 274/274, including withheld → repaired with `FrostReducedEnrollment` → signs | +| 4 | lightning-kmp `2043f254`, lightning-kmp-app `3794eb8`, Giza Phase 4 | lightning-kmp `crypto` tests 104/104; Giza `compileDebugKotlinAndroid`, `jvmTest` 1183/1183, audits | | 5 | `4040ae74` | `SecureDeleteJvmTest` (5, two of them controls that fail without the fix); `jvmTest` 1176/1176; `compileDebugKotlinAndroid`, `processDebugResources` | -| 6 | Phase 6 | `ShareGenerationsJvmTest` (7: a real 2-of-3 signature with hand-refreshed shares verifying as the unchanged room, a decline from a device without the generation, a withheld member who is not a signer); every existing signing test unedited; `jvmTest` 1183/1183; `compileDebugKotlinAndroid`; the M3, brand and wallet audits | +| 6 | `fce51e20` | `ShareGenerationsJvmTest` (7: a real 2-of-3 signature with hand-refreshed shares verifying as the unchanged room, a decline from a device without the generation, a withheld member who is not a signer); every existing signing test unedited; `jvmTest` 1183/1183; `compileDebugKotlinAndroid`; the M3, brand and wallet audits | + +**Nothing below Giza is pushed.** Each level's work is on a local `claude/frost-share-refresh` +branch (zkp, secp256k1-kmp, bitcoin-kmp, lightning-kmp, lightning-kmp-app), and every parent pins +its child's local commit. A clone of Giza at these commits cannot fetch them until the branches are +pushed bottom up, which waits on an explicit go-ahead. The tracked branches (`main`, `threshold`, +`master`) are untouched. Where the build chose differently from the plan: | what the plan said | what it turned out to be | |---|---| | Phase 5: a test overwrites a share and finds no copy | three. An overwrite in this schema happens to write the new cell over the old share, so it passed with `secure_delete` off too and proved nothing; a deleted row is the control that fails without it. And `secure_delete` alone leaves the share in `-wal` until a truncating checkpoint, so `GizaDatabase.scrubFreedPages` is part of the fix, with its own control | +| Phase 1: the module's C API | adds `secp256k1_frost_refresh_params_parse`, so the bindings carry the parameters as their serialization and parse them in every call, holding nothing between calls. Faults reuse `secp256k1_chilldkg_fault`, with the fault index a position in the recipient list; bitcoin-kmp's `FrostRefreshFault` translates it to an identifier. The round-1 zero-randomness check was variable time, which `ctime_tests` found; it is `secp256k1_is_zero_array` now | +| Phase 1: an investigation procedure | none. A dealt value that does not match the commitments is `UNKNOWN_FAULTY_PARTICIPANT_OR_COORDINATOR` and the session must be abandoned; frost_refresh.md names it as future work | | Phase 6: a manual `MIGRATION_37_38` backfills generation 0 into the new tables | no backfill, and no manual migration. Generation 0 stays where the ceremony wrote it, read by `ShareGenerations` with ids derived from the host keys exactly as `signerIds` derived them; rows exist from generation 1 on. A copy of generation 0 would have been a second source of truth for the one fact signing most needs to agree with the ceremony about, and `ShareGenerationsJvmTest` asserts the derivation instead of a copy. The migration is a Room `AutoMigration` | | Phase 6: a session at a generation this device lacks declines | so does one whose `frost_generation` is present and unreadable, filed at generation -1 so nothing reads it as a share this device holds. A decline's reason is `FrostSigningManager.GENERATION_REFUSAL` | | Phase 6: (not in the plan) | `DkgSessionDao.getKeyHoldingSessions` now counts a share of any generation, and `completedKey` asks `ShareGenerations.canSign`, so a refreshed key whose ceremony share is wiped is still found -- and a member withheld from the newest refresh is offered nothing to sign. `ShippedProfileUpgradeJvmTest` pins the built version at 38 | diff --git a/lightning-kmp-app b/lightning-kmp-app index e4779ffe..3794eb8c 160000 --- a/lightning-kmp-app +++ b/lightning-kmp-app @@ -1 +1 @@ -Subproject commit e4779ffe3076d17931eebfac347378c58427e42f +Subproject commit 3794eb8cbc7f66ecaa87f4f17e3fe5439839d65f From f8974aec815e829f001ebd73861bc08522dc3641 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Thu, 19 Nov 2026 23:25:45 +0200 Subject: [PATCH 05/12] feat: a group rotates its shares, end to end between devices (frost-share-refresh, Phase 7) ShareRefreshManager runs a FROST share refresh in the Marmot room the key derives, on kinds 30340-30345, in the image of ChillDkgRitualManager: every inbound message stored, every step recomputed from stored inputs, nothing of a member's own published before they approve, at two gates (DEAL, CONFIRM). Recipients are at least t and a majority of the ids not retired, and a device confirms one refresh per base generation -- ShareRefreshConfirmation, written in the same transaction as the pending generation it confirms -- so two refreshes from one generation cannot both complete. The certificate activates the new generation; a withheld device learns its table from the recovery data and files it with no share. Schema 39 (AutoMigration): ShareRefreshSession, ShareRefreshMessage, ShareRefreshConfirmation. Transcript lines as system lines; dispatch in the Marmot inbound path. ShareRefreshRitualJvmTest: three devices with real host keys refresh through bitcoin-kmp's FrostRefresh and then sign at generation 1 as the same room. jvmTest 1190/1190, compileDebugKotlinAndroid, audits. Co-Authored-By: Claude Opus 5.5 --- .../39.json | 4974 +++++++++++++++++ .../giza/compose/database/GizaDatabase.kt | 15 +- .../giza/compose/database/dao/NostrDao.kt | 13 + .../compose/database/dao/ShareRefreshDao.kt | 81 + .../compose/database/model/ChatMessage.kt | 37 +- .../model/ShareRefreshConfirmation.kt | 26 + .../database/model/ShareRefreshMessage.kt | 37 + .../database/model/ShareRefreshSession.kt | 117 + .../model/intermdiate/LocalChatRoom.kt | 2 + .../model/types/ShareRefreshApprovalStep.kt | 21 + .../database/model/types/ShareRefreshStage.kt | 19 + .../giza/compose/managers/ShareGenerations.kt | 28 +- .../compose/managers/ShareRefreshManager.kt | 674 +++ .../compose/nostr/frost/ShareRefreshEvents.kt | 98 + .../composable/widgets/chat/ChatTranscript.kt | 15 + .../ShippedProfileUpgradeJvmTest.kt | 9 +- .../managers/ShareRefreshRitualJvmTest.kt | 304 + docs/frost-share-refresh.md | 4 + 18 files changed, 6462 insertions(+), 12 deletions(-) create mode 100644 composeApp/schemas/mobi.giza.compose.database.GizaDatabase/39.json create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRefreshDao.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRefreshConfirmation.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRefreshMessage.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRefreshSession.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareRefreshApprovalStep.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareRefreshStage.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/ShareRefreshEvents.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt diff --git a/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/39.json b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/39.json new file mode 100644 index 00000000..f9dc2458 --- /dev/null +++ b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/39.json @@ -0,0 +1,4974 @@ +{ + "formatVersion": 1, + "database": { + "version": 39, + "identityHash": "789f1386afecf65498e83e6297995a88", + "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, `walletPolicy` 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": "walletPolicy", + "columnName": "walletPolicy", + "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, 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" + } + ], + "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, `generation` INTEGER, `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": "generation", + "columnName": "generation", + "affinity": "INTEGER" + }, + { + "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, `generation` INTEGER, `publicSharesHash` 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": "generation", + "columnName": "generation", + "affinity": "INTEGER" + }, + { + "fieldPath": "publicSharesHash", + "columnName": "publicSharesHash", + "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": "KeyShareGeneration", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`dkgSessionId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `secretShare` TEXT, `publicShares` TEXT NOT NULL, `state` TEXT NOT NULL, `refreshSessionId` TEXT, `recoveryData` TEXT, `activatedAt` INTEGER, `wipedAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`dkgSessionId`, `generation`), FOREIGN KEY(`dkgSessionId`) REFERENCES `DkgSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "secretShare", + "columnName": "secretShare", + "affinity": "TEXT" + }, + { + "fieldPath": "publicShares", + "columnName": "publicShares", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "state", + "columnName": "state", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "refreshSessionId", + "columnName": "refreshSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryData", + "columnName": "recoveryData", + "affinity": "TEXT" + }, + { + "fieldPath": "activatedAt", + "columnName": "activatedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "wipedAt", + "columnName": "wipedAt", + "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 + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "dkgSessionId", + "generation" + ] + }, + "indices": [ + { + "name": "index_KeyShareGeneration_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_KeyShareGeneration_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "DkgSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "dkgSessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "KeyShareMember", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`dkgSessionId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `participantId` INTEGER NOT NULL, `memberPublicKey` TEXT NOT NULL, `hostPublicKey` TEXT NOT NULL, `standing` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`dkgSessionId`, `generation`, `participantId`), FOREIGN KEY(`dkgSessionId`, `generation`) REFERENCES `KeyShareGeneration`(`dkgSessionId`, `generation`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantId", + "columnName": "participantId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "memberPublicKey", + "columnName": "memberPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "hostPublicKey", + "columnName": "hostPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "standing", + "columnName": "standing", + "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": false, + "columnNames": [ + "dkgSessionId", + "generation", + "participantId" + ] + }, + "indices": [ + { + "name": "index_KeyShareMember_dkgSessionId_generation", + "unique": false, + "columnNames": [ + "dkgSessionId", + "generation" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_KeyShareMember_dkgSessionId_generation` ON `${TABLE_NAME}` (`dkgSessionId`, `generation`)" + } + ], + "foreignKeys": [ + { + "table": "KeyShareGeneration", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "dkgSessionId", + "generation" + ], + "referencedColumns": [ + "dkgSessionId", + "generation" + ] + } + ] + }, + { + "tableName": "ShareRefreshConfirmation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`dkgSessionId` TEXT NOT NULL, `baseGeneration` INTEGER NOT NULL, `refreshSessionId` TEXT NOT NULL, `confirmedAt` INTEGER NOT NULL, PRIMARY KEY(`dkgSessionId`, `baseGeneration`))", + "fields": [ + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "baseGeneration", + "columnName": "baseGeneration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "refreshSessionId", + "columnName": "refreshSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "confirmedAt", + "columnName": "confirmedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "dkgSessionId", + "baseGeneration" + ] + } + }, + { + "tableName": "ShareRefreshMessage", + "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, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `participantPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `ShareRefreshSession`(`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 + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "participantPublicKey", + "kind" + ] + }, + "foreignKeys": [ + { + "table": "ShareRefreshSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ShareRefreshSession", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `baseGeneration` INTEGER NOT NULL, `recipientIds` TEXT NOT NULL, `withheld` TEXT, `stage` TEXT NOT NULL, `round1Random` TEXT NOT NULL, `auxRandom` TEXT NOT NULL, `dealApprovedAt` INTEGER, `confirmApprovedAt` INTEGER, `approvalRequestedThrough` TEXT, `coordinatorRound1` TEXT, `certificate` TEXT, `failureReason` 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": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorPublicKey", + "columnName": "coordinatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "baseGeneration", + "columnName": "baseGeneration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recipientIds", + "columnName": "recipientIds", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "withheld", + "columnName": "withheld", + "affinity": "TEXT" + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "round1Random", + "columnName": "round1Random", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "auxRandom", + "columnName": "auxRandom", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dealApprovedAt", + "columnName": "dealApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "confirmApprovedAt", + "columnName": "confirmApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequestedThrough", + "columnName": "approvalRequestedThrough", + "affinity": "TEXT" + }, + { + "fieldPath": "coordinatorRound1", + "columnName": "coordinatorRound1", + "affinity": "TEXT" + }, + { + "fieldPath": "certificate", + "columnName": "certificate", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "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_ShareRefreshSession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ShareRefreshSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_ShareRefreshSession_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ShareRefreshSession_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "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": "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, `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": "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": "MarmotSenderRatchet", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `epoch` INTEGER NOT NULL, `leafIndex` INTEGER NOT NULL, `applicationGeneration` INTEGER NOT NULL, `record` BLOB 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": "epoch", + "columnName": "epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "leafIndex", + "columnName": "leafIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "applicationGeneration", + "columnName": "applicationGeneration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "record", + "columnName": "record", + "affinity": "BLOB", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId" + ] + }, + "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, '789f1386afecf65498e83e6297995a88')" + ] + } +} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt index eca9b7a1..a2cbd810 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt @@ -25,6 +25,7 @@ import mobi.giza.compose.database.dao.GroupKeyStateDao import mobi.giza.compose.database.dao.GroupSignedEventDao import mobi.giza.compose.database.dao.InReplyToRelationDao import mobi.giza.compose.database.dao.KeyShareDao +import mobi.giza.compose.database.dao.ShareRefreshDao import mobi.giza.compose.database.dao.MarmotCommitResultDao import mobi.giza.compose.database.dao.MarmotOutboundDao import mobi.giza.compose.database.dao.MarmotGroupEventDao @@ -68,6 +69,9 @@ import mobi.giza.compose.database.model.GiftWrapSeal import mobi.giza.compose.database.model.GroupKeyState import mobi.giza.compose.database.model.KeyShareGeneration import mobi.giza.compose.database.model.KeyShareMember +import mobi.giza.compose.database.model.ShareRefreshConfirmation +import mobi.giza.compose.database.model.ShareRefreshMessage +import mobi.giza.compose.database.model.ShareRefreshSession import mobi.giza.compose.database.model.GroupSignedEvent import mobi.giza.compose.database.model.InReplyToRelation import mobi.giza.compose.database.model.MarmotCommitResult @@ -129,6 +133,9 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) GroupSignedEvent::class, KeyShareGeneration::class, KeyShareMember::class, + ShareRefreshConfirmation::class, + ShareRefreshMessage::class, + ShareRefreshSession::class, InReplyToRelation::class, MarmotCommitResult::class, MarmotGroupEvent::class, @@ -158,7 +165,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) UnsignedNostrEvent::class, Zap::class ], - version = 38, + version = 39, autoMigrations = [ // v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can // generate the migration itself — nothing existing changes shape. @@ -407,6 +414,10 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) // nullable columns, so Room generates it. Nothing is backfilled: generation 0 // stays where the ceremony put it, and a null generation reads as 0. AutoMigration(from = 37, to = 38), + // v39 adds share refresh (docs/frost-share-refresh.md, Phase 7): the + // ShareRefreshSession, ShareRefreshMessage and ShareRefreshConfirmation + // tables. Three new tables, so Room generates it. + AutoMigration(from = 38, to = 39), ] ) @ConstructedBy(GizaDatabaseConstructor::class) @@ -441,6 +452,8 @@ abstract class GizaDatabase: RoomDatabase() { abstract fun keyShareDao(): KeyShareDao + abstract fun shareRefreshDao(): ShareRefreshDao + abstract fun groupSignedEventDao(): GroupSignedEventDao diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt index 2c056f04..2fc470bd 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt @@ -61,6 +61,7 @@ import mobi.giza.compose.exceptions.MarmotMissingNostrGroupDataExtension import mobi.giza.compose.exceptions.MarmotNotMemberOfChatGroupException import mobi.giza.compose.extensions.toHex import mobi.giza.compose.managers.ChillDkgRitualManager +import mobi.giza.compose.managers.ShareRefreshManager import mobi.giza.compose.managers.CommitOrdering import mobi.giza.compose.managers.FrostSigningManager import mobi.giza.compose.managers.GroupKeyStateManager @@ -76,6 +77,7 @@ import mobi.giza.compose.managers.routingId import mobi.giza.compose.nostr.MarmotProfile import mobi.giza.compose.nostr.Relays import mobi.giza.compose.nostr.dkg.DkgRitualEvents +import mobi.giza.compose.nostr.frost.ShareRefreshEvents import mobi.giza.compose.nostr.frost.FrostSigningEvents @Dao @@ -1605,6 +1607,17 @@ abstract class NostrDao( nostrPrivateKey = activeKeyPair.privKey!! ) + // A share refresh runs in the room its key derives, and + // nowhere else (docs/frost-share-refresh.md, D7). + ShareRefreshEvents.isShareRefreshKind(innerEvent.kind) -> + ShareRefreshManager.processRefreshPayload( + database = database, + localChatRoom = localChatRoom, + innerEvent = innerEvent, + userPublicKey = activeKeyPair.pubKey.toHex(), + nostrPrivateKey = activeKeyPair.privKey!! + ) + // Nothing for the group Lightning wallet's kinds: Giza takes no // part in it, so a Bennu member's ceremony, co-signing and node // traffic are filed and ignored. docs/giza-wallet-removal.md. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRefreshDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRefreshDao.kt new file mode 100644 index 00000000..eefbf601 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRefreshDao.kt @@ -0,0 +1,81 @@ +package mobi.giza.compose.database.dao + +import androidx.room3.Dao +import androidx.room3.Insert +import androidx.room3.OnConflictStrategy +import androidx.room3.Query +import androidx.room3.Transaction +import androidx.room3.Upsert +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import kotlinx.coroutines.flow.Flow +import mobi.giza.compose.database.model.KeyShareGeneration +import mobi.giza.compose.database.model.KeyShareMember +import mobi.giza.compose.database.model.ShareRefreshConfirmation +import mobi.giza.compose.database.model.ShareRefreshMessage +import mobi.giza.compose.database.model.ShareRefreshSession + +/** Share refreshes (docs/frost-share-refresh.md, Phase 7). Read through `ShareRefreshManager`. */ +@Dao +abstract class ShareRefreshDao { + @Query("SELECT * FROM ShareRefreshSession WHERE id = :id") + abstract suspend fun getSessionById(id: String): ShareRefreshSession? + + @Query("SELECT * FROM ShareRefreshSession WHERE id = :id") + abstract fun observeSessionById(id: String): Flow + + /** The refreshes of one key, newest first. */ + @Query("SELECT * FROM ShareRefreshSession WHERE dkgSessionId = :dkgSessionId ORDER BY createdAt DESC") + abstract suspend fun getSessionsForKey(dkgSessionId: String): List + + @Query("SELECT * FROM ShareRefreshSession WHERE chatRoomId = :chatRoomId ORDER BY createdAt DESC") + abstract fun observeSessionsForRoom(chatRoomId: String): Flow> + + @Upsert + abstract suspend fun upsert(session: ShareRefreshSession) + + @Upsert + abstract suspend fun upsert(message: ShareRefreshMessage) + + @Query("SELECT * FROM ShareRefreshMessage WHERE sessionId = :sessionId AND kind = :kind") + abstract suspend fun getMessagesByKind(sessionId: String, kind: Kind): List + + @Query("SELECT * FROM ShareRefreshMessage WHERE sessionId = :sessionId AND kind = :kind AND participantPublicKey = :participantPublicKey") + abstract suspend fun getMessage(sessionId: String, kind: Kind, participantPublicKey: HexKey): ShareRefreshMessage? + + /** Never replaces: the first confirmation from a generation is the only one. */ + @Insert(onConflict = OnConflictStrategy.IGNORE) + protected abstract suspend fun insertConfirmation(confirmation: ShareRefreshConfirmation) + + @Query("SELECT * FROM ShareRefreshConfirmation WHERE dkgSessionId = :dkgSessionId AND baseGeneration = :baseGeneration") + abstract suspend fun getConfirmation(dkgSessionId: String, baseGeneration: Int): ShareRefreshConfirmation? + + @Upsert + protected abstract suspend fun upsertGeneration(generation: KeyShareGeneration) + + @Upsert + protected abstract suspend fun upsertMembers(members: List) + + /** + * Claims this device's one confirmation from [confirmation]'s base generation + * for [confirmation]'s refresh, and stores the new generation with it -- both + * or neither, so a confirmation never goes out for a share that is not on disk + * and a share is never stored for a refresh this device did not confirm. + * + * Returns the refresh that holds the claim. When it is not this one, nothing + * was written and the caller must not confirm. + */ + @Transaction + open suspend fun confirmAndStore( + confirmation: ShareRefreshConfirmation, + generation: KeyShareGeneration, + members: List, + ): String { + insertConfirmation(confirmation) + val holder = getConfirmation(confirmation.dkgSessionId, confirmation.baseGeneration)?.refreshSessionId + if (holder != confirmation.refreshSessionId) return holder.orEmpty() + upsertGeneration(generation) + upsertMembers(members) + return confirmation.refreshSessionId + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt index f6d282d7..670b3bf4 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt @@ -38,6 +38,7 @@ import mobi.giza.compose.nostr.MarmotDirectMessage import mobi.giza.compose.nostr.chronicle.ChronicleEvent import mobi.giza.compose.nostr.chronicle.ChronicleRequestEvent import mobi.giza.compose.nostr.dkg.DkgRitualEvents +import mobi.giza.compose.nostr.frost.ShareRefreshEvents import mobi.giza.compose.nostr.frost.FrostSigningEvents import mobi.giza.compose.nostr.frost.GroupKeyStateEvent import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent @@ -229,6 +230,35 @@ data class ChatMessage( TYPE_DKG_APPROVAL_NEEDED_LEGACY, ) + /** + * A share refresh, as lines in the group's chat (docs/frost-share-refresh.md, + * Phase 7). Not anybody's words, so drawn as system lines; the step lines name + * the member whose device took the step, the request line is addressed to the + * reader, and the last two report. + */ + const val TYPE_SHARE_REFRESH_STARTED = "shareRefreshStarted" + const val TYPE_SHARE_REFRESH_DEALT = "shareRefreshDealt" + const val TYPE_SHARE_REFRESH_CONFIRMED = "shareRefreshConfirmed" + const val TYPE_SHARE_REFRESH_APPROVAL_NEEDED = "shareRefreshApprovalNeeded" + const val TYPE_SHARE_REFRESH_COMPLETE = "shareRefreshComplete" + const val TYPE_SHARE_REFRESH_FAILED = "shareRefreshFailed" + + val SHARE_REFRESH_TYPES = setOf( + TYPE_SHARE_REFRESH_STARTED, + TYPE_SHARE_REFRESH_DEALT, + TYPE_SHARE_REFRESH_CONFIRMED, + TYPE_SHARE_REFRESH_APPROVAL_NEEDED, + TYPE_SHARE_REFRESH_COMPLETE, + TYPE_SHARE_REFRESH_FAILED, + ) + + /** The share refresh lines a named member's device did. */ + val SHARE_REFRESH_AUTHORED_TYPES = setOf( + TYPE_SHARE_REFRESH_STARTED, + TYPE_SHARE_REFRESH_DEALT, + TYPE_SHARE_REFRESH_CONFIRMED, + ) + val DKG_TYPES = setOf( TYPE_DKG_STARTED, TYPE_DKG_HOST_KEY, @@ -840,7 +870,8 @@ data class ChatMessage( val isDirectMessageEnvelope = MarmotDirectMessage.wrapInside(event) != null val isProtocolMessage = !isDirectMessageEnvelope && ( event.kind in DkgRitualEvents.ALL || - event.kind in FrostSigningEvents.ALL + event.kind in FrostSigningEvents.ALL || + event.kind in ShareRefreshEvents.ALL ) database.marmotInnerEventDao().upsert( @@ -1110,6 +1141,10 @@ data class ChatMessage( // none of their business. in DkgRitualEvents.ALL -> null + // A share refresh's protocol messages. `ShareRefreshManager` + // applies them and writes the lines that report them. + in ShareRefreshEvents.ALL -> null + ChatEvent.KIND -> { ChatMessage( giftWrapPayloadId = null, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRefreshConfirmation.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRefreshConfirmation.kt new file mode 100644 index 00000000..488d55c3 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRefreshConfirmation.kt @@ -0,0 +1,26 @@ +package mobi.giza.compose.database.model + +import androidx.room3.Entity +import kotlin.time.Clock +import kotlin.time.Instant + +/** + * The one refresh this device has confirmed from one generation of one key. + * Written once, before the confirmation goes out, and never replaced. + * + * This is the rule that keeps a group from splitting (docs/frost-share-refresh.md, + * D3a). Two refreshes from the same generation with different recipients could + * both complete -- each making a different next generation, and the group able + * to sign with neither. A certificate needs every recipient's confirmation, and + * recipients are a majority, so any two recipient sets share a member; that + * member confirming only one is what leaves the other without a certificate. + * It matters for the same reason the nonce rules on `FrostSigningSession` do: + * it is the one way the whole thing is lost. + */ +@Entity(primaryKeys = ["dkgSessionId", "baseGeneration"]) +data class ShareRefreshConfirmation( + val dkgSessionId: String, + val baseGeneration: Int, + val refreshSessionId: String, + val confirmedAt: Instant = Clock.System.now(), +) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRefreshMessage.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRefreshMessage.kt new file mode 100644 index 00000000..84050c8d --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRefreshMessage.kt @@ -0,0 +1,37 @@ +package mobi.giza.compose.database.model + +import androidx.room3.Entity +import androidx.room3.ForeignKey +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import kotlin.time.Clock +import kotlin.time.Instant +import mobi.giza.compose.database.model.traits.LocalStoreEntity +import mobi.giza.compose.database.model.traits.TimestampedEntity + +/** + * One recipient's round-1 or round-2 message in a share refresh. Keyed on + * (session, sender, kind) like `DkgParticipantMessage`, so a redelivery + * replaces rather than adds: a round advances on the count reaching the + * recipients, and a second row per sender would get it there early. + */ +@Entity( + primaryKeys = ["sessionId", "participantPublicKey", "kind"], + foreignKeys = [ + ForeignKey( + entity = ShareRefreshSession::class, + parentColumns = ["id"], + childColumns = ["sessionId"], + onDelete = ForeignKey.CASCADE, + ) + ], +) +data class ShareRefreshMessage( + val sessionId: String, + val participantPublicKey: HexKey, + val kind: Kind, + val payload: String, + override val createdAt: Instant = Clock.System.now(), + override val updatedAt: Instant = createdAt, + override val savedAt: Instant = createdAt, +) : TimestampedEntity, LocalStoreEntity diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRefreshSession.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRefreshSession.kt new file mode 100644 index 00000000..a7478251 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRefreshSession.kt @@ -0,0 +1,117 @@ +package mobi.giza.compose.database.model + +import androidx.room3.Entity +import androidx.room3.ForeignKey +import androidx.room3.Index +import androidx.room3.PrimaryKey +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlin.time.Clock +import kotlin.time.Instant +import mobi.giza.compose.database.model.traits.LocalStoreEntity +import mobi.giza.compose.database.model.traits.TimestampedEntity +import mobi.giza.compose.database.model.types.ShareRefreshApprovalStep +import mobi.giza.compose.database.model.types.ShareRefreshStage +import mobi.giza.compose.database.model.types.ShareStanding + +/** + * One share refresh of a group's key, as this device holds it + * (docs/frost-share-refresh.md, Phase 7). + * + * Like `DkgSession`, it stores inputs rather than protocol state: the + * randomness, the received messages and the two aggregates. Every step is a + * pure function of them, so a refresh survives the app being killed halfway + * and resumes on the next message. + */ +@Entity( + foreignKeys = [ + ForeignKey( + entity = ChatRoom::class, + parentColumns = ["id"], + childColumns = ["chatRoomId"], + onDelete = ForeignKey.CASCADE, + ) + ], + indices = [ + Index("chatRoomId"), + Index("dkgSessionId"), + ], +) +data class ShareRefreshSession( + /** The refresh id: 32 bytes hex, chosen by the proposer, bound into every message. */ + @PrimaryKey + val id: String, + + /** The Marmot room the refresh runs in, whose id the key derives. */ + val chatRoomId: String, + + /** The ceremony whose key is being refreshed. */ + val dkgSessionId: String, + + /** Who proposed it, and so who sums and certifies. A recipient, and untrusted like any coordinator. */ + val coordinatorPublicKey: HexKey, + + /** Whose device this row belongs to. */ + val userPublicKey: HexKey, + + /** The generation being refreshed. The refresh makes `baseGeneration + 1`. */ + val baseGeneration: Int, + + /** The recipients' participant ids, ascending, comma separated. Every one deals and confirms. */ + val recipientIds: String, + + /** + * The participant ids dealt nothing, and what each becomes, as `id:STANDING` + * comma separated -- `2:STALE` to be repaired later, `2:RETIRED` for good. + * Null when nobody is withheld. + */ + val withheld: String? = null, + + val stage: ShareRefreshStage = ShareRefreshStage.COLLECTING_ROUND_1, + + /** Secret. Round 1's fresh randomness. Kept because round 1 is pure in it. */ + val round1Random: HexKey, + + /** Secret-adjacent. Round 2's auxiliary randomness for the confirmation's signature. */ + val auxRandom: HexKey, + + val dealApprovedAt: Instant? = null, + val confirmApprovedAt: Instant? = null, + + /** The furthest step this device has asked its owner about, so the request line is written once. */ + val approvalRequestedThrough: ShareRefreshApprovalStep? = null, + + /** The coordinator's sum (cmsg1), hex, once it arrives. */ + val coordinatorRound1: HexKey? = null, + + /** The certificate (cmsg2), hex, once it arrives. */ + val certificate: HexKey? = null, + + val failureReason: String? = null, + + override val createdAt: Instant = Clock.System.now(), + override val updatedAt: Instant = createdAt, + override val savedAt: Instant = createdAt, +) : TimestampedEntity, LocalStoreEntity { + fun recipientIdList(): List = recipientIds.split(",").mapNotNull { it.trim().toIntOrNull() } + + fun withheldStandings(): Map = withheld.orEmpty() + .split(",") + .mapNotNull { entry -> + val (id, standing) = entry.split(":").takeIf { it.size == 2 } ?: return@mapNotNull null + val standingValue = ShareStanding.entries.firstOrNull { it.name == standing.trim().uppercase() } ?: return@mapNotNull null + id.trim().toIntOrNull()?.let { it to standingValue } + } + .toMap() + + fun isCoordinator(): Boolean = coordinatorPublicKey == userPublicKey + + override fun toString(): String = + "ShareRefreshSession(id=$id, key=$dkgSessionId, base=$baseGeneration, stage=$stage, recipients=$recipientIds, withheld=$withheld)" + + companion object { + fun formatIds(ids: Collection): String = ids.sorted().joinToString(",") + + fun formatWithheld(withheld: Map): String? = + withheld.takeIf { it.isNotEmpty() }?.entries?.sortedBy { it.key }?.joinToString(",") { "${it.key}:${it.value.name}" } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/intermdiate/LocalChatRoom.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/intermdiate/LocalChatRoom.kt index 9bb2374c..f819dfcc 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/intermdiate/LocalChatRoom.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/intermdiate/LocalChatRoom.kt @@ -140,12 +140,14 @@ data class LocalChatRoom( if (lastChatMessage.messageType in ChatMessage.DKG_TYPES || lastChatMessage.messageType in ChatMessage.FROST_TYPES || + lastChatMessage.messageType in ChatMessage.SHARE_REFRESH_TYPES || lastChatMessage.messageType in ChatMessage.CHRONICLE_TYPES || lastChatMessage.messageType in ChatMessage.MEMBERSHIP_TYPES || lastChatMessage.messageType in ChatMessage.SUBGROUP_TYPES || lastChatMessage.messageType in ChatMessage.GROUP_IDENTITY_TYPES ) { val isAuthored = lastChatMessage.messageType in ChatMessage.DKG_AUTHORED_TYPES || + lastChatMessage.messageType in ChatMessage.SHARE_REFRESH_AUTHORED_TYPES || lastChatMessage.messageType in ChatMessage.FROST_AUTHORED_TYPES return if (isAuthored) { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareRefreshApprovalStep.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareRefreshApprovalStep.kt new file mode 100644 index 00000000..e871ce94 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareRefreshApprovalStep.kt @@ -0,0 +1,21 @@ +package mobi.giza.compose.database.model.types + +/** + * The two decisions a recipient makes in a share refresh. Each publishes + * something different and commits the member to something different. + */ +enum class ShareRefreshApprovalStep { + /** + * Deal round 1: join the refresh, and agree to the withheld list. Withholding + * someone takes their signing away, so every recipient decides it, not only + * the proposer. + */ + DEAL, + + /** + * Confirm round 2: store the new generation and say so. This is what stops a + * coordinator substituting a table the recipients never dealt, and the one + * confirmation per base generation this device will ever give. + */ + CONFIRM, +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareRefreshStage.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareRefreshStage.kt new file mode 100644 index 00000000..a00481e8 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareRefreshStage.kt @@ -0,0 +1,19 @@ +package mobi.giza.compose.database.model.types + +/** + * How far a share refresh has got on this device (docs/frost-share-refresh.md, + * Phase 7). Declaration order is the ladder. + */ +enum class ShareRefreshStage { + /** Proposed; waiting on every recipient's round-1 message, or on this device's owner to deal. */ + COLLECTING_ROUND_1, + + /** The coordinator's sum is in; waiting on every recipient's confirmation, or on this device's owner to confirm. */ + COLLECTING_ROUND_2, + + /** The certificate verified: the new generation is the one the group signs with. */ + COMPLETE, + + /** Abandoned. See `ShareRefreshSession.failureReason`. */ + FAILED, +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareGenerations.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareGenerations.kt index 15bf2a79..e8b6fc1b 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareGenerations.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareGenerations.kt @@ -40,12 +40,22 @@ object ShareGenerations { val publicShares: List?, val signerIds: Map, val participantIds: Map, + /** Every participant id of the key in order, retired ones included: who holds it, their host key, and what they hold. */ + val roster: List = emptyList(), ) { override fun toString(): String = "Shares(generation=$generation, secretShare=${if (secretShare == null) "null" else ""}, " + "signers=${signerIds.size}/${participantIds.size})" } + /** One participant id at one generation. */ + data class RosterEntry( + val participantId: Int, + val memberPublicKey: HexKey, + val hostPublicKey: HexKey, + val standing: ShareStanding, + ) + /** * The generation the group signs with, by this device's account: the newest * active one, or the ceremony's while there has been no refresh. @@ -79,7 +89,7 @@ object ShareGenerations { /** [member]'s participant id in [key], whatever their standing. */ suspend fun participantIdOf(database: GizaDatabase, key: DkgSession, member: HexKey): Int? = - active(database, key).participantIds[member] ?: ceremonyIds(database, key)[member] + active(database, key).participantIds[member] ?: ceremonyIds(ceremonyHostKeys(database, key))[member] /** * Generation 0: the ceremony's own output, read where the ceremony wrote it. @@ -91,28 +101,33 @@ object ShareGenerations { * the ceremony that made the key. */ private suspend fun ceremony(database: GizaDatabase, key: DkgSession): Shares { - val ids = ceremonyIds(database, key) + val hostKeys = ceremonyHostKeys(database, key) + val ids = ceremonyIds(hostKeys) return Shares( generation = 0, secretShare = key.secretShare?.let { PrivateKey(ByteVector32(it)) }, publicShares = key.publicShareList(), signerIds = ids, participantIds = ids, + roster = ids.entries + .sortedBy { it.value } + .map { (member, id) -> RosterEntry(id, member, hostKeys.getValue(member), ShareStanding.LIVE) }, ) } - private suspend fun ceremonyIds(database: GizaDatabase, key: DkgSession): Map { - val hostKeys = database.dkgSessionDao() + private suspend fun ceremonyHostKeys(database: GizaDatabase, key: DkgSession): Map = + database.dkgSessionDao() .getMessagesByKind(key.id, DkgRitualEvents.HOST_KEY) .associate { it.participantPublicKey to it.payload.lowercase() } + private fun ceremonyIds(hostKeys: Map): Map { val order = hostKeys.values.sorted() - return hostKeys.mapNotNull { (member, hostKey) -> order.indexOf(hostKey).takeIf { it >= 0 }?.let { member to it } }.toMap() } + private suspend fun fromRow(database: GizaDatabase, row: KeyShareGeneration): Shares { val members = database.keyShareDao().getMembers(row.dkgSessionId, row.generation) return Shares( @@ -127,6 +142,9 @@ object ShareGenerations { participantIds = members .filter { it.standing != ShareStanding.RETIRED } .associate { it.memberPublicKey to it.participantId }, + roster = members + .sortedBy { it.participantId } + .map { RosterEntry(it.participantId, it.memberPublicKey, it.hostPublicKey.lowercase(), it.standing) }, ) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt new file mode 100644 index 00000000..b2c9557c --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt @@ -0,0 +1,674 @@ +package mobi.giza.compose.managers + +import co.touchlab.kermit.Logger +import com.vitorpamplona.crypto.random.RandomInstance +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.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.ByteVector64 +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.PublicKey +import fr.acinq.bitcoin.crypto.frost.FrostRefresh +import fr.acinq.bitcoin.crypto.frost.FrostRefreshFault +import fr.acinq.bitcoin.crypto.frost.FrostRefreshParams +import fr.acinq.secp256k1.ChilldkgFault +import kotlin.time.Clock +import kotlin.time.Instant +import kotlinx.coroutines.CancellationException +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.DkgSession +import mobi.giza.compose.database.model.KeyShareGeneration +import mobi.giza.compose.database.model.KeyShareMember +import mobi.giza.compose.database.model.MarmotInnerEvent +import mobi.giza.compose.database.model.ShareRefreshConfirmation +import mobi.giza.compose.database.model.ShareRefreshMessage +import mobi.giza.compose.database.model.ShareRefreshSession +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.database.model.types.DkgRitualStage +import mobi.giza.compose.database.model.types.ShareGenerationState +import mobi.giza.compose.database.model.types.ShareRefreshApprovalStep +import mobi.giza.compose.database.model.types.ShareRefreshStage +import mobi.giza.compose.database.model.types.ShareStanding +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.frost.ShareRefreshEvents + +/** + * Rotates a group's shares: every recipient gets a new share of the same key, so + * the shares from before stop combining with the shares after + * (docs/frost-share-refresh.md, Phase 7). + * + * Built in the image of [ChillDkgRitualManager]. Every inbound message is stored + * and then the refresh is asked whether it can move; every step is a pure + * function of stored inputs, so an app killed halfway resumes on the next + * message. It runs in the Marmot room whose id the key derives (D7) and travels + * as that room's inner events: the dealt values are encrypted to host keys by the + * protocol, so a message the whole room can read discloses nothing. + * + * Three rules hold the group together, and each is checked on proposal and on + * arrival: + * - **Recipients are at least t, and more than half the ids not retired** (D3b), + * so any two refreshes from one generation share a recipient. + * - **A device confirms at most one refresh per base generation** (D3a), so that + * shared recipient leaves at most one with a certificate. + * [ShareRefreshConfirmation] is the write-once claim. + * - **Every recipient takes part** (D2). A certificate needs them all; anyone + * who cannot is withheld, and repaired later. + * + * Nothing of this device's own goes out without its owner's approval, at two + * gates ([ShareRefreshApprovalStep]). [pendingApproval] mirrors them. + */ +object ShareRefreshManager { + private val logger = Logger.withTag("ShareRefreshManager") + + // ---- refusals ---------------------------------------------------------------------------------------------- + + /** + * Why a refresh of [key] from [shares] with these recipients and withheld ids + * must not run, or null when it can. + */ + fun refusal(key: DkgSession, shares: ShareGenerations.Shares, recipients: List, withheld: Map): String? { + val roster = shares.roster + if (roster.isEmpty() || shares.publicShares == null) return "this key has no public shares to refresh" + val notRetired = roster.filter { it.standing != ShareStanding.RETIRED }.map { it.participantId }.toSet() + val live = roster.filter { it.standing == ShareStanding.LIVE }.map { it.participantId }.toSet() + if (recipients.isEmpty() || recipients != recipients.sorted() || recipients.toSet().size != recipients.size) { + return "the recipients are not a set" + } + if (!live.containsAll(recipients)) return "a recipient holds no share of generation ${shares.generation}" + if (withheld.keys.any { it in recipients }) return "a participant is both a recipient and withheld" + if ((recipients.toSet() + withheld.keys) != notRetired) { + return "every participant who is not retired has to be a recipient or withheld" + } + if (withheld.values.any { it == ShareStanding.LIVE }) return "a withheld participant cannot stay live" + if (recipients.size < key.threshold) { + return "${recipients.size} recipients cannot carry a ${key.threshold}-of-${key.participantCount} key" + } + if (recipients.size * 2 <= notRetired.size) { + return "${recipients.size} of ${notRetired.size} is not a majority, so two such refreshes could both complete" + } + return null + } + + /** Whether [localChatRoom] is the room [key] signs as: its key state names the key, or its id derives from it. */ + private suspend fun isKeysRoom(database: GizaDatabase, localChatRoom: LocalChatRoom, key: DkgSession): Boolean { + if (localChatRoom.chatRoom.mlsGroupState == null) return false + val roomId = localChatRoom.chatRoom.id + if (GroupKeyStateManager.keyStateFor(database, roomId)?.dkgSessionId == key.id) return true + val thresholdPublicKey = key.thresholdPublicKey ?: return false + return SharedKeyDerivation.marmotGroupId(thresholdPublicKey) == roomId + } + + // ---- proposing ------------------------------------------------------------------------------------------------ + + /** + * Opens a refresh of [key], making this device the coordinator. Every live + * participant not in [withheld] is a recipient. + * + * The proposer is auto-approved for nothing: proposing a refresh is not + * agreeing to withhold whomever the form defaulted to, so it is asked at both + * gates like everyone else. + */ + suspend fun proposeRefresh( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + nostrPrivateKey: ByteArray, + key: DkgSession, + withheld: Map = emptyMap(), + ): ShareRefreshSession { + require(key.stage == DkgRitualStage.COMPLETE) { "Ceremony ${key.id} has not produced a key" } + require(isKeysRoom(database, localChatRoom, key)) { "${localChatRoom.chatRoom.id} is not the room key ${key.id} signs as" } + + running(database, key)?.let { return it } + + val shares = ShareGenerations.active(database, key) + requireNotNull(shares.secretShare) { "This device holds no share of generation ${shares.generation}" } + val myId = requireNotNull(shares.signerIds[userPublicKey]) { "This device is not a signer of generation ${shares.generation}" } + + val recipients = shares.roster + .filter { it.standing == ShareStanding.LIVE && it.participantId !in withheld } + .map { it.participantId } + // Stale participants are withheld again, as what they were: a refresh does + // not bring anybody back. That is a repair. + val allWithheld = withheld + shares.roster + .filter { it.standing == ShareStanding.STALE && it.participantId !in withheld } + .associate { it.participantId to ShareStanding.STALE } + refusal(key, shares, recipients, allWithheld)?.let { throw IllegalStateException("Cannot refresh: $it") } + require(myId in recipients) { "The proposer has to be a recipient" } + + val session = ShareRefreshSession( + id = RandomInstance.bytes(32).toHex(), + chatRoomId = localChatRoom.chatRoom.id, + dkgSessionId = key.id, + coordinatorPublicKey = userPublicKey, + userPublicKey = userPublicKey, + baseGeneration = shares.generation, + recipientIds = ShareRefreshSession.formatIds(recipients), + withheld = ShareRefreshSession.formatWithheld(allWithheld), + round1Random = RandomInstance.bytes(32).toHex(), + auxRandom = RandomInstance.bytes(32).toHex(), + ) + database.shareRefreshDao().upsert(session) + announce(database, session, ChatMessage.TYPE_SHARE_REFRESH_STARTED, startedLine(session, shares), userPublicKey) + logger.i("Proposing refresh ${session.id} of ${key.id} from generation ${shares.generation}: $session") + + broadcast( + database, localChatRoom, session, ShareRefreshEvents.PROPOSAL, "", + ShareRefreshEvents.assembleTags(session.id, key.id, shares.generation, recipients, allWithheld) + ) + advance(database, localChatRoom, session.id, nostrPrivateKey) + return session + } + + /** A refresh of [key] still running on this device, if there is one. One at a time per key. */ + private suspend fun running(database: GizaDatabase, key: DkgSession): ShareRefreshSession? = + database.shareRefreshDao().getSessionsForKey(key.id).firstOrNull { + it.stage != ShareRefreshStage.COMPLETE && it.stage != ShareRefreshStage.FAILED + } + + // ---- inbound --------------------------------------------------------------------------------------------------- + + /** + * Feeds one inbound refresh message in and advances as far as it will go. + * Safe to call twice with the same message. + */ + suspend fun processRefreshPayload( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + innerEvent: Event, + userPublicKey: HexKey, + nostrPrivateKey: ByteArray, + ) { + val sessionId = ShareRefreshEvents.parseSessionId(innerEvent.tags) ?: run { + logger.w("Refresh payload ${innerEvent.id} has no session tag; dropping") + return + } + + val session = if (innerEvent.kind == ShareRefreshEvents.PROPOSAL) { + acceptProposal(database, localChatRoom, innerEvent, sessionId, userPublicKey) + } else { + database.shareRefreshDao().getSessionById(sessionId) + } ?: return + + if (session.stage == ShareRefreshStage.FAILED) return + if (!record(database, session, innerEvent)) return + + advance(database, localChatRoom, session.id, nostrPrivateKey) + } + + private suspend fun acceptProposal( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + innerEvent: Event, + sessionId: String, + userPublicKey: HexKey, + ): ShareRefreshSession? { + database.shareRefreshDao().getSessionById(sessionId)?.let { return it } + + val key = ShareRefreshEvents.parseKey(innerEvent.tags) + ?.let { database.dkgSessionDao().getSessionById(it) } + ?.takeIf { it.stage == DkgRitualStage.COMPLETE } + ?: run { + logger.w("Refresh $sessionId names a key this device does not hold; dropping") + return null + } + val base = ShareRefreshEvents.parseBaseGeneration(innerEvent.tags) + val recipients = ShareRefreshEvents.parseRecipients(innerEvent.tags) + val withheld = ShareRefreshEvents.parseWithheld(innerEvent.tags) + if (base == null || recipients == null || withheld == null) { + logger.w("Refresh $sessionId has an unreadable generation, recipient or withheld tag; dropping") + return null + } + if (!isKeysRoom(database, localChatRoom, key)) { + logger.w("Refresh $sessionId of ${key.id} arrived in ${localChatRoom.chatRoom.id}, which is not its room; dropping") + return null + } + + // A member of the room with no id in the key has nothing to do with it. + val active = ShareGenerations.active(database, key) + if (userPublicKey !in active.roster.map { it.memberPublicKey }) return null + + val proposer = active.roster.firstOrNull { it.memberPublicKey == innerEvent.pubKey }?.participantId + + val session = ShareRefreshSession( + id = sessionId, + chatRoomId = localChatRoom.chatRoom.id, + dkgSessionId = key.id, + coordinatorPublicKey = innerEvent.pubKey, + userPublicKey = userPublicKey, + baseGeneration = base, + recipientIds = ShareRefreshSession.formatIds(recipients), + withheld = ShareRefreshSession.formatWithheld(withheld), + round1Random = RandomInstance.bytes(32).toHex(), + auxRandom = RandomInstance.bytes(32).toHex(), + ) + + val reason = when { + base != active.generation -> "it refreshes generation $base, and this device is at generation ${active.generation}" + proposer == null || proposer !in recipients -> "its proposer is not one of its recipients" + running(database, key) != null -> "another refresh of this key is still running here" + else -> refusal(key, active, recipients, withheld) + } + + database.shareRefreshDao().upsert(session) + announce(database, session, ChatMessage.TYPE_SHARE_REFRESH_STARTED, startedLine(session, active), innerEvent.pubKey) + + if (reason != null) { + logger.w("Refusing refresh $sessionId: $reason") + // A recipient that cannot take part ends the refresh for everyone, + // since a certificate needs it; anyone else just stays out. + val myId = active.participantIds[userPublicKey] + fail(database, session, "Refused: $reason") + if (myId != null && myId in recipients) { + broadcast(database, localChatRoom, session, ShareRefreshEvents.FAILURE, "Refused: $reason", ShareRefreshEvents.assembleTags(sessionId)) + } + return null + } + + replayStoredMessages(database, localChatRoom, session) + return database.shareRefreshDao().getSessionById(sessionId) + } + + /** Messages that arrived before the proposal, read back out of the room's inner events. */ + private suspend fun replayStoredMessages(database: GizaDatabase, localChatRoom: LocalChatRoom, session: ShareRefreshSession) { + database.marmotInnerEventDao() + .getByChatRoomAndKinds(chatRoomId = localChatRoom.chatRoom.id, kinds = (ShareRefreshEvents.ALL - ShareRefreshEvents.PROPOSAL).toList()) + .filter { ShareRefreshEvents.parseSessionId(it.tags) == session.id } + .sortedWith(compareBy({ it.createdAt }, { it.kind })) + .forEach { stored -> + val event = Event(stored.id, stored.publicKey, stored.createdAt.epochSeconds, stored.kind, stored.tags, stored.content, "") + if (!record(database, current(database, session), event)) return + } + } + + /** Files one message. False when it ends the refresh. */ + private suspend fun record(database: GizaDatabase, session: ShareRefreshSession, innerEvent: Event): Boolean { + val key = database.dkgSessionDao().getSessionById(session.dkgSessionId) ?: return false + val base = ShareGenerations.at(database, key, session.baseGeneration) ?: return true + val senderId = base.roster.firstOrNull { it.memberPublicKey == innerEvent.pubKey }?.participantId + val fromRecipient = senderId != null && senderId in session.recipientIdList() + + when (innerEvent.kind) { + ShareRefreshEvents.ROUND_1, ShareRefreshEvents.ROUND_2 -> { + if (!fromRecipient) { + logger.w("Refresh ${session.id}: kind ${innerEvent.kind} from ${innerEvent.pubKey.take(8)}, who is not a recipient; ignoring") + return true + } + val known = database.shareRefreshDao().getMessage(session.id, innerEvent.kind, innerEvent.pubKey) != null + database.shareRefreshDao().upsert(ShareRefreshMessage(session.id, innerEvent.pubKey, innerEvent.kind, innerEvent.content)) + if (!known && innerEvent.pubKey != session.userPublicKey) { + announce(database, session, stepType(innerEvent.kind), stepLine(innerEvent.kind), innerEvent.pubKey) + } + } + + ShareRefreshEvents.COORDINATOR_ROUND_1 -> { + if (innerEvent.pubKey != session.coordinatorPublicKey) return true + update(database, session) { if (it.coordinatorRound1 == null) it.copy(coordinatorRound1 = innerEvent.content) else it } + } + + ShareRefreshEvents.CERTIFICATE -> { + if (innerEvent.pubKey != session.coordinatorPublicKey) return true + update(database, session) { if (it.certificate == null) it.copy(certificate = innerEvent.content) else it } + } + + ShareRefreshEvents.FAILURE -> { + if (!fromRecipient) return true + fail(database, session, "Abandoned by ${innerEvent.pubKey.take(8)}: ${innerEvent.content}") + return false + } + } + return true + } + + // ---- advancing ------------------------------------------------------------------------------------------------ + + /** + * Takes every step the stored messages allow, stopping at the first that + * waits on somebody. Each step asks whether its output exists rather than + * what the stage says, so a crash or a redelivery repeats no work and skips + * none. + */ + private suspend fun advance(database: GizaDatabase, localChatRoom: LocalChatRoom, sessionId: String, nostrPrivateKey: ByteArray) { + var session = database.shareRefreshDao().getSessionById(sessionId) ?: return + if (session.stage == ShareRefreshStage.COMPLETE || session.stage == ShareRefreshStage.FAILED) return + + try { + val key = database.dkgSessionDao().getSessionById(session.dkgSessionId) ?: return + val base = ShareGenerations.at(database, key, session.baseGeneration) ?: return + val myId = base.roster.firstOrNull { it.memberPublicKey == session.userPublicKey }?.participantId ?: return + val recipients = session.recipientIdList() + val isRecipient = myId in recipients + val params = paramsFor(key, base, session) + val hostSecretKey = ChillDkgRitualManager.deriveHostSecretKey(nostrPrivateKey) + + if (isRecipient) { + if (session.dealApprovedAt == null) { + announceApprovalNeeded(database, session, ShareRefreshApprovalStep.DEAL) + return + } + if (ownMessage(database, session, ShareRefreshEvents.ROUND_1) == null) { + val pmsg1 = FrostRefresh.participantStep1(hostSecretKey, params, myId.toUInt(), ByteVector32(session.round1Random)).right + ?: throw IllegalStateException("round 1 refused this device's inputs") + publishOwn(database, localChatRoom, session, ShareRefreshEvents.ROUND_1, pmsg1.toHex()) + } + } + + if (session.isCoordinator() && session.coordinatorRound1 == null) { + val round1 = byRecipient(database, session, base, ShareRefreshEvents.ROUND_1) ?: return + val result = FrostRefresh.coordinatorStep1(round1.mapValues { ByteVector(it.value.hexToByteArray()) }, params) + result.fault.raiseIfFaulty("summing round 1", base) + val cmsg1 = result.message!!.toHex() + session = update(database, session) { it.copy(coordinatorRound1 = cmsg1) } + broadcast(database, localChatRoom, session, ShareRefreshEvents.COORDINATOR_ROUND_1, cmsg1, ShareRefreshEvents.assembleTags(session.id)) + } + + val cmsg1 = session.coordinatorRound1 ?: return + session = moveTo(database, session, ShareRefreshStage.COLLECTING_ROUND_2) + + if (isRecipient && ownMessage(database, session, ShareRefreshEvents.ROUND_2) == null) { + if (session.confirmApprovedAt == null) { + announceApprovalNeeded(database, session, ShareRefreshApprovalStep.CONFIRM) + return + } + val secretShare = base.secretShare ?: throw IllegalStateException("this device holds no share of generation ${base.generation}") + val step2 = FrostRefresh.participantStep2(hostSecretKey, secretShare, params, myId.toUInt(), ByteVector(cmsg1.hexToByteArray()), ByteVector32(session.auxRandom)) + step2.fault.raiseIfFaulty("round 2", base) + + // Stored before it is confirmed, and claimed as this device's one + // confirmation from this generation in the same transaction. + val holder = database.shareRefreshDao().confirmAndStore( + ShareRefreshConfirmation(key.id, session.baseGeneration, session.id), + KeyShareGeneration( + dkgSessionId = key.id, + generation = session.baseGeneration + 1, + secretShare = step2.newSecretShare!!.value.toHex(), + publicShares = step2.newPublicShares!!.joinToString(",") { it.value.toHex() }, + state = ShareGenerationState.PENDING, + refreshSessionId = session.id, + ), + newRoster(key, base, session), + ) + if (holder != session.id) { + throw IllegalStateException("this device has already confirmed refresh ${holder.take(8)} from generation ${session.baseGeneration}") + } + publishOwn(database, localChatRoom, session, ShareRefreshEvents.ROUND_2, step2.certEqSignature!!.toHex()) + } + + if (session.isCoordinator() && session.certificate == null) { + val round2 = byRecipient(database, session, base, ShareRefreshEvents.ROUND_2) ?: return + val result = FrostRefresh.coordinatorFinalize(params, ByteVector(cmsg1.hexToByteArray()), round2.mapValues { ByteVector64(it.value) }) + result.fault.raiseIfFaulty("certifying", base) + val cmsg2 = result.output!!.toHex() + session = update(database, session) { it.copy(certificate = cmsg2) } + broadcast(database, localChatRoom, session, ShareRefreshEvents.CERTIFICATE, cmsg2, ShareRefreshEvents.assembleTags(session.id)) + } + + val certificate = session.certificate ?: return + val finalized = FrostRefresh.participantFinalize(params, ByteVector(cmsg1.hexToByteArray()), ByteVector(certificate.hexToByteArray())) + finalized.fault.raiseIfFaulty("verifying the certificate", base) + activate(database, key, base, session, finalized.output!!, isRecipient) + + update(database, session) { it.copy(stage = ShareRefreshStage.COMPLETE) } + announce( + database, session, ChatMessage.TYPE_SHARE_REFRESH_COMPLETE, + "The group's shares were rotated. Shares held before stop working once everyone's device has deleted them.", + session.coordinatorPublicKey + ) + logger.i("Refresh ${session.id} complete: ${key.id} is at generation ${session.baseGeneration + 1}") + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + logger.e("Refresh $sessionId failed", e) + fail(database, session, e.message ?: e::class.simpleName ?: "Unknown error") + broadcast(database, localChatRoom, session, ShareRefreshEvents.FAILURE, e.message ?: "Refresh failed", ShareRefreshEvents.assembleTags(session.id)) + } + } + + private fun FrostRefreshFault.raiseIfFaulty(step: String, base: ShareGenerations.Shares) { + if (isOk) return + val who = participantId?.let { id -> base.roster.firstOrNull { it.participantId == id.toInt() }?.memberPublicKey?.take(8) ?: "participant $id" } + val what = when (code) { + ChilldkgFault.FAULTY_COORDINATOR -> "the coordinator is faulty" + ChilldkgFault.FAULTY_PARTICIPANT -> "a recipient is faulty ($who)" + ChilldkgFault.FAULTY_PARTICIPANT_OR_COORDINATOR -> "a recipient or the coordinator is faulty ($who)" + ChilldkgFault.UNKNOWN_FAULTY_PARTICIPANT_OR_COORDINATOR -> "what was dealt does not match the commitments" + else -> "the inputs were refused" + } + throw IllegalStateException("Share refresh, $step, failed: $what") + } + + /** The parameters every party derives from what it already holds. */ + private fun paramsFor(key: DkgSession, base: ShareGenerations.Shares, session: ShareRefreshSession): FrostRefreshParams = + FrostRefresh.params( + thresholdPublicKey = PublicKey(ByteVector(requireNotNull(key.thresholdPublicKey).hexToByteArray())), + hostPublicKeys = base.roster.map { PublicKey(ByteVector(it.hostPublicKey.hexToByteArray())) }, + publicShares = requireNotNull(base.publicShares), + threshold = key.threshold, + generation = session.baseGeneration.toUInt(), + recipientIds = session.recipientIdList().map { it.toUInt() }, + refreshId = ByteVector32(session.id), + ).let { result -> result.right ?: throw IllegalStateException("invalid refresh parameters: ${result.left?.message}") } + + /** Every recipient's message of [kind], keyed by participant id, or null while any is missing. */ + private suspend fun byRecipient(database: GizaDatabase, session: ShareRefreshSession, base: ShareGenerations.Shares, kind: Kind): Map? { + val idByMember = base.roster.associate { it.memberPublicKey to it.participantId } + val messages = database.shareRefreshDao().getMessagesByKind(session.id, kind) + .mapNotNull { message -> idByMember[message.participantPublicKey]?.let { it to message.payload } } + .toMap() + val recipients = session.recipientIdList() + if (!messages.keys.containsAll(recipients)) return null + return recipients.associate { it.toUInt() to messages.getValue(it) } + } + + /** The roster of the new generation: recipients live, the withheld as the proposal said, the retired retired. */ + private fun newRoster(key: DkgSession, base: ShareGenerations.Shares, session: ShareRefreshSession): List { + val recipients = session.recipientIdList().toSet() + val withheld = session.withheldStandings() + return base.roster.map { entry -> + KeyShareMember( + dkgSessionId = key.id, + generation = session.baseGeneration + 1, + participantId = entry.participantId, + memberPublicKey = entry.memberPublicKey, + hostPublicKey = entry.hostPublicKey, + standing = when { + entry.participantId in recipients -> ShareStanding.LIVE + else -> withheld[entry.participantId] ?: ShareStanding.RETIRED + }, + ) + } + } + + /** + * The certificate verified: the new generation is the one the group signs with + * here. A recipient's pending row becomes active; a withheld device learns the + * new table from the recovery data and files it with no share. The generation + * before becomes retiring -- its share is deleted in Phase 8, once the group has + * signed with the new one. + */ + private suspend fun activate(database: GizaDatabase, key: DkgSession, base: ShareGenerations.Shares, session: ShareRefreshSession, recovery: ByteVector, isRecipient: Boolean) { + val now = Clock.System.now() + val next = session.baseGeneration + 1 + val dao = database.keyShareDao() + + if (isRecipient) { + val pending = dao.getGeneration(key.id, next) ?: throw IllegalStateException("generation $next was confirmed but is not stored") + dao.upsert(pending.copy(state = ShareGenerationState.ACTIVE, recoveryData = recovery.toHex(), activatedAt = now, updatedAt = now)) + } else { + val public = FrostRefresh.publicRecover(recovery) + if (!public.fault.isOk) throw IllegalStateException("the certified recovery data does not recover") + dao.upsert( + KeyShareGeneration( + dkgSessionId = key.id, + generation = next, + secretShare = null, + publicShares = public.newPublicShares!!.joinToString(",") { it.value.toHex() }, + state = ShareGenerationState.ACTIVE, + refreshSessionId = session.id, + recoveryData = recovery.toHex(), + activatedAt = now, + ) + ) + dao.upsert(newRoster(key, base, session)) + } + + if (session.baseGeneration >= 1) { + dao.getGeneration(key.id, session.baseGeneration)?.let { previous -> + dao.upsert(previous.copy(state = ShareGenerationState.RETIRING, updatedAt = now)) + } + } + } + + // ---- approvals ------------------------------------------------------------------------------------------------ + + /** + * What this device's owner is being asked for, or null. **Must mirror the + * gates in [advance] exactly**: drift makes the screen offer an approval that + * does nothing, or none while the refresh sits still. + */ + suspend fun pendingApproval(database: GizaDatabase, session: ShareRefreshSession): ShareRefreshApprovalStep? { + if (session.stage == ShareRefreshStage.COMPLETE || session.stage == ShareRefreshStage.FAILED) return null + val key = database.dkgSessionDao().getSessionById(session.dkgSessionId) ?: return null + val base = ShareGenerations.at(database, key, session.baseGeneration) ?: return null + val myId = base.roster.firstOrNull { it.memberPublicKey == session.userPublicKey }?.participantId ?: return null + if (myId !in session.recipientIdList()) return null + if (session.dealApprovedAt == null) return ShareRefreshApprovalStep.DEAL + if (session.coordinatorRound1 != null && session.confirmApprovedAt == null && + ownMessage(database, session, ShareRefreshEvents.ROUND_2) == null + ) return ShareRefreshApprovalStep.CONFIRM + return null + } + + /** Approves the step this device's owner is being asked for, and moves on. */ + suspend fun approve(database: GizaDatabase, localChatRoom: LocalChatRoom, sessionId: String, nostrPrivateKey: ByteArray) { + val session = database.shareRefreshDao().getSessionById(sessionId) ?: return + val now = Clock.System.now() + when (pendingApproval(database, session)) { + ShareRefreshApprovalStep.DEAL -> update(database, session) { it.copy(dealApprovedAt = now) } + ShareRefreshApprovalStep.CONFIRM -> update(database, session) { it.copy(confirmApprovedAt = now) } + null -> return + } + advance(database, localChatRoom, sessionId, nostrPrivateKey) + } + + /** Ends a refresh for everyone. Only a recipient can; a refresh has no "no" short of this. */ + suspend fun abandon(database: GizaDatabase, localChatRoom: LocalChatRoom, sessionId: String) { + val session = database.shareRefreshDao().getSessionById(sessionId) ?: return + if (session.stage == ShareRefreshStage.COMPLETE || session.stage == ShareRefreshStage.FAILED) return + fail(database, session, ABANDONED) + broadcast(database, localChatRoom, session, ShareRefreshEvents.FAILURE, ABANDONED, ShareRefreshEvents.assembleTags(session.id)) + } + + private const val ABANDONED = "Abandoned by a recipient" + + // ---- persistence and transport -------------------------------------------------------------------------------- + + private suspend fun current(database: GizaDatabase, session: ShareRefreshSession): ShareRefreshSession = + database.shareRefreshDao().getSessionById(session.id) ?: session + + private suspend fun update(database: GizaDatabase, session: ShareRefreshSession, change: (ShareRefreshSession) -> ShareRefreshSession): ShareRefreshSession { + val now = Clock.System.now() + val updated = change(current(database, session)).copy(updatedAt = now, savedAt = now) + database.shareRefreshDao().upsert(updated) + return updated + } + + private suspend fun moveTo(database: GizaDatabase, session: ShareRefreshSession, stage: ShareRefreshStage): ShareRefreshSession = + update(database, session) { if (it.stage < stage) it.copy(stage = stage) else it } + + private suspend fun fail(database: GizaDatabase, session: ShareRefreshSession, reason: String) { + val now = current(database, session) + if (now.stage == ShareRefreshStage.FAILED || now.stage == ShareRefreshStage.COMPLETE) return + update(database, session) { it.copy(stage = ShareRefreshStage.FAILED, failureReason = reason) } + announce(database, session, ChatMessage.TYPE_SHARE_REFRESH_FAILED, "The share rotation ended: $reason", session.coordinatorPublicKey) + } + + private suspend fun ownMessage(database: GizaDatabase, session: ShareRefreshSession, kind: Kind): ShareRefreshMessage? = + database.shareRefreshDao().getMessage(session.id, kind, session.userPublicKey) + + /** Queues this device's own message and records it, so the coordinator's own is in its sums. */ + private suspend fun publishOwn(database: GizaDatabase, localChatRoom: LocalChatRoom, session: ShareRefreshSession, kind: Kind, content: String) { + broadcast(database, localChatRoom, session, kind, content, ShareRefreshEvents.assembleTags(session.id)) + val known = ownMessage(database, session, kind) != null + database.shareRefreshDao().upsert(ShareRefreshMessage(session.id, session.userPublicKey, kind, content)) + if (!known) announce(database, session, stepType(kind), stepLine(kind), session.userPublicKey) + } + + /** One of this device's messages, as an inner event of the key's Marmot room. */ + private suspend fun broadcast(database: GizaDatabase, localChatRoom: LocalChatRoom, session: ShareRefreshSession, kind: Kind, content: String, tags: Array>) { + var createdAt = Clock.System.now().epochSeconds + var id = EventHasher.hashId(pubKey = session.userPublicKey, createdAt = createdAt, kind = kind, tags = tags, content = content) + // Step past an id already queued: a repeat inside the same second hashes the same. + var attempts = 0 + while (attempts < 16 && database.marmotInnerEventDao().getById(id) != null) { + createdAt += 1 + id = EventHasher.hashId(pubKey = session.userPublicKey, createdAt = createdAt, kind = kind, tags = tags, content = content) + attempts += 1 + } + database.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = id, + publicKey = session.userPublicKey, + kind = kind, + createdAt = Instant.fromEpochSeconds(createdAt), + tags = tags, + content = content, + chatRoomId = localChatRoom.chatRoom.id, + ) + ) + } + + // ---- transcript ----------------------------------------------------------------------------------------------- + + private fun startedLine(session: ShareRefreshSession, shares: ShareGenerations.Shares): String { + val withheld = session.withheldStandings() + if (withheld.isEmpty()) return "started rotating the group's shares, with every member taking part." + val names = withheld.entries.joinToString(", ") { (id, standing) -> + val who = shares.roster.firstOrNull { it.participantId == id }?.memberPublicKey?.take(8) ?: "participant $id" + if (standing == ShareStanding.RETIRED) "$who for good" else "$who until they are brought back" + } + return "started rotating the group's shares without $names." + } + + private fun stepType(kind: Kind): String = when (kind) { + ShareRefreshEvents.ROUND_1 -> ChatMessage.TYPE_SHARE_REFRESH_DEALT + else -> ChatMessage.TYPE_SHARE_REFRESH_CONFIRMED + } + + private fun stepLine(kind: Kind): String = when (kind) { + ShareRefreshEvents.ROUND_1 -> "sent their part of the new shares." + else -> "stored their new share." + } + + private suspend fun announceApprovalNeeded(database: GizaDatabase, session: ShareRefreshSession, step: ShareRefreshApprovalStep) { + val now = current(database, session) + val through = now.approvalRequestedThrough + if (through != null && through >= step) return + update(database, session) { it.copy(approvalRequestedThrough = step) } + val line = when (step) { + ShareRefreshApprovalStep.DEAL -> "Your approval is needed to take part in rotating the group's shares." + ShareRefreshApprovalStep.CONFIRM -> "Your approval is needed to store your new share." + } + announce(database, session, ChatMessage.TYPE_SHARE_REFRESH_APPROVAL_NEEDED, line, session.userPublicKey) + } + + private suspend fun announce(database: GizaDatabase, session: ShareRefreshSession, messageType: String, content: String, actor: HexKey) { + database.chatMessageDao().upsert( + ChatMessage( + senderPublicKey = actor, + isUserMessage = actor == session.userPublicKey, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = session.chatRoomId, + content = content, + messageType = messageType, + ) + ) + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/ShareRefreshEvents.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/ShareRefreshEvents.kt new file mode 100644 index 00000000..afd6f8d8 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/ShareRefreshEvents.kt @@ -0,0 +1,98 @@ +package mobi.giza.compose.nostr.frost + +import com.vitorpamplona.quartz.nip01Core.core.Kind +import mobi.giza.compose.database.model.types.ShareStanding + +/** + * The kinds and tags of a share refresh (docs/frost-share-refresh.md, Phase 7). + * + * They travel as Marmot inner events in the room whose id the key derives, like + * the signing family beside them. The dealt values inside are encrypted to each + * recipient's ChillDKG host key by the protocol itself, so a message every member + * of the room can read discloses nothing -- which is not true of a repair, whose + * messages are raw scalars and go pairwise (Phase 10). + * + * 30338-30349 were unused when these were chosen, between the retired wallet + * kinds and the retired group Lightning wallet's. Bennu has not used them. + */ +object ShareRefreshEvents { + /** Proposer (coordinator): "refresh this key, from this generation, with these recipients". */ + val PROPOSAL: Kind = 30340 + + /** Recipient: round 1, the commitments and encrypted dealt values. */ + val ROUND_1: Kind = 30341 + + /** Coordinator: the sum of every recipient's round 1 (cmsg1). */ + val COORDINATOR_ROUND_1: Kind = 30342 + + /** Recipient: the confirmation that it has stored the new generation. */ + val ROUND_2: Kind = 30343 + + /** Coordinator: the certificate, every recipient's confirmation (cmsg2). */ + val CERTIFICATE: Kind = 30344 + + /** Any recipient: abandon. Content is the reason. */ + val FAILURE: Kind = 30345 + + val ALL: Set = setOf(PROPOSAL, ROUND_1, COORDINATOR_ROUND_1, ROUND_2, CERTIFICATE, FAILURE) + + fun isShareRefreshKind(kind: Kind): Boolean = kind in ALL + + private const val SESSION_TAG = "refresh_session" + private const val RECIPIENTS_TAG = "refresh_recipients" + private const val WITHHELD_TAG = "refresh_withheld" + private const val KEY_TAG = "frost_key" + private const val GENERATION_TAG = "frost_generation" + + /** + * Tags for a refresh message. The session is on every one; what the refresh + * is -- the key, the base generation, the recipients and the withheld -- only + * on the proposal, so that no later message has a say in it. + */ + fun assembleTags( + sessionId: String, + dkgSessionId: String? = null, + baseGeneration: Int? = null, + recipientIds: List? = null, + withheld: Map? = null, + ): Array> = buildList { + add(arrayOf(SESSION_TAG, sessionId)) + dkgSessionId?.let { add(arrayOf(KEY_TAG, it)) } + baseGeneration?.let { add(arrayOf(GENERATION_TAG, it.toString())) } + recipientIds?.let { add(arrayOf(RECIPIENTS_TAG, it.sorted().joinToString(","))) } + withheld?.takeIf { it.isNotEmpty() }?.let { w -> + add(arrayOf(WITHHELD_TAG, w.entries.sortedBy { it.key }.joinToString(",") { "${it.key}:${it.value.name.lowercase()}" })) + } + }.toTypedArray() + + private fun value(tags: Array>, name: String): String? = + tags.firstOrNull { it.size >= 2 && it[0] == name }?.get(1) + + fun parseSessionId(tags: Array>): String? = value(tags, SESSION_TAG)?.takeIf { it.length == 64 } + + fun parseKey(tags: Array>): String? = value(tags, KEY_TAG) + + fun parseBaseGeneration(tags: Array>): Int? = value(tags, GENERATION_TAG)?.toIntOrNull()?.takeIf { it >= 0 } + + /** The recipients, or null when the tag is absent or any entry is unreadable: a set read in part is a different set. */ + fun parseRecipients(tags: Array>): List? { + val raw = value(tags, RECIPIENTS_TAG) ?: return null + val ids = raw.split(",").map { it.trim().toIntOrNull() ?: return null } + return ids.takeIf { it.isNotEmpty() && it == it.sorted() && it.toSet().size == it.size && it.all { id -> id >= 0 } } + } + + /** The withheld and their standings: empty when the tag is absent, null when it is unreadable. */ + fun parseWithheld(tags: Array>): Map? { + val raw = value(tags, WITHHELD_TAG) ?: return emptyMap() + return raw.split(",").associate { entry -> + val parts = entry.split(":").takeIf { it.size == 2 } ?: return null + val id = parts[0].trim().toIntOrNull()?.takeIf { it >= 0 } ?: return null + val standing = when (parts[1].trim()) { + "stale" -> ShareStanding.STALE + "retired" -> ShareStanding.RETIRED + else -> return null + } + id to standing + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt index e70b510c..c38867ad 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt @@ -320,6 +320,21 @@ fun ChatTranscript( // settled for the same reason the chronicle's are // -- these report rather than ask, so they stay in // the quiet tint and offer nothing to review. + // A share refresh reports like a membership change: + // a system line, never a bubble. Its request line + // leads nowhere yet -- the refresh screen is + // docs/frost-share-refresh.md, Phase 11. + if (localChatMessage.chatMessage.messageType in ChatMessage.SHARE_REFRESH_TYPES) { + RitualNotice( + localChatMessage = localChatMessage, + isAnswered = true, + isSettled = true, + onClick = null, + opens = null, + ) + return@items + } + if (localChatMessage.chatMessage.messageType in ChatMessage.MEMBERSHIP_TYPES) { RitualNotice( localChatMessage = localChatMessage, diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt index 79db770f..dc58c3fb 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt @@ -62,12 +62,11 @@ class ShippedProfileUpgradeJvmTest { private val shipped = 36 /** - * The schema version this branch builds. 38 since share generations - * (docs/frost-share-refresh.md, Phase 6), so the upgrade crosses two - * generated migrations, 36 -> 37 -> 38, and the file has to come out at the - * second. + * The schema version this branch builds: 38 for share generations and 39 for + * share refresh (docs/frost-share-refresh.md, Phases 6 and 7), so the upgrade + * crosses three generated migrations and the file has to come out at the last. */ - private val current = 38 + private val current = 39 private val directory: File = Files.createTempDirectory("giza-shipped-profile").toFile() private val file: File = File(directory, "aux.db") diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt new file mode 100644 index 00000000..9a406c43 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt @@ -0,0 +1,304 @@ +package mobi.giza.compose.managers + +import androidx.room3.Room +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import com.vitorpamplona.quartz.nip01Core.crypto.Nip01Crypto +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 kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.DkgParticipantMessage +import mobi.giza.compose.database.model.DkgSession +import mobi.giza.compose.database.model.KeyShareGeneration +import mobi.giza.compose.database.model.MarmotInnerEvent +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.database.model.ShareRefreshConfirmation +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.database.model.types.DkgRitualStage +import mobi.giza.compose.database.model.types.FrostSigningStage +import mobi.giza.compose.database.model.types.ShareGenerationState +import mobi.giza.compose.database.model.types.ShareRefreshStage +import mobi.giza.compose.database.model.types.ShareStanding +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.dkg.DkgRitualEvents +import mobi.giza.compose.nostr.frost.FrostSigningEvents +import mobi.giza.compose.nostr.frost.ShareRefreshEvents + +/** + * A share refresh between devices (docs/frost-share-refresh.md, Phase 7). + * + * Every member has a real nostr key, so the ChillDKG host keys derive the way the + * app derives them, and the shares are dealt in the order those host keys sort + * in -- the order a ceremony would have given. Each device is its own database, + * and nothing passes between them but the inner events ferried by [pump]. The + * refresh is the real one, through bitcoin-kmp's FrostRefresh and the zkp module + * beneath it; when it is done the group signs with the new shares, through the + * real signing manager, as the room it always was. + */ +class ShareRefreshRitualJvmTest { + private val devices = mutableListOf() + + @AfterTest + fun closeDatabases() = devices.forEach { it.db.close() } + + private val ceremonyId = "ceremony".padEnd(64, '0') + + private inner class Group(n: Int, val t: Int) { + val keyPairs: List = List(n) { KeyPair() } + val members: List = keyPairs.map { it.pubKey.toHexKey() } + val hostKeys: List = keyPairs.map { ChillDkgRitualManager.deriveHostPublicKey(it.privKey!!).value.toHex() } + + /** Participant id of member i: its host key's place in the bytewise sort. */ + val idOf: List = hostKeys.map { hostKeys.sorted().indexOf(it) } + + val keyMaterial: KeyMaterial = Frost.trustedDealerKeygen(PrivateKey(ByteVector32("7e57ab1e".padEnd(64, '1'))), n, t) + val thresholdPublicKey: HexKey = keyMaterial.thresholdPublicKey.value.toHex() + val roomId: HexKey = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) + + fun memberWithId(id: Int): HexKey = members[idOf.indexOf(id)] + } + + private inner class Device(val group: Group, val index: Int, val db: GizaDatabase, val room: LocalChatRoom) { + val publicKey: HexKey get() = group.members[index] + val privateKey: ByteArray get() = group.keyPairs[index].privKey!! + val received = mutableSetOf() + suspend fun key(): DkgSession = db.dkgSessionDao().getSessionById(ceremonyId)!! + suspend fun refresh(id: String) = db.shareRefreshDao().getSessionById(id) + suspend fun active() = ShareGenerations.active(db, key()) + } + + private suspend fun device(group: Group, index: Int): Device { + val db = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + group.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 publicKey = group.members[index] + val chatRoom = ChatRoom(id = group.roomId, userPublicKey = publicKey, subject = "#Ekklesia", description = SharedKeyDerivation.describe("Admins."), mlsGroupState = "00") + db.chatRoomDao().upsert(chatRoom) + val id = group.idOf[index] + db.dkgSessionDao().upsert( + DkgSession( + id = ceremonyId, + chatRoomId = group.roomId, + coordinatorPublicKey = group.members.first(), + userPublicKey = publicKey, + threshold = group.t, + participantCount = group.members.size, + stage = DkgRitualStage.COMPLETE, + hostPublicKey = group.hostKeys[index], + round1Random = "1".repeat(64), + round2AuxRandom = "2".repeat(64), + thresholdPublicKey = group.thresholdPublicKey, + secretShare = group.keyMaterial.secretShares[id].value.toHex(), + publicShares = group.keyMaterial.publicShares.joinToString(",") { it.value.toHex() }, + ) + ) + group.members.forEachIndexed { i, member -> + db.dkgSessionDao().upsert(DkgParticipantMessage(sessionId = ceremonyId, participantPublicKey = member, kind = DkgRitualEvents.HOST_KEY, payload = group.hostKeys[i])) + } + return Device(group, index, db, LocalChatRoom(chatRoom = chatRoom)).also { devices += it } + } + + private suspend fun devicesFor(group: Group): List = group.members.indices.map { device(group, it) } + + // ---- the wire ---------------------------------------------------------------------------------------------- + + private val ferried = (ShareRefreshEvents.ALL + FrostSigningEvents.ALL).toList() + + private suspend fun outbox(device: Device): List = + device.db.marmotInnerEventDao() + .getByChatRoomAndKinds(chatRoomId = device.group.roomId, kinds = ferried) + .filter { it.publicKey == device.publicKey } + .sortedWith(compareBy({ it.createdAt }, { it.kind })) + + private suspend fun pump(between: List) { + var moved = true + while (moved) { + moved = false + for (from in between) for (to in between) { + if (from === to) continue + outbox(from).forEach { queued -> + if (!to.received.add(queued.id)) return@forEach + moved = true + to.db.marmotInnerEventDao().upsert(queued.copy(chatRoomId = to.group.roomId)) + val event = Event(queued.id, queued.publicKey, queued.createdAt.epochSeconds, queued.kind, queued.tags, queued.content, "") + if (ShareRefreshEvents.isShareRefreshKind(event.kind)) { + ShareRefreshManager.processRefreshPayload(to.db, to.room, event, to.publicKey, to.privateKey) + } else { + FrostSigningManager.processSigningPayload(to.db, to.room, event, to.publicKey) + } + } + } + } + } + + /** Every owner approves whatever they are asked, until nobody is asked anything. */ + private suspend fun approveAll(between: List, refreshId: String) { + var asked = true + while (asked) { + asked = false + for (device in between) { + val session = device.refresh(refreshId) ?: continue + if (ShareRefreshManager.pendingApproval(device.db, session) != null) { + ShareRefreshManager.approve(device.db, device.room, refreshId, device.privateKey) + asked = true + } + } + pump(between) + } + } + + private suspend fun propose(by: Device, withheld: Map = emptyMap()) = + ShareRefreshManager.proposeRefresh(by.db, by.room, by.publicKey, by.privateKey, by.key(), withheld) + + // ---- the tests --------------------------------------------------------------------------------------------- + + @Test + fun `a refresh rotates every share, and the group signs with the new ones as the same room`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val refresh = propose(all[0]) + pump(all) + approveAll(all, refresh.id) + + all.forEach { device -> + assertEquals(ShareRefreshStage.COMPLETE, device.refresh(refresh.id)?.stage, "on device ${device.index}") + val active = device.active() + assertEquals(1, active.generation) + val id = group.idOf[device.index] + val newShare = assertNotNull(active.secretShare) + assertNotEquals(group.keyMaterial.secretShares[id], newShare, "the share must have moved") + assertEquals(active.publicShares!![id], newShare.publicKey()) + } + val tables = all.map { it.active().publicShares } + assertTrue(tables.all { it == tables.first() }, "every device must arrive at the same table") + val shares = (0 until 3).map { id -> all.first { group.idOf[it.index] == id }.active().secretShare!! } + assertTrue(KeyMaterial(group.keyMaterial.thresholdPublicKey, shares, tables.first()!!, 2).isValid(), "the new shares are of the same key") + + // And the group signs with them, through the signing manager, as the room. + val (alice, bob) = all + val session = FrostSigningManager.proposeSigning(alice.db, alice.room, alice.publicKey, kind = 1, tags = arrayOf(), content = "After the rotation") + assertEquals(1, session.generation) + pump(all) + FrostSigningManager.approve(bob.db, bob.room, session.id) + pump(all) + val item = alice.db.frostSigningSessionDao().getItems(session.id).single() + assertEquals(FrostSigningStage.COMPLETE, alice.db.frostSigningSessionDao().getSessionById(session.id)?.stage) + assertTrue(Nip01Crypto.verify(assertNotNull(item.signature).hexToByteArray(), item.eventId.hexToByteArray(), group.roomId.hexToByteArray())) + } + + @Test + fun `nothing of a member's own goes out before they approve`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val refresh = propose(all[0]) + pump(all) + + all.forEach { device -> + assertEquals(listOf(ShareRefreshEvents.PROPOSAL).takeIf { device.index == 0 } ?: emptyList(), outbox(device).map { it.kind }, "device ${device.index}") + assertNotNull(ShareRefreshManager.pendingApproval(device.db, device.refresh(refresh.id)!!), "device ${device.index} must be asked") + } + // The proposer is asked like anyone: proposing is not agreeing to withhold whoever the form defaulted to. + assertTrue(all[0].db.chatMessageDao().getChatMessagesByChatRoomId(group.roomId).any { it.chatMessage.messageType == ChatMessage.TYPE_SHARE_REFRESH_APPROVAL_NEEDED }) + } + + @Test + fun `a withheld member ends with the new table and no share, and declines to sign`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val withheldDevice = all[2] + val withheldId = group.idOf[2] + val refresh = propose(all[0], mapOf(withheldId to ShareStanding.STALE)) + pump(all) + approveAll(all, refresh.id) + + // The withheld device never dealt nor confirmed... + assertTrue(outbox(withheldDevice).none { it.kind == ShareRefreshEvents.ROUND_1 || it.kind == ShareRefreshEvents.ROUND_2 }) + // ...but followed the certificate to the new generation, with no share of it. + val onWithheld = withheldDevice.active() + assertEquals(1, onWithheld.generation) + assertNull(onWithheld.secretShare) + assertEquals(ShareStanding.STALE, onWithheld.roster.single { it.participantId == withheldId }.standing) + assertEquals(all[0].active().publicShares, onWithheld.publicShares) + assertNull(FrostSigningManager.completedKey(withheldDevice.db, group.roomId)) + + val session = FrostSigningManager.proposeSigning(all[0].db, all[0].room, all[0].publicKey, kind = 1, tags = arrayOf(), content = "Without them") + pump(all) + assertEquals(FrostSigningManager.GENERATION_REFUSAL, outbox(withheldDevice).single { it.kind == FrostSigningEvents.DECLINE }.content) + } + + @Test + fun `fewer recipients than a majority is refused`() = runBlocking { + val group = Group(4, 2) + val all = devicesFor(group) + val proposer = all[0] + val others = (0 until 4).filter { it != group.idOf[0] }.take(2) + val error = assertFailsWith { propose(proposer, others.associateWith { ShareStanding.RETIRED }) } + assertTrue(error.message!!.contains("not a majority"), error.message) + assertNull(proposer.db.shareRefreshDao().getSessionsForKey(ceremonyId).firstOrNull()) + } + + /** + * The rule that keeps a group from splitting. Two refreshes from one + * generation could otherwise both complete; a device's one confirmation per + * generation is what stops the second. + */ + @Test + fun `a device confirms one refresh per generation`() = runBlocking { + val group = Group(3, 2) + val device = devicesFor(group).first() + val dao = device.db.shareRefreshDao() + fun generation(refresh: String) = KeyShareGeneration(ceremonyId, 1, "ab".repeat(32), "02".padEnd(66, '0'), ShareGenerationState.PENDING, refreshSessionId = refresh) + + assertEquals("a".repeat(64), dao.confirmAndStore(ShareRefreshConfirmation(ceremonyId, 0, "a".repeat(64)), generation("a".repeat(64)), emptyList())) + assertEquals("a".repeat(64), dao.confirmAndStore(ShareRefreshConfirmation(ceremonyId, 0, "b".repeat(64)), generation("b".repeat(64)), emptyList())) + assertEquals("a".repeat(64), device.db.keyShareDao().getGeneration(ceremonyId, 1)?.refreshSessionId, "the second refresh must have written nothing") + } + + @Test + fun `a second proposal while one runs hands back the first`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val first = propose(all[0]) + pump(all) + // Bob's own device has the first refresh running, so it opens nothing new + // and hands that one back. + assertEquals(first.id, propose(all[1]).id) + } + + @Test + fun `a redelivered transcript changes nothing`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val refresh = propose(all[0]) + pump(all) + approveAll(all, refresh.id) + val before = all.map { it.db.chatMessageDao().getChatMessagesByChatRoomId(group.roomId).size to it.active().secretShare } + + all.forEach { it.received.clear() } + pump(all) + + assertEquals(before, all.map { it.db.chatMessageDao().getChatMessagesByChatRoomId(group.roomId).size to it.active().secretShare }) + all.forEach { assertEquals(ShareRefreshStage.COMPLETE, it.refresh(refresh.id)?.stage) } + } +} diff --git a/docs/frost-share-refresh.md b/docs/frost-share-refresh.md index 26392f51..7b4f75e3 100644 --- a/docs/frost-share-refresh.md +++ b/docs/frost-share-refresh.md @@ -19,6 +19,7 @@ ceremony they describe and the rule that a room's id *is* the key it signs with. | 2 | secp256k1-kmp `7fd0d34`, `8beb781`, `0f5a710` | `:tests:jvmTest` and `:tests:linuxX64Test` 112/112, the zkp vector byte for byte through both backends | | 3 | bitcoin-kmp `d2e15b8`, `3cd82d1` | `jvmTest` 274/274, including withheld → repaired with `FrostReducedEnrollment` → signs | | 4 | lightning-kmp `2043f254`, lightning-kmp-app `3794eb8`, Giza Phase 4 | lightning-kmp `crypto` tests 104/104; Giza `compileDebugKotlinAndroid`, `jvmTest` 1183/1183, audits | +| 7 | Phase 7 | `ShareRefreshRitualJvmTest` (7: three devices with real host keys refresh through the real zkp module and then sign at generation 1 as the same room; nothing published before approval; a withheld member follows to the new table with no share and declines to sign; a minority refused; one confirmation per generation; a second proposal hands back the first; a redelivered transcript changes nothing); `jvmTest` 1190/1190; `compileDebugKotlinAndroid`; audits | | 5 | `4040ae74` | `SecureDeleteJvmTest` (5, two of them controls that fail without the fix); `jvmTest` 1176/1176; `compileDebugKotlinAndroid`, `processDebugResources` | | 6 | `fce51e20` | `ShareGenerationsJvmTest` (7: a real 2-of-3 signature with hand-refreshed shares verifying as the unchanged room, a decline from a device without the generation, a withheld member who is not a signer); every existing signing test unedited; `jvmTest` 1183/1183; `compileDebugKotlinAndroid`; the M3, brand and wallet audits | @@ -38,6 +39,9 @@ Where the build chose differently from the plan: | Phase 6: a manual `MIGRATION_37_38` backfills generation 0 into the new tables | no backfill, and no manual migration. Generation 0 stays where the ceremony wrote it, read by `ShareGenerations` with ids derived from the host keys exactly as `signerIds` derived them; rows exist from generation 1 on. A copy of generation 0 would have been a second source of truth for the one fact signing most needs to agree with the ceremony about, and `ShareGenerationsJvmTest` asserts the derivation instead of a copy. The migration is a Room `AutoMigration` | | Phase 6: a session at a generation this device lacks declines | so does one whose `frost_generation` is present and unreadable, filed at generation -1 so nothing reads it as a share this device holds. A decline's reason is `FrostSigningManager.GENERATION_REFUSAL` | | Phase 6: (not in the plan) | `DkgSessionDao.getKeyHoldingSessions` now counts a share of any generation, and `completedKey` asks `ShareGenerations.canSign`, so a refreshed key whose ceremony share is wiped is still found -- and a member withheld from the newest refresh is offered nothing to sign. `ShippedProfileUpgradeJvmTest` pins the built version at 38 | +| Phase 7: the refusals | one more: every participant not retired has to be a recipient or withheld, so a proposal cannot leave someone in neither list. A participant stale at the base generation is withheld again, as stale, automatically: a refresh brings nobody back, a repair does. A recipient that refuses a proposal on arrival broadcasts a failure, since the certificate needs it; anyone else refuses silently. D5's capability check waits for Phase 13 | +| Phase 7: a kill between storing the pending generation and sending the confirmation | handled the way the plan said -- `confirmAndStore` is idempotent for the refresh that holds the claim, so the next pass stores it again and sends -- but not tested on its own | +| Phase 7: the transcript | system lines through `RitualNotice`, settled. The request line opens nothing until the refresh screen exists (Phase 11) | | Phase 5: `dataExtractionRules` or `allowBackup="false"` | both. From Android 12 `allowBackup="false"` stops cloud backup but not a device-to-device transfer | ## The headline: enrollment cannot rotate a share From 51615992ee98c68a85d48432038e1c7d9388c1d0 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Thu, 19 Nov 2026 23:32:14 +0200 Subject: [PATCH 06/12] feat: the group signs its new generation, and every device deletes the old share (frost-share-refresh, Phase 8) When a refresh completes the coordinator asks the group to sign the key state at the new generation -- the same room, key, path and parentage, plus frost_generation, a hash of the public-share table, the refresh and any retired ids. It is the new shares' first signature, and what D6 waits on: a device that files that state, holds the generation active and agrees with the group's table fails every signing session left at an older generation, out loud, and deletes the older shares, the ceremony's randomness that rebuilds generation 0's, and the WAL's page images of them. A key state at a higher generation wins whatever its timestamp, in the DAO and among signed events. A proposal at a generation this device has confirmed and is still waiting on the certificate for waits instead of declining, and resumes when the generation activates. jvmTest 1193/1193, compileDebugKotlinAndroid, audits. Co-Authored-By: Claude Opus 5.5 --- .../database/dao/FrostSigningSessionDao.kt | 4 + .../compose/database/dao/GroupKeyStateDao.kt | 10 +- .../compose/managers/FrostSigningManager.kt | 45 ++++++++- .../compose/managers/GroupKeyStateManager.kt | 90 ++++++++++++++++- .../giza/compose/managers/ShareGenerations.kt | 38 ++++++++ .../compose/managers/ShareRefreshManager.kt | 14 +++ .../compose/nostr/frost/GroupKeyStateEvent.kt | 48 ++++++++- .../managers/ShareRefreshRitualJvmTest.kt | 97 ++++++++++++++++++- docs/frost-share-refresh.md | 6 +- 9 files changed, 342 insertions(+), 10 deletions(-) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/FrostSigningSessionDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/FrostSigningSessionDao.kt index 305f8109..b1f23073 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/FrostSigningSessionDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/FrostSigningSessionDao.kt @@ -82,6 +82,10 @@ interface FrostSigningSessionDao { @Query("SELECT * FROM FrostSigningSession WHERE chatRoomId = :chatRoomId ORDER BY createdAt DESC") suspend fun getSessionsForChatRoom(chatRoomId: String): List + /** Sessions of one key still running: what a share rotation has to end. */ + @Query("SELECT * FROM FrostSigningSession WHERE dkgSessionId = :dkgSessionId AND stage NOT IN ('COMPLETE', 'FAILED')") + suspend fun getOpenSessionsForKey(dkgSessionId: String): List + @Upsert suspend fun upsert(frostSigningSession: FrostSigningSession) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupKeyStateDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupKeyStateDao.kt index 23c6c47b..974ed11b 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupKeyStateDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupKeyStateDao.kt @@ -62,7 +62,15 @@ abstract class GroupKeyStateDao { open suspend fun replace(groupKeyState: GroupKeyState): GroupKeyState { val known = getByChatRoomId(groupKeyState.chatRoomId) - if (known != null && known.announcedAt >= groupKeyState.announcedAt) return known + // The highest generation wins, then the newest: an older generation's + // state is still validly signed, and `created_at` is the author's to + // choose (docs/frost-share-refresh.md, Phase 8). + if (known != null) { + val knownGeneration = known.generation ?: 0 + val newGeneration = groupKeyState.generation ?: 0 + if (knownGeneration > newGeneration) return known + if (knownGeneration == newGeneration && known.announcedAt >= groupKeyState.announcedAt) return known + } val stamped = groupKeyState.copy( createdAt = known?.createdAt ?: groupKeyState.createdAt, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt index 46ff773a..0970d7f0 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt @@ -41,6 +41,7 @@ import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.database.model.types.DkgRitualStage import mobi.giza.compose.database.model.types.FrostSigningStage import mobi.giza.compose.database.model.types.FrostSigningSubject +import mobi.giza.compose.database.model.types.ShareGenerationState import mobi.giza.compose.extensions.toHex import mobi.giza.compose.nostr.dkg.DkgRitualEvents import mobi.giza.compose.nostr.frost.FrostSigningEvents @@ -647,7 +648,16 @@ object FrostSigningManager { // Withheld from a refresh, or never told of one, this device declines. // docs/frost-share-refresh.md, Phase 6. val signable = generation?.let { ShareGenerations.at(database, key, it) } - if (generation == null || signable?.secretShare == null || signable.signerIds[userPublicKey] == null) { + // A generation this device has confirmed and is waiting on the + // certificate for is not one it lacks: the proposal routinely arrives + // first, since the coordinator asks the group to sign the moment its own + // refresh completes. The session waits, and the refresh resumes it when + // the generation activates (ShareRefreshManager). + val awaitingCertificate = generation != null && signable == null && + database.keyShareDao().getGeneration(key.id, generation)?.state == ShareGenerationState.PENDING + if (!awaitingCertificate && + (generation == null || signable?.secretShare == null || signable.signerIds[userPublicKey] == null) + ) { logger.w( "Signing proposal $sessionId signs with generation ${generation ?: "(unreadable)"} of key " + "${key.id}, of which this device holds no share; declining" @@ -670,7 +680,7 @@ object FrostSigningManager { } } - val session = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation) + val session = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path, generation ?: 0) database.frostSigningSessionDao().upsert(session) database.frostSigningSessionDao().upsertItems(itemsOver(sessionId, unsignedEvents)) announceStarted(database, session) @@ -1903,6 +1913,37 @@ object FrostSigningManager { * a refusal that tips the count writes its own, because what happened there * is that a member declined, and the abandonment is the arithmetic of it. */ + /** + * Takes another pass at every session of [dkgSessionId] still running at + * [generation], which has just become signable here. A session proposed while + * this device still waited on that generation's certificate stops at the share + * it did not yet have; nothing else would wake it until the next message. + */ + suspend fun resumeAt(database: GizaDatabase, localChatRoom: LocalChatRoom, dkgSessionId: String, generation: Int) { + database.frostSigningSessionDao().getOpenSessionsForKey(dkgSessionId) + .filter { (it.generation ?: 0) == generation && it.chatRoomId == localChatRoom.chatRoom.id } + .forEach { advance(database, localChatRoom, it.id) } + } + + /** + * Ends every session of [dkgSessionId] still running at a generation older than + * [generation], whose shares are about to be deleted (docs/frost-share-refresh.md, + * Phase 8). Out loud: a session that would otherwise stall on a share that no + * longer exists says why, and it is safe to ask again. + */ + suspend fun failRotated(database: GizaDatabase, dkgSessionId: String, generation: Int) { + database.frostSigningSessionDao().getOpenSessionsForKey(dkgSessionId) + .filter { (it.generation ?: 0) < generation } + .forEach { session -> + fail( + database = database, + session = session, + reason = "This share was rotated before the session finished", + content = "was asked to sign with shares the group has since rotated. Nothing was signed, and it is safe to ask again." + ) + } + } + private suspend fun fail( database: GizaDatabase, session: FrostSigningSession, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt index e76b6fd1..1eb9cdf7 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt @@ -11,6 +11,7 @@ import mobi.giza.compose.database.model.FrostSigningSession import mobi.giza.compose.database.model.GroupKeyState import mobi.giza.compose.database.model.GroupSignedEvent import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.database.model.types.ShareStanding import mobi.giza.compose.nostr.frost.GroupKeyStateEvent import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent import mobi.giza.compose.nostr.subgroup.SubgroupParentage @@ -212,7 +213,80 @@ object GroupKeyStateManager { return null } - return database.groupKeyStateDao().replace(state) + val filed = database.groupKeyStateDao().replace(state) + // `replace` re-stamps what it files, so the row is compared on what it says. + if (filed.generation == state.generation && filed.announcedAt == state.announcedAt) retireOlderShares(database, state) + return filed + } + + /** + * The group has signed with generation [state]'s generation, which proves t + * members hold working shares of it: the older generations' shares go + * (docs/frost-share-refresh.md, D6). Only when this device holds that + * generation, active, with the same public-share table the group signed -- + * a device behind the group, or one that disagrees with it about who holds + * what, keeps what it has and says so. + */ + private suspend fun retireOlderShares(database: GizaDatabase, state: GroupKeyState) { + val generation = state.generation ?: return + val key = database.dkgSessionDao().getSessionById(state.dkgSessionId) ?: return + val shares = ShareGenerations.at(database, key, generation) + if (shares == null || ShareGenerations.active(database, key).generation != generation) { + logger.w("The group signs with generation $generation of ${key.id}, which this device does not hold; keeping what it has") + return + } + val local = shares.publicShares?.let(ShareGenerations::publicSharesHash) + if (local != state.publicSharesHash) { + logger.w("The group's generation $generation of ${key.id} has a public-share table this device disagrees with; keeping what it has") + return + } + FrostSigningManager.failRotated(database, key.id, generation) + ShareGenerations.wipeBefore(database, key, generation) + } + + /** + * Asks the group to sign the key state at the generation it now signs with, + * after a refresh (docs/frost-share-refresh.md, Phase 8). The same room, key + * and path, and the same parentage if the room has one, plus what the + * refresh changed. Signed with the new shares, which makes it the proof that + * they work -- and what every device waits on before deleting the old ones. + */ + suspend fun proposeGeneration( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + key: DkgSession, + refreshId: String?, + ): FrostSigningSession { + val shares = ShareGenerations.active(database, key) + check(shares.generation >= 1) { "Generation 0 is the ceremony's, and needs no new key state" } + val publicShares = requireNotNull(shares.publicShares) { "Generation ${shares.generation} has no public shares" } + val current = keyStateFor(database, localChatRoom.chatRoom.id) + val path = current?.pathIndices() ?: SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH + val parent = current?.parentChatRoomId?.let { parentId -> + current.birthCertificateJson?.let { Event.fromJsonOrNull(it) }?.let { SubgroupParentage(parentId, it) } + } + val thresholdPublicKey = requireNotNull(key.thresholdPublicKey) + return FrostSigningManager.proposeSigning( + database = database, + localChatRoom = localChatRoom, + userPublicKey = userPublicKey, + kind = GroupKeyStateEvent.KIND, + tags = GroupKeyStateEvent.assembleTags( + chatRoomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey, path), + dkgSessionId = key.id, + path = path, + parent = parent, + generation = GroupKeyStateEvent.ShareGenerationTags( + generation = shares.generation, + publicSharesHash = ShareGenerations.publicSharesHash(publicShares), + refreshId = refreshId, + retiredIds = shares.roster.filter { it.standing == ShareStanding.RETIRED }.map { it.participantId }, + ), + ), + content = thresholdPublicKey, + key = key, + ) } /** @@ -306,7 +380,10 @@ object GroupKeyStateManager { // every room at once, so a state that names no room names nothing. .filter { GroupKeyStateEvent.parseChatRoomId(it.tags) == chatRoomId } .mapNotNull { signed -> stateFrom(chatRoomId, signed.toEvent())?.let { signed to it } } - .maxByOrNull { (_, state) -> state.announcedAt } + // The highest generation, then the newest: `created_at` is the + // author's to choose, and a state at an older generation is still + // validly signed by the group (docs/frost-share-refresh.md, Phase 8). + .maxWithOrNull(compareBy({ (_, state) -> state.generation ?: 0 }, { (_, state) -> state.announcedAt })) /** * The state an event amounts to, or null if it amounts to none. @@ -463,6 +540,11 @@ object GroupKeyStateManager { val parent = parentageOf(announced, thresholdPublicKey, innerEvent) ?: return null + val shareGeneration = GroupKeyStateEvent.parseShareGeneration(innerEvent.tags).getOrElse { + logger.w("Key state in $chatRoomId names a share generation this device cannot read (${it.message}); dropping") + return null + } + val state = GroupKeyState( chatRoomId = announced, dkgSessionId = dkgSessionId, @@ -471,7 +553,9 @@ object GroupKeyStateManager { announcedBy = innerEvent.pubKey, announcedAt = Instant.fromEpochSeconds(innerEvent.createdAt), parentChatRoomId = parent.value?.parentChatRoomId, - birthCertificateJson = parent.value?.certificate?.toJson() + birthCertificateJson = parent.value?.certificate?.toJson(), + generation = shareGeneration?.generation, + publicSharesHash = shareGeneration?.publicSharesHash ) // Half the trust model, in one line, and the half that does not care who diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareGenerations.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareGenerations.kt index e8b6fc1b..5b11b293 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareGenerations.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareGenerations.kt @@ -2,6 +2,9 @@ package mobi.giza.compose.managers import com.vitorpamplona.quartz.nip01Core.core.HexKey import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Crypto +import kotlin.time.Clock +import mobi.giza.compose.extensions.toHex import fr.acinq.bitcoin.PrivateKey import fr.acinq.bitcoin.PublicKey import mobi.giza.compose.database.GizaDatabase @@ -83,6 +86,41 @@ object ShareGenerations { return fromRow(database, row) } + /** + * The hash of a public-share table that a signed key state carries, so a + * device can check its own table against the one the group signed: SHA-256 + * of the 33-byte shares in participant order. + */ + fun publicSharesHash(publicShares: List): String = + Crypto.sha256(publicShares.fold(ByteArray(0)) { acc, p -> acc + p.value.toByteArray() }).toHex() + + /** + * Deletes this device's shares of every generation of [key] older than + * [generation] (docs/frost-share-refresh.md, Phase 8, and D6). The public + * tables stay; the secrets go, and so does the ceremony randomness that + * rebuilds generation 0's share on its own -- a wipe that left it would wipe + * nothing. Then the write-ahead log is scrubbed, since it keeps page images + * of everything written (`GizaDatabase.scrubFreedPages`). + * + * Nothing here proves deletion to anybody else. Each member's wipe is on + * their own device, on trust. + */ + suspend fun wipeBefore(database: GizaDatabase, key: DkgSession, generation: Int) { + val now = Clock.System.now() + database.keyShareDao().getGenerations(key.id) + .filter { it.generation < generation && (it.secretShare != null || it.state != ShareGenerationState.WIPED) } + .forEach { row -> + database.keyShareDao().upsert(row.copy(secretShare = null, state = ShareGenerationState.WIPED, wipedAt = now, updatedAt = now)) + } + if (generation >= 1 && (key.secretShare != null || key.round1Random.isNotEmpty() || key.round2AuxRandom.isNotEmpty())) { + // Emptied rather than nulled: the columns are not nullable, and a + // COMPLETE ceremony never reads them again (ChillDkgRitualManager.advance + // returns before it would). + database.dkgSessionDao().upsert(key.copy(secretShare = null, round1Random = "", round2AuxRandom = "")) + } + database.scrubFreedPages() + } + /** Whether this device can sign with [key] today: it holds a share of the generation the group signs with. */ suspend fun canSign(database: GizaDatabase, key: DkgSession): Boolean = active(database, key).secretShare != null diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt index b2c9557c..6befea3c 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt @@ -420,6 +420,20 @@ object ShareRefreshManager { session.coordinatorPublicKey ) logger.i("Refresh ${session.id} complete: ${key.id} is at generation ${session.baseGeneration + 1}") + + // The coordinator asks the group to sign the new generation's key state: + // its first signature with the new shares, and what every device waits on + // before deleting the old ones (D6). Anyone can propose it again if this + // device is gone. + if (session.isCoordinator() && isRecipient) { + // Its own failure is not the refresh's, which is complete: logged, + // and anyone can propose the key state again. + runCatching { GroupKeyStateManager.proposeGeneration(database, localChatRoom, session.userPublicKey, key, session.id) } + .onFailure { if (it is CancellationException) throw it; logger.e("Could not propose generation ${session.baseGeneration + 1}'s key state", it) } + } + // A signing session at the new generation that arrived before the + // certificate has been waiting on the share it now has. + if (isRecipient) FrostSigningManager.resumeAt(database, localChatRoom, key.id, session.baseGeneration + 1) } catch (e: CancellationException) { throw e } catch (e: Throwable) { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GroupKeyStateEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GroupKeyStateEvent.kt index 118cdcd4..95a1de3a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GroupKeyStateEvent.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GroupKeyStateEvent.kt @@ -110,12 +110,13 @@ object GroupKeyStateEvent { chatRoomId: String, dkgSessionId: String, path: List = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH, - parent: SubgroupParentage? = null + parent: SubgroupParentage? = null, + generation: ShareGenerationTags? = null ): Array> = arrayOf( DTag.assemble(chatRoomId), FrostKeyTag.assemble(dkgSessionId), FrostDerivationPathTag.assemble(path) - ) + ( + ) + (generation?.toTags() ?: emptyArray()) + ( parent?.let { // Both or neither, which is why this arrives as one value rather // than as two nullable parameters a caller could half-fill. A state @@ -135,6 +136,49 @@ object GroupKeyStateEvent { * Read alongside [parseBirthCertificate] and never on its own -- see * `GroupKeyStateManager.stateFrom`. */ + /** + * What a state says about the key's shares, from generation 1 + * (docs/frost-share-refresh.md, Phase 8): the generation the group signs with, + * a hash of its public-share table, the refresh that made it, and the ids + * retired for good. A state from before shares could change carries none of + * these and reads as generation 0. + */ + data class ShareGenerationTags( + val generation: Int, + val publicSharesHash: String, + val refreshId: String?, + val retiredIds: List, + ) { + fun toTags(): Array> = ( + listOf(arrayOf(GENERATION_TAG, generation.toString()), arrayOf(PUBSHARES_TAG, publicSharesHash)) + + listOfNotNull(refreshId?.let { arrayOf(REFRESH_TAG, it) }) + + retiredIds.sorted().map { arrayOf(RETIRED_TAG, it.toString()) } + ).toTypedArray() + } + + private const val GENERATION_TAG = "frost_generation" + private const val PUBSHARES_TAG = "frost_pubshares" + private const val REFRESH_TAG = "frost_refresh" + private const val RETIRED_TAG = "frost_retired" + + /** + * The share generation a state names: null for none (generation 0), and a + * failure for a tag present but unreadable -- which names a generation this + * device cannot tell, and is not the same as naming none. + */ + fun parseShareGeneration(tags: Array>): Result { + val value = { name: String -> tags.firstOrNull { it.size >= 2 && it[0] == name }?.get(1) } + val rawGeneration = value(GENERATION_TAG) ?: return Result.success(null) + val generation = rawGeneration.toIntOrNull()?.takeIf { it >= 1 } + ?: return Result.failure(IllegalArgumentException("unreadable generation $rawGeneration")) + val hash = value(PUBSHARES_TAG)?.takeIf { it.length == 64 } + ?: return Result.failure(IllegalArgumentException("generation $generation without a public-share hash")) + val retired = tags.filter { it.size >= 2 && it[0] == RETIRED_TAG }.map { + it[1].toIntOrNull() ?: return Result.failure(IllegalArgumentException("unreadable retired id ${it[1]}")) + } + return Result.success(ShareGenerationTags(generation, hash, value(REFRESH_TAG), retired)) + } + fun parseParentChatRoomId(tags: Array>): HexKey? = tags.firstNotNullOfOrNull(SubgroupParentTag::parse)?.parentChatRoomId diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt index 9a406c43..a514781c 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt @@ -244,7 +244,8 @@ class ShareRefreshRitualJvmTest { val session = FrostSigningManager.proposeSigning(all[0].db, all[0].room, all[0].publicKey, kind = 1, tags = arrayOf(), content = "Without them") pump(all) - assertEquals(FrostSigningManager.GENERATION_REFUSAL, outbox(withheldDevice).single { it.kind == FrostSigningEvents.DECLINE }.content) + val decline = outbox(withheldDevice).single { it.kind == FrostSigningEvents.DECLINE && FrostSigningEvents.parseSessionId(it.tags) == session.id } + assertEquals(FrostSigningManager.GENERATION_REFUSAL, decline.content) } @Test @@ -301,4 +302,98 @@ class ShareRefreshRitualJvmTest { assertEquals(before, all.map { it.db.chatMessageDao().getChatMessagesByChatRoomId(group.roomId).size to it.active().secretShare }) all.forEach { assertEquals(ShareRefreshStage.COMPLETE, it.refresh(refresh.id)?.stage) } } + + // ---- Phase 8: the cutover ---------------------------------------------------------------------------------- + + /** Every owner approves every signing session waiting on them, until none is. */ + private suspend fun approveSigning(between: List) { + var asked = true + while (asked) { + asked = false + for (device in between) { + device.db.frostSigningSessionDao().getSessionsForChatRoom(device.group.roomId) + .filter { it.signApprovedAt == null && it.signDeclinedAt == null && it.stage != FrostSigningStage.COMPLETE && it.stage != FrostSigningStage.FAILED } + .forEach { FrostSigningManager.approve(device.db, device.room, it.id); asked = true } + } + pump(between) + } + } + + /** + * The point of the phase. The coordinator asks the group to sign the new + * generation's key state as the refresh completes; once a quorum has, every + * device that holds the new generation deletes the ceremony's share and the + * randomness that rebuilds it, and keeps signing with the new one. + */ + @Test + fun `once the group signs the new generation, every device deletes its old share`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val refresh = propose(all[0]) + pump(all) + approveAll(all, refresh.id) + + // Not yet: the old share stays until the new ones have signed something. + all.forEach { assertNotNull(it.key().secretShare, "device ${it.index} deleted before the group signed") } + + approveSigning(all) + + all.forEach { device -> + val state = assertNotNull(device.db.groupKeyStateDao().getByChatRoomId(group.roomId), "device ${device.index} filed no key state") + assertEquals(1, state.generation) + assertEquals(ShareGenerations.publicSharesHash(device.active().publicShares!!), state.publicSharesHash) + val key = device.key() + assertNull(key.secretShare, "device ${device.index} kept the ceremony's share") + assertEquals("", key.round1Random, "the randomness that rebuilds the share has to go too") + assertEquals("", key.round2AuxRandom) + assertNull(ShareGenerations.at(device.db, key, 0)!!.secretShare) + assertNotNull(device.active().secretShare, "and the new share stays") + } + + // The group still signs, with the new shares. + val session = FrostSigningManager.proposeSigning(all[1].db, all[1].room, all[1].publicKey, kind = 1, tags = arrayOf(), content = "Still the room") + pump(all) + approveSigning(all) + assertEquals(FrostSigningStage.COMPLETE, all[1].db.frostSigningSessionDao().getSessionById(session.id)?.stage) + } + + @Test + fun `a session left at the old generation fails out loud when its shares go`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val old = FrostSigningManager.proposeSigning(all[0].db, all[0].room, all[0].publicKey, kind = 1, tags = arrayOf(), content = "Before the rotation") + assertEquals(0, old.generation) + pump(all) + + val refresh = propose(all[0]) + pump(all) + approveAll(all, refresh.id) + // Approve only the key state's session, not the old one. + all.forEach { device -> + device.db.frostSigningSessionDao().getSessionsForChatRoom(group.roomId) + .filter { it.id != old.id && it.signApprovedAt == null && it.signDeclinedAt == null } + .forEach { FrostSigningManager.approve(device.db, device.room, it.id) } + } + pump(all) + + val failed = all[0].db.frostSigningSessionDao().getSessionById(old.id)!! + assertEquals(FrostSigningStage.FAILED, failed.stage) + assertEquals("This share was rotated before the session finished", failed.failureReason) + } + + @Test + fun `a key state at an older generation loses whatever its timestamp`() = runBlocking { + val group = Group(3, 2) + val device = devicesFor(group).first() + val dao = device.db.groupKeyStateDao() + val base = mobi.giza.compose.database.model.GroupKeyState( + chatRoomId = group.roomId, dkgSessionId = ceremonyId, thresholdPublicKey = group.thresholdPublicKey, + derivationPath = SharedKeyDerivation.formatPath(), announcedBy = device.publicKey, + announcedAt = kotlin.time.Instant.fromEpochSeconds(2_000), generation = 1, publicSharesHash = "aa".repeat(32), + ) + dao.replace(base) + val older = base.copy(announcedAt = kotlin.time.Instant.fromEpochSeconds(9_000), generation = null, publicSharesHash = null) + assertEquals(1, dao.replace(older).generation) + assertEquals(1, dao.getByChatRoomId(group.roomId)?.generation) + } } diff --git a/docs/frost-share-refresh.md b/docs/frost-share-refresh.md index 7b4f75e3..b6f246ca 100644 --- a/docs/frost-share-refresh.md +++ b/docs/frost-share-refresh.md @@ -19,7 +19,8 @@ ceremony they describe and the rule that a room's id *is* the key it signs with. | 2 | secp256k1-kmp `7fd0d34`, `8beb781`, `0f5a710` | `:tests:jvmTest` and `:tests:linuxX64Test` 112/112, the zkp vector byte for byte through both backends | | 3 | bitcoin-kmp `d2e15b8`, `3cd82d1` | `jvmTest` 274/274, including withheld → repaired with `FrostReducedEnrollment` → signs | | 4 | lightning-kmp `2043f254`, lightning-kmp-app `3794eb8`, Giza Phase 4 | lightning-kmp `crypto` tests 104/104; Giza `compileDebugKotlinAndroid`, `jvmTest` 1183/1183, audits | -| 7 | Phase 7 | `ShareRefreshRitualJvmTest` (7: three devices with real host keys refresh through the real zkp module and then sign at generation 1 as the same room; nothing published before approval; a withheld member follows to the new table with no share and declines to sign; a minority refused; one confirmation per generation; a second proposal hands back the first; a redelivered transcript changes nothing); `jvmTest` 1190/1190; `compileDebugKotlinAndroid`; audits | +| 7 | `f8974aec` | `ShareRefreshRitualJvmTest` (7: three devices with real host keys refresh through the real zkp module and then sign at generation 1 as the same room; nothing published before approval; a withheld member follows to the new table with no share and declines to sign; a minority refused; one confirmation per generation; a second proposal hands back the first; a redelivered transcript changes nothing); `jvmTest` 1190/1190; `compileDebugKotlinAndroid`; audits | +| 8 | Phase 8 | three more in `ShareRefreshRitualJvmTest`: once the group signs the generation-1 key state every device deletes the ceremony's share and its randomness and still signs; a gen-0 session left open fails with "This share was rotated before the session finished"; a key state at an older generation loses whatever its timestamp. `jvmTest` 1193/1193; `compileDebugKotlinAndroid`; audits | | 5 | `4040ae74` | `SecureDeleteJvmTest` (5, two of them controls that fail without the fix); `jvmTest` 1176/1176; `compileDebugKotlinAndroid`, `processDebugResources` | | 6 | `fce51e20` | `ShareGenerationsJvmTest` (7: a real 2-of-3 signature with hand-refreshed shares verifying as the unchanged room, a decline from a device without the generation, a withheld member who is not a signer); every existing signing test unedited; `jvmTest` 1183/1183; `compileDebugKotlinAndroid`; the M3, brand and wallet audits | @@ -42,6 +43,9 @@ Where the build chose differently from the plan: | Phase 7: the refusals | one more: every participant not retired has to be a recipient or withheld, so a proposal cannot leave someone in neither list. A participant stale at the base generation is withheld again, as stale, automatically: a refresh brings nobody back, a repair does. A recipient that refuses a proposal on arrival broadcasts a failure, since the certificate needs it; anyone else refuses silently. D5's capability check waits for Phase 13 | | Phase 7: a kill between storing the pending generation and sending the confirmation | handled the way the plan said -- `confirmAndStore` is idempotent for the refresh that holds the claim, so the next pass stores it again and sends -- but not tested on its own | | Phase 7: the transcript | system lines through `RitualNotice`, settled. The request line opens nothing until the refresh screen exists (Phase 11) | +| Phase 8: any recipient proposes the new key state | the coordinator does, automatically, the moment its refresh completes; anyone can again. That races the certificate to the other devices, and lost in the first test run: a device still holding the generation as pending declined. A proposal at a generation this device has confirmed and is waiting on the certificate for now waits instead, and the refresh resumes it on activation (`FrostSigningManager.resumeAt`) | +| Phase 8: `ShareRefreshCutoverJvmTest` | the cutover tests live in `ShareRefreshRitualJvmTest`, which has the multi-device harness. The bytes-on-disk check is `SecureDeleteJvmTest`'s, against a file; these devices are in memory. A device that disagrees with the group's table keeps its share and logs it, untested | +| Phase 8: gen-0's randomness nulled | emptied: `round1Random` and `round2AuxRandom` are not nullable, and a complete ceremony never reads them again | | Phase 5: `dataExtractionRules` or `allowBackup="false"` | both. From Android 12 `allowBackup="false"` stops cloud backup but not a device-to-device transfer | ## The headline: enrollment cannot rotate a share From c4fe4c9c26986c678af9d470ed31de54fbffba85 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Thu, 19 Nov 2026 23:36:48 +0200 Subject: [PATCH 07/12] feat: rotating a group's shares without a member it removed (frost-share-refresh, Phase 9) A removal takes a member out of the room, not out of the key: their share still helps sign. After an admin removes a member who holds a live share, the room screen offers to rotate without them -- a second act, never folded into the removal, since it needs every remaining holder. ShareRefreshManager.proposeWithout withholds them for good (RETIRED); the refusals say when that would leave fewer than t holders (the group could not sign at all) or not a majority (remove fewer at a time). Tested in the ritual harness: in a 2-of-3, the other two sign at generation 1 and the removed member's old share signs nothing with a new one. jvmTest 1195/1195, compileDebugKotlinAndroid, audits. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 4 ++ .../repository/DatabaseChatRepository.kt | 12 ++++ .../compose/managers/ShareRefreshManager.kt | 38 +++++++++- .../giza/compose/repository/ChatRepository.kt | 17 +++++ .../ui/composable/ChatRoomDetailScreen.kt | 28 ++++++++ .../ui/view/model/ChatRoomDetailViewModel.kt | 30 +++++++- .../managers/ShareRefreshRitualJvmTest.kt | 72 +++++++++++++++++++ docs/frost-share-refresh.md | 4 +- 8 files changed, 202 insertions(+), 3 deletions(-) diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 393549ba..6cafefea 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -111,6 +111,10 @@ This group was disbanded. Nothing more can be sent into it, and nobody can rejoin. Ends the group for everyone. Nobody can rejoin; a new conversation is a new group. Removal sent; it takes effect once a relay accepts it + Rotate shares without them? + They are out of the room, but their share of the group key still helps sign until the shares are rotated without them. Rotating asks every remaining member to take part. Shares held before the rotation stop working once every device has deleted them. + Rotate shares + Share rotation proposed; every remaining member is asked to take part Library Lightning invoice Open in a wallet app diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index ca74f6b3..c7c28652 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -40,6 +40,7 @@ import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.database.model.types.MarmotReindexReport import mobi.giza.compose.identity.Identity import mobi.giza.compose.identity.toKeyPair +import mobi.giza.compose.managers.ShareRefreshManager import mobi.giza.compose.managers.ChronicleManager import mobi.giza.compose.managers.FrostSigningManager import mobi.giza.compose.managers.GroupKeyStateManager @@ -631,6 +632,17 @@ class DatabaseChatRepository( database.marmotOutboundDao().removeMember(localChatRoom, memberPublicKey) } + override suspend fun holdsShare(localChatRoom: LocalChatRoom, memberPublicKey: HexKey): Boolean = + runCatching { ShareRefreshManager.liveIdOf(database, localChatRoom, memberPublicKey) != null }.getOrDefault(false) + + override suspend fun rotateSharesWithout(localChatRoom: LocalChatRoom, memberPublicKey: HexKey): String? { + val identity = activeIdentity.value ?: return "No identity is signed in" + val nostrPrivateKey = identity.toKeyPair().privKey ?: return "This identity cannot sign" + return runCatching { + ShareRefreshManager.proposeWithout(database, localChatRoom, identity.nostrPublicKey, nostrPrivateKey, memberPublicKey) + }.exceptionOrNull()?.let { it.message ?: it::class.simpleName ?: "Unknown error" } + } + override suspend fun disbandChatRoom(localChatRoom: LocalChatRoom) { database.marmotOutboundDao().disband(localChatRoom) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt index 6befea3c..160ff004 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt @@ -86,7 +86,8 @@ object ShareRefreshManager { } if (withheld.values.any { it == ShareStanding.LIVE }) return "a withheld participant cannot stay live" if (recipients.size < key.threshold) { - return "${recipients.size} recipients cannot carry a ${key.threshold}-of-${key.participantCount} key" + return "it would leave ${recipients.size} members holding shares, fewer than the ${key.threshold} it takes to sign; " + + "the group could not sign at all, and only a new ceremony goes on from there" } if (recipients.size * 2 <= notRetired.size) { return "${recipients.size} of ${notRetired.size} is not a majority, so two such refreshes could both complete" @@ -165,6 +166,41 @@ object ShareRefreshManager { return session } + /** + * The participant id [memberPublicKey] holds a live share of [localChatRoom]'s + * key under, or null when they hold none -- the question a removal asks + * before offering to rotate without them (docs/frost-share-refresh.md, Phase 9). + */ + suspend fun liveIdOf(database: GizaDatabase, localChatRoom: LocalChatRoom, memberPublicKey: HexKey): Int? { + val key = FrostSigningManager.completedKey(database, localChatRoom.chatRoom.id) ?: return null + if (!isKeysRoom(database, localChatRoom, key)) return null + return ShareGenerations.active(database, key).signerIds[memberPublicKey] + } + + /** + * Opens a refresh that withholds [memberPublicKey] for good, after they were + * removed from the room (docs/frost-share-refresh.md, Phase 9). The removal is + * one admin's commit; this needs every remaining holder, so it is a second + * act, never folded into the first. + * + * Refused, with a reason, when it would leave fewer than t live ids -- the + * group could not sign at all, and only a new ceremony goes on from there -- + * or when the remaining recipients are not a majority (remove fewer at a time). + */ + suspend fun proposeWithout( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + nostrPrivateKey: ByteArray, + memberPublicKey: HexKey, + ): ShareRefreshSession { + val key = FrostSigningManager.completedKey(database, localChatRoom.chatRoom.id) + ?: throw IllegalStateException("This group has no shared key this device can rotate") + val id = ShareGenerations.active(database, key).signerIds[memberPublicKey] + ?: throw IllegalStateException("They hold no share of the group's key") + return proposeRefresh(database, localChatRoom, userPublicKey, nostrPrivateKey, key, mapOf(id to ShareStanding.RETIRED)) + } + /** A refresh of [key] still running on this device, if there is one. One at a time per key. */ private suspend fun running(database: GizaDatabase, key: DkgSession): ShareRefreshSession? = database.shareRefreshDao().getSessionsForKey(key.id).firstOrNull { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt index c50ba407..0cc98225 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -259,6 +259,19 @@ interface ChatRepository { */ suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) + /** + * Whether [memberPublicKey] holds a live share of the room's key, and so + * whether a removal leaves them able to help sign until the shares are + * rotated without them (docs/frost-share-refresh.md, Phase 9). + */ + suspend fun holdsShare(localChatRoom: LocalChatRoom, memberPublicKey: HexKey): Boolean + + /** + * Proposes rotating the room's shares without [memberPublicKey], withheld for + * good. Returns null when the proposal went out, or why it could not. + */ + suspend fun rotateSharesWithout(localChatRoom: LocalChatRoom, memberPublicKey: HexKey): String? + /** * Disbands a current-profile room this device administers. Absorbing: once the * disband commit is applied nobody rejoins, and a replacement conversation is a @@ -447,6 +460,10 @@ interface ChatRepository { override suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) = Unit + override suspend fun holdsShare(localChatRoom: LocalChatRoom, memberPublicKey: HexKey): Boolean = false + + override suspend fun rotateSharesWithout(localChatRoom: LocalChatRoom, memberPublicKey: HexKey): String? = null + override suspend fun disbandChatRoom(localChatRoom: LocalChatRoom) = Unit override suspend fun softDeleteChatRoom( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt index 472db605..204e780e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt @@ -102,6 +102,12 @@ import mobi.giza.compose.resources.direct_message_functionality_will_be_here import mobi.giza.compose.resources.invite_new_member import mobi.giza.compose.resources.leave_group import mobi.giza.compose.resources.remove_from_group +import mobi.giza.compose.resources.share_rotation_requested +import mobi.giza.compose.resources.not_now +import mobi.giza.compose.resources.rotate_shares +import mobi.giza.compose.resources.rotate_shares_without_body +import mobi.giza.compose.resources.rotate_shares_without_title +import androidx.compose.material3.AlertDialog import mobi.giza.compose.resources.disband_group import mobi.giza.compose.resources.disband_group_explainer import mobi.giza.compose.resources.group_disbanded @@ -160,6 +166,28 @@ fun ChatRoomDetailScreen( // composable, and a lambda passed to onClick is not. val notify = rememberNotifier(rememberCoroutineScope()) val removalRequested = stringResource(Res.string.member_removal_requested) + val rotationRequested = stringResource(Res.string.share_rotation_requested) + + // Offered after removing a member who still holds a share of the room's key: + // the removal took them out of the room, not out of the key + // (docs/frost-share-refresh.md, Phase 9). + chatRoomDetailViewModel.rotationOffer?.let { offer -> + AlertDialog( + onDismissRequest = { chatRoomDetailViewModel.dismissRotationOffer() }, + title = { Text(stringResource(Res.string.rotate_shares_without_title)) }, + text = { Text(stringResource(Res.string.rotate_shares_without_body)) }, + confirmButton = { + TextButton(onClick = { chatRoomDetailViewModel.rotateSharesWithout(offer) { failure -> notify(failure ?: rotationRequested) } }) { + Text(stringResource(Res.string.rotate_shares)) + } + }, + dismissButton = { + TextButton(onClick = { chatRoomDetailViewModel.dismissRotationOffer() }) { + Text(stringResource(Res.string.not_now)) + } + }, + ) + } ScreenStateTransition(chatRoomDetailViewModel.chatRoomDetailUIState) { uiState -> when (val chatRoomDetailUIState = uiState) { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt index d66e38b5..f67a7b78 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -118,10 +118,38 @@ class ChatRoomDetailViewModel( */ fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey, onDone: (String?) -> Unit = {}) { viewModelScope.launch(Dispatchers.IO) { + // Asked before the removal, while they are still in the room's roster. + val heldShare = chatRepository.holdsShare(localChatRoom, memberPublicKey) val failure = runCatching { chatRepository.removeMember(localChatRoom, memberPublicKey) } .exceptionOrNull() initiateChatRoomDetail() - viewModelScope.launch(Dispatchers.Main) { onDone(failure?.message) } + viewModelScope.launch(Dispatchers.Main) { + onDone(failure?.message) + // The removal takes them out of the room, not out of the key: they + // can still help sign until the shares are rotated without them. + // A second act, offered rather than folded in -- it needs every + // remaining holder (docs/frost-share-refresh.md, Phase 9). + if (failure == null && heldShare) rotationOffer = RotationOffer(localChatRoom, memberPublicKey) + } + } + } + + /** A removed member who still holds a share of the room's key, for the offer to rotate without them. */ + data class RotationOffer(val localChatRoom: LocalChatRoom, val memberPublicKey: HexKey) + + var rotationOffer: RotationOffer? by mutableStateOf(null) + private set + + fun dismissRotationOffer() { + rotationOffer = null + } + + /** Proposes the rotation [rotationOffer] offered. [onDone] gets null on success, or why it could not. */ + fun rotateSharesWithout(offer: RotationOffer, onDone: (String?) -> Unit) { + rotationOffer = null + viewModelScope.launch(Dispatchers.IO) { + val failure = chatRepository.rotateSharesWithout(offer.localChatRoom, offer.memberPublicKey) + viewModelScope.launch(Dispatchers.Main) { onDone(failure) } } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt index a514781c..0e048a54 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt @@ -396,4 +396,76 @@ class ShareRefreshRitualJvmTest { assertEquals(1, dao.replace(older).generation) assertEquals(1, dao.getByChatRoomId(group.roomId)?.generation) } + + // ---- Phase 9: rotating without a removed member -------------------------------------------------------------- + + /** + * A removed member is out of the room but still holds a share. Rotating + * without them, withheld for good, leaves the other two signing at the new + * generation -- and the removed member's share, which their device still has, + * combines with nothing of it. + */ + @Test + fun `rotating without a removed member leaves their share useless`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val (alice, bob, carol) = all + val carolId = group.idOf[2] + assertEquals(carolId, ShareRefreshManager.liveIdOf(alice.db, alice.room, carol.publicKey)) + + val refresh = ShareRefreshManager.proposeWithout(alice.db, alice.room, alice.publicKey, alice.privateKey, carol.publicKey) + assertEquals(mapOf(carolId to ShareStanding.RETIRED), refresh.withheldStandings()) + pump(all) + approveAll(all, refresh.id) + approveSigning(all) + + listOf(alice, bob).forEach { device -> + val active = device.active() + assertEquals(1, active.generation) + assertEquals(ShareStanding.RETIRED, active.roster.single { it.participantId == carolId }.standing) + assertNull(active.signerIds[carol.publicKey], "carol must not be a signer") + assertNull(ShareRefreshManager.liveIdOf(device.db, device.room, carol.publicKey)) + } + // Retired is not stale: carol's id is gone from the ids that count. + assertNull(alice.active().participantIds[carol.publicKey]) + + // Alice and Bob sign at generation 1. + val session = FrostSigningManager.proposeSigning(alice.db, alice.room, alice.publicKey, kind = 1, tags = arrayOf(), content = "Without carol") + assertEquals(1, session.generation) + pump(all) + approveSigning(all) + assertEquals(FrostSigningStage.COMPLETE, alice.db.frostSigningSessionDao().getSessionById(session.id)?.stage) + + // Carol's old share and Alice's new one: no signature. + val table = alice.active().publicShares!! + val aliceId = group.idOf[0] + val mixed = (0 until 3).map { id -> + when (id) { + carolId -> group.keyMaterial.secretShares[carolId] + aliceId -> alice.active().secretShare!! + else -> bob.active().secretShare!! + } + } + val km = KeyMaterial(group.keyMaterial.thresholdPublicKey, mixed, table, 2) + val signers = listOf(aliceId, carolId).sorted().map { it.toUInt() } + val msg = ByteVector32("5a".repeat(32)) + val signs = runCatching { + val nonces = signers.map { id -> Frost.generateNonce(ByteVector32("0${id}".padEnd(64, '7')), km.secretShares[id.toInt()], km.publicShares[id.toInt()], km.tweakCache().tweakedPublicKey, msg, null) } + val publicNonces = nonces.map { it.second } + val partials = signers.mapIndexed { i, id -> Frost.sign(km.secretShares[id.toInt()], nonces[i].first, id, msg, signers, km, publicNonces).right!! } + val sig = Frost.aggregatePartialSignatures(partials, msg, signers, km, publicNonces).right!! + fr.acinq.bitcoin.Crypto.verifySignatureSchnorr(msg, sig, km.tweakCache().tweakedPublicKey) + }.getOrDefault(false) + assertTrue(!signs, "a removed member's old share must not sign with a new one") + } + + @Test + fun `rotating without a member is refused when too few would be left to sign`() = runBlocking { + val group = Group(2, 2) + val (alice, bob) = devicesFor(group) + val error = assertFailsWith { + ShareRefreshManager.proposeWithout(alice.db, alice.room, alice.publicKey, alice.privateKey, bob.publicKey) + } + assertTrue(error.message!!.contains("fewer than the 2 it takes to sign"), error.message) + } } diff --git a/docs/frost-share-refresh.md b/docs/frost-share-refresh.md index b6f246ca..99b5f70f 100644 --- a/docs/frost-share-refresh.md +++ b/docs/frost-share-refresh.md @@ -20,7 +20,8 @@ ceremony they describe and the rule that a room's id *is* the key it signs with. | 3 | bitcoin-kmp `d2e15b8`, `3cd82d1` | `jvmTest` 274/274, including withheld → repaired with `FrostReducedEnrollment` → signs | | 4 | lightning-kmp `2043f254`, lightning-kmp-app `3794eb8`, Giza Phase 4 | lightning-kmp `crypto` tests 104/104; Giza `compileDebugKotlinAndroid`, `jvmTest` 1183/1183, audits | | 7 | `f8974aec` | `ShareRefreshRitualJvmTest` (7: three devices with real host keys refresh through the real zkp module and then sign at generation 1 as the same room; nothing published before approval; a withheld member follows to the new table with no share and declines to sign; a minority refused; one confirmation per generation; a second proposal hands back the first; a redelivered transcript changes nothing); `jvmTest` 1190/1190; `compileDebugKotlinAndroid`; audits | -| 8 | Phase 8 | three more in `ShareRefreshRitualJvmTest`: once the group signs the generation-1 key state every device deletes the ceremony's share and its randomness and still signs; a gen-0 session left open fails with "This share was rotated before the session finished"; a key state at an older generation loses whatever its timestamp. `jvmTest` 1193/1193; `compileDebugKotlinAndroid`; audits | +| 8 | `51615992` | three more in `ShareRefreshRitualJvmTest`: once the group signs the generation-1 key state every device deletes the ceremony's share and its randomness and still signs; a gen-0 session left open fails with "This share was rotated before the session finished"; a key state at an older generation loses whatever its timestamp. `jvmTest` 1193/1193; `compileDebugKotlinAndroid`; audits | +| 9 | Phase 9 | two more in `ShareRefreshRitualJvmTest`: rotating without a removed member of a 2-of-3 leaves the other two signing at generation 1 and the removed member's old share signing nothing with a new one; a 2-of-2 is refused with "fewer than the 2 it takes to sign". `jvmTest` 1195/1195; `compileDebugKotlinAndroid`; audits. The dialog has not been seen on a device | | 5 | `4040ae74` | `SecureDeleteJvmTest` (5, two of them controls that fail without the fix); `jvmTest` 1176/1176; `compileDebugKotlinAndroid`, `processDebugResources` | | 6 | `fce51e20` | `ShareGenerationsJvmTest` (7: a real 2-of-3 signature with hand-refreshed shares verifying as the unchanged room, a decline from a device without the generation, a withheld member who is not a signer); every existing signing test unedited; `jvmTest` 1183/1183; `compileDebugKotlinAndroid`; the M3, brand and wallet audits | @@ -46,6 +47,7 @@ Where the build chose differently from the plan: | Phase 8: any recipient proposes the new key state | the coordinator does, automatically, the moment its refresh completes; anyone can again. That races the certificate to the other devices, and lost in the first test run: a device still holding the generation as pending declined. A proposal at a generation this device has confirmed and is waiting on the certificate for now waits instead, and the refresh resumes it on activation (`FrostSigningManager.resumeAt`) | | Phase 8: `ShareRefreshCutoverJvmTest` | the cutover tests live in `ShareRefreshRitualJvmTest`, which has the multi-device harness. The bytes-on-disk check is `SecureDeleteJvmTest`'s, against a file; these devices are in memory. A device that disagrees with the group's table keeps its share and logs it, untested | | Phase 8: gen-0's randomness nulled | emptied: `round1Random` and `round2AuxRandom` are not nullable, and a complete ceremony never reads them again | +| Phase 9: an action on the members screen | a dialog the room detail screen raises after a removal succeeds, when the member held a live share (asked before the removal, while they are still in the roster). "Not now" leaves it; nothing offers it again yet -- Phase 11's Shares section is where a rotation can be started at any time. `MemberRemovalRefreshJvmTest` is two tests in the ritual harness | | Phase 5: `dataExtractionRules` or `allowBackup="false"` | both. From Android 12 `allowBackup="false"` stops cloud backup but not a device-to-device transfer | ## The headline: enrollment cannot rotate a share From 1c3e0e934eea4a63890dbf1c4fbbed5ec0167de6 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Thu, 19 Nov 2026 23:46:38 +0200 Subject: [PATCH 08/12] feat: re-enrollment, a stale member repaired into the generation the group signs with (frost-share-refresh, Phase 10) ShareRepairManager brings back a participant id a refresh left stale, with FrostReducedEnrollment in repair mode, on kinds 30346-30349. t live helpers approve and run it; their round-1.1 shares and round-1.2 sums are raw additive shares, so each goes NIP-44-encrypted between the two parties' ChillDKG host keys. The target checks the result against the public share the group signed -- never one the helpers supply -- stores it, and proves it with a Schnorr signature by the share, which every device checks before marking the id live. The share is a point of the new polynomial that the old device never had. 10b: a new identity at an id -- a lost device, a compromised account -- is bound by a group-signed key state first (frost_member, GroupKeyState .memberBindings, schema 40), applied only to an id that is not live. Until then its request waits, with nothing sent. A key state amending one at the same generation is stamped a second later, so a binding can never tie with the state it adds to. jvmTest 1198/1198, compileDebugKotlinAndroid, audits. Co-Authored-By: Claude Opus 5.5 --- .../40.json | 5200 +++++++++++++++++ .../giza/compose/database/GizaDatabase.kt | 13 +- .../giza/compose/database/dao/NostrDao.kt | 12 + .../compose/database/dao/ShareRepairDao.kt | 27 + .../compose/database/model/ChatMessage.kt | 17 +- .../compose/database/model/GroupKeyState.kt | 9 + .../database/model/ShareRepairMessage.kt | 33 + .../database/model/ShareRepairSession.kt | 53 + .../database/model/types/ShareRepairStage.kt | 19 + .../compose/managers/GroupKeyStateManager.kt | 75 +- .../compose/managers/ShareRepairManager.kt | 430 ++ .../compose/nostr/frost/GroupKeyStateEvent.kt | 28 +- .../compose/nostr/frost/ShareRepairEvents.kt | 43 + .../ShippedProfileUpgradeJvmTest.kt | 9 +- .../managers/ShareRefreshRitualJvmTest.kt | 161 +- docs/frost-share-refresh.md | 7 +- 16 files changed, 6121 insertions(+), 15 deletions(-) create mode 100644 composeApp/schemas/mobi.giza.compose.database.GizaDatabase/40.json create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRepairDao.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRepairMessage.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRepairSession.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareRepairStage.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRepairManager.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/ShareRepairEvents.kt diff --git a/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/40.json b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/40.json new file mode 100644 index 00000000..0326d68b --- /dev/null +++ b/composeApp/schemas/mobi.giza.compose.database.GizaDatabase/40.json @@ -0,0 +1,5200 @@ +{ + "formatVersion": 1, + "database": { + "version": 40, + "identityHash": "a0861ae568a9ad3ab9b9c61a0c9678ab", + "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, `walletPolicy` 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": "walletPolicy", + "columnName": "walletPolicy", + "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, 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" + } + ], + "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, `generation` INTEGER, `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": "generation", + "columnName": "generation", + "affinity": "INTEGER" + }, + { + "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, `generation` INTEGER, `publicSharesHash` TEXT, `memberBindings` 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": "generation", + "columnName": "generation", + "affinity": "INTEGER" + }, + { + "fieldPath": "publicSharesHash", + "columnName": "publicSharesHash", + "affinity": "TEXT" + }, + { + "fieldPath": "memberBindings", + "columnName": "memberBindings", + "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": "KeyShareGeneration", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`dkgSessionId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `secretShare` TEXT, `publicShares` TEXT NOT NULL, `state` TEXT NOT NULL, `refreshSessionId` TEXT, `recoveryData` TEXT, `activatedAt` INTEGER, `wipedAt` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`dkgSessionId`, `generation`), FOREIGN KEY(`dkgSessionId`) REFERENCES `DkgSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "secretShare", + "columnName": "secretShare", + "affinity": "TEXT" + }, + { + "fieldPath": "publicShares", + "columnName": "publicShares", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "state", + "columnName": "state", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "refreshSessionId", + "columnName": "refreshSessionId", + "affinity": "TEXT" + }, + { + "fieldPath": "recoveryData", + "columnName": "recoveryData", + "affinity": "TEXT" + }, + { + "fieldPath": "activatedAt", + "columnName": "activatedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "wipedAt", + "columnName": "wipedAt", + "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 + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "dkgSessionId", + "generation" + ] + }, + "indices": [ + { + "name": "index_KeyShareGeneration_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_KeyShareGeneration_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "DkgSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "dkgSessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "KeyShareMember", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`dkgSessionId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `participantId` INTEGER NOT NULL, `memberPublicKey` TEXT NOT NULL, `hostPublicKey` TEXT NOT NULL, `standing` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`dkgSessionId`, `generation`, `participantId`), FOREIGN KEY(`dkgSessionId`, `generation`) REFERENCES `KeyShareGeneration`(`dkgSessionId`, `generation`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "participantId", + "columnName": "participantId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "memberPublicKey", + "columnName": "memberPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "hostPublicKey", + "columnName": "hostPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "standing", + "columnName": "standing", + "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": false, + "columnNames": [ + "dkgSessionId", + "generation", + "participantId" + ] + }, + "indices": [ + { + "name": "index_KeyShareMember_dkgSessionId_generation", + "unique": false, + "columnNames": [ + "dkgSessionId", + "generation" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_KeyShareMember_dkgSessionId_generation` ON `${TABLE_NAME}` (`dkgSessionId`, `generation`)" + } + ], + "foreignKeys": [ + { + "table": "KeyShareGeneration", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "dkgSessionId", + "generation" + ], + "referencedColumns": [ + "dkgSessionId", + "generation" + ] + } + ] + }, + { + "tableName": "ShareRefreshConfirmation", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`dkgSessionId` TEXT NOT NULL, `baseGeneration` INTEGER NOT NULL, `refreshSessionId` TEXT NOT NULL, `confirmedAt` INTEGER NOT NULL, PRIMARY KEY(`dkgSessionId`, `baseGeneration`))", + "fields": [ + { + "fieldPath": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "baseGeneration", + "columnName": "baseGeneration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "refreshSessionId", + "columnName": "refreshSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "confirmedAt", + "columnName": "confirmedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "dkgSessionId", + "baseGeneration" + ] + } + }, + { + "tableName": "ShareRefreshMessage", + "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, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `participantPublicKey`, `kind`), FOREIGN KEY(`sessionId`) REFERENCES `ShareRefreshSession`(`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 + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAt", + "columnName": "savedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "sessionId", + "participantPublicKey", + "kind" + ] + }, + "foreignKeys": [ + { + "table": "ShareRefreshSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ShareRefreshSession", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `coordinatorPublicKey` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `baseGeneration` INTEGER NOT NULL, `recipientIds` TEXT NOT NULL, `withheld` TEXT, `stage` TEXT NOT NULL, `round1Random` TEXT NOT NULL, `auxRandom` TEXT NOT NULL, `dealApprovedAt` INTEGER, `confirmApprovedAt` INTEGER, `approvalRequestedThrough` TEXT, `coordinatorRound1` TEXT, `certificate` TEXT, `failureReason` 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": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "coordinatorPublicKey", + "columnName": "coordinatorPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "baseGeneration", + "columnName": "baseGeneration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recipientIds", + "columnName": "recipientIds", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "withheld", + "columnName": "withheld", + "affinity": "TEXT" + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "round1Random", + "columnName": "round1Random", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "auxRandom", + "columnName": "auxRandom", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dealApprovedAt", + "columnName": "dealApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "confirmApprovedAt", + "columnName": "confirmApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequestedThrough", + "columnName": "approvalRequestedThrough", + "affinity": "TEXT" + }, + { + "fieldPath": "coordinatorRound1", + "columnName": "coordinatorRound1", + "affinity": "TEXT" + }, + { + "fieldPath": "certificate", + "columnName": "certificate", + "affinity": "TEXT" + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "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_ShareRefreshSession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ShareRefreshSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_ShareRefreshSession_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ShareRefreshSession_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "table": "ChatRoom", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "chatRoomId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ShareRepairMessage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sessionId` TEXT NOT NULL, `senderPublicKey` TEXT NOT NULL, `kind` INTEGER NOT NULL, `recipientPublicKey` TEXT NOT NULL, `payload` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `savedAt` INTEGER NOT NULL, PRIMARY KEY(`sessionId`, `senderPublicKey`, `kind`, `recipientPublicKey`), FOREIGN KEY(`sessionId`) REFERENCES `ShareRepairSession`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "sessionId", + "columnName": "sessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderPublicKey", + "columnName": "senderPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recipientPublicKey", + "columnName": "recipientPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "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": false, + "columnNames": [ + "sessionId", + "senderPublicKey", + "kind", + "recipientPublicKey" + ] + }, + "foreignKeys": [ + { + "table": "ShareRepairSession", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "sessionId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "ShareRepairSession", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `chatRoomId` TEXT NOT NULL, `dkgSessionId` TEXT NOT NULL, `generation` INTEGER NOT NULL, `targetId` INTEGER NOT NULL, `targetPublicKey` TEXT NOT NULL, `targetHostPublicKey` TEXT NOT NULL, `helperIds` TEXT NOT NULL, `userPublicKey` TEXT NOT NULL, `stage` TEXT NOT NULL, `sessionRandom` TEXT NOT NULL, `helpApprovedAt` INTEGER, `approvalRequested` INTEGER NOT NULL, `failureReason` 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": "dkgSessionId", + "columnName": "dkgSessionId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "generation", + "columnName": "generation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "targetId", + "columnName": "targetId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "targetPublicKey", + "columnName": "targetPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "targetHostPublicKey", + "columnName": "targetHostPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "helperIds", + "columnName": "helperIds", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userPublicKey", + "columnName": "userPublicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sessionRandom", + "columnName": "sessionRandom", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "helpApprovedAt", + "columnName": "helpApprovedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "approvalRequested", + "columnName": "approvalRequested", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "failureReason", + "columnName": "failureReason", + "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_ShareRepairSession_chatRoomId", + "unique": false, + "columnNames": [ + "chatRoomId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ShareRepairSession_chatRoomId` ON `${TABLE_NAME}` (`chatRoomId`)" + }, + { + "name": "index_ShareRepairSession_dkgSessionId", + "unique": false, + "columnNames": [ + "dkgSessionId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_ShareRepairSession_dkgSessionId` ON `${TABLE_NAME}` (`dkgSessionId`)" + } + ], + "foreignKeys": [ + { + "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": "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, `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": "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": "MarmotSenderRatchet", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatRoomId` TEXT NOT NULL, `epoch` INTEGER NOT NULL, `leafIndex` INTEGER NOT NULL, `applicationGeneration` INTEGER NOT NULL, `record` BLOB 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": "epoch", + "columnName": "epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "leafIndex", + "columnName": "leafIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "applicationGeneration", + "columnName": "applicationGeneration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "record", + "columnName": "record", + "affinity": "BLOB", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "chatRoomId" + ] + }, + "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, 'a0861ae568a9ad3ab9b9c61a0c9678ab')" + ] + } +} \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt index a2cbd810..475a6321 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt @@ -26,6 +26,7 @@ import mobi.giza.compose.database.dao.GroupSignedEventDao import mobi.giza.compose.database.dao.InReplyToRelationDao import mobi.giza.compose.database.dao.KeyShareDao import mobi.giza.compose.database.dao.ShareRefreshDao +import mobi.giza.compose.database.dao.ShareRepairDao import mobi.giza.compose.database.dao.MarmotCommitResultDao import mobi.giza.compose.database.dao.MarmotOutboundDao import mobi.giza.compose.database.dao.MarmotGroupEventDao @@ -72,6 +73,8 @@ import mobi.giza.compose.database.model.KeyShareMember import mobi.giza.compose.database.model.ShareRefreshConfirmation import mobi.giza.compose.database.model.ShareRefreshMessage import mobi.giza.compose.database.model.ShareRefreshSession +import mobi.giza.compose.database.model.ShareRepairMessage +import mobi.giza.compose.database.model.ShareRepairSession import mobi.giza.compose.database.model.GroupSignedEvent import mobi.giza.compose.database.model.InReplyToRelation import mobi.giza.compose.database.model.MarmotCommitResult @@ -136,6 +139,8 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) ShareRefreshConfirmation::class, ShareRefreshMessage::class, ShareRefreshSession::class, + ShareRepairMessage::class, + ShareRepairSession::class, InReplyToRelation::class, MarmotCommitResult::class, MarmotGroupEvent::class, @@ -165,7 +170,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) UnsignedNostrEvent::class, Zap::class ], - version = 39, + version = 40, autoMigrations = [ // v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can // generate the migration itself — nothing existing changes shape. @@ -418,6 +423,10 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) // ShareRefreshSession, ShareRefreshMessage and ShareRefreshConfirmation // tables. Three new tables, so Room generates it. AutoMigration(from = 38, to = 39), + // v40 adds share repair (docs/frost-share-refresh.md, Phase 10): the + // ShareRepairSession and ShareRepairMessage tables, and the nullable + // GroupKeyState.memberBindings. Room generates it. + AutoMigration(from = 39, to = 40), ] ) @ConstructedBy(GizaDatabaseConstructor::class) @@ -454,6 +463,8 @@ abstract class GizaDatabase: RoomDatabase() { abstract fun shareRefreshDao(): ShareRefreshDao + abstract fun shareRepairDao(): ShareRepairDao + abstract fun groupSignedEventDao(): GroupSignedEventDao diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt index 2fc470bd..80a643f1 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt @@ -62,6 +62,7 @@ import mobi.giza.compose.exceptions.MarmotNotMemberOfChatGroupException import mobi.giza.compose.extensions.toHex import mobi.giza.compose.managers.ChillDkgRitualManager import mobi.giza.compose.managers.ShareRefreshManager +import mobi.giza.compose.managers.ShareRepairManager import mobi.giza.compose.managers.CommitOrdering import mobi.giza.compose.managers.FrostSigningManager import mobi.giza.compose.managers.GroupKeyStateManager @@ -78,6 +79,7 @@ import mobi.giza.compose.nostr.MarmotProfile import mobi.giza.compose.nostr.Relays import mobi.giza.compose.nostr.dkg.DkgRitualEvents import mobi.giza.compose.nostr.frost.ShareRefreshEvents +import mobi.giza.compose.nostr.frost.ShareRepairEvents import mobi.giza.compose.nostr.frost.FrostSigningEvents @Dao @@ -1618,6 +1620,16 @@ abstract class NostrDao( nostrPrivateKey = activeKeyPair.privKey!! ) + // And a repair, in the same room (Phase 10). + ShareRepairEvents.isShareRepairKind(innerEvent.kind) -> + ShareRepairManager.processRepairPayload( + database = database, + localChatRoom = localChatRoom, + innerEvent = innerEvent, + userPublicKey = activeKeyPair.pubKey.toHex(), + nostrPrivateKey = activeKeyPair.privKey!! + ) + // Nothing for the group Lightning wallet's kinds: Giza takes no // part in it, so a Bennu member's ceremony, co-signing and node // traffic are filed and ignored. docs/giza-wallet-removal.md. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRepairDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRepairDao.kt new file mode 100644 index 00000000..af833344 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRepairDao.kt @@ -0,0 +1,27 @@ +package mobi.giza.compose.database.dao + +import androidx.room3.Dao +import androidx.room3.Query +import androidx.room3.Upsert +import com.vitorpamplona.quartz.nip01Core.core.Kind +import mobi.giza.compose.database.model.ShareRepairMessage +import mobi.giza.compose.database.model.ShareRepairSession + +/** Share repairs (docs/frost-share-refresh.md, Phase 10). Read through `ShareRepairManager`. */ +@Dao +interface ShareRepairDao { + @Query("SELECT * FROM ShareRepairSession WHERE id = :id") + suspend fun getSessionById(id: String): ShareRepairSession? + + @Query("SELECT * FROM ShareRepairSession WHERE dkgSessionId = :dkgSessionId ORDER BY createdAt DESC") + suspend fun getSessionsForKey(dkgSessionId: String): List + + @Upsert + suspend fun upsert(session: ShareRepairSession) + + @Upsert + suspend fun upsert(message: ShareRepairMessage) + + @Query("SELECT * FROM ShareRepairMessage WHERE sessionId = :sessionId AND kind = :kind") + suspend fun getMessagesByKind(sessionId: String, kind: Kind): List +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt index 670b3bf4..a0907524 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt @@ -39,6 +39,7 @@ import mobi.giza.compose.nostr.chronicle.ChronicleEvent import mobi.giza.compose.nostr.chronicle.ChronicleRequestEvent import mobi.giza.compose.nostr.dkg.DkgRitualEvents import mobi.giza.compose.nostr.frost.ShareRefreshEvents +import mobi.giza.compose.nostr.frost.ShareRepairEvents import mobi.giza.compose.nostr.frost.FrostSigningEvents import mobi.giza.compose.nostr.frost.GroupKeyStateEvent import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent @@ -243,6 +244,12 @@ data class ChatMessage( const val TYPE_SHARE_REFRESH_COMPLETE = "shareRefreshComplete" const val TYPE_SHARE_REFRESH_FAILED = "shareRefreshFailed" + /** A share repair -- re-enrollment -- as lines in the chat (docs/frost-share-refresh.md, Phase 10). */ + const val TYPE_SHARE_REPAIR_REQUESTED = "shareRepairRequested" + const val TYPE_SHARE_REPAIR_APPROVAL_NEEDED = "shareRepairApprovalNeeded" + const val TYPE_SHARE_REPAIRED = "shareRepaired" + const val TYPE_SHARE_REPAIR_FAILED = "shareRepairFailed" + val SHARE_REFRESH_TYPES = setOf( TYPE_SHARE_REFRESH_STARTED, TYPE_SHARE_REFRESH_DEALT, @@ -250,6 +257,10 @@ data class ChatMessage( TYPE_SHARE_REFRESH_APPROVAL_NEEDED, TYPE_SHARE_REFRESH_COMPLETE, TYPE_SHARE_REFRESH_FAILED, + TYPE_SHARE_REPAIR_REQUESTED, + TYPE_SHARE_REPAIR_APPROVAL_NEEDED, + TYPE_SHARE_REPAIRED, + TYPE_SHARE_REPAIR_FAILED, ) /** The share refresh lines a named member's device did. */ @@ -257,6 +268,8 @@ data class ChatMessage( TYPE_SHARE_REFRESH_STARTED, TYPE_SHARE_REFRESH_DEALT, TYPE_SHARE_REFRESH_CONFIRMED, + TYPE_SHARE_REPAIR_REQUESTED, + TYPE_SHARE_REPAIRED, ) val DKG_TYPES = setOf( @@ -871,7 +884,8 @@ data class ChatMessage( val isProtocolMessage = !isDirectMessageEnvelope && ( event.kind in DkgRitualEvents.ALL || event.kind in FrostSigningEvents.ALL || - event.kind in ShareRefreshEvents.ALL + event.kind in ShareRefreshEvents.ALL || + event.kind in ShareRepairEvents.ALL ) database.marmotInnerEventDao().upsert( @@ -1144,6 +1158,7 @@ data class ChatMessage( // A share refresh's protocol messages. `ShareRefreshManager` // applies them and writes the lines that report them. in ShareRefreshEvents.ALL -> null + in ShareRepairEvents.ALL -> null ChatEvent.KIND -> { ChatMessage( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupKeyState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupKeyState.kt index 0f2199a7..5472949f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupKeyState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/GroupKeyState.kt @@ -143,6 +143,15 @@ data class GroupKeyState( */ val publicSharesHash: String? = null, + /** + * Participant ids the group has bound to a new identity, as + * `id:npub:hostkey` comma separated, or null for none + * (docs/frost-share-refresh.md, Phase 10b). A member who lost their device, + * or whose account is compromised, comes back under a new identity at their + * old id, and the group says which -- before any repair can target it. + */ + val memberBindings: String? = null, + override val createdAt: Instant = Clock.System.now(), override val updatedAt: Instant = createdAt, override val savedAt: Instant = createdAt, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRepairMessage.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRepairMessage.kt new file mode 100644 index 00000000..2ad997db --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRepairMessage.kt @@ -0,0 +1,33 @@ +package mobi.giza.compose.database.model + +import androidx.room3.Entity +import androidx.room3.ForeignKey +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import kotlin.time.Clock +import kotlin.time.Instant +import mobi.giza.compose.database.model.traits.LocalStoreEntity +import mobi.giza.compose.database.model.traits.TimestampedEntity + +/** + * One repair message: a helper's share for another helper, a helper's sum for + * the target, or the target's proof. Encrypted to its recipient's host key + * where it carries a secret. Keyed so a redelivery replaces rather than adds. + */ +@Entity( + primaryKeys = ["sessionId", "senderPublicKey", "kind", "recipientPublicKey"], + foreignKeys = [ + ForeignKey(entity = ShareRepairSession::class, parentColumns = ["id"], childColumns = ["sessionId"], onDelete = ForeignKey.CASCADE) + ], +) +data class ShareRepairMessage( + val sessionId: String, + val senderPublicKey: HexKey, + val kind: Kind, + /** Who it is for; empty for a message to everyone. */ + val recipientPublicKey: HexKey, + val payload: String, + override val createdAt: Instant = Clock.System.now(), + override val updatedAt: Instant = createdAt, + override val savedAt: Instant = createdAt, +) : TimestampedEntity, LocalStoreEntity diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRepairSession.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRepairSession.kt new file mode 100644 index 00000000..f8b12700 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRepairSession.kt @@ -0,0 +1,53 @@ +package mobi.giza.compose.database.model + +import androidx.room3.Entity +import androidx.room3.ForeignKey +import androidx.room3.Index +import androidx.room3.PrimaryKey +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlin.time.Clock +import kotlin.time.Instant +import mobi.giza.compose.database.model.traits.LocalStoreEntity +import mobi.giza.compose.database.model.traits.TimestampedEntity +import mobi.giza.compose.database.model.types.ShareRepairStage + +/** + * One repair of a participant id at one generation -- bringing back a member a + * refresh left stale, with reduced FROST enrollment (docs/frost-share-refresh.md, + * Phase 10). The id is the session id the enrollment binds every message to. + */ +@Entity( + foreignKeys = [ + ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE) + ], + indices = [Index("chatRoomId"), Index("dkgSessionId")], +) +data class ShareRepairSession( + /** 32 bytes hex, chosen by the target, and the enrollment's session id. */ + @PrimaryKey + val id: String, + val chatRoomId: String, + val dkgSessionId: String, + /** The generation the target is brought back into. */ + val generation: Int, + /** The participant id being repaired. */ + val targetId: Int, + /** Who asked: the identity that will hold the share. */ + val targetPublicKey: HexKey, + /** The host key the target asked under, which the helpers encrypt to. */ + val targetHostPublicKey: HexKey, + /** The helpers' participant ids, ascending, comma separated: t live members of the generation. */ + val helperIds: String, + val userPublicKey: HexKey, + val stage: ShareRepairStage = ShareRepairStage.COLLECTING, + /** Secret. A helper's round-1.1 randomness. */ + val sessionRandom: HexKey, + val helpApprovedAt: Instant? = null, + val approvalRequested: Boolean = false, + val failureReason: String? = null, + override val createdAt: Instant = Clock.System.now(), + override val updatedAt: Instant = createdAt, + override val savedAt: Instant = createdAt, +) : TimestampedEntity, LocalStoreEntity { + fun helperIdList(): List = helperIds.split(",").mapNotNull { it.trim().toIntOrNull() } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareRepairStage.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareRepairStage.kt new file mode 100644 index 00000000..f8b34f5a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareRepairStage.kt @@ -0,0 +1,19 @@ +package mobi.giza.compose.database.model.types + +/** + * How far a share repair -- re-enrollment of a member a refresh left stale -- + * has got on this device (docs/frost-share-refresh.md, Phase 10). + */ +enum class ShareRepairStage { + /** The id asking is not yet bound to the identity asking: the group has to sign that first (10b). */ + AWAITING_BINDING, + + /** Helpers exchanging their round-1.1 shares and sending the target their sums. */ + COLLECTING, + + /** The target holds its share and has proved it; every device marks the id live. */ + COMPLETE, + + /** Abandoned. See `ShareRepairSession.failureReason`. */ + FAILED, +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt index 1eb9cdf7..307b7af0 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt @@ -215,7 +215,10 @@ object GroupKeyStateManager { val filed = database.groupKeyStateDao().replace(state) // `replace` re-stamps what it files, so the row is compared on what it says. - if (filed.generation == state.generation && filed.announcedAt == state.announcedAt) retireOlderShares(database, state) + if (filed.generation == state.generation && filed.announcedAt == state.announcedAt) { + retireOlderShares(database, state) + applyBindings(database, state) + } return filed } @@ -244,6 +247,57 @@ object GroupKeyStateManager { ShareGenerations.wipeBefore(database, key, generation) } + /** + * Rebinds the ids a signed state names to their new identities, in this + * device's roster of that generation (docs/frost-share-refresh.md, Phase 10b). + * Only an id that is not live can change hands: a live one is somebody's + * working share, and binding it elsewhere would leave two holders of one point. + * Then any repair that was waiting on the binding goes on. + */ + private suspend fun applyBindings(database: GizaDatabase, state: GroupKeyState) { + val generation = state.generation ?: return + val bindings = GroupKeyStateEvent.MemberBinding.decodeAll(state.memberBindings) + if (bindings.isEmpty()) return + val members = database.keyShareDao().getMembers(state.dkgSessionId, generation) + val changed = bindings.mapNotNull { binding -> + val row = members.firstOrNull { it.participantId == binding.participantId } ?: return@mapNotNull null + if (row.standing == ShareStanding.LIVE) { + logger.w("Key state binds live id ${binding.participantId} of ${state.dkgSessionId} elsewhere; ignoring that binding") + return@mapNotNull null + } + if (row.memberPublicKey == binding.memberPublicKey && row.hostPublicKey.equals(binding.hostPublicKey, ignoreCase = true)) return@mapNotNull null + row.copy(memberPublicKey = binding.memberPublicKey, hostPublicKey = binding.hostPublicKey, standing = ShareStanding.STALE, updatedAt = Clock.System.now()) + } + if (changed.isEmpty()) return + database.keyShareDao().upsert(changed) + ShareRepairManager.resumeAwaitingBinding(database, state.dkgSessionId) + } + + /** + * Asks the group to bind participant id [participantId] to a new identity + * (docs/frost-share-refresh.md, Phase 10b): [memberPublicKey], asking under + * ChillDKG host key [hostPublicKey]. The id must already be withheld -- the + * old identity's share made worthless by a refresh -- or a repair to the new + * one would hand it the point the old device still has. + */ + suspend fun proposeRebind( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + key: DkgSession, + participantId: Int, + memberPublicKey: HexKey, + hostPublicKey: HexKey, + ): FrostSigningSession { + val entry = ShareGenerations.active(database, key).roster.firstOrNull { it.participantId == participantId } + ?: throw IllegalStateException("Id $participantId is not in the key") + check(entry.standing != ShareStanding.LIVE) { + "Id $participantId still holds a live share; rotate the shares without it before binding it to anyone else" + } + val binding = GroupKeyStateEvent.MemberBinding(participantId, memberPublicKey.lowercase(), hostPublicKey.lowercase()) + return proposeGeneration(database, localChatRoom, userPublicKey, key, refreshId = null, newBinding = binding) + } + /** * Asks the group to sign the key state at the generation it now signs with, * after a refresh (docs/frost-share-refresh.md, Phase 8). The same room, key @@ -257,6 +311,7 @@ object GroupKeyStateManager { userPublicKey: HexKey, key: DkgSession, refreshId: String?, + newBinding: GroupKeyStateEvent.MemberBinding? = null, ): FrostSigningSession { val shares = ShareGenerations.active(database, key) check(shares.generation >= 1) { "Generation 0 is the ceremony's, and needs no new key state" } @@ -282,10 +337,25 @@ object GroupKeyStateManager { publicSharesHash = ShareGenerations.publicSharesHash(publicShares), refreshId = refreshId, retiredIds = shares.roster.filter { it.standing == ShareStanding.RETIRED }.map { it.participantId }, + // Bindings already in force at this generation stay said, so a + // later state does not quietly undo them; a new one replaces any + // earlier binding of the same id. + bindings = ( + GroupKeyStateEvent.MemberBinding.decodeAll(current?.takeIf { it.generation == shares.generation }?.memberBindings) + .filter { it.participantId != newBinding?.participantId } + listOfNotNull(newBinding) + ), ), ), content = thresholdPublicKey, key = key, + // Later than the state it amends, by a second if it must be. Two states + // at one generation are told apart by their time alone, and a rebind + // stamped in the same second as the state it adds to would tie with it + // -- and the binding could be the one that loses. + createdAt = maxOf( + Clock.System.now().epochSeconds, + (current?.takeIf { (it.generation ?: 0) == shares.generation }?.announcedAt?.epochSeconds ?: 0L) + 1 + ), ) } @@ -555,7 +625,8 @@ object GroupKeyStateManager { parentChatRoomId = parent.value?.parentChatRoomId, birthCertificateJson = parent.value?.certificate?.toJson(), generation = shareGeneration?.generation, - publicSharesHash = shareGeneration?.publicSharesHash + publicSharesHash = shareGeneration?.publicSharesHash, + memberBindings = shareGeneration?.bindings?.takeIf { it.isNotEmpty() }?.joinToString(",") { it.encode() } ) // Half the trust model, in one line, and the half that does not care who diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRepairManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRepairManager.kt new file mode 100644 index 00000000..55542a2d --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRepairManager.kt @@ -0,0 +1,430 @@ +package mobi.giza.compose.managers + +import co.touchlab.kermit.Logger +import com.vitorpamplona.crypto.random.RandomInstance +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.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import com.vitorpamplona.quartz.nip44Encryption.Nip44 +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.ByteVector64 +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.PublicKey +import fr.acinq.bitcoin.crypto.frost.FrostReducedEnrollment +import fr.acinq.bitcoin.crypto.frost.ReducedEnrollmentMessage +import fr.acinq.bitcoin.crypto.frost.ReducedShareAggregation +import kotlin.time.Clock +import kotlin.time.Instant +import kotlinx.coroutines.CancellationException +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.DkgSession +import mobi.giza.compose.database.model.MarmotInnerEvent +import mobi.giza.compose.database.model.ShareRepairMessage +import mobi.giza.compose.database.model.ShareRepairSession +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.database.model.types.DkgRitualStage +import mobi.giza.compose.database.model.types.ShareRepairStage +import mobi.giza.compose.database.model.types.ShareStanding +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.frost.ShareRepairEvents + +/** + * Re-enrollment: brings a participant id a refresh left stale back to the + * generation the group signs with, by reduced FROST enrollment in repair mode + * (docs/frost-share-refresh.md, Phase 10). + * + * The target gets its point on the NEW polynomial, which its old device never + * had -- so a repair after a refresh is how a member comes back without bringing + * back anything a lost or removed device still holds. Two cases share this code: + * - **10a**, the same identity, which missed the refresh; + * - **10b**, a new identity at the id, which the group binds with a signed key + * state first ([GroupKeyStateManager.proposeRebind]). Until that binding is on + * file, a request waits in [ShareRepairStage.AWAITING_BINDING]: a repair to an + * identity the group has not bound is a repair to whoever asked. + * + * t live helpers run it. Their round-1.1 shares and round-1.2 sums are raw + * additive shares, so each travels encrypted with NIP-44 between the sender's and + * the recipient's ChillDKG host keys -- confidential to the two of them, and + * authenticated by the same token. The target checks the result against the + * public share the group signed (never one the helpers supply) and proves it + * holds it with a Schnorr signature by the share over the session id; every + * device checks that proof against the same public share before marking the id + * live. + */ +object ShareRepairManager { + private val logger = Logger.withTag("ShareRepairManager") + + /** + * Asks to bring back [targetId] -- this device's own stale id when null -- at + * the generation the group signs with, with the first t live ids as helpers. + */ + suspend fun requestRepair( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + nostrPrivateKey: ByteArray, + key: DkgSession, + targetId: Int? = null, + ): ShareRepairSession { + require(key.stage == DkgRitualStage.COMPLETE) { "Ceremony ${key.id} has not produced a key" } + val shares = ShareGenerations.active(database, key) + val id = targetId ?: shares.roster.firstOrNull { it.memberPublicKey == userPublicKey }?.participantId + ?: throw IllegalStateException("This identity holds no id in the key; name the id to be repaired") + val entry = shares.roster.firstOrNull { it.participantId == id } ?: throw IllegalStateException("Id $id is not in the key") + check(entry.standing == ShareStanding.STALE) { "Id $id is ${entry.standing.name.lowercase()}, and only a stale id is repaired" } + val helpers = shares.roster.filter { it.standing == ShareStanding.LIVE }.map { it.participantId }.sorted().take(key.threshold) + check(helpers.size >= key.threshold) { "Only ${helpers.size} members hold live shares; a repair needs ${key.threshold}" } + val hostPublicKey = ChillDkgRitualManager.deriveHostPublicKey(nostrPrivateKey).value.toHex() + + val session = ShareRepairSession( + id = RandomInstance.bytes(32).toHex(), + chatRoomId = localChatRoom.chatRoom.id, + dkgSessionId = key.id, + generation = shares.generation, + targetId = id, + targetPublicKey = userPublicKey, + targetHostPublicKey = hostPublicKey, + helperIds = helpers.joinToString(","), + userPublicKey = userPublicKey, + stage = if (isBound(entry, userPublicKey, hostPublicKey)) ShareRepairStage.COLLECTING else ShareRepairStage.AWAITING_BINDING, + sessionRandom = RandomInstance.bytes(32).toHex(), + ) + database.shareRepairDao().upsert(session) + announce(database, session, ChatMessage.TYPE_SHARE_REPAIR_REQUESTED, "asked to be brought back into the group's signing.", userPublicKey) + broadcast( + database, localChatRoom, userPublicKey, ShareRepairEvents.REQUEST, "", + arrayOf( + arrayOf(ShareRepairEvents.SESSION_TAG, session.id), + arrayOf(ShareRepairEvents.KEY_TAG, key.id), + arrayOf(ShareRepairEvents.GENERATION_TAG, shares.generation.toString()), + arrayOf(ShareRepairEvents.TARGET_TAG, id.toString()), + arrayOf(ShareRepairEvents.HELPERS_TAG, session.helperIds), + arrayOf(ShareRepairEvents.HOST_KEY_TAG, hostPublicKey), + ) + ) + return session + } + + private fun isBound(entry: ShareGenerations.RosterEntry, memberPublicKey: HexKey, hostPublicKey: HexKey): Boolean = + entry.memberPublicKey == memberPublicKey && entry.hostPublicKey.equals(hostPublicKey, ignoreCase = true) + + /** Feeds one inbound repair message in and advances. Safe to call twice. */ + suspend fun processRepairPayload( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + innerEvent: Event, + userPublicKey: HexKey, + nostrPrivateKey: ByteArray, + ) { + val sessionId = ShareRepairEvents.parseSessionId(innerEvent.tags) ?: return + val session = if (innerEvent.kind == ShareRepairEvents.REQUEST) { + acceptRequest(database, localChatRoom, innerEvent, sessionId, userPublicKey) + } else { + database.shareRepairDao().getSessionById(sessionId) + } ?: return + if (session.stage == ShareRepairStage.FAILED || session.stage == ShareRepairStage.COMPLETE) return + + record(database, session, innerEvent) + advance(database, localChatRoom, session.id, nostrPrivateKey) + } + + private suspend fun acceptRequest(database: GizaDatabase, localChatRoom: LocalChatRoom, event: Event, sessionId: String, userPublicKey: HexKey): ShareRepairSession? { + database.shareRepairDao().getSessionById(sessionId)?.let { return it } + val tag = { name: String -> ShareRepairEvents.value(event.tags, name) } + val key = tag(ShareRepairEvents.KEY_TAG)?.let { database.dkgSessionDao().getSessionById(it) }?.takeIf { it.stage == DkgRitualStage.COMPLETE } ?: return null + val generation = tag(ShareRepairEvents.GENERATION_TAG)?.toIntOrNull() ?: return null + val targetId = tag(ShareRepairEvents.TARGET_TAG)?.toIntOrNull() ?: return null + val hostKey = tag(ShareRepairEvents.HOST_KEY_TAG)?.takeIf { it.length == 66 }?.lowercase() ?: return null + val helpers = tag(ShareRepairEvents.HELPERS_TAG)?.split(",")?.map { it.trim().toIntOrNull() ?: return null } ?: return null + val shares = ShareGenerations.active(database, key) + val entry = shares.roster.firstOrNull { it.participantId == targetId } + + val reason = when { + shares.generation != generation -> "it repairs into generation $generation, and this device is at ${shares.generation}" + entry == null -> "id $targetId is not in the key" + entry.standing != ShareStanding.STALE -> "id $targetId is ${entry.standing.name.lowercase()}" + helpers != helpers.sorted() || helpers.toSet().size != helpers.size -> "the helpers are not a set" + helpers.size < key.threshold -> "${helpers.size} helpers cannot carry a ${key.threshold}-of-${key.participantCount} key" + targetId in helpers -> "the target cannot help repair itself" + !shares.roster.filter { it.standing == ShareStanding.LIVE }.map { it.participantId }.containsAll(helpers) -> "a helper holds no live share" + else -> null + } + if (reason != null) { + logger.w("Ignoring repair $sessionId: $reason") + return null + } + val session = ShareRepairSession( + id = sessionId, + chatRoomId = localChatRoom.chatRoom.id, + dkgSessionId = key.id, + generation = generation, + targetId = targetId, + targetPublicKey = event.pubKey, + targetHostPublicKey = hostKey, + helperIds = helpers.joinToString(","), + userPublicKey = userPublicKey, + stage = if (isBound(entry!!, event.pubKey, hostKey)) ShareRepairStage.COLLECTING else ShareRepairStage.AWAITING_BINDING, + sessionRandom = RandomInstance.bytes(32).toHex(), + ) + database.shareRepairDao().upsert(session) + announce( + database, session, ChatMessage.TYPE_SHARE_REPAIR_REQUESTED, + if (session.stage == ShareRepairStage.AWAITING_BINDING) { + "asked to be brought back into the group's signing under a new identity. The group has to bind them to the id first." + } else { + "asked to be brought back into the group's signing." + }, + event.pubKey + ) + return session + } + + private suspend fun record(database: GizaDatabase, session: ShareRepairSession, event: Event) { + when (event.kind) { + ShareRepairEvents.SHARE, ShareRepairEvents.SIGMA -> { + val to = ShareRepairEvents.value(event.tags, ShareRepairEvents.TO_TAG) ?: return + // Only what is addressed here can be opened here. + if (to != session.userPublicKey) return + database.shareRepairDao().upsert(ShareRepairMessage(session.id, event.pubKey, event.kind, to, event.content)) + } + ShareRepairEvents.DONE -> { + if (event.pubKey != session.targetPublicKey) return + database.shareRepairDao().upsert(ShareRepairMessage(session.id, event.pubKey, event.kind, "", event.content)) + } + } + } + + /** Repairs waiting on a binding the group has now signed. Called when a key state's bindings are applied. */ + suspend fun resumeAwaitingBinding(database: GizaDatabase, dkgSessionId: String) { + database.shareRepairDao().getSessionsForKey(dkgSessionId) + .filter { it.stage == ShareRepairStage.AWAITING_BINDING } + .forEach { session -> + val room = database.chatRoomDao().findChatRoomById(session.chatRoomId) ?: return@forEach + bindingCheck(database, session) + // No private key here to go further; the next message, or the owner's + // approval, takes the next step. + logger.i("Repair ${session.id} has its binding: ${database.shareRepairDao().getSessionById(session.id)?.stage} in ${room.chatRoom.id}") + } + } + + /** Moves an awaiting session on once its target is bound. Returns the session as it now stands. */ + private suspend fun bindingCheck(database: GizaDatabase, session: ShareRepairSession): ShareRepairSession { + if (session.stage != ShareRepairStage.AWAITING_BINDING) return session + val key = database.dkgSessionDao().getSessionById(session.dkgSessionId) ?: return session + val entry = ShareGenerations.at(database, key, session.generation)?.roster?.firstOrNull { it.participantId == session.targetId } ?: return session + if (!isBound(entry, session.targetPublicKey, session.targetHostPublicKey)) return session + return update(database, session) { it.copy(stage = ShareRepairStage.COLLECTING) } + } + + private suspend fun advance(database: GizaDatabase, localChatRoom: LocalChatRoom, sessionId: String, nostrPrivateKey: ByteArray) { + var session = database.shareRepairDao().getSessionById(sessionId) ?: return + session = bindingCheck(database, session) + if (session.stage != ShareRepairStage.COLLECTING) return + + try { + val key = database.dkgSessionDao().getSessionById(session.dkgSessionId) ?: return + val shares = ShareGenerations.at(database, key, session.generation) ?: return + val table = shares.publicShares ?: return + val thresholdPublicKey = PublicKey(ByteVector(requireNotNull(key.thresholdPublicKey).hexToByteArray())) + val helpers = session.helperIdList() + val helperIds = helpers.map { it.toUInt() } + val n = key.participantCount + val t = key.threshold + val sid = ByteVector32(session.id) + val hostSecretKey = ChillDkgRitualManager.deriveHostSecretKey(nostrPrivateKey) + val myId = shares.roster.firstOrNull { it.memberPublicKey == session.userPublicKey && it.standing == ShareStanding.LIVE }?.participantId + val rosterById = shares.roster.associateBy { it.participantId } + + // ---- every device: the target's proof makes the id live here ---- + database.shareRepairDao().getMessagesByKind(session.id, ShareRepairEvents.DONE).firstOrNull()?.let { done -> + val proof = runCatching { ByteVector64(done.payload) }.getOrNull() + val expected = table[session.targetId] + if (proof == null || !Crypto.verifySignatureSchnorr(sid, proof, expected.xOnly())) { + throw IllegalStateException("the repaired member's proof does not match the group's public share") + } + markLive(database, key, session) + complete(database, session, "was brought back into the group's signing.", session.targetPublicKey) + return + } + + // ---- a helper ---- + if (myId != null && myId in helpers && session.userPublicKey != session.targetPublicKey) { + if (session.helpApprovedAt == null) { + if (!session.approvalRequested) { + update(database, session) { it.copy(approvalRequested = true) } + announce(database, session, ChatMessage.TYPE_SHARE_REPAIR_APPROVAL_NEEDED, "Your approval is needed to help bring a member back into the group's signing.", session.userPublicKey) + } + return + } + val secretShare = shares.secretShare ?: throw IllegalStateException("this device holds no share of generation ${session.generation}") + val rows = FrostReducedEnrollment.generateShares(ByteVector32(session.sessionRandom), secretShare, thresholdPublicKey, helperIds, myId.toUInt(), session.targetId.toUInt(), n, t, sid).right + ?: throw IllegalStateException("round 1.1 refused this device's inputs") + for (j in helpers.filter { it > myId }) { + val recipient = rosterById.getValue(j) + if (sent(database, session, ShareRepairEvents.SHARE, recipient.memberPublicKey)) continue + val payload = seal(rows.messageFor(j.toUInt()), hostSecretKey, recipient.hostPublicKey) + publishOwn(database, localChatRoom, session, ShareRepairEvents.SHARE, recipient.memberPublicKey, payload) + } + if (!sent(database, session, ShareRepairEvents.SIGMA, session.targetPublicKey)) { + val inbox = database.shareRepairDao().getMessagesByKind(session.id, ShareRepairEvents.SHARE) + .filter { it.recipientPublicKey == session.userPublicKey } + .mapNotNull { message -> + val sender = shares.roster.firstOrNull { it.memberPublicKey == message.senderPublicKey } ?: return@mapNotNull null + if (sender.participantId !in helpers || sender.participantId >= myId) return@mapNotNull null + sender.participantId.toUInt() to open(message.payload, hostSecretKey, sender.hostPublicKey) + } + .toMap() + if (inbox.size < helpers.count { it < myId }) return + val aggregated = FrostReducedEnrollment.aggregateShares(rows.kept, inbox, thresholdPublicKey, helperIds, myId.toUInt(), session.targetId.toUInt(), n, t, sid).right + when (aggregated) { + is ReducedShareAggregation.Aggregated -> { + val payload = seal(aggregated.message, hostSecretKey, session.targetHostPublicKey) + publishOwn(database, localChatRoom, session, ShareRepairEvents.SIGMA, session.targetPublicKey, payload) + } + is ReducedShareAggregation.HelperAtFault -> throw IllegalStateException("helper ${aggregated.helperId} disagreed on the repair's parameters") + null -> throw IllegalStateException("round 1.2 refused this device's inputs") + } + } + return + } + + // ---- the target ---- + if (session.userPublicKey == session.targetPublicKey) { + val sigmas = database.shareRepairDao().getMessagesByKind(session.id, ShareRepairEvents.SIGMA) + .filter { it.recipientPublicKey == session.userPublicKey } + .mapNotNull { message -> + val sender = shares.roster.firstOrNull { it.memberPublicKey == message.senderPublicKey } ?: return@mapNotNull null + if (sender.participantId !in helpers) return@mapNotNull null + sender.participantId.toUInt() to open(message.payload, hostSecretKey, sender.hostPublicKey) + } + .toMap() + if (sigmas.size < helpers.size) return + // Checked against the public share the group signed into this + // generation's table -- never one the helpers supply. + val expected = table[session.targetId] + val repaired = FrostReducedEnrollment.generateSecretShare(sigmas, thresholdPublicKey, helperIds, session.targetId.toUInt(), n, t, sid, expected) + val share = repaired.right ?: throw IllegalStateException("the repaired share does not match the group's public share: ${repaired.left?.message}") + storeShare(database, key, session, share) + val proof = Crypto.signSchnorr(sid, share, null) + broadcast(database, localChatRoom, session.userPublicKey, ShareRepairEvents.DONE, proof.toHex(), arrayOf(arrayOf(ShareRepairEvents.SESSION_TAG, session.id))) + markLive(database, key, session) + complete(database, session, "was brought back into the group's signing.", session.targetPublicKey) + } + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + logger.e("Repair $sessionId failed", e) + update(database, session) { it.copy(stage = ShareRepairStage.FAILED, failureReason = e.message) } + announce(database, session, ChatMessage.TYPE_SHARE_REPAIR_FAILED, "Bringing a member back into the group's signing failed: ${e.message}", session.targetPublicKey) + } + } + + /** Approves helping with a repair, and moves on. */ + suspend fun approve(database: GizaDatabase, localChatRoom: LocalChatRoom, sessionId: String, nostrPrivateKey: ByteArray) { + val session = database.shareRepairDao().getSessionById(sessionId) ?: return + if (session.helpApprovedAt != null) return + update(database, session) { it.copy(helpApprovedAt = Clock.System.now()) } + advance(database, localChatRoom, sessionId, nostrPrivateKey) + } + + /** Whether this device's owner is being asked to help with [session]. */ + suspend fun isAwaitingApproval(database: GizaDatabase, session: ShareRepairSession): Boolean { + if (session.stage != ShareRepairStage.COLLECTING || session.helpApprovedAt != null) return false + val key = database.dkgSessionDao().getSessionById(session.dkgSessionId) ?: return false + val shares = ShareGenerations.at(database, key, session.generation) ?: return false + val myId = shares.roster.firstOrNull { it.memberPublicKey == session.userPublicKey && it.standing == ShareStanding.LIVE }?.participantId + return myId != null && myId in session.helperIdList() + } + + // ---- storage --------------------------------------------------------------------------------------------------- + + private suspend fun storeShare(database: GizaDatabase, key: DkgSession, session: ShareRepairSession, share: PrivateKey) { + val row = database.keyShareDao().getGeneration(key.id, session.generation) + ?: throw IllegalStateException("generation ${session.generation} is not on this device") + val now = Clock.System.now() + database.keyShareDao().upsert(row.copy(secretShare = share.value.toHex(), updatedAt = now)) + } + + private suspend fun markLive(database: GizaDatabase, key: DkgSession, session: ShareRepairSession) { + val member = database.keyShareDao().getMembers(key.id, session.generation).firstOrNull { it.participantId == session.targetId } ?: return + if (member.standing == ShareStanding.LIVE) return + database.keyShareDao().upsert(listOf(member.copy(standing = ShareStanding.LIVE, updatedAt = Clock.System.now()))) + } + + private suspend fun complete(database: GizaDatabase, session: ShareRepairSession, line: String, actor: HexKey) { + val now = database.shareRepairDao().getSessionById(session.id) ?: session + if (now.stage == ShareRepairStage.COMPLETE) return + update(database, now) { it.copy(stage = ShareRepairStage.COMPLETE) } + announce(database, now, ChatMessage.TYPE_SHARE_REPAIRED, line, actor) + } + + private suspend fun update(database: GizaDatabase, session: ShareRepairSession, change: (ShareRepairSession) -> ShareRepairSession): ShareRepairSession { + val current = database.shareRepairDao().getSessionById(session.id) ?: session + val now = Clock.System.now() + val updated = change(current).copy(updatedAt = now, savedAt = now) + database.shareRepairDao().upsert(updated) + return updated + } + + private suspend fun sent(database: GizaDatabase, session: ShareRepairSession, kind: Kind, to: HexKey): Boolean = + database.shareRepairDao().getMessagesByKind(session.id, kind).any { it.senderPublicKey == session.userPublicKey && it.recipientPublicKey == to } + + private suspend fun publishOwn(database: GizaDatabase, localChatRoom: LocalChatRoom, session: ShareRepairSession, kind: Kind, to: HexKey, payload: String) { + broadcast( + database, localChatRoom, session.userPublicKey, kind, payload, + arrayOf(arrayOf(ShareRepairEvents.SESSION_TAG, session.id), arrayOf(ShareRepairEvents.TO_TAG, to)) + ) + database.shareRepairDao().upsert(ShareRepairMessage(session.id, session.userPublicKey, kind, to, payload)) + } + + // ---- the pairwise channel ------------------------------------------------------------------------------------ + + /** NIP-44 between this device's host key and [toHostPublicKey]: only the two of them hold the conversation key. */ + private fun seal(message: ReducedEnrollmentMessage, hostSecretKey: PrivateKey, toHostPublicKey: HexKey): String = + Nip44.encrypt("${message.share.toHex()}:${message.paramsHash.toHex()}", hostSecretKey.value.toByteArray(), xOnly(toHostPublicKey)).encodePayload() + + private fun open(payload: String, hostSecretKey: PrivateKey, fromHostPublicKey: HexKey): ReducedEnrollmentMessage { + val plain = Nip44.decrypt(payload, hostSecretKey.value.toByteArray(), xOnly(fromHostPublicKey)) + val (share, hash) = plain.split(":").takeIf { it.size == 2 } ?: throw IllegalStateException("an unreadable repair message") + return ReducedEnrollmentMessage(ByteVector32(share), ByteVector32(hash)) + } + + /** The x coordinate of a compressed host key, which is all NIP-44's ECDH reads. */ + private fun xOnly(hostPublicKey: HexKey): ByteArray = hostPublicKey.hexToByteArray().copyOfRange(1, 33) + + // ---- transport and transcript -------------------------------------------------------------------------------- + + private suspend fun broadcast(database: GizaDatabase, localChatRoom: LocalChatRoom, author: HexKey, kind: Kind, content: String, tags: Array>) { + var createdAt = Clock.System.now().epochSeconds + var id = EventHasher.hashId(pubKey = author, createdAt = createdAt, kind = kind, tags = tags, content = content) + var attempts = 0 + while (attempts < 16 && database.marmotInnerEventDao().getById(id) != null) { + createdAt += 1 + id = EventHasher.hashId(pubKey = author, createdAt = createdAt, kind = kind, tags = tags, content = content) + attempts += 1 + } + database.marmotInnerEventDao().upsert( + MarmotInnerEvent(id = id, publicKey = author, kind = kind, createdAt = Instant.fromEpochSeconds(createdAt), tags = tags, content = content, chatRoomId = localChatRoom.chatRoom.id) + ) + } + + private suspend fun announce(database: GizaDatabase, session: ShareRepairSession, messageType: String, content: String, actor: HexKey) { + database.chatMessageDao().upsert( + ChatMessage( + senderPublicKey = actor, + isUserMessage = actor == session.userPublicKey, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = session.chatRoomId, + content = content, + messageType = messageType, + ) + ) + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GroupKeyStateEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GroupKeyStateEvent.kt index 95a1de3a..e08eb33c 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GroupKeyStateEvent.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/GroupKeyStateEvent.kt @@ -148,18 +148,39 @@ object GroupKeyStateEvent { val publicSharesHash: String, val refreshId: String?, val retiredIds: List, + /** Ids bound to a new identity (Phase 10b). */ + val bindings: List = emptyList(), ) { fun toTags(): Array> = ( listOf(arrayOf(GENERATION_TAG, generation.toString()), arrayOf(PUBSHARES_TAG, publicSharesHash)) + listOfNotNull(refreshId?.let { arrayOf(REFRESH_TAG, it) }) + - retiredIds.sorted().map { arrayOf(RETIRED_TAG, it.toString()) } + retiredIds.sorted().map { arrayOf(RETIRED_TAG, it.toString()) } + + bindings.sortedBy { it.participantId }.map { arrayOf(MEMBER_TAG, it.encode()) } ).toTypedArray() } + /** Participant id [participantId] is held by [memberPublicKey], under ChillDKG host key [hostPublicKey]. */ + data class MemberBinding(val participantId: Int, val memberPublicKey: HexKey, val hostPublicKey: HexKey) { + fun encode(): String = "$participantId:$memberPublicKey:$hostPublicKey" + + companion object { + fun decode(value: String): MemberBinding? { + val parts = value.split(":").takeIf { it.size == 3 } ?: return null + val id = parts[0].toIntOrNull()?.takeIf { it >= 0 } ?: return null + if (parts[1].length != 64 || parts[2].length != 66) return null + return MemberBinding(id, parts[1].lowercase(), parts[2].lowercase()) + } + + fun decodeAll(value: String?): List = + value?.split(",")?.mapNotNull { decode(it.trim()) }.orEmpty() + } + } + private const val GENERATION_TAG = "frost_generation" private const val PUBSHARES_TAG = "frost_pubshares" private const val REFRESH_TAG = "frost_refresh" private const val RETIRED_TAG = "frost_retired" + private const val MEMBER_TAG = "frost_member" /** * The share generation a state names: null for none (generation 0), and a @@ -176,7 +197,10 @@ object GroupKeyStateEvent { val retired = tags.filter { it.size >= 2 && it[0] == RETIRED_TAG }.map { it[1].toIntOrNull() ?: return Result.failure(IllegalArgumentException("unreadable retired id ${it[1]}")) } - return Result.success(ShareGenerationTags(generation, hash, value(REFRESH_TAG), retired)) + val bindings = tags.filter { it.size >= 2 && it[0] == MEMBER_TAG }.map { + MemberBinding.decode(it[1]) ?: return Result.failure(IllegalArgumentException("unreadable member binding ${it[1]}")) + } + return Result.success(ShareGenerationTags(generation, hash, value(REFRESH_TAG), retired, bindings)) } fun parseParentChatRoomId(tags: Array>): HexKey? = diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/ShareRepairEvents.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/ShareRepairEvents.kt new file mode 100644 index 00000000..f09ee84a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/ShareRepairEvents.kt @@ -0,0 +1,43 @@ +package mobi.giza.compose.nostr.frost + +import com.vitorpamplona.quartz.nip01Core.core.Kind + +/** + * The kinds and tags of a share repair (docs/frost-share-refresh.md, Phase 10). + * + * Inner events of the key's Marmot room, like the refresh beside them. Unlike + * the refresh's, two of these carry raw additive shares, which the room must + * not read: each is encrypted with NIP-44 between the sender's and the + * recipient's ChillDKG host keys, so only the two of them hold the conversation + * key -- confidential, and authenticated by the same token. Never an MLS + * application message in the clear. + */ +object ShareRepairEvents { + /** Target: "bring participant k back at generation g, with these helpers, under this host key". */ + val REQUEST: Kind = 30346 + + /** Helper to larger-id helper: a round-1.1 share, encrypted. */ + val SHARE: Kind = 30347 + + /** Helper to target: the round-1.2 sum, encrypted. */ + val SIGMA: Kind = 30348 + + /** Target: done, with a Schnorr signature by the repaired share over the session id. */ + val DONE: Kind = 30349 + + val ALL: Set = setOf(REQUEST, SHARE, SIGMA, DONE) + + fun isShareRepairKind(kind: Kind): Boolean = kind in ALL + + const val SESSION_TAG = "repair_session" + const val TARGET_TAG = "repair_target" + const val HELPERS_TAG = "repair_helpers" + const val HOST_KEY_TAG = "repair_host_key" + const val TO_TAG = "repair_to" + const val KEY_TAG = "frost_key" + const val GENERATION_TAG = "frost_generation" + + fun value(tags: Array>, name: String): String? = tags.firstOrNull { it.size >= 2 && it[0] == name }?.get(1) + + fun parseSessionId(tags: Array>): String? = value(tags, SESSION_TAG)?.takeIf { it.length == 64 } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt index dc58c3fb..d4b988d7 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/ShippedProfileUpgradeJvmTest.kt @@ -62,11 +62,12 @@ class ShippedProfileUpgradeJvmTest { private val shipped = 36 /** - * The schema version this branch builds: 38 for share generations and 39 for - * share refresh (docs/frost-share-refresh.md, Phases 6 and 7), so the upgrade - * crosses three generated migrations and the file has to come out at the last. + * The schema version this branch builds: 38 for share generations, 39 for share + * refresh and 40 for share repair (docs/frost-share-refresh.md, Phases 6, 7 and + * 10), so the upgrade crosses four generated migrations and the file has to come + * out at the last. */ - private val current = 39 + private val current = 40 private val directory: File = Files.createTempDirectory("giza-shipped-profile").toFile() private val file: File = File(directory, "aux.db") diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt index 0e048a54..f8ae41f9 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt @@ -76,9 +76,9 @@ class ShareRefreshRitualJvmTest { fun memberWithId(id: Int): HexKey = members[idOf.indexOf(id)] } - private inner class Device(val group: Group, val index: Int, val db: GizaDatabase, val room: LocalChatRoom) { - val publicKey: HexKey get() = group.members[index] - val privateKey: ByteArray get() = group.keyPairs[index].privKey!! + private inner class Device(val group: Group, val index: Int, val db: GizaDatabase, val room: LocalChatRoom, val keyPair: KeyPair = group.keyPairs[index]) { + val publicKey: HexKey get() = keyPair.pubKey.toHexKey() + val privateKey: ByteArray get() = keyPair.privKey!! val received = mutableSetOf() suspend fun key(): DkgSession = db.dkgSessionDao().getSessionById(ceremonyId)!! suspend fun refresh(id: String) = db.shareRefreshDao().getSessionById(id) @@ -123,7 +123,7 @@ class ShareRefreshRitualJvmTest { // ---- the wire ---------------------------------------------------------------------------------------------- - private val ferried = (ShareRefreshEvents.ALL + FrostSigningEvents.ALL).toList() + private val ferried = (ShareRefreshEvents.ALL + FrostSigningEvents.ALL + mobi.giza.compose.nostr.frost.ShareRepairEvents.ALL).toList() private suspend fun outbox(device: Device): List = device.db.marmotInnerEventDao() @@ -144,6 +144,8 @@ class ShareRefreshRitualJvmTest { val event = Event(queued.id, queued.publicKey, queued.createdAt.epochSeconds, queued.kind, queued.tags, queued.content, "") if (ShareRefreshEvents.isShareRefreshKind(event.kind)) { ShareRefreshManager.processRefreshPayload(to.db, to.room, event, to.publicKey, to.privateKey) + } else if (mobi.giza.compose.nostr.frost.ShareRepairEvents.isShareRepairKind(event.kind)) { + ShareRepairManager.processRepairPayload(to.db, to.room, event, to.publicKey, to.privateKey) } else { FrostSigningManager.processSigningPayload(to.db, to.room, event, to.publicKey) } @@ -468,4 +470,155 @@ class ShareRefreshRitualJvmTest { } assertTrue(error.message!!.contains("fewer than the 2 it takes to sign"), error.message) } + + // ---- Phase 10: re-enrollment ----------------------------------------------------------------------------------- + + /** Every helper approves every repair waiting on them. */ + private suspend fun approveRepairs(between: List) { + var asked = true + while (asked) { + asked = false + for (device in between) { + device.db.shareRepairDao().getSessionsForKey(ceremonyId) + .filter { ShareRepairManager.isAwaitingApproval(device.db, it) } + .forEach { ShareRepairManager.approve(device.db, device.room, it.id, device.privateKey); asked = true } + } + pump(between) + } + } + + /** A 3-member 2-of-3 group that has rotated without [withheldIndex], left stale, with its key state signed and its old shares deleted. */ + private suspend fun rotatedWithout(withheldIndex: Int): Pair> { + val group = Group(3, 2) + val all = devicesFor(group) + val refresh = propose(all.first { it.index != withheldIndex }, mapOf(group.idOf[withheldIndex] to ShareStanding.STALE)) + pump(all) + approveAll(all, refresh.id) + approveSigning(all) + return group to all + } + + /** + * 10a: a member withheld from a refresh -- offline, or on a build that could + * not take part -- is brought back by two helpers, with a share of the new + * generation its old one is not, and signs. + */ + @Test + fun `a stale member is repaired into the new generation and signs`() = runBlocking { + val (group, all) = rotatedWithout(2) + val (alice, bob, carol) = all + val carolId = group.idOf[2] + assertNull(carol.active().secretShare) + + val repair = ShareRepairManager.requestRepair(carol.db, carol.room, carol.publicKey, carol.privateKey, carol.key()) + assertEquals(mobi.giza.compose.database.model.types.ShareRepairStage.COLLECTING, repair.stage) + pump(all) + // Nothing of a helper's goes out before its owner approves. + assertTrue(outbox(alice).none { it.kind in mobi.giza.compose.nostr.frost.ShareRepairEvents.ALL }) + approveRepairs(all) + + val repaired = assertNotNull(carol.active().secretShare, "carol must hold a share of generation 1") + assertEquals(carol.active().publicShares!![carolId], repaired.publicKey()) + assertNotEquals(group.keyMaterial.secretShares[carolId], repaired, "not the share her old device had") + all.forEach { device -> + assertEquals(ShareStanding.LIVE, device.active().roster.single { it.participantId == carolId }.standing, "on device ${device.index}") + } + + // Carol signs, with Alice; Bob stays out. + val session = FrostSigningManager.proposeSigning(alice.db, alice.room, alice.publicKey, kind = 1, tags = arrayOf(), content = "Carol is back") + pump(all) + FrostSigningManager.approve(carol.db, carol.room, session.id) + pump(all) + assertEquals(FrostSigningStage.COMPLETE, alice.db.frostSigningSessionDao().getSessionById(session.id)?.stage) + assertTrue(alice.db.frostSigningSessionDao().getSessionById(session.id)!!.signerIdList()!!.contains(carolId)) + assertNull(bob.db.frostSigningSessionDao().getSessionById(session.id)?.signApprovedAt) + } + + /** A repair whose expected public share is not the one the group signed fails at round 2, not at signing. */ + @Test + fun `a repair checked against the wrong public share stores nothing`() = runBlocking { + val (group, all) = rotatedWithout(2) + val carol = all[2] + val carolId = group.idOf[2] + // Carol's table says something else at her id. + val row = carol.db.keyShareDao().getGeneration(ceremonyId, 1)!! + val table = row.publicShareList()!!.toMutableList().also { it[carolId] = it[(carolId + 1) % 3] } + carol.db.keyShareDao().upsert(row.copy(publicShares = table.joinToString(",") { it.value.toHex() })) + + val repair = ShareRepairManager.requestRepair(carol.db, carol.room, carol.publicKey, carol.privateKey, carol.key()) + pump(all) + approveRepairs(all) + + assertEquals(mobi.giza.compose.database.model.types.ShareRepairStage.FAILED, carol.db.shareRepairDao().getSessionById(repair.id)?.stage) + assertNull(carol.active().secretShare) + assertEquals(ShareStanding.STALE, all[0].active().roster.single { it.participantId == carolId }.standing, "nobody marks her live without a proof") + } + + /** + * 10b: Carol's device is lost; Dave -- her new identity -- comes back at her + * id. A request from an identity the group has not bound waits, with nothing + * sent; once the group signs the binding, the same repair runs, and Dave signs. + */ + @Test + fun `a new identity is bound to a stale id before it is repaired into it`() = runBlocking { + val (group, all) = rotatedWithout(2) + val (alice, bob) = all + val carolId = group.idOf[2] + val daveKeys = KeyPair() + val daveHost = ChillDkgRitualManager.deriveHostPublicKey(daveKeys.privKey!!).value.toHex() + val dave = newcomer(group, daveKeys, from = alice) + val everyone = listOf(alice, bob, dave) + + // Dave asks before the group has bound him: everyone waits, and no helper sends anything. + val repair = ShareRepairManager.requestRepair(dave.db, dave.room, dave.publicKey, dave.privateKey, dave.key(), targetId = carolId) + assertEquals(mobi.giza.compose.database.model.types.ShareRepairStage.AWAITING_BINDING, repair.stage) + pump(everyone) + listOf(alice, bob).forEach { + assertEquals(mobi.giza.compose.database.model.types.ShareRepairStage.AWAITING_BINDING, it.db.shareRepairDao().getSessionById(repair.id)?.stage) + assertTrue(!ShareRepairManager.isAwaitingApproval(it.db, it.db.shareRepairDao().getSessionById(repair.id)!!)) + } + + // The group binds Carol's id to Dave, and Dave's device learns it as the chronicle would hand it over. + GroupKeyStateManager.proposeRebind(alice.db, alice.room, alice.publicKey, alice.key(), carolId, dave.publicKey, daveHost) + pump(everyone) + approveSigning(listOf(alice, bob)) + pump(everyone) + val signed = assertNotNull(GroupKeyStateManager.signedEventFor(alice.db, group.roomId)).toEvent() + GroupKeyStateManager.record(dave.db, group.roomId, signed) + everyone.forEach { device -> + val entry = device.active().roster.single { it.participantId == carolId } + assertEquals(dave.publicKey, entry.memberPublicKey, "on device ${device.index}") + assertEquals(ShareStanding.STALE, entry.standing) + } + + approveRepairs(everyone) + val share = assertNotNull(dave.active().secretShare, "dave must hold carol's id's share of generation 1") + assertEquals(dave.active().publicShares!![carolId], share.publicKey()) + listOf(alice, bob).forEach { assertEquals(ShareStanding.LIVE, it.active().roster.single { e -> e.participantId == carolId }.standing) } + } + + /** + * A newcomer's device, seeded with what the member chronicle would hand it: + * the key's public record -- the ceremony without a share, its host keys, and + * the current generation's table and roster -- and nothing secret. + */ + private suspend fun newcomer(group: Group, keyPair: KeyPair, from: Device): Device { + val db = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + val publicKey = keyPair.pubKey.toHexKey() + (group.members + publicKey).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 = group.roomId, userPublicKey = publicKey, subject = "#Ekklesia", description = SharedKeyDerivation.describe("Admins."), mlsGroupState = "00") + db.chatRoomDao().upsert(chatRoom) + val key = from.key() + db.dkgSessionDao().upsert(key.copy(userPublicKey = publicKey, secretShare = null, round1Random = "", round2AuxRandom = "", hostPublicKey = ChillDkgRitualManager.deriveHostPublicKey(keyPair.privKey!!).value.toHex())) + from.db.dkgSessionDao().getMessagesByKind(ceremonyId, DkgRitualEvents.HOST_KEY).forEach { db.dkgSessionDao().upsert(it) } + from.db.keyShareDao().getGenerations(ceremonyId).forEach { generation -> + db.keyShareDao().upsert(generation.copy(secretShare = null)) + db.keyShareDao().upsert(from.db.keyShareDao().getMembers(ceremonyId, generation.generation)) + } + return Device(group, -1, db, LocalChatRoom(chatRoom = chatRoom), keyPair).also { devices += it } + } } diff --git a/docs/frost-share-refresh.md b/docs/frost-share-refresh.md index 99b5f70f..2e3254bf 100644 --- a/docs/frost-share-refresh.md +++ b/docs/frost-share-refresh.md @@ -21,7 +21,8 @@ ceremony they describe and the rule that a room's id *is* the key it signs with. | 4 | lightning-kmp `2043f254`, lightning-kmp-app `3794eb8`, Giza Phase 4 | lightning-kmp `crypto` tests 104/104; Giza `compileDebugKotlinAndroid`, `jvmTest` 1183/1183, audits | | 7 | `f8974aec` | `ShareRefreshRitualJvmTest` (7: three devices with real host keys refresh through the real zkp module and then sign at generation 1 as the same room; nothing published before approval; a withheld member follows to the new table with no share and declines to sign; a minority refused; one confirmation per generation; a second proposal hands back the first; a redelivered transcript changes nothing); `jvmTest` 1190/1190; `compileDebugKotlinAndroid`; audits | | 8 | `51615992` | three more in `ShareRefreshRitualJvmTest`: once the group signs the generation-1 key state every device deletes the ceremony's share and its randomness and still signs; a gen-0 session left open fails with "This share was rotated before the session finished"; a key state at an older generation loses whatever its timestamp. `jvmTest` 1193/1193; `compileDebugKotlinAndroid`; audits | -| 9 | Phase 9 | two more in `ShareRefreshRitualJvmTest`: rotating without a removed member of a 2-of-3 leaves the other two signing at generation 1 and the removed member's old share signing nothing with a new one; a 2-of-2 is refused with "fewer than the 2 it takes to sign". `jvmTest` 1195/1195; `compileDebugKotlinAndroid`; audits. The dialog has not been seen on a device | +| 9 | `c4fe4c9c` | two more in `ShareRefreshRitualJvmTest`: rotating without a removed member of a 2-of-3 leaves the other two signing at generation 1 and the removed member's old share signing nothing with a new one; a 2-of-2 is refused with "fewer than the 2 it takes to sign". `jvmTest` 1195/1195; `compileDebugKotlinAndroid`; audits. The dialog has not been seen on a device | +| 10 | Phase 10 | three more in `ShareRefreshRitualJvmTest`: 10a, a stale member repaired by two helpers into generation 1 and signing with one of them; a repair checked against the wrong public share fails at round 2 and stores nothing, and nobody marks the member live without a proof; 10b, a new identity's request waits with nothing sent until the group signs the binding, then is repaired and holds the id's share. `jvmTest` 1198/1198; `compileDebugKotlinAndroid`; audits | | 5 | `4040ae74` | `SecureDeleteJvmTest` (5, two of them controls that fail without the fix); `jvmTest` 1176/1176; `compileDebugKotlinAndroid`, `processDebugResources` | | 6 | `fce51e20` | `ShareGenerationsJvmTest` (7: a real 2-of-3 signature with hand-refreshed shares verifying as the unchanged room, a decline from a device without the generation, a withheld member who is not a signer); every existing signing test unedited; `jvmTest` 1183/1183; `compileDebugKotlinAndroid`; the M3, brand and wallet audits | @@ -48,6 +49,10 @@ Where the build chose differently from the plan: | Phase 8: `ShareRefreshCutoverJvmTest` | the cutover tests live in `ShareRefreshRitualJvmTest`, which has the multi-device harness. The bytes-on-disk check is `SecureDeleteJvmTest`'s, against a file; these devices are in memory. A device that disagrees with the group's table keeps its share and logs it, untested | | Phase 8: gen-0's randomness nulled | emptied: `round1Random` and `round2AuxRandom` are not nullable, and a complete ceremony never reads them again | | Phase 9: an action on the members screen | a dialog the room detail screen raises after a removal succeeds, when the member held a live share (asked before the removal, while they are still in the roster). "Not now" leaves it; nothing offers it again yet -- Phase 11's Shares section is where a rotation can be started at any time. `MemberRemovalRefreshJvmTest` is two tests in the ritual harness | +| Phase 10: pairwise channels -- a gift wrap to one npub, or the MIP-03 carve-out | NIP-44 between the two ChillDKG host keys, as room-wide inner events. Only the two endpoints hold the conversation key, so the room can carry the message without reading it, and the keys are the ones the refresh already encrypts to -- including a new identity's, which it names in its request | +| Phase 10: other devices learn a repair succeeded | the target proves it: a Schnorr signature by the repaired share over the session id, checked against the group-signed public share before any device marks the id live (kind 30349, `DONE`). Kinds 30346-30349 | +| Phase 10b: a `frost_member` tag | `id:npub:hostkey`, kept on `GroupKeyState.memberBindings` (schema 40) and applied to the roster of that generation when the group's signature is filed -- only to an id that is not live. A key state at a generation already on file is stamped at least a second after it: the first 10b test run lost a binding to a tie with the state it amended, in the same second | +| Phase 10b: the newcomer's device | seeded in the test with the key's public record, as the member chronicle would hand it over; that hand-over is not built for share generations yet | | Phase 5: `dataExtractionRules` or `allowBackup="false"` | both. From Android 12 `allowBackup="false"` stops cloud backup but not a device-to-device transfer | ## The headline: enrollment cannot rotate a share From 992290903bc8f3b3af9201c7e19a9da1d92fd6f3 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Thu, 19 Nov 2026 23:53:06 +0200 Subject: [PATCH 09/12] feat: a Shares section, behind a flag that is off in release (frost-share-refresh, Phases 11 and 13) The room detail screen shows a key share by share: the generation the group signs with, who holds a share, who waits to be brought back and who was removed for good; what this device is being asked (take part in a rotation, store the new share, help bring a member back), with approve and abandon; and the two things it may start -- rotate the shares, or ask to be brought back. The copy says what a rotation does not do. ExperimentalFeatures.shareRefresh gates all of it (D4): on in debug and development builds, off in release until the zkp modules are reviewed. Off, nothing is offered, and a rotation this device is asked into is declined out loud. The desktop build can opt in with -Dgiza.experimental=true. The iOS actual was not built. Co-Authored-By: Claude Opus 5.5 --- .../compose/ExperimentalFeatures.android.kt | 5 + .../composeResources/values/strings.xml | 13 ++ .../mobi/giza/compose/ExperimentalFeatures.kt | 22 +++ .../repository/DatabaseChatRepository.kt | 87 +++++++++++- .../compose/managers/ShareRefreshManager.kt | 5 + .../compose/managers/ShareRepairManager.kt | 3 + .../giza/compose/repository/ChatRepository.kt | 26 ++++ .../ui/composable/ChatRoomDetailScreen.kt | 130 ++++++++++++++++++ .../ui/view/model/ChatRoomDetailViewModel.kt | 27 ++++ .../ui/view/state/ChatRoomDetailUIState.kt | 6 + .../compose/ui/view/state/SharesSummary.kt | 26 ++++ .../giza/compose/ExperimentalFeatures.ios.kt | 6 + .../giza/compose/ExperimentalFeatures.jvm.kt | 10 ++ 13 files changed, 365 insertions(+), 1 deletion(-) create mode 100644 composeApp/src/androidMain/kotlin/mobi/giza/compose/ExperimentalFeatures.android.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ExperimentalFeatures.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SharesSummary.kt create mode 100644 composeApp/src/iosMain/kotlin/mobi/giza/compose/ExperimentalFeatures.ios.kt create mode 100644 composeApp/src/jvmMain/kotlin/mobi/giza/compose/ExperimentalFeatures.jvm.kt diff --git a/composeApp/src/androidMain/kotlin/mobi/giza/compose/ExperimentalFeatures.android.kt b/composeApp/src/androidMain/kotlin/mobi/giza/compose/ExperimentalFeatures.android.kt new file mode 100644 index 00000000..43db5092 --- /dev/null +++ b/composeApp/src/androidMain/kotlin/mobi/giza/compose/ExperimentalFeatures.android.kt @@ -0,0 +1,5 @@ +package mobi.giza.compose + +import mobi.giza.android.BuildConfig + +actual fun isDevelopmentBuild(): Boolean = BuildConfig.DEBUG diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 6cafefea..79166d68 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -114,6 +114,19 @@ Rotate shares without them? They are out of the room, but their share of the group key still helps sign until the shares are rotated without them. Rotating asks every remaining member to take part. Shares held before the rotation stop working once every device has deleted them. Rotate shares + Shares + Generation %1$d + Holds a share + Waiting to be brought back + Removed for good + %1$s (you) + Rotating gives every member a new share of the same key, so the group keeps its room and everything it has signed. Shares held before stop working once every device has deleted them. A rotation does not undo a compromised account. + Ask to be brought back + Approve + Take part in rotating the shares + Store your new share + Help bring a member back + Sent to the group Share rotation proposed; every remaining member is asked to take part Library Lightning invoice diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ExperimentalFeatures.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ExperimentalFeatures.kt new file mode 100644 index 00000000..2d1b6d65 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ExperimentalFeatures.kt @@ -0,0 +1,22 @@ +package mobi.giza.compose + +/** + * Features built but not shipped: on in a debug or development build, off in a + * release one, and overridable in tests. + * + * Share rotation (docs/frost-share-refresh.md, D4) stays here until upstream + * drops "experimental" from the secp256k1-zkp enrollment module and the + * frost_refresh module has had independent review. Off, the app offers no + * rotation or repair, and declines a rotation it is asked to take part in, + * out loud. + */ +object ExperimentalFeatures { + /** Set by a test that has to see the build a release would be. */ + var shareRefreshOverride: Boolean? = null + + val shareRefresh: Boolean + get() = shareRefreshOverride ?: isDevelopmentBuild() +} + +/** Whether this is a debug or development build of the app, rather than a release. */ +expect fun isDevelopmentBuild(): Boolean diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index c7c28652..2dcc72df 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -41,6 +41,16 @@ import mobi.giza.compose.database.model.types.MarmotReindexReport import mobi.giza.compose.identity.Identity import mobi.giza.compose.identity.toKeyPair import mobi.giza.compose.managers.ShareRefreshManager +import mobi.giza.compose.ui.view.state.SharesSummary +import mobi.giza.compose.database.model.types.ShareStanding +import mobi.giza.compose.database.model.types.ShareRepairStage +import mobi.giza.compose.database.model.types.ShareRefreshStage +import mobi.giza.compose.database.model.types.ShareRefreshApprovalStep +import mobi.giza.compose.database.model.types.DkgRitualStage +import mobi.giza.compose.database.model.DkgSession +import mobi.giza.compose.managers.ShareGenerations +import mobi.giza.compose.managers.ShareRepairManager +import mobi.giza.compose.ExperimentalFeatures import mobi.giza.compose.managers.ChronicleManager import mobi.giza.compose.managers.FrostSigningManager import mobi.giza.compose.managers.GroupKeyStateManager @@ -633,7 +643,82 @@ class DatabaseChatRepository( } override suspend fun holdsShare(localChatRoom: LocalChatRoom, memberPublicKey: HexKey): Boolean = - runCatching { ShareRefreshManager.liveIdOf(database, localChatRoom, memberPublicKey) != null }.getOrDefault(false) + ExperimentalFeatures.shareRefresh && + runCatching { ShareRefreshManager.liveIdOf(database, localChatRoom, memberPublicKey) != null }.getOrDefault(false) + + /** The key the room's Shares section is about: the one its key state names, else the one this device signs it with. */ + private suspend fun shareKeyOf(localChatRoom: LocalChatRoom): DkgSession? { + val roomId = localChatRoom.chatRoom.id + return GroupKeyStateManager.keyStateFor(database, roomId)?.dkgSessionId?.let { database.dkgSessionDao().getSessionById(it) } + ?.takeIf { it.stage == DkgRitualStage.COMPLETE } + ?: FrostSigningManager.completedKey(database, roomId) + } + + override suspend fun sharesSummary(localChatRoom: LocalChatRoom): SharesSummary? = runCatching { + if (localChatRoom.chatRoom.mlsGroupState == null) return null + val key = shareKeyOf(localChatRoom) ?: return null + val me = localChatRoom.chatRoom.userPublicKey + val shares = ShareGenerations.active(database, key) + if (shares.roster.isEmpty()) return null + val names = localChatRoom.localParticipants.associate { it.participant.participantPublicKey to it.profile?.humanReadableNameOrPubkey() } + val refreshes = database.shareRefreshDao().getSessionsForKey(key.id) + val repairs = database.shareRepairDao().getSessionsForKey(key.id) + val pending = refreshes.mapNotNull { session -> + when (ShareRefreshManager.pendingApproval(database, session)) { + ShareRefreshApprovalStep.DEAL -> SharesSummary.PendingApproval(session.id, SharesSummary.PendingApproval.Kind.REFRESH_DEAL) + ShareRefreshApprovalStep.CONFIRM -> SharesSummary.PendingApproval(session.id, SharesSummary.PendingApproval.Kind.REFRESH_CONFIRM) + null -> null + } + } + repairs.filter { ShareRepairManager.isAwaitingApproval(database, it) } + .map { SharesSummary.PendingApproval(it.id, SharesSummary.PendingApproval.Kind.REPAIR_HELP) } + val running = refreshes.any { it.stage != ShareRefreshStage.COMPLETE && it.stage != ShareRefreshStage.FAILED } + val mine = shares.roster.firstOrNull { it.memberPublicKey == me } + val repairing = repairs.any { it.targetPublicKey == me && it.stage != ShareRepairStage.FAILED && it.stage != ShareRepairStage.COMPLETE } + SharesSummary( + generation = shares.generation, + members = shares.roster.map { entry -> + SharesSummary.Member(entry.memberPublicKey, names[entry.memberPublicKey] ?: entry.memberPublicKey.take(8), entry.standing, entry.memberPublicKey == me) + }, + pending = if (ExperimentalFeatures.shareRefresh) pending else emptyList(), + canRotate = ExperimentalFeatures.shareRefresh && shares.secretShare != null && !running, + canAskToBeRepaired = ExperimentalFeatures.shareRefresh && mine?.standing == ShareStanding.STALE && !repairing, + ) + }.getOrNull() + + private fun failureOf(t: Throwable?): String? = t?.let { it.message ?: it::class.simpleName ?: "Unknown error" } + + private fun privateKeyOrNull(): Pair? { + val identity = activeIdentity.value ?: return null + val privateKey = identity.toKeyPair().privKey ?: return null + return identity.nostrPublicKey to privateKey + } + + override suspend fun rotateShares(localChatRoom: LocalChatRoom): String? { + val (me, privateKey) = privateKeyOrNull() ?: return "This identity cannot sign" + val key = shareKeyOf(localChatRoom) ?: return "This group has no shared key" + return failureOf(runCatching { ShareRefreshManager.proposeRefresh(database, localChatRoom, me, privateKey, key) }.exceptionOrNull()) + } + + override suspend fun approveShares(localChatRoom: LocalChatRoom, approval: SharesSummary.PendingApproval): String? { + val (_, privateKey) = privateKeyOrNull() ?: return "This identity cannot sign" + return failureOf(runCatching { + when (approval.kind) { + SharesSummary.PendingApproval.Kind.REFRESH_DEAL, SharesSummary.PendingApproval.Kind.REFRESH_CONFIRM -> + ShareRefreshManager.approve(database, localChatRoom, approval.sessionId, privateKey) + SharesSummary.PendingApproval.Kind.REPAIR_HELP -> + ShareRepairManager.approve(database, localChatRoom, approval.sessionId, privateKey) + } + }.exceptionOrNull()) + } + + override suspend fun abandonRotation(localChatRoom: LocalChatRoom, sessionId: String): String? = + failureOf(runCatching { ShareRefreshManager.abandon(database, localChatRoom, sessionId) }.exceptionOrNull()) + + override suspend fun askToBeRepaired(localChatRoom: LocalChatRoom): String? { + val (me, privateKey) = privateKeyOrNull() ?: return "This identity cannot sign" + val key = shareKeyOf(localChatRoom) ?: return "This group has no shared key" + return failureOf(runCatching { ShareRepairManager.requestRepair(database, localChatRoom, me, privateKey, key) }.exceptionOrNull()) + } override suspend fun rotateSharesWithout(localChatRoom: LocalChatRoom, memberPublicKey: HexKey): String? { val identity = activeIdentity.value ?: return "No identity is signed in" diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt index 160ff004..2cc97bd7 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt @@ -34,6 +34,7 @@ import mobi.giza.compose.database.model.types.ShareGenerationState import mobi.giza.compose.database.model.types.ShareRefreshApprovalStep import mobi.giza.compose.database.model.types.ShareRefreshStage import mobi.giza.compose.database.model.types.ShareStanding +import mobi.giza.compose.ExperimentalFeatures import mobi.giza.compose.extensions.toHex import mobi.giza.compose.nostr.frost.ShareRefreshEvents @@ -122,6 +123,7 @@ object ShareRefreshManager { key: DkgSession, withheld: Map = emptyMap(), ): ShareRefreshSession { + check(ExperimentalFeatures.shareRefresh) { "This build does not rotate shares" } require(key.stage == DkgRitualStage.COMPLETE) { "Ceremony ${key.id} has not produced a key" } require(isKeysRoom(database, localChatRoom, key)) { "${localChatRoom.chatRoom.id} is not the room key ${key.id} signs as" } @@ -285,6 +287,9 @@ object ShareRefreshManager { ) val reason = when { + // Built but not shipped (D4): a release build declines, out loud, rather + // than leaving a refresh that needs it waiting forever. + !ExperimentalFeatures.shareRefresh -> "this build cannot rotate shares" base != active.generation -> "it refreshes generation $base, and this device is at generation ${active.generation}" proposer == null || proposer !in recipients -> "its proposer is not one of its recipients" running(database, key) != null -> "another refresh of this key is still running here" diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRepairManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRepairManager.kt index 55542a2d..41dcaa31 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRepairManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRepairManager.kt @@ -30,6 +30,7 @@ import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.database.model.types.DkgRitualStage import mobi.giza.compose.database.model.types.ShareRepairStage import mobi.giza.compose.database.model.types.ShareStanding +import mobi.giza.compose.ExperimentalFeatures import mobi.giza.compose.extensions.toHex import mobi.giza.compose.nostr.frost.ShareRepairEvents @@ -71,6 +72,7 @@ object ShareRepairManager { key: DkgSession, targetId: Int? = null, ): ShareRepairSession { + check(ExperimentalFeatures.shareRefresh) { "This build does not repair shares" } require(key.stage == DkgRitualStage.COMPLETE) { "Ceremony ${key.id} has not produced a key" } val shares = ShareGenerations.active(database, key) val id = targetId ?: shares.roster.firstOrNull { it.memberPublicKey == userPublicKey }?.participantId @@ -135,6 +137,7 @@ object ShareRepairManager { private suspend fun acceptRequest(database: GizaDatabase, localChatRoom: LocalChatRoom, event: Event, sessionId: String, userPublicKey: HexKey): ShareRepairSession? { database.shareRepairDao().getSessionById(sessionId)?.let { return it } + if (!ExperimentalFeatures.shareRefresh) return null val tag = { name: String -> ShareRepairEvents.value(event.tags, name) } val key = tag(ShareRepairEvents.KEY_TAG)?.let { database.dkgSessionDao().getSessionById(it) }?.takeIf { it.stage == DkgRitualStage.COMPLETE } ?: return null val generation = tag(ShareRepairEvents.GENERATION_TAG)?.toIntOrNull() ?: return null diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt index 0cc98225..cd4e6cad 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -21,6 +21,7 @@ import mobi.giza.compose.managers.MarmotGroupCreation import mobi.giza.compose.managers.SharedKeyDerivation import mobi.giza.compose.managers.SubgroupManager import mobi.giza.compose.nostr.MarmotProfile +import mobi.giza.compose.ui.view.state.SharesSummary interface ChatRepository { suspend fun observeChatRoomListByPublicKey(publicKey: String): Flow> @@ -272,6 +273,21 @@ interface ChatRepository { */ suspend fun rotateSharesWithout(localChatRoom: LocalChatRoom, memberPublicKey: HexKey): String? + /** The room's key as the Shares section shows it, or null when the room has none. */ + suspend fun sharesSummary(localChatRoom: LocalChatRoom): SharesSummary? + + /** Proposes rotating every share of the room's key. Null on success, or why not. */ + suspend fun rotateShares(localChatRoom: LocalChatRoom): String? + + /** Answers what [approval] asks. Null on success, or why not. */ + suspend fun approveShares(localChatRoom: LocalChatRoom, approval: SharesSummary.PendingApproval): String? + + /** Ends the rotation [sessionId] for everyone. Null on success, or why not. */ + suspend fun abandonRotation(localChatRoom: LocalChatRoom, sessionId: String): String? + + /** Asks the group to bring this device's stale id back. Null on success, or why not. */ + suspend fun askToBeRepaired(localChatRoom: LocalChatRoom): String? + /** * Disbands a current-profile room this device administers. Absorbing: once the * disband commit is applied nobody rejoins, and a replacement conversation is a @@ -464,6 +480,16 @@ interface ChatRepository { override suspend fun rotateSharesWithout(localChatRoom: LocalChatRoom, memberPublicKey: HexKey): String? = null + override suspend fun sharesSummary(localChatRoom: LocalChatRoom): SharesSummary? = null + + override suspend fun rotateShares(localChatRoom: LocalChatRoom): String? = null + + override suspend fun approveShares(localChatRoom: LocalChatRoom, approval: SharesSummary.PendingApproval): String? = null + + override suspend fun abandonRotation(localChatRoom: LocalChatRoom, sessionId: String): String? = null + + override suspend fun askToBeRepaired(localChatRoom: LocalChatRoom): String? = null + override suspend fun disbandChatRoom(localChatRoom: LocalChatRoom) = Unit override suspend fun softDeleteChatRoom( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt index 204e780e..2b3ac801 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt @@ -102,6 +102,23 @@ import mobi.giza.compose.resources.direct_message_functionality_will_be_here import mobi.giza.compose.resources.invite_new_member import mobi.giza.compose.resources.leave_group import mobi.giza.compose.resources.remove_from_group +import mobi.giza.compose.resources.shares_action_sent +import mobi.giza.compose.resources.pending_repair_help +import mobi.giza.compose.resources.pending_rotation_confirm +import mobi.giza.compose.resources.pending_rotation_deal +import mobi.giza.compose.resources.abandon +import mobi.giza.compose.resources.approve +import mobi.giza.compose.resources.ask_to_be_brought_back +import mobi.giza.compose.resources.shares_rotation_caveat +import mobi.giza.compose.resources.share_standing_you +import mobi.giza.compose.resources.share_standing_retired +import mobi.giza.compose.resources.share_standing_stale +import mobi.giza.compose.resources.share_standing_live +import mobi.giza.compose.resources.share_generation +import mobi.giza.compose.resources.shares +import mobi.giza.compose.ui.view.state.SharesSummary +import mobi.giza.compose.database.model.types.ShareStanding +import androidx.compose.foundation.layout.Row import mobi.giza.compose.resources.share_rotation_requested import mobi.giza.compose.resources.not_now import mobi.giza.compose.resources.rotate_shares @@ -167,6 +184,7 @@ fun ChatRoomDetailScreen( val notify = rememberNotifier(rememberCoroutineScope()) val removalRequested = stringResource(Res.string.member_removal_requested) val rotationRequested = stringResource(Res.string.share_rotation_requested) + val sharesActionSent = stringResource(Res.string.shares_action_sent) // Offered after removing a member who still holds a share of the room's key: // the removal took them out of the room, not out of the key @@ -343,6 +361,118 @@ fun ChatRoomDetailScreen( HorizontalDivider() } + // The room's key, share by share (docs/frost-share-refresh.md, + // Phase 11): which generation the group signs with, who + // holds what, what this device is being asked, and the two + // things it may start. Absent where the room has no key. + chatRoomDetailUIState.shares?.let { shares -> + item { + Text( + text = stringResource(Res.string.shares), + style = MaterialTheme.typography.labelMedium + ) + } + item { + Text( + text = stringResource(Res.string.share_generation, shares.generation), + style = MaterialTheme.typography.bodyMedium + ) + } + items(items = shares.members, key = { member -> "share-${member.publicKey}" }) { member -> + ListItem( + headlineContent = { + Text(if (member.isSelf) stringResource(Res.string.share_standing_you, member.name) else member.name) + }, + supportingContent = { + Text( + stringResource( + when (member.standing) { + ShareStanding.LIVE -> Res.string.share_standing_live + ShareStanding.STALE -> Res.string.share_standing_stale + ShareStanding.RETIRED -> Res.string.share_standing_retired + } + ) + ) + } + ) + } + items(items = shares.pending, key = { approval -> "pending-${approval.sessionId}-${approval.kind}" }) { approval -> + ListItem( + headlineContent = { + Text( + stringResource( + when (approval.kind) { + SharesSummary.PendingApproval.Kind.REFRESH_DEAL -> Res.string.pending_rotation_deal + SharesSummary.PendingApproval.Kind.REFRESH_CONFIRM -> Res.string.pending_rotation_confirm + SharesSummary.PendingApproval.Kind.REPAIR_HELP -> Res.string.pending_repair_help + } + ) + ) + }, + trailingContent = { + Row(horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { + if (approval.kind != SharesSummary.PendingApproval.Kind.REPAIR_HELP) { + TextButton( + onClick = { + chatRoomDetailViewModel.abandonRotation(chatRoomDetailUIState.localChatRoom, approval.sessionId) { failure -> + notify(failure ?: sharesActionSent) + } + } + ) { + Text(stringResource(Res.string.abandon)) + } + } + FilledTonalButton( + onClick = { + chatRoomDetailViewModel.approveShares(chatRoomDetailUIState.localChatRoom, approval) { failure -> + notify(failure ?: sharesActionSent) + } + } + ) { + Text(stringResource(Res.string.approve)) + } + } + } + ) + } + if (shares.canRotate || shares.canAskToBeRepaired) { + item { + Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { + Text( + text = stringResource(Res.string.shares_rotation_caveat), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + if (shares.canRotate) { + FilledTonalButton( + onClick = { + chatRoomDetailViewModel.rotateShares(chatRoomDetailUIState.localChatRoom) { failure -> + notify(failure ?: rotationRequested) + } + } + ) { + Text(stringResource(Res.string.rotate_shares)) + } + } + if (shares.canAskToBeRepaired) { + TextButton( + onClick = { + chatRoomDetailViewModel.askToBeRepaired(chatRoomDetailUIState.localChatRoom) { failure -> + notify(failure ?: sharesActionSent) + } + } + ) { + Text(stringResource(Res.string.ask_to_be_brought_back)) + } + } + } + } + } + item { + HorizontalDivider() + } + } + item { Text( text = stringResource(Res.string.subgroups), diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt index f67a7b78..3cb13a0e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -27,6 +27,7 @@ import mobi.giza.compose.repository.NostrRepository import mobi.giza.compose.ui.composable.navigation.routes.HomeRoute import mobi.giza.compose.ui.composable.navigation.routes.Route import mobi.giza.compose.ui.view.state.ChatRoomDetailUIState +import mobi.giza.compose.ui.view.state.SharesSummary class ChatRoomDetailViewModel( val chatRoomId: String, @@ -106,6 +107,7 @@ class ChatRoomDetailViewModel( subgroupsNeedAWallet = canSign && subgroupsNeedAWallet, canGovern = canGovern, isDisbanded = isDisbanded, + shares = chatRepository.sharesSummary(localChatRoom), ) } } @@ -134,6 +136,31 @@ class ChatRoomDetailViewModel( } } + /** + * Runs one Shares section action, reloads the screen, and reports: null for + * done, or why not. Every one of them is a proposal or an answer the group + * goes on with in the background, so done means sent, not finished. + */ + private fun sharesAction(onDone: (String?) -> Unit, action: suspend () -> String?) { + viewModelScope.launch(Dispatchers.IO) { + val failure = action() + initiateChatRoomDetail() + viewModelScope.launch(Dispatchers.Main) { onDone(failure) } + } + } + + fun rotateShares(localChatRoom: LocalChatRoom, onDone: (String?) -> Unit) = + sharesAction(onDone) { chatRepository.rotateShares(localChatRoom) } + + fun approveShares(localChatRoom: LocalChatRoom, approval: SharesSummary.PendingApproval, onDone: (String?) -> Unit) = + sharesAction(onDone) { chatRepository.approveShares(localChatRoom, approval) } + + fun abandonRotation(localChatRoom: LocalChatRoom, sessionId: String, onDone: (String?) -> Unit) = + sharesAction(onDone) { chatRepository.abandonRotation(localChatRoom, sessionId) } + + fun askToBeRepaired(localChatRoom: LocalChatRoom, onDone: (String?) -> Unit) = + sharesAction(onDone) { chatRepository.askToBeRepaired(localChatRoom) } + /** A removed member who still holds a share of the room's key, for the offer to rotate without them. */ data class RotationOffer(val localChatRoom: LocalChatRoom, val memberPublicKey: HexKey) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt index acb5c4e6..5b7b8511 100755 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt @@ -78,6 +78,12 @@ sealed interface ChatRoomDetailUIState { * and nobody rejoins, so every write entrance is hidden and the room says so. */ val isDisbanded: Boolean = false, + /** + * The room's key as the Shares section shows it: the generation, who + * holds what, and what this device is asked or may start. Null when the + * room has no key (docs/frost-share-refresh.md, Phase 11). + */ + val shares: SharesSummary? = null, ): ChatRoomDetailUIState data class Error( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SharesSummary.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SharesSummary.kt new file mode 100644 index 00000000..720377f0 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SharesSummary.kt @@ -0,0 +1,26 @@ +package mobi.giza.compose.ui.view.state + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.database.model.types.ShareStanding + +/** + * A room's key, as the Shares section shows it (docs/frost-share-refresh.md, + * Phase 11): the generation the group signs with, who holds what, what this + * device is being asked, and what it may start. + */ +data class SharesSummary( + val generation: Int, + val members: List, + val pending: List, + /** This device holds a live share and no rotation is running: it may propose one. */ + val canRotate: Boolean, + /** This device's own id is stale and nothing is bringing it back yet. */ + val canAskToBeRepaired: Boolean, +) { + data class Member(val publicKey: HexKey, val name: String, val standing: ShareStanding, val isSelf: Boolean) + + /** Something this device's owner is being asked, and the session it is for. */ + data class PendingApproval(val sessionId: String, val kind: Kind) { + enum class Kind { REFRESH_DEAL, REFRESH_CONFIRM, REPAIR_HELP } + } +} diff --git a/composeApp/src/iosMain/kotlin/mobi/giza/compose/ExperimentalFeatures.ios.kt b/composeApp/src/iosMain/kotlin/mobi/giza/compose/ExperimentalFeatures.ios.kt new file mode 100644 index 00000000..f8e99f15 --- /dev/null +++ b/composeApp/src/iosMain/kotlin/mobi/giza/compose/ExperimentalFeatures.ios.kt @@ -0,0 +1,6 @@ +package mobi.giza.compose + +import kotlin.experimental.ExperimentalNativeApi + +@OptIn(ExperimentalNativeApi::class) +actual fun isDevelopmentBuild(): Boolean = Platform.isDebugBinary diff --git a/composeApp/src/jvmMain/kotlin/mobi/giza/compose/ExperimentalFeatures.jvm.kt b/composeApp/src/jvmMain/kotlin/mobi/giza/compose/ExperimentalFeatures.jvm.kt new file mode 100644 index 00000000..e683dab4 --- /dev/null +++ b/composeApp/src/jvmMain/kotlin/mobi/giza/compose/ExperimentalFeatures.jvm.kt @@ -0,0 +1,10 @@ +package mobi.giza.compose + +/** + * A packaged distribution carries a jar manifest with its version (see + * [AppVersion]); running from class directories -- gradle, a test -- does not. + * A packaged build can still opt in with `-Dgiza.experimental=true`. + */ +actual fun isDevelopmentBuild(): Boolean = + AppVersion::class.java.`package`?.implementationVersion == null || + System.getProperty("giza.experimental") == "true" From 4949f0fefe5d3608b3a32b564305d68b219c7439 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Thu, 19 Nov 2026 23:53:07 +0200 Subject: [PATCH 10/12] feat: the recovery walk, from the host key to the live share (frost-share-refresh, Phase 12) ShareGenerations.recover rebuilds a device's share of every generation from its host secret key alone: ChillDKG's recovery data gives generation 0, and each refresh's recovery data, applied to the generation before, gives the next. It stops at a generation the host key was withheld from, since a repaired share leaves no recovery data. Nothing calls it yet. Tested three refreshes on, against every device's live share and each generation's table. With the release-build test, jvmTest 1200/1200, compileDebugKotlinAndroid and the audits pass. Co-Authored-By: Claude Opus 5.5 --- .../giza/compose/managers/ShareGenerations.kt | 35 +++++++++++++ .../managers/ShareRefreshRitualJvmTest.kt | 52 ++++++++++++++++++- docs/frost-share-refresh.md | 10 +++- 3 files changed, 94 insertions(+), 3 deletions(-) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareGenerations.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareGenerations.kt index 5b11b293..b1591f68 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareGenerations.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareGenerations.kt @@ -1,7 +1,11 @@ package mobi.giza.compose.managers import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.ByteVector import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.crypto.dkg.chill.ChillDKG +import fr.acinq.bitcoin.crypto.frost.FrostRefresh +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray import fr.acinq.bitcoin.Crypto import kotlin.time.Clock import mobi.giza.compose.extensions.toHex @@ -121,6 +125,37 @@ object ShareGenerations { database.scrubFreedPages() } + /** + * Rebuilds this device's share of every generation of [key] from its host + * secret key alone, as a restored device would (docs/frost-share-refresh.md, + * Phase 12): ChillDKG's recovery data gives generation 0, and each refresh's + * recovery data, applied to the generation before, gives the next. + * + * The walk stops at the first generation this host key was withheld from -- + * its share there came from a repair, which leaves no recovery data, or from + * nothing -- and at the first generation whose recovery data is not on file. + * Returns the shares it could rebuild, by generation. + */ + suspend fun recover(database: GizaDatabase, key: DkgSession, hostSecretKey: PrivateKey): Map { + val recovery = key.recoveryData ?: return emptyMap() + val generation0 = ChillDKG.participantRecover(hostSecretKey, ByteVector(recovery.hexToByteArray())).secretShare ?: return emptyMap() + return recoverFrom(database, key, hostSecretKey, generation0) + } + + /** [recover], from a generation-0 share already in hand. */ + suspend fun recoverFrom(database: GizaDatabase, key: DkgSession, hostSecretKey: PrivateKey, generation0: PrivateKey): Map { + val shares = linkedMapOf(0 to generation0) + var share = generation0 + for (row in database.keyShareDao().getGenerations(key.id).sortedBy { it.generation }) { + if (row.generation != shares.size) break + val data = row.recoveryData ?: break + val next = FrostRefresh.participantRecover(hostSecretKey, share, ByteVector(data.hexToByteArray())) + share = next.newSecretShare?.takeIf { next.fault.isOk } ?: break + shares[row.generation] = share + } + return shares + } + /** Whether this device can sign with [key] today: it holds a share of the generation the group signs with. */ suspend fun canSign(database: GizaDatabase, key: DkgSession): Boolean = active(database, key).secretShare != null diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt index f8ae41f9..a135d260 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt @@ -57,7 +57,10 @@ class ShareRefreshRitualJvmTest { private val devices = mutableListOf() @AfterTest - fun closeDatabases() = devices.forEach { it.db.close() } + fun closeDatabases() { + devices.forEach { it.db.close() } + mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = null + } private val ceremonyId = "ceremony".padEnd(64, '0') @@ -621,4 +624,51 @@ class ShareRefreshRitualJvmTest { } return Device(group, -1, db, LocalChatRoom(chatRoom = chatRoom), keyPair).also { devices += it } } + + // ---- Phase 12: restore --------------------------------------------------------------------------------------- + + /** + * A restored device has its nsec and the room's backlog. ChillDKG's recovery + * gives it generation 0 (here dealt by hand, so given), and every refresh's + * recovery data, applied in turn, gives the next: the walk lands on the share + * the device holds live, three refreshes later. + */ + @Test + fun `the recovery walk rebuilds the live share three refreshes on`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + repeat(3) { round -> + val refresh = propose(all[round % 3]) + pump(all) + approveAll(all, refresh.id) + } + all.forEach { device -> + assertEquals(3, device.active().generation) + val hostSecretKey = ChillDkgRitualManager.deriveHostSecretKey(device.privateKey) + val id = group.idOf[device.index] + val walked = ShareGenerations.recoverFrom(device.db, device.key(), hostSecretKey, group.keyMaterial.secretShares[id]) + assertEquals((0..3).toList(), walked.keys.toList(), "on device ${device.index}") + assertEquals(device.active().secretShare, walked[3]) + (1..3).forEach { g -> + val table = device.db.keyShareDao().getGeneration(ceremonyId, g)!!.publicShareList()!! + assertEquals(table[id], walked.getValue(g).publicKey(), "generation $g on device ${device.index}") + } + } + } + + // ---- Phase 13: a release build --------------------------------------------------------------------------------- + + /** A build without the feature declines a rotation it is asked into, out loud, rather than leaving it waiting. */ + @Test + fun `a release build declines a rotation out loud`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val refresh = propose(all[0]) + mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = false + pump(all) + + assertEquals(ShareRefreshStage.FAILED, all[0].refresh(refresh.id)?.stage) + assertTrue(all[0].refresh(refresh.id)!!.failureReason!!.contains("this build cannot rotate shares"), all[0].refresh(refresh.id)!!.failureReason) + assertFailsWith { propose(all[1]) } + } } diff --git a/docs/frost-share-refresh.md b/docs/frost-share-refresh.md index 2e3254bf..1284894d 100644 --- a/docs/frost-share-refresh.md +++ b/docs/frost-share-refresh.md @@ -5,7 +5,7 @@ signs as it always has (same key, same room, same certificates) while the shares stop being useful. Those old shares may be a lost phone's, a removed member's, or a database a backup service still holds. -This is a phased plan, being built. It was written against `d4dd87f2` on 2026-11-19, +This is a phased plan, built: every phase is in, one or two commits each, with the gaps named in the table below. It was written against `d4dd87f2` on 2026-11-19, right after [submodule-refresh.md](./submodule-refresh.md) carried reduced (v2) FROST enrollment up to Giza. Read [shared-key-ceremony.md](./shared-key-ceremony.md) and [shared-key-derivation.md](./shared-key-derivation.md) first. Everything below assumes the @@ -22,7 +22,10 @@ ceremony they describe and the rule that a room's id *is* the key it signs with. | 7 | `f8974aec` | `ShareRefreshRitualJvmTest` (7: three devices with real host keys refresh through the real zkp module and then sign at generation 1 as the same room; nothing published before approval; a withheld member follows to the new table with no share and declines to sign; a minority refused; one confirmation per generation; a second proposal hands back the first; a redelivered transcript changes nothing); `jvmTest` 1190/1190; `compileDebugKotlinAndroid`; audits | | 8 | `51615992` | three more in `ShareRefreshRitualJvmTest`: once the group signs the generation-1 key state every device deletes the ceremony's share and its randomness and still signs; a gen-0 session left open fails with "This share was rotated before the session finished"; a key state at an older generation loses whatever its timestamp. `jvmTest` 1193/1193; `compileDebugKotlinAndroid`; audits | | 9 | `c4fe4c9c` | two more in `ShareRefreshRitualJvmTest`: rotating without a removed member of a 2-of-3 leaves the other two signing at generation 1 and the removed member's old share signing nothing with a new one; a 2-of-2 is refused with "fewer than the 2 it takes to sign". `jvmTest` 1195/1195; `compileDebugKotlinAndroid`; audits. The dialog has not been seen on a device | -| 10 | Phase 10 | three more in `ShareRefreshRitualJvmTest`: 10a, a stale member repaired by two helpers into generation 1 and signing with one of them; a repair checked against the wrong public share fails at round 2 and stores nothing, and nobody marks the member live without a proof; 10b, a new identity's request waits with nothing sent until the group signs the binding, then is repaired and holds the id's share. `jvmTest` 1198/1198; `compileDebugKotlinAndroid`; audits | +| 10 | `1c3e0e93` | three more in `ShareRefreshRitualJvmTest`: 10a, a stale member repaired by two helpers into generation 1 and signing with one of them; a repair checked against the wrong public share fails at round 2 and stores nothing, and nobody marks the member live without a proof; 10b, a new identity's request waits with nothing sent until the group signs the binding, then is repaired and holds the id's share. `jvmTest` 1198/1198; `compileDebugKotlinAndroid`; audits | +| 11 | Phase 11 | `compileDebugKotlinAndroid`; the M3 audit at its budgets. **Not seen on a device or a desktop window** | +| 12 | Phase 12 | `ShareRefreshRitualJvmTest`: three refreshes in a row, then the recovery walk from the generation-0 share lands on every device's live share, each generation checked against its table. `jvmTest` 1200/1200 | +| 13 | Phase 11 | `ShareRefreshRitualJvmTest`: with the flag off, the recipients decline a rotation out loud and it fails; proposing one throws. Android, desktop and iOS device checks not done | | 5 | `4040ae74` | `SecureDeleteJvmTest` (5, two of them controls that fail without the fix); `jvmTest` 1176/1176; `compileDebugKotlinAndroid`, `processDebugResources` | | 6 | `fce51e20` | `ShareGenerationsJvmTest` (7: a real 2-of-3 signature with hand-refreshed shares verifying as the unchanged room, a decline from a device without the generation, a withheld member who is not a signer); every existing signing test unedited; `jvmTest` 1183/1183; `compileDebugKotlinAndroid`; the M3, brand and wallet audits | @@ -53,6 +56,9 @@ Where the build chose differently from the plan: | Phase 10: other devices learn a repair succeeded | the target proves it: a Schnorr signature by the repaired share over the session id, checked against the group-signed public share before any device marks the id live (kind 30349, `DONE`). Kinds 30346-30349 | | Phase 10b: a `frost_member` tag | `id:npub:hostkey`, kept on `GroupKeyState.memberBindings` (schema 40) and applied to the roster of that generation when the group's signature is filed -- only to an id that is not live. A key state at a generation already on file is stamped at least a second after it: the first 10b test run lost a binding to a tie with the state it amended, in the same second | | Phase 10b: the newcomer's device | seeded in the test with the key's public record, as the member chronicle would hand it over; that hand-over is not built for share generations yet | +| Phase 11: a Shares section on the key's screen, a refresh screen, a repair screen | one Shares section on the room detail screen, carrying all of it: the generation, each member's standing, every approval this device owes with approve and abandon, and the two actions. No pushed screen, and so no route; the transcript's request lines still open nothing. The stale "banner" is the member's own standing, "Waiting to be brought back", above an "Ask to be brought back" button | +| Phase 12: the recovery walk | `ShareGenerations.recover` and `recoverFrom`. The walk stops at a generation this host key was withheld from, since a repaired share leaves no recovery data -- a repaired member restoring from the phrase is repaired again. Nothing calls it yet: wiring it into a restore flow is the restore flow's | +| Phase 13: the flag | `ExperimentalFeatures.shareRefresh`, from `isDevelopmentBuild()`: `BuildConfig.DEBUG` on Android, an unpackaged run or `-Dgiza.experimental=true` on desktop, `Platform.isDebugBinary` on iOS (unbuilt). D5's capability is **not built**: nothing advertises support, so a refresh including a member on an older build waits on them until a recipient abandons it | | Phase 5: `dataExtractionRules` or `allowBackup="false"` | both. From Android 12 `allowBackup="false"` stops cloud backup but not a device-to-device transfer | ## The headline: enrollment cannot rotate a share From 8278ffd5dfaca6111cf9f28d845edf42fdcb7ce8 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Thu, 19 Nov 2026 23:53:13 +0200 Subject: [PATCH 11/12] docs: share refresh is built, phase by phase, and what is left Co-Authored-By: Claude Opus 5.5 --- docs/frost-share-refresh.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/frost-share-refresh.md b/docs/frost-share-refresh.md index 1284894d..fcd74f6e 100644 --- a/docs/frost-share-refresh.md +++ b/docs/frost-share-refresh.md @@ -23,9 +23,9 @@ ceremony they describe and the rule that a room's id *is* the key it signs with. | 8 | `51615992` | three more in `ShareRefreshRitualJvmTest`: once the group signs the generation-1 key state every device deletes the ceremony's share and its randomness and still signs; a gen-0 session left open fails with "This share was rotated before the session finished"; a key state at an older generation loses whatever its timestamp. `jvmTest` 1193/1193; `compileDebugKotlinAndroid`; audits | | 9 | `c4fe4c9c` | two more in `ShareRefreshRitualJvmTest`: rotating without a removed member of a 2-of-3 leaves the other two signing at generation 1 and the removed member's old share signing nothing with a new one; a 2-of-2 is refused with "fewer than the 2 it takes to sign". `jvmTest` 1195/1195; `compileDebugKotlinAndroid`; audits. The dialog has not been seen on a device | | 10 | `1c3e0e93` | three more in `ShareRefreshRitualJvmTest`: 10a, a stale member repaired by two helpers into generation 1 and signing with one of them; a repair checked against the wrong public share fails at round 2 and stores nothing, and nobody marks the member live without a proof; 10b, a new identity's request waits with nothing sent until the group signs the binding, then is repaired and holds the id's share. `jvmTest` 1198/1198; `compileDebugKotlinAndroid`; audits | -| 11 | Phase 11 | `compileDebugKotlinAndroid`; the M3 audit at its budgets. **Not seen on a device or a desktop window** | -| 12 | Phase 12 | `ShareRefreshRitualJvmTest`: three refreshes in a row, then the recovery walk from the generation-0 share lands on every device's live share, each generation checked against its table. `jvmTest` 1200/1200 | -| 13 | Phase 11 | `ShareRefreshRitualJvmTest`: with the flag off, the recipients decline a rotation out loud and it fails; proposing one throws. Android, desktop and iOS device checks not done | +| 11 | `99229090` | `compileDebugKotlinAndroid`; the M3 audit at its budgets. **Not seen on a device or a desktop window** | +| 12 | `4949f0fe` | `ShareRefreshRitualJvmTest`: three refreshes in a row, then the recovery walk from the generation-0 share lands on every device's live share, each generation checked against its table. `jvmTest` 1200/1200 | +| 13 | `99229090` | `ShareRefreshRitualJvmTest`: with the flag off, the recipients decline a rotation out loud and it fails; proposing one throws. Android, desktop and iOS device checks not done | | 5 | `4040ae74` | `SecureDeleteJvmTest` (5, two of them controls that fail without the fix); `jvmTest` 1176/1176; `compileDebugKotlinAndroid`, `processDebugResources` | | 6 | `fce51e20` | `ShareGenerationsJvmTest` (7: a real 2-of-3 signature with hand-refreshed shares verifying as the unchanged room, a decline from a device without the generation, a withheld member who is not a signer); every existing signing test unedited; `jvmTest` 1183/1183; `compileDebugKotlinAndroid`; the M3, brand and wallet audits | From 08b5c56f7eb23ffa840029cc623268d40adc490a Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Thu, 19 Nov 2026 23:55:50 +0200 Subject: [PATCH 12/12] docs: the share refresh chain is pushed Co-Authored-By: Claude Opus 5.5 --- docs/frost-share-refresh.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/frost-share-refresh.md b/docs/frost-share-refresh.md index fcd74f6e..2ba0b94a 100644 --- a/docs/frost-share-refresh.md +++ b/docs/frost-share-refresh.md @@ -29,11 +29,11 @@ ceremony they describe and the rule that a room's id *is* the key it signs with. | 5 | `4040ae74` | `SecureDeleteJvmTest` (5, two of them controls that fail without the fix); `jvmTest` 1176/1176; `compileDebugKotlinAndroid`, `processDebugResources` | | 6 | `fce51e20` | `ShareGenerationsJvmTest` (7: a real 2-of-3 signature with hand-refreshed shares verifying as the unchanged room, a decline from a device without the generation, a withheld member who is not a signer); every existing signing test unedited; `jvmTest` 1183/1183; `compileDebugKotlinAndroid`; the M3, brand and wallet audits | -**Nothing below Giza is pushed.** Each level's work is on a local `claude/frost-share-refresh` -branch (zkp, secp256k1-kmp, bitcoin-kmp, lightning-kmp, lightning-kmp-app), and every parent pins -its child's local commit. A clone of Giza at these commits cannot fetch them until the branches are -pushed bottom up, which waits on an explicit go-ahead. The tracked branches (`main`, `threshold`, -`master`) are untouched. +**Pushed on 2026-11-19, bottom up, as `claude/frost-share-refresh` at every level** (zkp to +`code.sigidli.com/frost/secp256k1-zkp`, secp256k1-kmp, bitcoin-kmp, lightning-kmp and +lightning-kmp-app to `github.com/kngako`), and every parent's pin checked against its child's +remote branch. The tracked branches (`main`, `threshold`, `master`) are untouched: moving them is a +fast-forward to these branches once the work is reviewed, as submodule-refresh.md did. Where the build chose differently from the plan: