diff --git a/CLAUDE.md b/CLAUDE.md index ac7371c1..21c68b9c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -217,18 +217,6 @@ rename. ./gradlew :composeApp:compileDebugKotlinAndroid :composeApp:jvmTest ``` -A change to the group Lightning wallet's node, co-signing or sweeps also has an end-to-end run against -a regtest network with a real LSP, which `jvmTest` reports as skipped unless asked for. -[testing/regtest/README.md](testing/regtest/README.md) has the prerequisites and what a failure means: - -```bash -testing/regtest/regtest.sh up -``` - -```bash -GIZA_REGTEST=1 ./gradlew :composeApp:jvmTest --tests '*GroupLightningRegtestJvmTest' -``` - `docs/scripts/` also holds the tools each phase was done with — `m3-spacing-positions.py`, `m3-touch-targets.py`, `m3-title-case.py` and the two string extractors — each of which takes `--list` to show the sites rather than the count. diff --git a/README.md b/README.md index b18bd952..74551a69 100644 --- a/README.md +++ b/README.md @@ -96,10 +96,6 @@ packaged. adds hardcoded spacing or colours, title-case strings, or touch targets under 48dp. [CLAUDE.md](CLAUDE.md) lists the UI conventions the audit enforces. -The group Lightning wallet also has an end-to-end test against a regtest network with a real -LSP. It is skipped unless asked for; [testing/regtest/README.md](testing/regtest/README.md) -explains how to run it. - ## Layout - [composeApp](./composeApp/src) is the shared app. `commonMain` holds most of the code, and @@ -108,7 +104,6 @@ explains how to run it. - [lightning-kmp-app](https://github.com/kngako/lightning-kmp-app) is the wallet library, a submodule. - [docs](docs/README.md) holds the design notes. -- [testing/regtest](testing/regtest/README.md) holds the regtest network. ## License diff --git a/composeApp/build.gradle.kts b/composeApp/build.gradle.kts index 2d54de37..9e04875f 100644 --- a/composeApp/build.gradle.kts +++ b/composeApp/build.gradle.kts @@ -385,13 +385,6 @@ val brandAudit = tasks.register("brandAudit") { tasks.named("check") { dependsOn(brandAudit) } -// The group Lightning wallet's regtest run (testing/regtest/README.md) runs only when GIZA_REGTEST=1. -// An environment variable is not a task input, so without this a skipped run would leave jvmTest up to -// date, and asking for the run afterwards would replay the skip. -tasks.withType().configureEach { - inputs.property("gizaRegtest", providers.environmentVariable("GIZA_REGTEST").orElse("")) -} - compose.desktop { application { mainClass = "mobi.giza.desktop.MainKt" diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index cb03a75a..d3e3bf33 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -114,7 +114,6 @@ 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 - Removal sent; it takes effect once a relay accepts it. They still hold a share of the Lightning wallet's key and its node's seed until the group opens a new Lightning wallet without them. Library Lightning invoice LIVE @@ -379,12 +378,8 @@ Send your contribution to the key Check the combined result and confirm it The group has its key — finish setting it up - The Lightning wallet's key ceremony needs you - The Lightning wallet's key is ready Open the shared key ceremony - Open the Lightning wallet's key ceremony Open the proposal - Open the Lightning wallet You approved this Open Ask again @@ -470,8 +465,6 @@ %1$s onchain wallet Open a group onchain wallet - Not opened yet - Open on %1$s This group has not opened a wallet. Opening a wallet asks the group to agree that it keeps coins here. Any quorum of members can then spend them together, and nobody can spend them alone. Each member's share of the group's key is stored unencrypted on their device. Anyone with an unlocked device, or a copy of its data, holds that member's share. @@ -568,110 +561,9 @@ Sent again Couldn't bump the fee: there isn't enough left over to pay it. While the wallet is new, a spend on mainnet can send at most %1$s sats. - Lightning wallet key - This group has no key for a Lightning wallet yet. - A Lightning wallet closes to the group's onchain wallet. Open that first. - A Lightning wallet needs at least four members who hold the onchain wallet's key. - The key is made by everyone who holds the onchain wallet's key. Every payment will need %1$s of their devices online. - Start a key ceremony - Signers needed: %1$s of %2$s - Waiting for everyone to join - Waiting for everyone's contributions - Waiting for everyone to confirm - The group has a key for a Lightning wallet. - Join the ceremony - Send your contributions - Confirm what you saw - Joining publishes commitments to your contributions. Your device then takes the other two steps by itself, checking each one, and sends your contributions only encrypted to the members who will hold them. - If it hasn't finished %1$s hours after it was proposed, it is abandoned and the group can start another. - Couldn't abandon the ceremony. - Each contribution is encrypted to the members who will hold it. Your randomness starts shaping the key here. - Confirming publishes your public share and a hash of every commitment you saw, so the group can check it agrees. - %1$s of 3 steps - Couldn't approve this step. - Your share of this key is stored unencrypted on this device, as the onchain wallet's is. - Lightning wallet - Lightning is only available once the group has an onchain wallet. - Make a key - See the key ceremony - Open a Lightning wallet - Opening a Lightning wallet asks the group to sign for its node, its LSP and how much can be in flight at once. The scheme behind its key has not been reviewed outside the project, so for now a channel holds at most %1$s sats: keep in it only what the group can afford to lose. - Node %1$s - LSP %1$s - At most %1$s sats in flight - Nobody runs this wallet yet - Run by %1$s, term %2$s - Run this wallet on my device - The operator's device runs the wallet's node and has to stay online. Every other member's device signs for it automatically while it is open. - Step down - Couldn't propose this to the group. - The group is making a key for its Lightning wallet. - Reported by the operator in term %1$s. Your device checks each channel against the last commitment it signed. - %1$s sats can be received - The operator hasn't reported the wallet yet. - Channels - %1$s of %2$s sats are the group's - Matches what your device signed - Your device signed for %1$s sats, not what the operator reports - Your device hasn't signed for this channel - Payments - No payments yet. - Received %1$s sats - Sent %1$s sats, with a fee of %2$s sats - Couldn't send %1$s sats - A channel closed: %1$s sats to the onchain wallet - A channel is closing: %1$s sats to the onchain wallet - Receive - What it's for - Leave the amount empty to let the payer choose. - Ask for an invoice - Waiting for the operator's device to make the invoice. It has to be online. - This invoice pays the group's node, the one the group signed for. Whatever it receives is the group's. - Copy invoice - Invoice copied - Nobody runs this wallet yet, so there is no node to make an invoice. - Couldn't ask for an invoice. - The invoice names the amount: %1$s sats. - Fee limit in sats - Left empty, %1$s sats. - Ask the group to pay - The group signs for this payment as for any decision. Once it has, the operator's device pays it, and no member's device lets more than the amount and the fee limit leave. - That isn't a Lightning invoice. - That invoice is for another network, not %1$s. - That invoice has expired. - That invoice names no amount, so give one. - That invoice pays this wallet's own node. - Close to the onchain wallet - Force close - Channel actions - This device could not check this sweep, so it cannot be signed here. - Sweep into the group's onchain wallet - Spends %1$s outputs a closed Lightning channel left the group. Every one goes to the group's own onchain wallet. - %1$s sats wait in closed channels - They are the group's alone, under its own keys. Sweeping asks the group to sign moving them to the onchain wallet; the sweep is sent once the channel's delay is over. - Sweep into the onchain wallet - %1$s people who have left the group still hold a share of this wallet's key and its node's seed. Make a new Lightning wallet without them, then close this one's channels. - Open a new Lightning wallet - Earlier wallet %1$s - %1$s sats in %2$s channels - Close its channels - Sweep %1$s sats - Nobody runs its node, and its channels close only through it. - Hasn't answered the proposal yet. Their device may need an update that knows Lightning wallets. - The group's offer - Anyone can pay this offer, as often as they like, without asking for an invoice first. It pays the group's node, the one the group signed for. - Copy offer - Offer copied - The subgroup's wallet Guarded wallet - Unguarded wallet - This group can spend any coin in it once it has waited as long as the delay below. - This group, after the delay below, and the %1$d above it, after the delays they chose, can spend any coin in it. - Only the subgroup can spend from its wallet. Groups above it can't reach it or anything beneath it. - This group is guarded, so its subgroups are too. - This group's own guardian keys can't be read, so it can't guard a subgroup. The subgroup's wallet will be guarded: this group can spend any coin in it once it has waited %1$s, and each group above it after the delay it chose. The subgroup's wallet will not be guarded: only the subgroup can spend from it. The group above this one decided this group's wallet is guarded. Each group above it can spend any coin in it that has waited as long as its own delay, without this group agreeing: @@ -680,7 +572,6 @@ %1$s, %2$s %1$s: after %2$s - How long before this group can spend a coin 1 hour 2 hours 1 day @@ -690,10 +581,8 @@ Longest Custom Delay in blocks - A coin the subgroup moves starts waiting again, so a long delay lets it keep its coins out of reach by moving them. A group above this one This group can spend a coin here after %1$s - Guarded wallet, after %1$s Only coins that have waited %1$s can be spent from this guarded wallet. %1$s block @@ -750,39 +639,11 @@ Doesn't guard members' wallets Stopped guarding new members' wallets After %1$s - Guard members' wallets How long before this group can take a coin from a member's wallet A coin the member moves starts waiting again, so a long delay lets them keep their coins out of reach by moving them. Wallets already guarded keep the delay they were guarded at. Members whose app is older than this one can only be guarded at 12 blocks, and don't know this group can close. Ask the group - Add liquidity - Plan ahead your liquidity - The LSP adds this much to the channel, so the group can be paid that much more without the LSP splicing it first. - Current liquidity: %1$s sats - Liquidity to add: %1$s sats - The channel grows from %1$s to %2$s sats. - Miner fee - Service fee - Duration - 1 year - Total - After a year, the LSP may reclaim the liquidity that is still unused. - The fee is a quarter of the amount or more. - The fee is more than the group's balance. - Priced on your device at %1$s sat/vbyte, the feerate the operator reported in term %2$s. The miner fee may rise before the node buys. - Buying liquidity asks the group to sign. The operator's node buys it once enough members have, and every member's device checks the splice before it signs. - Review the purchase - This is an initial amount of inbound liquidity. It is used up as the group is paid, and after a year the LSP may reclaim what is unused. The fee comes out of the group's balance. - I understand - Receive a payment first: it opens the channel. - The channel holds the most a channel may on this network for now. - The operator hasn't reported what the LSP sells yet. - The LSP sells none of the amounts this app offers. - Adding %1$s sats of inbound liquidity - Waiting for the channel's last splice before adding %1$s sats - Couldn't add liquidity: %1$s - Inbound liquidity added: %1$s sats, for %2$s sats in fees Stop guarding new wallets Stop guarding new members' wallets? Wallets already guarded stay guarded, and this group can still take their coins after their delay. @@ -801,9 +662,6 @@ this group a group below %1$s a group below this one - another group - the wallet guarded by %1$s - Spend from %1$s as %2$s Members' wallets %1$s, %2$s @@ -849,10 +707,5 @@ In the mempool @%1$s Members' guarded wallets - Ask this group to guard a wallet for you - Asked by %1$s, not yet signed - Put to the group - Couldn't put it to the group. - Wallets your groups guard This device tells the groups above about these on its own when it can. Share now if a group above hasn't heard. 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 88d3abd7..a6ba95b2 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt @@ -3,7 +3,6 @@ package mobi.giza.compose.database import mobi.giza.compose.database.model.GroupLightningSnapshotRow import mobi.giza.compose.database.model.GroupLightningPaymentRow import mobi.giza.compose.database.model.GroupLightningInvoiceRow -import mobi.giza.compose.database.dao.GroupLightningRecordsDao import mobi.giza.compose.database.model.IcebergShareRow import mobi.giza.compose.database.model.IcebergNonceRow import mobi.giza.compose.database.model.IcebergLabelLedger @@ -11,10 +10,7 @@ import mobi.giza.compose.database.model.IcebergLabelAssignment import mobi.giza.compose.database.model.IcebergEchoRow import mobi.giza.compose.database.model.IcebergChannelLedger import mobi.giza.compose.database.model.IcebergBudgetSpend -import mobi.giza.compose.database.dao.IcebergCoSigningDao -import mobi.giza.compose.database.dao.GroupLightningSeedDao import mobi.giza.compose.database.model.GroupLightningSeed -import mobi.giza.compose.database.dao.IcebergKeySessionDao import mobi.giza.compose.database.model.IcebergParticipantMessage import mobi.giza.compose.database.model.IcebergKeySession import mobi.giza.compose.database.model.GroupTransaction @@ -469,13 +465,9 @@ abstract class GizaDatabase: RoomDatabase() { abstract fun inReplyToRelationDao(): InReplyToRelationDao - abstract fun icebergKeySessionDao(): IcebergKeySessionDao - abstract fun groupLightningSeedDao(): GroupLightningSeedDao - abstract fun icebergCoSigningDao(): IcebergCoSigningDao - abstract fun groupLightningRecordsDao(): GroupLightningRecordsDao abstract fun marmotCommitResultDao(): MarmotCommitResultDao diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupLightningRecordsDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupLightningRecordsDao.kt deleted file mode 100644 index 888d57a4..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupLightningRecordsDao.kt +++ /dev/null @@ -1,36 +0,0 @@ -package mobi.giza.compose.database.dao - -import androidx.room3.Dao -import androidx.room3.Query -import androidx.room3.Upsert -import mobi.giza.compose.database.model.GroupLightningInvoiceRow -import mobi.giza.compose.database.model.GroupLightningPaymentRow -import mobi.giza.compose.database.model.GroupLightningSnapshotRow -import kotlinx.coroutines.flow.Flow - -@Dao -interface GroupLightningRecordsDao { - @Upsert - suspend fun upsertSnapshot(row: GroupLightningSnapshotRow) - - @Query("SELECT * FROM GroupLightningSnapshotRow WHERE wallet = :wallet") - suspend fun snapshot(wallet: String): GroupLightningSnapshotRow? - - @Query("SELECT * FROM GroupLightningSnapshotRow WHERE wallet = :wallet") - fun observeSnapshot(wallet: String): Flow - - @Upsert - suspend fun upsertPayment(row: GroupLightningPaymentRow) - - @Query("SELECT * FROM GroupLightningPaymentRow WHERE wallet = :wallet ORDER BY completedAt DESC") - fun observePayments(wallet: String): Flow> - - @Upsert - suspend fun upsertInvoice(row: GroupLightningInvoiceRow) - - @Query("SELECT * FROM GroupLightningInvoiceRow WHERE wallet = :wallet AND requestId = :requestId") - suspend fun invoice(wallet: String, requestId: String): GroupLightningInvoiceRow? - - @Query("SELECT * FROM GroupLightningInvoiceRow WHERE wallet = :wallet AND requestId = :requestId") - fun observeInvoice(wallet: String, requestId: String): Flow -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupLightningSeedDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupLightningSeedDao.kt deleted file mode 100644 index 92d62b8c..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupLightningSeedDao.kt +++ /dev/null @@ -1,17 +0,0 @@ -package mobi.giza.compose.database.dao - -import androidx.room3.Dao -import androidx.room3.Insert -import androidx.room3.OnConflictStrategy -import androidx.room3.Query -import mobi.giza.compose.database.model.GroupLightningSeed - -@Dao -interface GroupLightningSeedDao { - /** First copy wins: a seed for a node id is that node id's whatever arrives later. */ - @Insert(onConflict = OnConflictStrategy.IGNORE) - suspend fun insertIfAbsent(seed: GroupLightningSeed) - - @Query("SELECT * FROM GroupLightningSeed WHERE chatRoomId = :chatRoomId AND nodeId = :nodeId") - suspend fun get(chatRoomId: String, nodeId: String): GroupLightningSeed? -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/IcebergCoSigningDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/IcebergCoSigningDao.kt deleted file mode 100644 index 4a69e90f..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/IcebergCoSigningDao.kt +++ /dev/null @@ -1,77 +0,0 @@ -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.Upsert -import mobi.giza.compose.database.model.IcebergBudgetSpend -import mobi.giza.compose.database.model.IcebergChannelLedger -import mobi.giza.compose.database.model.IcebergEchoRow -import mobi.giza.compose.database.model.IcebergLabelAssignment -import mobi.giza.compose.database.model.IcebergLabelLedger -import mobi.giza.compose.database.model.IcebergNonceRow -import mobi.giza.compose.database.model.IcebergShareRow - -@Dao -interface IcebergCoSigningDao { - @Insert(onConflict = OnConflictStrategy.IGNORE) - suspend fun insertNonce(row: IcebergNonceRow) - - @Query("SELECT * FROM IcebergNonceRow WHERE wallet = :wallet AND counter = :counter") - suspend fun noncesFor(wallet: String, counter: Long): List - - @Query("SELECT MAX(counter) FROM IcebergNonceRow WHERE wallet = :wallet AND participant = :participant") - suspend fun highestNonce(wallet: String, participant: String): Long? - - @Insert(onConflict = OnConflictStrategy.ABORT) - suspend fun insertAssignment(row: IcebergLabelAssignment) - - @Query("SELECT * FROM IcebergLabelAssignment WHERE wallet = :wallet AND purpose = :purpose LIMIT 1") - suspend fun assignmentFor(wallet: String, purpose: String): IcebergLabelAssignment? - - @Query("SELECT MAX(counter) FROM IcebergLabelAssignment WHERE wallet = :wallet") - suspend fun highestAssignment(wallet: String): Long? - - @Query("SELECT * FROM IcebergLabelAssignment WHERE wallet = :wallet") - suspend fun assignments(wallet: String): List - - /** First write wins: a label is echoed once, under one message. */ - @Insert(onConflict = OnConflictStrategy.IGNORE) - suspend fun insertLedger(row: IcebergLabelLedger) - - @Query("SELECT * FROM IcebergLabelLedger WHERE wallet = :wallet AND label = :label") - suspend fun ledgerFor(wallet: String, label: String): IcebergLabelLedger? - - @Upsert - suspend fun upsertLedger(row: IcebergLabelLedger) - - @Insert(onConflict = OnConflictStrategy.IGNORE) - suspend fun insertEcho(row: IcebergEchoRow) - - @Query("SELECT * FROM IcebergEchoRow WHERE wallet = :wallet AND label = :label") - suspend fun echoesFor(wallet: String, label: String): List - - @Insert(onConflict = OnConflictStrategy.IGNORE) - suspend fun insertShare(row: IcebergShareRow) - - @Query("SELECT * FROM IcebergShareRow WHERE wallet = :wallet AND requestId = :requestId") - suspend fun sharesFor(wallet: String, requestId: String): List - - /** The ledger of the newest funding output of [channelId] this device has signed for. */ - @Query("SELECT * FROM IcebergChannelLedger WHERE wallet = :wallet AND channelId = :channelId ORDER BY fundingTxIndex DESC LIMIT 1") - suspend fun channelLedger(wallet: String, channelId: String): IcebergChannelLedger? - - /** Every funding output of [channelId] this device has signed for, oldest first. */ - @Query("SELECT * FROM IcebergChannelLedger WHERE wallet = :wallet AND channelId = :channelId ORDER BY fundingTxIndex") - suspend fun channelLedgers(wallet: String, channelId: String): List - - @Upsert - suspend fun upsertChannelLedger(row: IcebergChannelLedger) - - @Query("SELECT * FROM IcebergBudgetSpend WHERE wallet = :wallet") - suspend fun budgetSpends(wallet: String): List - - @Upsert - suspend fun upsertBudgetSpend(row: IcebergBudgetSpend) -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/IcebergKeySessionDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/IcebergKeySessionDao.kt deleted file mode 100644 index aaa5e5ae..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/IcebergKeySessionDao.kt +++ /dev/null @@ -1,46 +0,0 @@ -package mobi.giza.compose.database.dao - -import androidx.room3.Dao -import androidx.room3.Query -import androidx.room3.Upsert -import mobi.giza.compose.database.model.IcebergKeySession -import mobi.giza.compose.database.model.IcebergParticipantMessage -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.flow.Flow - -@Dao -interface IcebergKeySessionDao { - @Query("SELECT * FROM IcebergKeySession WHERE id = :sessionId") - suspend fun getSessionById(sessionId: String): IcebergKeySession? - - @Query("SELECT * FROM IcebergKeySession WHERE id = :sessionId") - fun observeSessionById(sessionId: String): Flow - - @Query("SELECT * FROM IcebergKeySession WHERE chatRoomId = :chatRoomId ORDER BY createdAt DESC") - suspend fun getSessionsForChatRoom(chatRoomId: String): List - - @Query("SELECT * FROM IcebergKeySession WHERE chatRoomId = :chatRoomId ORDER BY createdAt DESC") - fun observeSessionsForChatRoom(chatRoomId: String): Flow> - - @Query("SELECT * FROM IcebergKeySession WHERE stage = 'COMPLETE'") - suspend fun getCompletedSessions(): List - - /** Every ceremony still under way, on any identity's account: neither finished nor failed. */ - @Query("SELECT * FROM IcebergKeySession WHERE stage NOT IN ('COMPLETE', 'FAILED')") - suspend fun getRunningSessions(): List - - @Upsert - suspend fun upsert(session: IcebergKeySession) - - @Upsert - suspend fun upsert(message: IcebergParticipantMessage) - - @Query("SELECT * FROM IcebergParticipantMessage WHERE sessionId = :sessionId AND kind = :kind") - suspend fun getMessagesByKind(sessionId: String, kind: Int): List - - @Query("SELECT * FROM IcebergParticipantMessage WHERE sessionId = :sessionId AND kind = :kind AND participantPublicKey = :participantPublicKey") - suspend fun getMessage(sessionId: String, kind: Int, participantPublicKey: HexKey): IcebergParticipantMessage? - - @Query("SELECT COUNT(*) FROM IcebergParticipantMessage WHERE sessionId = :sessionId AND kind = :kind") - suspend fun countMessagesByKind(sessionId: String, kind: Int): Int -} 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 c8a1dd4e..f9773854 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 @@ -2,13 +2,6 @@ package mobi.giza.compose.database.model import mobi.giza.compose.nostr.RetiredKinds -import mobi.giza.compose.managers.GroupLightningWalletManager -import mobi.giza.compose.nostr.lightning.GroupLightningOperatorStatementEvent -import mobi.giza.compose.text.grouped -import fr.acinq.bitcoin.Satoshi -import mobi.giza.compose.nostr.lightning.GroupLightningAuthorisationEvent -import mobi.giza.compose.nostr.lightning.GroupLightningWalletStatementEvent -import mobi.giza.compose.nostr.lightning.GroupLightningEvents import mobi.giza.compose.text.describe import mobi.giza.compose.text.BlockDuration import mobi.giza.compose.nostr.wallet.MemberWalletPolicyEvent @@ -1049,17 +1042,13 @@ data class ChatMessage( // Treating every 30330 as a decline dropped every direct // message in a current-profile room. // - // The Lightning wallet's protocol is the third family, and was - // missed: its ceremony, its co-signing and the operator's - // traffic each left a raw-JSON bubble beside the lines their - // managers write. docs/group-lightning-transcript.md, Phase 1. - // The kinds the group signs are not among them -- they reach - // `applyInnerEvent`, which checks and describes them. + // Bennu's wallet kinds are not protocol here: Giza takes no part, + // so nothing acts on them, and `applyInnerEvent` gives each one a + // line or none. docs/giza-wallet-removal.md. val isDirectMessageEnvelope = MarmotDirectMessage.wrapInside(event) != null val isProtocolMessage = !isDirectMessageEnvelope && ( event.kind in DkgRitualEvents.ALL || - event.kind in FrostSigningEvents.ALL || - event.kind in GroupLightningEvents.PROTOCOL + event.kind in FrostSigningEvents.ALL ) database.marmotInnerEventDao().upsert( @@ -1330,12 +1319,6 @@ data class ChatMessage( // none of their business. in DkgRitualEvents.ALL -> null - // The Lightning wallet's ceremony, its co-signing and the - // operator's traffic, for the same reason again: the managers - // `NostrDao` dispatches them to act on them and write what is - // worth a line. Not the three the group signs, which have arms - // of their own below. - in GroupLightningEvents.PROTOCOL -> null ChatEvent.KIND -> { ChatMessage( @@ -1513,73 +1496,6 @@ data class ChatMessage( ) } - // The group keeping a Lightning wallet, checked as the wallet screen checks it. - GroupLightningWalletStatementEvent.KIND -> { - val signed = GroupSignedEvent.fromEvent(event, chatRoomId = groupId) - val wallet = GroupLightningWalletManager.verify(database, groupId, signed) ?: return null - ChatMessage( - giftWrapPayloadId = null, - messageType = TYPE_GROUP_LIGHTNING_WALLET_OPENED, - marmotGroupEventId = marmotGroupEventId, - marmotInnerEventId = marmotInnerEventId, - senderPublicKey = senderPublicKey, - isUserMessage = isUserMessage, - chatRoomId = groupId, - createdAt = createdAt, - content = "The group opened a Lightning wallet on ${GroupWalletStatementEvent.chainName(wallet.statement.chain)}. " + - "${wallet.statement.threshold} of ${wallet.statement.participants.size} sign for it." - ) - } - - // A new operator, or none. Signed by the room, which is all the line claims. - GroupLightningOperatorStatementEvent.KIND -> { - val signed = GroupSignedEvent.fromEvent(event, chatRoomId = groupId) - if (!signed.verifies()) return null - val statement = GroupLightningOperatorStatementEvent.read(event.tags) ?: return null - ChatMessage( - giftWrapPayloadId = null, - messageType = TYPE_GROUP_LIGHTNING_OPERATOR_ELECTED, - marmotGroupEventId = marmotGroupEventId, - marmotInnerEventId = marmotInnerEventId, - senderPublicKey = senderPublicKey, - isUserMessage = isUserMessage, - chatRoomId = groupId, - createdAt = createdAt, - // Who, since that is the one thing the line is for. The term is - // a counter the wallet's screen keeps; it means nothing to a reader. - content = when (val operator = statement.operator) { - null -> "Nobody runs the group's Lightning wallet now. It stops until someone is chosen." - else -> "@${memberName(database, operator)} runs the group's Lightning wallet now." - } - ) - } - - // A payment the group signed for. The line says how much and that the operator's node - // pays it; whether it went is the snapshot's to say, on the wallet's screen. - GroupLightningAuthorisationEvent.KIND -> { - val signed = GroupSignedEvent.fromEvent(event, chatRoomId = groupId) - if (!signed.verifies()) return null - val pay = GroupLightningAuthorisationEvent.read(event.tags) - val buy = if (pay == null) GroupLightningAuthorisationEvent.readBuyLiquidity(event.tags) else null - val channelAction = if (pay == null && buy == null) GroupLightningAuthorisationEvent.readChannelAction(event.tags) ?: return null else null - ChatMessage( - giftWrapPayloadId = null, - messageType = TYPE_GROUP_LIGHTNING_PAYMENT_AUTHORISED, - marmotGroupEventId = marmotGroupEventId, - marmotInnerEventId = marmotInnerEventId, - senderPublicKey = senderPublicKey, - isUserMessage = isUserMessage, - chatRoomId = groupId, - createdAt = createdAt, - content = when { - pay != null -> "The group authorised a Lightning payment of ${Satoshi(pay.amountMsat / 1000).grouped()} sats. The operator's node pays it." - buy != null -> "The group authorised adding ${Satoshi(buy.amountSat).grouped()} sats of inbound liquidity, for at most ${Satoshi(buy.maxFeeSat).grouped()} sats in fees. The operator's node buys it." - channelAction?.action == GroupLightningAuthorisationEvent.FORCE_CLOSE -> "The group authorised force-closing a Lightning channel. Its money reaches the onchain wallet after a delay." - else -> "The group authorised closing a Lightning channel to its onchain wallet." - } - ) - } - // A profile or a relay list -- the group's or a member's own -- // travelling through the room. The app no longer reads either as // the group's, and both are identity plumbing nobody sends into a 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 5b948c48..07410715 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 @@ -3,7 +3,6 @@ package mobi.giza.compose.database.repository import mobi.giza.compose.managers.GuardianDerivation import mobi.giza.compose.nostr.subgroup.WalletPolicyReading import fr.acinq.bitcoin.Chain -import mobi.giza.compose.managers.GroupLightningWalletManager import mobi.giza.compose.managers.GroupWalletManager import mobi.giza.compose.managers.GuardianManager import mobi.giza.compose.managers.GroupWalletDerivation @@ -158,9 +157,6 @@ class DatabaseChatRepository( null } - override suspend fun lightningParticipants(chatRoomId: String, chain: Chain): Set = - runCatching { GroupLightningWalletManager.current(database, chatRoomId, chain)?.statement?.participants?.toSet() }.getOrNull().orEmpty() - override suspend fun groupWallet(chatRoomId: String, chain: Chain): GroupWallet? = try { GroupWalletManager.walletFor(database, chatRoomId, chain) } catch (e: Throwable) { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseFrostSigningRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseFrostSigningRepository.kt index 84a62934..8c259551 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseFrostSigningRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseFrostSigningRepository.kt @@ -2,7 +2,6 @@ package mobi.giza.compose.database.repository import mobi.giza.compose.database.model.GroupTransaction import mobi.giza.compose.wallet.GroupSpend -import mobi.giza.compose.wallet.lightning.GroupSweep import fr.acinq.bitcoin.Chain import fr.acinq.bitcoin.OutPoint import fr.acinq.bitcoin.psbt.Psbt @@ -173,13 +172,6 @@ class DatabaseFrostSigningRepository( null } - override suspend fun checkedSweep(sessionId: String): GroupSweep.Checked? = try { - FrostSigningManager.checkedSweep(database, sessionId) - } catch (e: Throwable) { - logger.e("Error checking the sweep of $sessionId", e) - null - } - override suspend fun reservedOutPoints(chatRoomId: String): Set = try { FrostSigningManager.reservedOutPoints(database, chatRoomId) } catch (e: Throwable) { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupLightningRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupLightningRepository.kt deleted file mode 100644 index 94c08123..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupLightningRepository.kt +++ /dev/null @@ -1,127 +0,0 @@ -package mobi.giza.compose.database.repository - -import mobi.giza.compose.database.GizaDatabase -import mobi.giza.compose.database.model.IcebergKeySession -import mobi.giza.compose.database.model.IcebergParticipantMessage -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.database.model.types.IcebergApprovalStep -import mobi.giza.compose.managers.FrostSigningManager -import mobi.giza.compose.database.model.FrostSigningSession -import mobi.giza.compose.database.model.GroupLightningInvoiceRow -import mobi.giza.compose.database.model.GroupLightningPaymentRow -import mobi.giza.compose.managers.GroupLightningAuthorisations -import mobi.giza.compose.managers.GroupLightningCoSigner -import mobi.giza.compose.managers.GroupLightningOperatorManager -import mobi.giza.compose.managers.GroupLightningReports -import mobi.giza.compose.managers.GroupLightningWalletManager -import mobi.giza.compose.managers.GroupWalletManager -import fr.acinq.phoenixd.conf.LSP -import mobi.giza.compose.managers.IcebergRitualManager -import mobi.giza.compose.nostr.lightning.GroupLightningAuthorisationEvent -import mobi.giza.compose.nostr.lightning.GroupLightningEvents -import mobi.giza.compose.repository.GroupLightningRepository -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.Chain -import mobi.giza.compose.managers.GroupLightningSweeps -import mobi.giza.compose.wallet.lightning.GroupSweep -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.map - -class DatabaseGroupLightningRepository(private val database: GizaDatabase) : GroupLightningRepository { - override suspend fun completedCeremony(chatRoomId: String): IcebergKeySession? = IcebergRitualManager.completedKey(database, chatRoomId) - - override suspend fun lightningWallet(chatRoomId: String, chain: Chain): GroupLightningWalletManager.Wallet? = - GroupLightningWalletManager.current(database, chatRoomId, chain) - - override suspend fun earlierWallets(chatRoomId: String, chain: Chain): List = - GroupLightningWalletManager.wallets(database, chatRoomId, chain).dropLast(1) - - override suspend fun departed(wallet: GroupLightningWalletManager.Wallet): List = - GroupLightningWalletManager.departed(database, wallet) - - override suspend fun hasUnusedKey(chatRoomId: String, chain: Chain): Boolean = - GroupLightningWalletManager.unusedKey(database, chatRoomId, chain) != null - - override suspend fun unusedKey(chatRoomId: String, chain: Chain): IcebergKeySession? = - GroupLightningWalletManager.unusedKey(database, chatRoomId, chain) - - override suspend fun operator(chatRoomId: String, chain: Chain, wallet: Long): GroupLightningOperatorManager.Operator? = - GroupLightningOperatorManager.current(database, chatRoomId, chain, wallet) - - override fun lspNodeId(chain: Chain): HexKey? = - runCatching { LSP.from(chain).walletParams.trampolineNode.id.toString() }.getOrNull() - - override suspend fun proposeWallet(localChatRoom: LocalChatRoom, userPublicKey: HexKey, nostrPrivateKey: ByteArray, chain: Chain): FrostSigningSession = - GroupLightningWalletManager.proposeWallet(database, localChatRoom, userPublicKey, nostrPrivateKey, chain, requireNotNull(lspNodeId(chain)) { "No LSP is known for ${chain.name}" }) - - override suspend fun nominateSelf(localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain, wallet: Long): FrostSigningSession = - GroupLightningOperatorManager.nominateSelf(database, localChatRoom, userPublicKey, chain, wallet) - - override suspend fun stepDown(localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain, wallet: Long): FrostSigningSession = - GroupLightningOperatorManager.stepDown(database, localChatRoom, userPublicKey, chain, wallet) - - override fun observeReport(chatRoomId: String, chain: Chain, wallet: Long): Flow { - val key = GroupLightningCoSigner.walletKey(chatRoomId, chain, wallet) - return database.groupLightningRecordsDao().observeSnapshot(key).map { GroupLightningReports.latest(database, key) } - } - - override fun observePayments(chatRoomId: String, chain: Chain, wallet: Long): Flow> = - database.groupLightningRecordsDao().observePayments(GroupLightningCoSigner.walletKey(chatRoomId, chain, wallet)) - - override suspend fun requestInvoice(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, amountMsat: Long?, description: String): String = - GroupLightningReports.requestInvoice(database, localChatRoom, userPublicKey, wallet, amountMsat, description) - - override fun observeInvoice(chatRoomId: String, chain: Chain, wallet: Long, requestId: String): Flow = - database.groupLightningRecordsDao().observeInvoice(GroupLightningCoSigner.walletKey(chatRoomId, chain, wallet), requestId) - - override suspend fun proposePayment(localChatRoom: LocalChatRoom, userPublicKey: HexKey, pay: GroupLightningAuthorisationEvent.Pay): FrostSigningSession = - GroupLightningAuthorisations.propose(database, localChatRoom, userPublicKey, pay) - - override suspend fun proposeLiquidity(localChatRoom: LocalChatRoom, userPublicKey: HexKey, buy: GroupLightningAuthorisationEvent.BuyLiquidity): FrostSigningSession = - GroupLightningAuthorisations.proposeBuyLiquidity(database, localChatRoom, userPublicKey, buy) - - override suspend fun proposeClose(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelId: String, force: Boolean): FrostSigningSession = - GroupLightningAuthorisations.proposeChannelAction(database, localChatRoom, userPublicKey, wallet, channelId, force) - - override suspend fun proposeCloseAll(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelIds: List): FrostSigningSession = - GroupLightningAuthorisations.proposeCloseAll(database, localChatRoom, userPublicKey, wallet, channelIds) - - override suspend fun unswept(chatRoomId: String, report: GroupLightningReports.Report?): List = - GroupLightningSweeps.unswept(database, chatRoomId, report) - - override suspend fun proposeSweep(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, inputs: List): FrostSigningSession = - GroupLightningSweeps.propose(database, localChatRoom, userPublicKey, wallet, inputs) - - override fun observeCeremony(sessionId: String): Flow = - database.icebergKeySessionDao().observeSessionById(sessionId) - - override fun observeCeremonies(chatRoomId: String): Flow> = - database.icebergKeySessionDao().observeSessionsForChatRoom(chatRoomId) - - override suspend fun ceremonyMessages(sessionId: String): List = - GroupLightningEvents.CEREMONY.flatMap { database.icebergKeySessionDao().getMessagesByKind(sessionId, it) } - - override suspend fun pendingApproval(session: IcebergKeySession): IcebergApprovalStep? = - IcebergRitualManager.pendingApproval(database, session) - - override suspend fun ceremonyThresholds(chatRoomId: String): List = - IcebergRitualManager.thresholds(database, chatRoomId) - - override suspend fun keyHolderCount(chatRoomId: String): Int = - FrostSigningManager.completedKey(database, chatRoomId)?.let { IcebergRitualManager.holdersInRoom(database, chatRoomId, it).size } ?: 0 - - override suspend fun hasOnchainWallet(chatRoomId: String, chain: Chain): Boolean = - GroupWalletManager.walletFor(database, chatRoomId, chain) != null - - override suspend fun proposeCeremony(localChatRoom: LocalChatRoom, userPublicKey: HexKey, nostrPrivateKey: ByteArray, threshold: Int, chain: Chain): IcebergKeySession = - IcebergRitualManager.proposeCeremony(database, localChatRoom, userPublicKey, nostrPrivateKey, threshold, chain) - - override suspend fun approveCeremony(localChatRoom: LocalChatRoom, sessionId: String, step: IcebergApprovalStep, nostrPrivateKey: ByteArray) = - IcebergRitualManager.approve(database, localChatRoom, sessionId, step, nostrPrivateKey) - - override suspend fun resumeCeremony(localChatRoom: LocalChatRoom, sessionId: String, nostrPrivateKey: ByteArray) = - IcebergRitualManager.resume(database, localChatRoom, sessionId, nostrPrivateKey) - - override suspend fun abandonCeremony(localChatRoom: LocalChatRoom, sessionId: String): Boolean = - IcebergRitualManager.abandon(database, localChatRoom, sessionId) -} 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 b8d8bbef..d679a773 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt @@ -17,8 +17,6 @@ import fr.acinq.bitcoin.crypto.frost.TweakCache import fr.acinq.bitcoin.psbt.Psbt import fr.acinq.secp256k1.Hex import co.touchlab.kermit.Logger -import mobi.giza.compose.network.serialization.CommonJson -import mobi.giza.compose.wallet.lightning.GroupSweep import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.core.Kind @@ -414,12 +412,13 @@ object FrostSigningManager { userPublicKey = userPublicKey ) } else if (innerEvent.kind == FrostSigningEvents.TRANSACTION_PROPOSAL && FrostSigningEvents.parseSweep(innerEvent.tags) != null) { - acceptSweepProposal( + declineWalletProposal( database = database, localChatRoom = localChatRoom, innerEvent = innerEvent, sessionId = sessionId, - userPublicKey = userPublicKey + userPublicKey = userPublicKey, + subject = FrostSigningSubject.SWEEP ) } else if (innerEvent.kind == FrostSigningEvents.TRANSACTION_PROPOSAL) { acceptSpendProposal( @@ -475,6 +474,37 @@ object FrostSigningManager { advance(database, localChatRoom, session.id) } + /** + * Files a proposal over a transaction or a sweep as a session this device has + * declined, without reading what it spends: Giza signs neither, and can no longer + * check either (docs/giza-wallet-removal.md). [advance] publishes the decline, so + * the group counts it rather than waiting. Null for a proposal this device could + * not have signed anyway -- a key it does not hold -- which is dropped as before. + */ + private suspend fun declineWalletProposal( + database: GizaDatabase, + localChatRoom: LocalChatRoom, + innerEvent: Event, + sessionId: String, + userPublicKey: HexKey, + subject: FrostSigningSubject + ): FrostSigningSession? { + database.frostSigningSessionDao().getSessionById(sessionId)?.let { return it } + + val key = FrostSigningEvents.parseKey(innerEvent.tags) + ?.let { database.dkgSessionDao().getSessionById(it) } + ?.takeIf { it.stage == DkgRitualStage.COMPLETE } + ?: return null + val signerId = signerIdOf(database, key, userPublicKey) ?: return null + + logger.w("Signing proposal $sessionId is a wallet's ($subject); declining") + val declined = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path = null) + .copy(subject = subject, signDeclinedAt = Clock.System.now()) + database.frostSigningSessionDao().upsert(declined) + announceStarted(database, declined) + return declined + } + private fun newSession( sessionId: String, localChatRoom: LocalChatRoom, @@ -1099,226 +1129,6 @@ object FrostSigningManager { return transaction to (opened?.account ?: GroupWalletDerivation.account(thresholdPublicKey, chain, transaction.account)) } - /** - * Opens a sweep of what a closed Lightning channel left the group into the - * onchain wallet at [account] on [chain], after every check [GroupSweep.check] - * makes. Like a spend, proposing it is agreeing to it. - */ - suspend fun proposeSweep( - database: GizaDatabase, - localChatRoom: LocalChatRoom, - userPublicKey: HexKey, - sweep: GroupSweep.Sweep, - chain: Chain, - account: Long = 0L, - ): FrostSigningSession { - val chatRoomId = localChatRoom.chatRoom.id - val ceremony = completedKey(database, chatRoomId) - ?: throw IllegalStateException("This group has no shared key to sign with") - val thresholdPublicKey = ceremony.thresholdPublicKey - ?: throw IllegalStateException("Ceremony ${ceremony.id} holds no threshold key") - val signerId = signerIdOf(database, ceremony, userPublicKey) - ?: throw IllegalStateException("This device is not a participant in ceremony ${ceremony.id}") - val checked = when (val result = checkSweep(database, chatRoomId, thresholdPublicKey, chain, account, sweep)) { - is GroupSweep.Result.Ok -> result.checked - is GroupSweep.Result.Refused -> throw IllegalArgumentException("This sweep ${result.reason}") - } - - val session = FrostSigningSession( - id = RandomInstance.bytes(32).toHex(), - chatRoomId = chatRoomId, - coordinatorPublicKey = userPublicKey, - userPublicKey = userPublicKey, - dkgSessionId = ceremony.id, - threshold = ceremony.threshold, - participantCount = ceremony.participantCount, - signerId = signerId, - derivationPath = null, - subject = FrostSigningSubject.SWEEP, - signApprovedAt = Clock.System.now() - ) - writeSweep(database, session, checked, chain, account) - announceStarted(database, session) - logger.i("Proposing sweep ${session.id}: ${checked.inputs.size} output(s), ${checked.amount.sat} sats to the wallet, ${checked.fee.sat} sats fee") - - broadcast( - database = database, - localChatRoom = localChatRoom, - session = session, - kind = FrostSigningEvents.TRANSACTION_PROPOSAL, - content = CommonJson.encodeToString(GroupSweep.Sweep.serializer(), sweep), - includeKey = true, - extraTags = FrostSigningEvents.sweepTags(GroupWalletStatementEvent.chainName(chain), account, sweep.wallet) - ) - advance(database, localChatRoom, session.id) - return session - } - - /** - * Records a proposed sweep, after every check [GroupSweep.check] makes, against - * the group's own basepoints and the onchain wallet the room opened. Write-once, - * as a spend is. - */ - private suspend fun acceptSweepProposal( - database: GizaDatabase, - localChatRoom: LocalChatRoom, - innerEvent: Event, - sessionId: String, - userPublicKey: HexKey - ): FrostSigningSession? { - val sweep = decodeSweep(innerEvent.content) - database.frostSigningSessionDao().getSessionById(sessionId)?.let { existing -> - val stored = database.groupTransactionDao().getBySessionId(sessionId)?.let { decodeSweep(it.psbt) } - if (existing.subject != FrostSigningSubject.SWEEP || stored == null || stored != sweep) { - logger.w("Session $sessionId re-proposed with a different sweep; ignoring") - } - return existing - } - if (sweep == null) { - logger.w("Sweep proposal $sessionId does not carry a sweep; dropping") - return null - } - val key = FrostSigningEvents.parseKey(innerEvent.tags) - ?.let { database.dkgSessionDao().getSessionById(it) } - ?.takeIf { it.stage == DkgRitualStage.COMPLETE } - val thresholdPublicKey = key?.thresholdPublicKey - if (key == null || thresholdPublicKey == null) { - logger.w("Sweep proposal $sessionId names a key this device does not hold; dropping") - return null - } - val signerId = signerIdOf(database, key, userPublicKey) ?: run { - logger.w("Sweep proposal $sessionId is for a ceremony this device did not take part in; dropping") - return null - } - val (chainName, account) = FrostSigningEvents.parseWallet(innerEvent.tags) ?: run { - logger.w("Sweep proposal $sessionId names no wallet; dropping") - return null - } - val chain = GroupWalletStatementEvent.chainNamed(chainName) ?: return null - if (FrostSigningEvents.parseSweep(innerEvent.tags) != sweep.wallet) { - logger.w("Sweep proposal $sessionId names one Lightning wallet in its tags and another in its content; dropping") - return null - } - val checked = when (val result = checkSweep(database, localChatRoom.chatRoom.id, thresholdPublicKey, chain, account, sweep)) { - is GroupSweep.Result.Ok -> result.checked - is GroupSweep.Result.Refused -> { - logger.w("Sweep proposal $sessionId ${result.reason}; dropping") - return null - } - } - val session = FrostSigningSession( - id = sessionId, - chatRoomId = localChatRoom.chatRoom.id, - coordinatorPublicKey = innerEvent.pubKey, - userPublicKey = userPublicKey, - dkgSessionId = key.id, - threshold = key.threshold, - participantCount = key.participantCount, - signerId = signerId, - derivationPath = null, - subject = FrostSigningSubject.SWEEP, - ) - writeSweep(database, session, checked, chain, account) - announceStarted(database, session) - logger.i("Recorded sweep $sessionId: ${checked.amount.sat} sats to the wallet, ${checked.fee.sat} sats fee; awaiting approval") - announceApprovalNeeded(database, session) - replayStoredMessages(database, localChatRoom, session) - return session - } - - /** - * [sweep] checked against the Lightning wallet the room agreed for its - * network and number, whose basepoints derive from [thresholdPublicKey], and - * the onchain wallet at [account] it must pay. - */ - private suspend fun checkSweep(database: GizaDatabase, chatRoomId: String, thresholdPublicKey: HexKey, chain: Chain, account: Long, sweep: GroupSweep.Sweep): GroupSweep.Result { - GroupLightningWalletManager.walletFor(database, chatRoomId, chain, sweep.wallet) - ?: return GroupSweep.Result.Refused("sweeps a Lightning wallet the group has not opened") - val onchain = GroupWalletManager.walletFor(database, chatRoomId, thresholdPublicKey, chain, account) - ?: return GroupSweep.Result.Refused("pays an onchain wallet the group has not opened") - return GroupSweep.check(sweep, GroupLightningDerivation.basepoints(thresholdPublicKey, chain, sweep.wallet), onchain.account) - } - - private suspend fun writeSweep(database: GizaDatabase, session: FrostSigningSession, checked: GroupSweep.Checked, chain: Chain, account: Long) { - database.frostSigningSessionDao().upsert(session) - database.frostSigningSessionDao().upsertItems( - checked.inputs.map { input -> - FrostSigningItem( - sessionId = session.id, - itemIndex = input.index, - unsignedEventJson = """{"input":${input.index}}""", - eventId = input.sighash.toHex(), - nonceRandom = RandomInstance.bytes(32).toHex(), - inputIndex = input.index, - ) - } - ) - // The row a spend keeps, so the watcher broadcasts the sweep like any of the group's - // transactions; its PSBT column holds the sweep as proposed instead. - database.groupTransactionDao().insertIfAbsent( - GroupTransaction( - frostSigningSessionId = session.id, - chatRoomId = session.chatRoomId, - chain = GroupWalletStatementEvent.chainName(chain), - account = account, - psbt = CommonJson.encodeToString(GroupSweep.Sweep.serializer(), checked.sweep), - txid = checked.tx.txid.toString(), - ) - ) - } - - private fun decodeSweep(content: String): GroupSweep.Sweep? = - runCatching { CommonJson.decodeFromString(GroupSweep.Sweep.serializer(), content) }.getOrNull() - - /** The sweep a sweep session signs, checked again from its row, or null. */ - private suspend fun sweepOf(database: GizaDatabase, session: FrostSigningSession, thresholdPublicKey: HexKey): GroupSweep.Checked? { - val transaction = database.groupTransactionDao().getBySessionId(session.id) ?: return null - val sweep = decodeSweep(transaction.psbt) ?: return null - val chain = GroupWalletStatementEvent.chainNamed(transaction.chain) ?: return null - return (checkSweep(database, session.chatRoomId, thresholdPublicKey, chain, transaction.account, sweep) as? GroupSweep.Result.Ok)?.checked - } - - /** The sweep [sessionId] signs, as the approval screen shows it, or null for any other session. */ - suspend fun checkedSweep(database: GizaDatabase, sessionId: String): GroupSweep.Checked? { - val session = database.frostSigningSessionDao().getSessionById(sessionId) ?: return null - if (session.subject != FrostSigningSubject.SWEEP) return null - val thresholdPublicKey = database.dkgSessionDao().getSessionById(session.dkgSessionId)?.thresholdPublicKey ?: return null - return sweepOf(database, session, thresholdPublicKey) - } - - /** A sweep's signatures, each checked under its leaf key, witnessed, and run through the interpreter. */ - private suspend fun completeSweep(database: GizaDatabase, session: FrostSigningSession, items: List) { - val thresholdPublicKey = database.dkgSessionDao().getSessionById(session.dkgSessionId)?.thresholdPublicKey - ?: throw IllegalStateException("The ceremony this sweep signs under is gone") - val checked = sweepOf(database, session, thresholdPublicKey) ?: throw IllegalStateException("This sweep no longer checks out") - val signatures = items.mapIndexed { index, item -> - val input = checked.inputs[index] - val signature = ByteVector64(item.signature!!) - if (!Crypto.verifySignatureSchnorr(input.sighash, signature, input.leafKey)) { - throw IllegalStateException("The aggregated signature for input $index does not verify under its leaf key") - } - signature - } - val signed = GroupSweep.witnessed(checked.tx, checked.inputs, signatures) - signed.correctlySpends(checked.inputs.associate { it.outPoint to it.txOut }, ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) - update(database, session) { it.copy(stage = FrostSigningStage.COMPLETE) } - try { - val transaction = database.groupTransactionDao().getBySessionId(session.id) ?: return - database.groupTransactionDao().upsert(transaction.copy(signedTransaction = Hex.encode(Transaction.write(signed)))) - } catch (e: Throwable) { - logger.e("Signed sweep ${session.id} but could not record it", e) - } - announce( - database = database, - session = session, - messageType = ChatMessage.TYPE_FROST_COMPLETE, - content = "The group signed a sweep of ${checked.amount.sat} sats from its Lightning wallet into its onchain wallet, " + - "with ${checked.fee.sat} sats in fees. It is sent once its delay is over.", - actor = session.coordinatorPublicKey - ) - logger.i("Sweep ${session.id} complete: txid ${signed.txid}") - } - /** * The spend a transaction session signs, checked again from its stored PSBT, * or null for an event session or one whose spend no longer checks out. @@ -1937,9 +1747,8 @@ object FrostSigningManager { FrostSigningSubject.TRANSACTION -> spendCaches(database, session, thresholdPublicKey, items) ?: throw IllegalStateException("The coins this transaction spends no longer derive under the group's wallet") - FrostSigningSubject.SWEEP -> sweepOf(database, session, thresholdPublicKey) - ?.inputs?.map { it.cache } - ?: throw IllegalStateException("The outputs this sweep spends no longer derive under the group's basepoints") + // Declined on arrival, so never approved, and never here. + FrostSigningSubject.SWEEP -> throw IllegalStateException("This device does not sign sweeps") } val messages = items.map { ByteVector(it.eventId.hexToByteArray()) } @@ -2129,10 +1938,8 @@ object FrostSigningManager { completeSpend(database, session, items) return } - if (session.subject == FrostSigningSubject.SWEEP) { - completeSweep(database, session, items) - return - } + // Declined on arrival, so never signed, and never here. + if (session.subject == FrostSigningSubject.SWEEP) return // Every signature is checked before any event is applied. A batch is // all-or-nothing, so a bad one anywhere has to fail the session rather @@ -3127,19 +2934,10 @@ object FrostSigningManager { ) } - // The sweep as proposed, which the transaction row keeps where a spend keeps its PSBT. + // Declined on arrival: this device proposed none, so has none to resend. FrostSigningSubject.SWEEP -> { - val transaction = database.groupTransactionDao().getBySessionId(sessionId) - val sweep = transaction?.let { decodeSweep(it.psbt) } - if (transaction == null || sweep == null) { - logger.w("Session $sessionId: no sweep on file; nothing to resend") - return false - } - Triple( - FrostSigningEvents.TRANSACTION_PROPOSAL, - transaction.psbt, - FrostSigningEvents.sweepTags(transaction.chain, transaction.account, sweep.wallet) - ) + logger.w("Session $sessionId: a sweep, which this device does not propose; nothing to resend") + return false } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupIcebergTransport.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupIcebergTransport.kt deleted file mode 100644 index d44f3de5..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupIcebergTransport.kt +++ /dev/null @@ -1,217 +0,0 @@ -package mobi.giza.compose.managers - -import co.touchlab.kermit.Logger -import mobi.giza.compose.database.GizaDatabase -import mobi.giza.compose.database.model.IcebergLabelAssignment -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.extensions.toHex -import mobi.giza.compose.network.serialization.CommonJson -import mobi.giza.compose.nostr.lightning.GroupLightningEvents -import mobi.giza.compose.wallet.lightning.CoSigningWire -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.utils.RandomInstance -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.TxId -import fr.acinq.bitcoin.crypto.iceberg.NonceContribution -import fr.acinq.bitcoin.crypto.iceberg.SignatureShare -import fr.acinq.bitcoin.utils.Either -import fr.acinq.lightning.crypto.FundingSigner -import fr.acinq.lightning.crypto.IcebergGroupTransport -import fr.acinq.lightning.crypto.IcebergRoundTwoRequest -import fr.acinq.lightning.transactions.Transactions -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Job -import kotlinx.coroutines.delay -import kotlinx.coroutines.isActive -import kotlinx.coroutines.launch -import kotlinx.coroutines.withTimeoutOrNull -import kotlin.time.Clock -import kotlin.time.Duration.Companion.milliseconds -import kotlin.time.Duration.Companion.seconds - -/** - * The operator's side of co-signing: what lightning-kmp's `RemoteIcebergFundingSigner` talks to on the - * operator's device (`docs/group-lightning-wallet.md`, Phases 8 and 9). - * - * **Round one is a pool.** Every label the node will use comes from one sequence of pool counters - * ([GroupLightningCoSigner.poolLabel]), and every participant publishes its contributions for the next - * [GroupLightningCoSigner.POOL_WINDOW] counters ahead of any need. A verification nonce's funding txid - * does not exist until the channel is being negotiated, so a label cannot be computed from it in advance; - * instead each new need is *assigned* the next counter, and the assignment is kept so the same need gets - * the same label again. The interface lightning-kmp calls for round one is synchronous, so the pool and - * the assignments are held in memory, loaded at start and refreshed as batches arrive. - * - * **Round two is a request.** [roundTwo] queues a signing request for the room, hands it to this - * device's own co-signer at once -- the operator holds a share like everyone else -- and waits until - * `2t-1` signature shares are filed: the quorum the scheme wants online for round two, of which - * aggregation uses as few as `t`. - * - * Losing an assignment in a crash costs a verification nonce that cannot be re-derived, which costs a - * force close's signature, never a share: a counter handed out twice is a label the co-signers' ledgers - * already hold under another message, and every one of them refuses it. - */ -class GroupIcebergTransport private constructor( - private val database: GizaDatabase, - private val localChatRoom: LocalChatRoom, - private val userPublicKey: HexKey, - private val wallet: GroupLightningWalletManager.Wallet, - private val term: Long, - private val scope: CoroutineScope, -) : IcebergGroupTransport { - private val logger = Logger.withTag("GroupIcebergTransport") - private val key = GroupLightningCoSigner.walletKey(localChatRoom.chatRoom.id, wallet.statement.chain, wallet.statement.wallet) - - override val n: Int = wallet.statement.participants.size - override val t: Int = wallet.statement.threshold - - private val labelsByCounter = mutableMapOf() - private val countersByLabel = mutableMapOf() - private val assignments = mutableMapOf() - private val pool = mutableMapOf>() - private var nextCounter = 0L - private var refresher: Job? = null - - /** The highest counter whose label has been handed out, for the snapshot and for provisioning. */ - val highestAssigned: Long get() = nextCounter - 1 - - /** Every need given a label so far, by purpose: what a snapshot hands the next operator. */ - fun assignments(): Map = assignments.toMap() - - private fun label(counter: Long): ByteVector32 = labelsByCounter.getOrPut(counter) { - GroupLightningCoSigner.poolLabel(wallet.statement.icebergKey, counter).also { countersByLabel[it] = counter } - } - - private suspend fun reload() { - val dao = database.icebergCoSigningDao() - dao.assignments(key).forEach { a -> - assignments[a.purpose] = a.counter - label(a.counter) - } - nextCounter = maxOf(nextCounter, (dao.highestAssignment(key) ?: -1) + 1) - val upTo = nextCounter + GroupLightningCoSigner.POOL_WINDOW - // Every counter already handed out stays loaded too: a verification nonce is signed under long - // after it was assigned, at a force close. - for (counter in assignments.values + (nextCounter..upTo)) { - val rows = dao.noncesFor(key, counter) - if (rows.size >= 2 * t - 1) pool[counter] = rows.sortedBy { it.contribution }.map { NonceContribution(it.contribution) } - } - } - - private fun assign(purpose: String?): ByteVector32 { - purpose?.let { p -> assignments[p]?.let { return label(it) } } - val counter = nextCounter++ - purpose?.let { assignments[it] = counter } - val assigned = label(counter) - scope.launch { - runCatching { database.icebergCoSigningDao().insertAssignment(IcebergLabelAssignment(key, counter, assigned.toHex(), purpose ?: "fresh:$counter")) } - .onFailure { logger.e("Could not record pool counter $counter", it) } - } - maybeProvision() - return assigned - } - - /** Asks the group for more round one when the pool is running out ahead of the counters handed out. */ - private fun maybeProvision() { - val ready = pool.keys.filter { it >= nextCounter }.size - if (ready > GroupLightningCoSigner.POOL_WINDOW / 3) return - scope.launch { provision(nextCounter + GroupLightningCoSigner.POOL_WINDOW) } - } - - /** Sends the room a provision request up to [upTo], and publishes this device's own contributions. */ - suspend fun provision(upTo: Long) { - val request = CoSigningWire.SigningRequest( - wallet = key, term = term, requestId = RandomInstance.bytes(16).toHex(), kind = GroupLightningCoSigner.PROVISION, - label = "", counter = upTo, tx = "", input = CoSigningWire.Input("", 0, 0, ""), fundingTxId = "", remoteFundingPubKey = "", - contributions = emptyList(), cosignerAggregatedNonce = "", - ) - GroupLightningWalletManager.queue(database, localChatRoom, userPublicKey, GroupLightningEvents.SIGNING_REQUEST, CommonJson.encodeToString(CoSigningWire.SigningRequest.serializer(), request)) - GroupLightningCoSigner.provision(database, localChatRoom, userPublicKey, wallet, upTo) - reload() - } - - /** - * Waits until round one is in hand for the next [counters] pool counters, reloading as batches land, - * for at most [timeout]. False when the group has not sent enough: a node that connected now could be - * asked to sign before it could. - */ - suspend fun awaitPool(counters: Int, timeout: kotlin.time.Duration): Boolean { - if (counters <= 0) return true - val ready = { (nextCounter until nextCounter + counters).all { it in pool } } - return withTimeoutOrNull(timeout) { - while (true) { - reload() - if (ready()) return@withTimeoutOrNull true - delay(POLL) - } - @Suppress("UNREACHABLE_CODE") false - } ?: false - } - - override fun contributions(label: ByteVector32): List? = countersByLabel[label]?.let { pool[it] } - - override fun verificationLabel(id: FundingSigner.VerificationNonceId): ByteVector32 = - assign("verification:${id.fundingTxId}:${id.remoteFundingPubKey}:${id.commitIndex}") - - override fun nextFreshLabel(fundingTxId: TxId): ByteVector32 = assign(null) - - override suspend fun roundTwo(request: IcebergRoundTwoRequest): Either> { - val counter = countersByLabel[request.label] ?: return Either.Left(IllegalStateException("label ${request.label} is not from this wallet's pool")) - val requestId = RandomInstance.bytes(16).toHex() - val wire = CoSigningWire.SigningRequest( - wallet = key, - term = term, - requestId = requestId, - kind = request.kind.name, - label = request.label.toHex(), - counter = counter, - tx = CoSigningWire.tx(request.tx.tx), - input = CoSigningWire.input(request.tx.input), - fundingTxId = request.fundingTxId.toString(), - remoteFundingPubKey = request.remoteFundingPubKey.toString(), - commitIndex = request.commitIndex, - contributions = request.contributions.map { it.toByteArray().toHex() }, - cosignerAggregatedNonce = request.cosignerAggregatedNonce.data.toHex(), - context = CoSigningWire.context(request.context), - extraUtxos = request.extraUtxos.map { (outPoint, txOut) -> CoSigningWire.input(Transactions.InputInfo(outPoint, txOut)) }, - ) - val content = CommonJson.encodeToString(CoSigningWire.SigningRequest.serializer(), wire) - GroupLightningWalletManager.queue(database, localChatRoom, userPublicKey, GroupLightningEvents.SIGNING_REQUEST, content) - // This device is a co-signer too, and answers its own request the way the inbound path would. - GroupLightningCoSigner.process(database, localChatRoom, Event("", userPublicKey, Clock.System.now().epochSeconds, GroupLightningEvents.SIGNING_REQUEST, emptyArray(), content, ""), userPublicKey) - - val wanted = minOf(n, 2 * t - 1) - while (true) { - val shares = database.icebergCoSigningDao().sharesFor(key, requestId) - if (shares.size >= wanted) return Either.Right(shares.map { SignatureShare(it.share) }) - delay(POLL) - } - } - - /** Re-reads the pool every [REFRESH], so batches filed by the inbound path reach the synchronous round one. */ - fun start() { - refresher?.cancel() - refresher = scope.launch { - while (isActive) { - runCatching { reload() }.onFailure { logger.e("Could not reload the round-one pool", it) } - delay(REFRESH) - } - } - } - - fun stop() { - refresher?.cancel() - } - - companion object { - private val POLL = 100.milliseconds - private val REFRESH = 2.seconds - - /** - * The transport for [wallet], with its pool and assignments loaded. The first counter it hands out - * is past every one this device has recorded assigning. - */ - suspend fun create(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, term: Long, scope: CoroutineScope): GroupIcebergTransport = - GroupIcebergTransport(database, localChatRoom, userPublicKey, wallet, term, scope).also { it.reload() } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningAuthorisations.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningAuthorisations.kt deleted file mode 100644 index 7fc4df72..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningAuthorisations.kt +++ /dev/null @@ -1,185 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.database.GizaDatabase -import mobi.giza.compose.database.model.FrostSigningSession -import mobi.giza.compose.database.model.IcebergBudgetSpend -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.extensions.toHex -import mobi.giza.compose.nostr.lightning.GroupLightningAuthorisationEvent -import mobi.giza.compose.nostr.lightning.GroupLightningWalletStatementEvent -import mobi.giza.compose.wallet.GroupLightningRollout -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.utils.RandomInstance -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.lightning.payment.Bolt11Invoice -import kotlin.time.Clock -import kotlin.time.Duration -import kotlin.time.Duration.Companion.hours -import kotlin.time.Instant - -/** - * What the group has authorised its Lightning wallet to spend, as a co-signer reads it and the operator's - * node acts on it (`docs/group-lightning-wallet.md`, Phases 12 and 13). - * - * An authorisation is a group-signed event (kind 30363, [GroupLightningAuthorisationEvent]). The group - * may sign two for one invoice -- once more after the first expired, say. They are one payment: the - * budget is the larger, and it is open while either is. A close or force close names one channel, and - * lasts [CHANNEL_ACTION_LIFETIME]. - */ -object GroupLightningAuthorisations { - /** How long an authorisation stays open when its invoice does not say sooner. */ - val DEFAULT_LIFETIME: Duration = 24.hours - - /** Every payment the group has authorised for [wallet], as this device verifies it, oldest first. */ - suspend fun payments(database: GizaDatabase, wallet: GroupLightningWalletManager.Wallet): List = - database.groupSignedEventDao().getByChatRoomIdAndKind(wallet.signedEvent.chatRoomId, GroupLightningAuthorisationEvent.KIND) - .filter { it.verifies() } - .sortedWith(compareBy({ it.createdAt }, { it.id })) - .mapNotNull { GroupLightningAuthorisationEvent.read(it.tags) } - .filter { it.chain == wallet.statement.chain && it.wallet == wallet.statement.wallet } - - /** Every payment the group has authorised, with its whole budget, by payment hash, in millisatoshi. */ - suspend fun authorisedPayments(database: GizaDatabase, wallet: GroupLightningWalletManager.Wallet): Map = - payments(database, wallet).groupBy { it.paymentHash }.mapValues { (_, all) -> all.maxOf { it.budgetMsat } } - - /** The payment hashes whose every authorisation has expired at [now]: no new HTLC pays them. */ - suspend fun expired(database: GizaDatabase, wallet: GroupLightningWalletManager.Wallet, now: Instant = Clock.System.now()): Set = - payments(database, wallet).groupBy { it.paymentHash }.filterValues { all -> all.all { it.expiresAt <= now.epochSeconds } }.keys - - /** What each authorised payment has left to spend, by payment hash, in millisatoshi. */ - suspend fun budgets(database: GizaDatabase, wallet: GroupLightningWalletManager.Wallet): Map { - val key = GroupLightningCoSigner.walletKey(wallet.signedEvent.chatRoomId, wallet.statement.chain, wallet.statement.wallet) - val spent = database.icebergCoSigningDao().budgetSpends(key).associate { it.paymentHash to it.consumedMsat } - return authorisedPayments(database, wallet).mapValues { (hash, amount) -> amount - (spent[hash] ?: 0) }.filterValues { it > 0 } - } - - /** Records that a commitment spent [consumed] of each authorisation, by payment hash. */ - suspend fun consume(database: GizaDatabase, wallet: GroupLightningWalletManager.Wallet, consumed: Map) { - if (consumed.isEmpty()) return - val key = GroupLightningCoSigner.walletKey(wallet.signedEvent.chatRoomId, wallet.statement.chain, wallet.statement.wallet) - val dao = database.icebergCoSigningDao() - val spent = dao.budgetSpends(key).associate { it.paymentHash to it.consumedMsat } - consumed.forEach { (hash, amount) -> dao.upsertBudgetSpend(IcebergBudgetSpend(key, hash, (spent[hash] ?: 0) + amount)) } - } - - /** The authorised payments the operator's node should make at [now]: open, one per payment hash, oldest first. */ - suspend fun toPay(database: GizaDatabase, wallet: GroupLightningWalletManager.Wallet, now: Instant = Clock.System.now()): List = - payments(database, wallet).filter { it.expiresAt > now.epochSeconds }.distinctBy { it.paymentHash } - - /** Why [bolt11] cannot be authorised for [wallet], or null when it can. */ - sealed class Problem { - data object Unreadable : Problem() - data object OtherNetwork : Problem() - data object Expired : Problem() - data object NeedsAmount : Problem() - /** The invoice pays the group's own node: a payment to itself that would only cost fees. */ - data object PaysTheGroup : Problem() - } - - /** The authorisation [bolt11] would be, or the [Problem] with it. [amountMsat] is used only when the invoice names none. */ - fun prepare(wallet: GroupLightningWalletManager.Wallet, bolt11: String, amountMsat: Long?, maxFeeMsat: Long, now: Instant = Clock.System.now()): Result { - val text = bolt11.trim().removePrefix("lightning:").removePrefix("LIGHTNING:") - val invoice = runCatching { Bolt11Invoice.read(text).get() }.getOrNull() ?: return Result.failure(ProblemException(Problem.Unreadable)) - if (invoice.chain != wallet.statement.chain) return Result.failure(ProblemException(Problem.OtherNetwork)) - if (invoice.isExpired(now.epochSeconds)) return Result.failure(ProblemException(Problem.Expired)) - if (invoice.nodeId.toString() == wallet.statement.nodeId) return Result.failure(ProblemException(Problem.PaysTheGroup)) - val amount = invoice.amount?.msat ?: amountMsat?.takeIf { it > 0 } ?: return Result.failure(ProblemException(Problem.NeedsAmount)) - val invoiceExpiry = invoice.timestampSeconds + (invoice.expirySeconds ?: Bolt11Invoice.DEFAULT_EXPIRY_SECONDS.toLong()) - val expires = minOf(invoiceExpiry, (now + DEFAULT_LIFETIME).epochSeconds) - return Result.success( - GroupLightningAuthorisationEvent.Pay(wallet.statement.chain, wallet.statement.wallet, text, amount, maxFeeMsat, invoice.paymentHash.toHex(), expires) - ) - } - - class ProblemException(val problem: Problem) : IllegalArgumentException(problem.toString()) - - /** Proposes [pay] to the group; it is authorised once a quorum signs. */ - suspend fun propose(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, pay: GroupLightningAuthorisationEvent.Pay): FrostSigningSession { - val template = GroupLightningAuthorisationEvent.template(pay) - return FrostSigningManager.proposeSigning(database, localChatRoom, userPublicKey, template.kind, template.tags, template.content) - } - - /** How long a close or force close stays open: long enough for the operator's device to come online. */ - val CHANNEL_ACTION_LIFETIME: Duration = 72.hours - - /** Every close and force close the group has authorised in [chatRoomId] for the wallet [statement] names, open at [now]. */ - suspend fun channelActions(database: GizaDatabase, chatRoomId: String, statement: GroupLightningWalletStatementEvent.Statement, now: Instant = Clock.System.now()): List = - database.groupSignedEventDao().getByChatRoomIdAndKind(chatRoomId, GroupLightningAuthorisationEvent.KIND) - .filter { it.verifies() } - .sortedWith(compareBy({ it.createdAt }, { it.id })) - .mapNotNull { GroupLightningAuthorisationEvent.readChannelAction(it.tags) } - .filter { it.chain == statement.chain && it.wallet == statement.wallet && it.expiresAt > now.epochSeconds } - - /** Whether the group has authorised a force close of [channelId] that is still open. */ - suspend fun forceCloseAuthorised(database: GizaDatabase, chatRoomId: String, statement: GroupLightningWalletStatementEvent.Statement, channelId: ByteVector32): Boolean = - channelActions(database, chatRoomId, statement).any { it.action == GroupLightningAuthorisationEvent.FORCE_CLOSE && it.channelId == channelId.toHex() } - - /** Proposes closing every one of [channelIds] of [wallet] to the onchain wallet, as one signing session. */ - suspend fun proposeCloseAll(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelIds: List): FrostSigningSession { - require(channelIds.isNotEmpty()) { "There are no channels to close" } - val expires = (Clock.System.now() + CHANNEL_ACTION_LIFETIME).epochSeconds - val templates = channelIds.map { channelId -> - GroupLightningAuthorisationEvent.template(GroupLightningAuthorisationEvent.ChannelAction(GroupLightningAuthorisationEvent.CLOSE, wallet.statement.chain, wallet.statement.wallet, channelId, expires)) - } - return FrostSigningManager.proposeSigningBatch(database, localChatRoom, userPublicKey, templates) - } - - /** Proposes that the operator's node close [channelId] -- mutually, or by force when [force]. */ - suspend fun proposeChannelAction(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelId: String, force: Boolean): FrostSigningSession { - val action = GroupLightningAuthorisationEvent.ChannelAction( - if (force) GroupLightningAuthorisationEvent.FORCE_CLOSE else GroupLightningAuthorisationEvent.CLOSE, - wallet.statement.chain, wallet.statement.wallet, channelId, (Clock.System.now() + CHANNEL_ACTION_LIFETIME).epochSeconds, - ) - val template = GroupLightningAuthorisationEvent.template(action) - return FrostSigningManager.proposeSigning(database, localChatRoom, userPublicKey, template.kind, template.tags, template.content) - } - - /** Why a liquidity purchase cannot be proposed. */ - sealed class LiquidityProblem { - /** A purchase of nothing. */ - data object NothingToBuy : LiquidityProblem() - /** A purchase that would take the channel over what a channel may hold on this network. */ - data class OverTheCap(val capSat: Long) : LiquidityProblem() - } - - class LiquidityProblemException(val problem: LiquidityProblem) : IllegalArgumentException(problem.toString()) - - /** How long a liquidity purchase stays open: as long as a close, for the same reason. */ - val LIQUIDITY_LIFETIME: Duration = CHANNEL_ACTION_LIFETIME - - /** - * Every liquidity purchase the group has authorised for [wallet], open at [now], oldest first - * (`docs/group-lightning-liquidity.md`, Phase 4). Whether one has already been spent is each - * co-signer's ledger to say. - */ - suspend fun liquidityPurchases(database: GizaDatabase, wallet: GroupLightningWalletManager.Wallet, now: Instant = Clock.System.now()): List = - database.groupSignedEventDao().getByChatRoomIdAndKind(wallet.signedEvent.chatRoomId, GroupLightningAuthorisationEvent.KIND) - .filter { it.verifies() } - .sortedWith(compareBy({ it.createdAt }, { it.id })) - .mapNotNull { GroupLightningAuthorisationEvent.readBuyLiquidity(it.tags) } - .filter { it.chain == wallet.statement.chain && it.wallet == wallet.statement.wallet && it.expiresAt > now.epochSeconds } - - /** - * The purchase of [amountSat] for [channelId], which holds [capacitySat] now, at most [maxFeeSat] in - * fees, or the [LiquidityProblem] with it. The proposer is not trusted on the cap: every co-signer holds the - * new funding output to it again. - */ - fun prepareBuyLiquidity(wallet: GroupLightningWalletManager.Wallet, channelId: String, capacitySat: Long, amountSat: Long, maxFeeSat: Long, now: Instant = Clock.System.now()): Result { - if (amountSat <= 0) return Result.failure(LiquidityProblemException(LiquidityProblem.NothingToBuy)) - GroupLightningRollout.channelCapFor(wallet.statement.chain)?.let { cap -> - if (capacitySat + amountSat > cap.sat) return Result.failure(LiquidityProblemException(LiquidityProblem.OverTheCap(cap.sat))) - } - return Result.success( - GroupLightningAuthorisationEvent.BuyLiquidity( - wallet.statement.chain, wallet.statement.wallet, channelId, amountSat, maxFeeSat.coerceAtLeast(0), - (now + LIQUIDITY_LIFETIME).epochSeconds, RandomInstance.bytes(8).toHex(), - ) - ) - } - - /** Proposes [buy] to the group; the operator's node buys once a quorum signs. */ - suspend fun proposeBuyLiquidity(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, buy: GroupLightningAuthorisationEvent.BuyLiquidity): FrostSigningSession { - val template = GroupLightningAuthorisationEvent.template(buy) - return FrostSigningManager.proposeSigning(database, localChatRoom, userPublicKey, template.kind, template.tags, template.content) - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningCoSigner.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningCoSigner.kt deleted file mode 100644 index be1741a2..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningCoSigner.kt +++ /dev/null @@ -1,645 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.database.model.ChatMessage -import co.touchlab.kermit.Logger -import mobi.giza.compose.database.GizaDatabase -import mobi.giza.compose.database.model.IcebergChannelLedger -import mobi.giza.compose.database.model.IcebergEchoRow -import mobi.giza.compose.database.model.IcebergLabelLedger -import mobi.giza.compose.database.model.IcebergNonceRow -import mobi.giza.compose.database.model.IcebergShareRow -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.extensions.toHex -import mobi.giza.compose.network.serialization.CommonJson -import mobi.giza.compose.nostr.lightning.GroupLightningEvents -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import mobi.giza.compose.wallet.GroupLightningRollout -import mobi.giza.compose.wallet.lightning.CoSignerPolicy -import mobi.giza.compose.wallet.lightning.CoSigningWire -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.Crypto -import fr.acinq.bitcoin.PublicKey -import fr.acinq.bitcoin.SigHash -import fr.acinq.bitcoin.Transaction -import fr.acinq.bitcoin.crypto.Pack -import fr.acinq.bitcoin.crypto.iceberg.Iceberg -import fr.acinq.bitcoin.crypto.iceberg.NonceContribution -import fr.acinq.bitcoin.crypto.musig2.AggregatedNonce -import fr.acinq.bitcoin.crypto.musig2.KeyAggCache -import fr.acinq.bitcoin.utils.Either -import fr.acinq.lightning.channel.Commitments -import fr.acinq.lightning.crypto.LocalKeyManager -import fr.acinq.lightning.transactions.Scripts -import fr.acinq.lightning.transactions.Transactions -import fr.acinq.phoenixd.conf.LSP -import kotlin.time.Clock -import kotlinx.serialization.Serializable - -/** - * The co-signer every Iceberg participant runs: it answers the operator's node for the group, without a - * person in the loop, under the policy the group signed (`docs/group-lightning-wallet.md`, Phase 9). - * - * Four kinds reach it. A **nonce batch** is filed: round one is published ahead of time, for a pool of - * labels nothing has been assigned to yet. A **signing request** is checked -- the sender is the - * current operator, the label is one from the pool this device has never answered, the transaction is - * the one its context rebuilds to, and what it does to the group's money is something the group agreed - * to -- and, if it passes, *echoed*: the co-signer tells the room the hash it would sign under that - * label, and will never sign anything else under it. An **echo** is counted; once `n - t + 1` - * participants have echoed the same hash for a label, this device signs, and once a member sees two - * hashes echoed for one label it signs neither. A **signature share** is filed for the operator. - * - * Why `n - t + 1`: any two sets of that many share `n - 2t + 2` members, which is at least `t` when - * `n >= 3t - 2`, and so contains an honest member who echoed only one hash. So no two different - * messages can ever both be signed under one label (decision D7). - */ -object GroupLightningCoSigner { - private val logger = Logger.withTag("GroupLightningCoSigner") - - /** How many round-one contributions a co-signer keeps published ahead of the operator's latest need. */ - const val POOL_WINDOW: Long = 64 - - /** The most a single provision request makes a co-signer publish. */ - const val MAX_BATCH: Long = 128 - - /** - * A swap-in xpub for [LocalKeyManager], which wants one; a group node never swaps in, so any valid one - * does -- for the network. lightning-kmp checks the prefix: a tpub on mainnet throws, and so would the - * first key manager every co-signer and the operator's node built. So mainnet takes the mainnet LSP's - * published one, and every other network this tpub. Nothing derives from either: the node id and - * every channel key come from the seed. - */ - internal const val UNUSED_SWAP_IN_TPUB = "tpubDAmCFB21J9ExKBRPDcVxSvGs9jtcf8U1wWWbS1xTYmnUsuUHPCoFdCnEGxLE3THSWcQE48GHJnyz8XPbYUivBMbLSMBifFd3G9KmafkM9og" - - private fun unusedSwapInXpub(chain: Chain): String = if (chain.isMainnet()) LSP.from(Chain.Mainnet).swapInXpub else UNUSED_SWAP_IN_TPUB - - fun walletKey(chatRoomId: String, chain: Chain, wallet: Long): String = "$chatRoomId:${GroupWalletStatementEvent.chainName(chain)}:$wallet" - - /** - * The label of pool counter [counter] for the group key [icebergKey]: every member computes the same, - * on Bennu or on Giza, which is why the tag keeps its `bennu/` prefix. - */ - fun poolLabel(icebergKey: HexKey, counter: Long): ByteVector32 = - Crypto.taggedHash(ByteVector(icebergKey).toByteArray() + Pack.writeInt64BE(counter), "bennu/iceberg/pool/v1") - - /** The key manager a group node runs, and a co-signer rebuilds commitments with. */ - fun keyManagerOf(seed: ByteVector, chain: Chain): LocalKeyManager = LocalKeyManager(seed, chain, unusedSwapInXpub(chain)) - - /** - * What a co-signer stores of a funding output's ledger, in JSON. [consumed] is what its last - * commitment spent of each authorisation, by payment hash: while a splice is unconfirmed the same - * payment settles on both outputs' commitments at one number, and spends its budget once. - */ - @Serializable - private data class StoredLedger( - val commitIndex: Long, - val commitTxId: String, - val oursMsat: Long, - val offered: Map>, - val incoming: Map, - val floorMsat: Long, - val consumed: Map = emptyMap(), - ) - - internal fun store(l: CoSignerPolicy.Ledger, consumed: Map = emptyMap()) = CommonJson.encodeToString( - StoredLedger.serializer(), - StoredLedger(l.commitIndex, l.commitTxId, l.oursMsat, l.offered.entries.associate { (id, h) -> id.toString() to listOf(h.paymentHash, h.amountMsat.toString()) }, l.incoming.entries.associate { (id, a) -> id.toString() to a }, l.floorMsat, consumed), - ) - - private fun consumedBy(json: String): Map = CommonJson.decodeFromString(StoredLedger.serializer(), json).consumed - - /** - * What the other funding outputs' commitments at [commitIndex] already spent of each budget: the - * most any of them spent, since each settles the same payments. - */ - private fun spentBySiblings(siblings: List, commitIndex: Long): Map = - siblings.filter { load(it.ledger).commitIndex == commitIndex }.map { consumedBy(it.ledger) } - .fold(emptyMap()) { acc, m -> (acc.keys + m.keys).associateWith { maxOf(acc[it] ?: 0, m[it] ?: 0) } } - - private fun load(json: String): CoSignerPolicy.Ledger = CommonJson.decodeFromString(StoredLedger.serializer(), json).let { s -> - CoSignerPolicy.Ledger(s.commitIndex, s.commitTxId, s.oursMsat, s.offered.entries.associate { (id, v) -> id.toLong() to CoSignerPolicy.OfferedHtlc(v[0], v[1].toLong()) }, s.incoming.entries.associate { (id, a) -> id.toLong() to a }, s.floorMsat) - } - - /** - * What the last counterparty commitment this device signed for [channelId] left the group, HTLCs it - * offered excluded, or null when this device has signed none for that channel. - */ - suspend fun signedOursMsat(database: GizaDatabase, walletKey: String, channelId: String): Long? = - database.icebergCoSigningDao().channelLedger(walletKey, channelId)?.let { load(it.ledger).oursMsat } - - /** The wallet a message for [walletKey] is about, if this device believes it. */ - internal suspend fun walletOf(database: GizaDatabase, chatRoomId: String, walletKey: String): GroupLightningWalletManager.Wallet? { - val parts = walletKey.split(":") - if (parts.size != 3 || parts[0] != chatRoomId) return null - val chain = GroupWalletStatementEvent.chainNamed(parts[1]) ?: return null - return GroupLightningWalletManager.walletFor(database, chatRoomId, chain, parts[2].toLongOrNull() ?: return null) - } - - private fun indexOf(wallet: GroupLightningWalletManager.Wallet, participant: HexKey): Int? = - wallet.statement.participants.indexOf(participant.lowercase()).takeIf { it >= 0 }?.plus(1) - - /** Publishes this device's round-one contributions for every pool counter up to [upTo] it has not published yet. */ - suspend fun provision(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, upTo: Long) { - val share = wallet.ceremony?.let(IcebergRitualManager::shareOf) ?: return - val key = walletKey(localChatRoom.chatRoom.id, wallet.statement.chain, wallet.statement.wallet) - val me = userPublicKey.lowercase() - val dao = database.icebergCoSigningDao() - val from = (dao.highestNonce(key, me) ?: -1L) + 1 - val to = minOf(upTo, from + MAX_BATCH - 1) - if (to < from) return - val contributions = (from..to).map { counter -> - Iceberg.generateNonce(share, null, poolLabel(wallet.statement.icebergKey, counter)).toByteArray().toHex() - .also { dao.insertNonce(IcebergNonceRow(key, counter, me, it)) } - } - GroupLightningWalletManager.queue(database, localChatRoom, userPublicKey, GroupLightningEvents.NONCE_BATCH, CommonJson.encodeToString(CoSigningWire.NonceBatch.serializer(), CoSigningWire.NonceBatch(key, from, contributions))) - } - - /** Routes one inbound co-signing message. [nostrPrivateKey] is not needed to sign: the share is. */ - suspend fun process(database: GizaDatabase, localChatRoom: LocalChatRoom, innerEvent: Event, userPublicKey: HexKey) { - try { - when (innerEvent.kind) { - GroupLightningEvents.NONCE_BATCH -> fileNonces(database, localChatRoom, innerEvent) - GroupLightningEvents.SIGNING_REQUEST -> handleRequest(database, localChatRoom, innerEvent, userPublicKey) - GroupLightningEvents.ECHO -> fileEcho(database, localChatRoom, innerEvent, userPublicKey) - GroupLightningEvents.SIGNATURE_SHARE -> fileShare(database, localChatRoom, innerEvent) - } - } catch (e: Throwable) { - if (e is kotlinx.coroutines.CancellationException) throw e - logger.e("Could not process co-signing kind ${innerEvent.kind}", e) - } - } - - private suspend fun fileNonces(database: GizaDatabase, localChatRoom: LocalChatRoom, event: Event) { - val batch = CommonJson.decodeFromString(CoSigningWire.NonceBatch.serializer(), event.content) - val wallet = walletOf(database, localChatRoom.chatRoom.id, batch.wallet) ?: return - if (indexOf(wallet, event.pubKey) == null) return - if (batch.contributions.size > MAX_BATCH) return - batch.contributions.forEachIndexed { i, c -> - database.icebergCoSigningDao().insertNonce(IcebergNonceRow(batch.wallet, batch.from + i, event.pubKey.lowercase(), c)) - } - } - - private suspend fun fileShare(database: GizaDatabase, localChatRoom: LocalChatRoom, event: Event) { - val message = CommonJson.decodeFromString(CoSigningWire.SignatureShareMessage.serializer(), event.content) - val wallet = walletOf(database, localChatRoom.chatRoom.id, message.wallet) ?: return - if (indexOf(wallet, event.pubKey) == null) return - database.icebergCoSigningDao().insertShare(IcebergShareRow(message.wallet, message.requestId, event.pubKey.lowercase(), message.share)) - } - - /** The provision request: a signing request whose kind is `PROVISION`, asking for contributions up to its counter. */ - const val PROVISION = "PROVISION" - - /** The context type of a splice's shared input. */ - const val SPLICE = "splice" - - private suspend fun handleRequest(database: GizaDatabase, localChatRoom: LocalChatRoom, event: Event, userPublicKey: HexKey) { - val request = CommonJson.decodeFromString(CoSigningWire.SigningRequest.serializer(), event.content) - val roomId = localChatRoom.chatRoom.id - val wallet = walletOf(database, roomId, request.wallet) ?: return - if (wallet.ceremony?.share == null || userPublicKey.lowercase() !in wallet.statement.participants) return - - // Check 1: the current operator, in the current term. - val operator = GroupLightningOperatorManager.current(database, roomId, wallet.statement.chain, wallet.statement.wallet) - if (operator?.publicKey?.lowercase() != event.pubKey.lowercase() || operator.term != request.term) { - logger.w("Refusing request ${request.requestId}: ${event.pubKey.take(8)} is not the operator of term ${operator?.term}") - return - } - if (request.kind == PROVISION) { - provision(database, localChatRoom, userPublicKey, wallet, request.counter) - return - } - - val refusal = check(database, roomId, wallet, request) - if (refusal != null) { - logger.w("Refusing request ${request.requestId}: $refusal") - // Its owner is never shown a commitment, so a refusal is the one thing about - // co-signing a person sees -- and on this device only, which is whose check it was. - GroupLightningLines.writeFact( - database, roomId, ChatMessage.TYPE_LIGHTNING_REFUSED, request.requestId, userPublicKey, - "Your device refused to co-sign for the Lightning node: $refusal.", Clock.System.now(), - ) - return - } - val message = messageOf(request) ?: return - - // Echo, and commit to this hash under this label for good. A label already answered under any - // other message is never answered again. - val dao = database.icebergCoSigningDao() - val existing = dao.ledgerFor(request.wallet, request.label) - if (existing != null && existing.messageHash != message.toHex()) { - logger.w("Refusing request ${request.requestId}: label ${request.label.take(16)} was already echoed for another message") - raiseEquivocation(database, roomId, request.label, event.pubKey) - return - } - commitLedger(database, roomId, wallet, request) - if (existing == null) { - dao.insertLedger(IcebergLabelLedger(request.wallet, request.label, request.requestId, message.toHex())) - dao.insertEcho(IcebergEchoRow(request.wallet, request.label, userPublicKey.lowercase(), message.toHex())) - GroupLightningWalletManager.queue(database, localChatRoom, userPublicKey, GroupLightningEvents.ECHO, CommonJson.encodeToString(CoSigningWire.Echo.serializer(), CoSigningWire.Echo(request.wallet, request.requestId, request.label, message.toHex()))) - } - maybeSign(database, localChatRoom, wallet, request.wallet, request.label, userPublicKey) - } - - private suspend fun fileEcho(database: GizaDatabase, localChatRoom: LocalChatRoom, event: Event, userPublicKey: HexKey) { - val echo = CommonJson.decodeFromString(CoSigningWire.Echo.serializer(), event.content) - val wallet = walletOf(database, localChatRoom.chatRoom.id, echo.wallet) ?: return - if (indexOf(wallet, event.pubKey) == null) return - database.icebergCoSigningDao().insertEcho(IcebergEchoRow(echo.wallet, echo.label, event.pubKey.lowercase(), echo.messageHash)) - maybeSign(database, localChatRoom, wallet, echo.wallet, echo.label, userPublicKey) - } - - /** - * The alarm the echo rule exists to raise: the operator's node asked for two messages under one - * label. Said once per label, in the error tint, attributed to the operator whose node asked. - */ - private suspend fun raiseEquivocation(database: GizaDatabase, chatRoomId: String, label: String, operator: HexKey) = - GroupLightningLines.writeFact( - database, chatRoomId, ChatMessage.TYPE_LIGHTNING_EQUIVOCATION, label, operator, - "The operator's node asked the group to sign two different things under one label. Nobody will sign either.", - Clock.System.now(), - ) - - /** Signs under [label] once enough participants echoed this device's hash and nobody echoed another. */ - private suspend fun maybeSign(database: GizaDatabase, localChatRoom: LocalChatRoom, wallet: GroupLightningWalletManager.Wallet, key: String, label: String, userPublicKey: HexKey) { - val dao = database.icebergCoSigningDao() - val mine = dao.ledgerFor(key, label) ?: return - if (mine.signedAt != null) return - val echoes = dao.echoesFor(key, label) - if (echoes.any { it.messageHash != mine.messageHash }) { - logger.e("Label ${label.take(16)} was echoed for two different messages: the operator is equivocating, and nobody signs it") - val operator = GroupLightningOperatorManager.current(database, localChatRoom.chatRoom.id, wallet.statement.chain, wallet.statement.wallet) - raiseEquivocation(database, localChatRoom.chatRoom.id, label, operator?.publicKey ?: userPublicKey) - return - } - val n = wallet.statement.participants.size - val t = wallet.statement.threshold - if (echoes.map { it.participant }.toSet().size < n - t + 1) return - - val request = requestFor(database, localChatRoom.chatRoom.id, mine.requestId) ?: return - val share = wallet.ceremony?.let(IcebergRitualManager::shareOf) ?: return - val groupKey = PublicKey.fromHex(wallet.statement.icebergKey) - val remoteKey = PublicKey.fromHex(request.remoteFundingPubKey) - val sortedKeys = Scripts.sort(listOf(groupKey, remoteKey)) - val tweak = Scripts.Taproot.musig2Aggregate(groupKey, remoteKey).tweak(Crypto.TaprootTweak.KeyPathTweak) - val cache = when (val c = KeyAggCache.create(sortedKeys).second.tweak(tweak, isXonly = true)) { - is Either.Right -> c.value.first - is Either.Left -> return - } - val signatureShare = Iceberg.partialSign( - share, null, ByteVector32(label), request.contributions.map { NonceContribution(it) }, groupKey, cache, - ByteVector32(mine.messageHash), AggregatedNonce(ByteVector(request.cosignerAggregatedNonce)), - ) - when (signatureShare) { - is Either.Left -> logger.e("Could not sign under ${label.take(16)}", signatureShare.value) - is Either.Right -> { - dao.upsertLedger(mine.copy(signedAt = Clock.System.now())) - GroupLightningWalletManager.queue(database, localChatRoom, userPublicKey, GroupLightningEvents.SIGNATURE_SHARE, CommonJson.encodeToString(CoSigningWire.SignatureShareMessage.serializer(), CoSigningWire.SignatureShareMessage(key, mine.requestId, label, signatureShare.value.toByteArray().toHex()))) - dao.insertShare(IcebergShareRow(key, mine.requestId, userPublicKey.lowercase(), signatureShare.value.toByteArray().toHex())) - } - } - } - - private suspend fun requestFor(database: GizaDatabase, chatRoomId: String, requestId: String): CoSigningWire.SigningRequest? = - database.marmotInnerEventDao().getByChatRoomAndKinds(chatRoomId, listOf(GroupLightningEvents.SIGNING_REQUEST)) - .mapNotNull { runCatching { CommonJson.decodeFromString(CoSigningWire.SigningRequest.serializer(), it.content) }.getOrNull() } - .firstOrNull { it.requestId == requestId } - - /** - * The hash the request's transaction signs: recomputed, never read off the request. It is the input - * spending [CoSigningWire.SigningRequest.input], over every output the transaction spends, which BIP341 - * commits the signature to. A request that misstates what the other inputs spend gets a signature - * nobody can mine, never one that moves money; one that omits them gets nothing, since there is no - * hash to compute. Null then. - */ - fun messageOf(request: CoSigningWire.SigningRequest): ByteVector32? { - val tx = CoSigningWire.tx(request.tx) - val input = CoSigningWire.inputInfo(request.input) - val index = tx.txIn.indexOfFirst { it.outPoint == input.outPoint }.takeIf { it >= 0 } ?: return null - val spent = CoSigningWire.spentOutputs(tx, input, request.extraUtxos) ?: return null - return tx.hashForSigningTaprootKeyPath(index, spent, SigHash.SIGHASH_DEFAULT) - } - - /** - * Every check before an echo, as the plan numbers them. Null when the request may be signed; - * otherwise why not. - */ - private suspend fun check(database: GizaDatabase, roomId: String, wallet: GroupLightningWalletManager.Wallet, request: CoSigningWire.SigningRequest): String? { - val statement = wallet.statement - val dao = database.icebergCoSigningDao() - - // Check 2: a pool label, for the counter it claims, and its contributions are exactly what the - // participants they name published for it. - if (poolLabel(statement.icebergKey, request.counter).toHex() != request.label) return "the label is not pool counter ${request.counter}" - val published = dao.noncesFor(request.wallet, request.counter).associate { it.contribution to it.participant } - if (request.contributions.size < 2 * statement.threshold - 1) return "round one has fewer than 2t-1 contributions" - val from = request.contributions.map { published[it] ?: return "a contribution was not published by the participant it names" } - if (from.toSet().size != from.size) return "a participant's contribution appears twice" - request.contributions.zip(from).forEach { (c, participant) -> - if (ByteVector(c)[0].toInt() != indexOf(wallet, participant)) return "a contribution carries another participant's index" - } - - // Check 3: the funding output is the group key with the counterparty's. A commitment or a close - // spends it alone; a splice spends it once, beside the counterparty's own inputs. - val tx = CoSigningWire.tx(request.tx) - val input = CoSigningWire.inputInfo(request.input) - val isSplice = request.context?.type == SPLICE - if (isSplice) { - if (tx.txIn.count { it.outPoint == input.outPoint } != 1) return "the splice does not spend the funding output once" - } else if (tx.txIn.size != 1 || tx.txIn[0].outPoint != input.outPoint) { - return "the transaction does not spend exactly the funding output" - } - if (messageOf(request) == null) return "the request does not say what every input of the transaction spends" - val remoteKey = PublicKey.fromHex(request.remoteFundingPubKey) - val groupKey = PublicKey.fromHex(statement.icebergKey) - val expected = Transactions.makeFundingInputInfo(input.outPoint.txid, input.outPoint.index, input.txOut.amount, groupKey, remoteKey, Transactions.CommitmentFormat.SimpleTaprootChannels) - if (expected.txOut != input.txOut) return "the funding output is not the group's key with ${request.remoteFundingPubKey.take(16)}" - - // Check 4 onwards: what the transaction is. - val context = request.context ?: return "the operator did not say what this signs" - val params = CoSigningWire.params(context.params) - if (params.localParams.nodeId.toString() != statement.nodeId) return "the channel is not the wallet's node's" - if (params.remoteParams.nodeId.toString() != statement.lspNodeId) return "the channel is not with the wallet's LSP" - val onchain = GroupWalletManager.walletFor(database, roomId, statement.chain, statement.onchainAccount) ?: return "the onchain wallet is not open" - val closeTo = GroupWalletDerivation.derive(onchain.account, GroupWalletDerivation.RECEIVE, 0).pubkeyScript - if (params.localParams.defaultFinalScriptPubKey != closeTo) return "the channel does not close to the group's onchain wallet" - - // The channel is pinned to its funding output the first time this device signs for it, and to - // each output a splice it checked moved the channel to. A request on any other output is the - // first commitment on a splice's new one, which answers to its parent's ledger, or is refused. - val ledgers = dao.channelLedgers(request.wallet, params.channelId.toHex()) - val pinned = ledgers.firstOrNull { it.fundingOutPoint == outPointOf(input) } - if (pinned != null && pinned.remoteFundingPubKey != request.remoteFundingPubKey) return "the channel's funding output changed" - if (pinned == null && ledgers.isNotEmpty() && context.type != "remote") return "the channel's funding output changed" - - return when (context.type) { - "remote" -> when { - pinned == null && ledgers.isNotEmpty() -> when (val opening = openingOf(database, wallet, request, context, params, tx, ledgers)) { - is Opening.Refused -> opening.reason - is Opening.Opens -> null - } - else -> checkRemote(database, wallet, request, context, params, tx, pinned, ledgers - listOfNotNull(pinned).toSet()) - } - "closing" -> checkClosing(statement, context, tx, closeTo) - "local" -> checkLocal(database, wallet, request, context, params, tx, pinned) - SPLICE -> checkSplice(database, wallet, request, context, tx, pinned ?: return "this device has signed for none of the channel's funding outputs", ledgers) - else -> "an unknown kind of transaction" - } - } - - private fun outPointOf(input: Transactions.InputInfo) = "${input.outPoint.txid}:${input.outPoint.index}" - - /** The first commitment on a splice's new funding output: refused, or the ledger it opens. */ - private sealed class Opening { - data class Refused(val reason: String) : Opening() - data class Opens(val parent: IcebergChannelLedger, val ledger: CoSignerPolicy.Ledger, val purchase: mobi.giza.compose.nostr.lightning.GroupLightningAuthorisationEvent.BuyLiquidity) : Opening() - } - - /** - * Whether a commitment on a funding output this device has no ledger for is the first commitment on - * the new output of a splice the group authorised (`docs/group-lightning-liquidity.md`, Phase 5). - * It must follow the newest output this device signed for, by one index; rebuild from its context; - * and leave the group what the parent's ledger did, at the same number and with the same HTLCs, less - * at most the fee cap of an open `buy-liquidity` for the channel. That authorisation is bound to the - * first parent output it was used from: every attempt at the purchase spends that output, so at most - * one of them can ever confirm. - */ - private suspend fun openingOf( - database: GizaDatabase, - wallet: GroupLightningWalletManager.Wallet, - request: CoSigningWire.SigningRequest, - context: CoSigningWire.Context, - params: fr.acinq.lightning.channel.ChannelParams, - tx: Transaction, - ledgers: List, - ): Opening { - // The output one index below, and of those -- an earlier splice may have had attempts that never - // confirmed -- the one still carrying commitments. A splice's own failed attempt sits beside this - // one, at its index, and is never its parent. - val parent = ledgers.filter { it.fundingTxIndex == context.fundingTxIndex - 1 }.maxByOrNull { load(it.ledger).commitIndex } - ?: return Opening.Refused("a commitment on funding output ${context.fundingTxIndex}, which no splice this device checked would make") - if (ledgers.any { it.fundingTxIndex > context.fundingTxIndex }) return Opening.Refused("a commitment on funding output ${context.fundingTxIndex}, older than one this device has signed for") - rebuildsRemote(wallet, request, context, params, tx)?.let { return Opening.Refused(it) } - val commitIndex = context.commitIndex ?: return Opening.Refused("no commitment number") - val spec = CoSigningWire.spec(context.spec ?: return Opening.Refused("no commitment spec"), params.channelId) - val channelId = params.channelId.toHex() - val purchases = GroupLightningAuthorisations.liquidityPurchases(database, wallet).filter { it.channelId == channelId } - .filter { buy -> ledgers.none { it.purchaseId == buy.id && it.parentOutPoint != parent.fundingOutPoint } } - if (purchases.isEmpty()) return Opening.Refused("the group has not authorised buying liquidity for this channel") - var refusal = "the group has not authorised buying liquidity for this channel" - for (buy in purchases) { - when (val verdict = CoSignerPolicy.openSplice(load(parent.ledger), commitIndex, tx.txid.toString(), spec, buy.maxFeeSat * 1000)) { - is CoSignerPolicy.Verdict.Sign -> return Opening.Opens(parent, verdict.ledger, buy) - is CoSignerPolicy.Verdict.Refuse -> refusal = verdict.reason - } - } - return Opening.Refused(refusal) - } - - /** - * A splice's shared input: the funding output this device has pinned, given up for a new one only - * when the splice is the liquidity purchase the group authorised (`docs/group-lightning-liquidity.md`, - * Phase 5, rules S1 to S6). Every amount read here is the transaction's own or its spent outputs', - * which the signature commits to, so a request that misstates one gets nothing a miner would take. - */ - private suspend fun checkSplice( - database: GizaDatabase, - wallet: GroupLightningWalletManager.Wallet, - request: CoSigningWire.SigningRequest, - context: CoSigningWire.Context, - tx: Transaction, - parent: IcebergChannelLedger, - ledgers: List, - ): String? { - val statement = wallet.statement - // S2: it spends the output this device pinned, and says so. - val parentInput = CoSigningWire.inputInfo(request.input) - if (context.parentFunding?.let(CoSigningWire::inputInfo) != parentInput || context.parentFundingTxIndex != parent.fundingTxIndex) return "the splice does not say it spends the funding output it spends" - if (context.fundingTxIndex != parent.fundingTxIndex + 1) return "the splice skips a funding index" - // S3: one new funding output, the group's key with the LSP's new one, under the cap. - val index = context.fundingOutputIndex?.takeIf { it in tx.txOut.indices } ?: return "the splice names no new funding output" - val newKey = PublicKey.fromHex(context.newRemoteFundingPubKey ?: return "the splice names no key for the new funding output") - val newOutput = tx.txOut[index] - val expected = Transactions.makeFundingInputInfo(tx.txid, index.toLong(), newOutput.amount, PublicKey.fromHex(statement.icebergKey), newKey, Transactions.CommitmentFormat.SimpleTaprootChannels).txOut.publicKeyScript - if (newOutput.publicKeyScript != expected) return "the splice's new funding output is not the group's key with the LSP's" - if (tx.txOut.count { it.publicKeyScript == expected } != 1) return "the splice pays the group's funding script twice" - GroupLightningRollout.channelCapFor(statement.chain)?.let { cap -> - if (newOutput.amount > cap) return "the splice makes a channel of ${newOutput.amount.sat} sats, over the ${cap.sat} a channel may hold on mainnet for now" - } - // S6: this device already approved the first commitment on that output, from this parent. - val child = ledgers.firstOrNull { it.fundingOutPoint == "${tx.txid}:$index" } ?: return "this device has not signed the first commitment on the splice's new output" - if (child.parentOutPoint != parent.fundingOutPoint || child.remoteFundingPubKey != newKey.toString()) return "the first commitment this device signed on that output came from another splice" - // S1: the purchase the group authorised, for the amount it named. - val purchase = context.purchase ?: return "the splice buys no liquidity, and the group authorised only buying it" - val buy = GroupLightningAuthorisations.liquidityPurchases(database, wallet).firstOrNull { it.id == child.purchaseId } ?: return "the group's authorisation for this purchase is not open" - if (purchase.amountSat != buy.amountSat) return "the splice buys ${purchase.amountSat} sats, not the ${buy.amountSat} the group authorised" - // S5: paid from the channel balance alone, within the cap. - if (purchase.paymentType != CoSigningWire.FROM_CHANNEL_BALANCE || purchase.feeCreditUsedMsat != null) return "the purchase is paid ${purchase.paymentType}, and the group pays only from its balance" - val local = context.localContributionSat ?: return "the splice does not say what the group adds" - val remote = context.remoteContributionSat ?: return "the splice does not say what the LSP adds" - if (local > 0) return "the splice adds the group's own money, which this device does not sign" - val fee = -local + purchase.miningFeeSat + purchase.serviceFeeSat - if (fee > buy.maxFeeSat) return "the purchase costs $fee sats, over the ${buy.maxFeeSat} the group agreed to" - // S4: the LSP put in what it is paid for, and the new output holds exactly what the two added. - if (remote < purchase.amountSat) return "the LSP adds $remote sats for a purchase of ${purchase.amountSat}" - if (newOutput.amount.sat != parentInput.txOut.amount.sat + local + remote) return "the new funding output does not hold the old one plus what each side added" - // And the first commitment on it took from the group exactly what the purchase costs. - val taken = load(parent.ledger).valueMsat - load(child.ledger).valueMsat - if (taken != fee * 1000) return "the splice's first commitment took $taken msat from the group, not the ${fee * 1000} the purchase costs" - return null - } - - /** - * Our own commitment, which the group signs only to force-close: authorised, rebuilt from its context, - * and no older than the counterparty commitment this device last signed for the channel, less one. - * The two numbers move together, so a local commitment further behind than that is one this channel - * has revoked, and publishing it would hand the counterparty everything. - */ - private suspend fun checkLocal( - database: GizaDatabase, - wallet: GroupLightningWalletManager.Wallet, - request: CoSigningWire.SigningRequest, - context: CoSigningWire.Context, - params: fr.acinq.lightning.channel.ChannelParams, - tx: Transaction, - pinned: IcebergChannelLedger?, - ): String? { - if (!GroupLightningAuthorisations.forceCloseAuthorised(database, wallet.signedEvent.chatRoomId, wallet.statement, params.channelId)) return "the group has not authorised a force close" - val seed = wallet.seed ?: return "this device does not hold the node's seed, and cannot rebuild the commitment" - val commitParams = CoSigningWire.commit(context.commit ?: return "no commitment parameters") - val commitIndex = context.commitIndex ?: return "no commitment number" - pinned?.let { if (commitIndex < load(it.ledger).commitIndex - 1) return "commitment $commitIndex is older than this channel's current one, and revoked" } - val keys = keyManagerOf(ByteVector(seed.seed), wallet.statement.chain).channelKeys(params.localParams.fundingKeyPath) - .withGroupBasepoints(wallet.basepoints.forChannel) - val (rebuilt, _) = Commitments.makeLocalTxs( - channelParams = params, - commitParams = commitParams, - commitKeys = keys.localCommitmentKeys(params, commitIndex), - commitTxNumber = commitIndex, - localFundingPubkey = PublicKey.fromHex(wallet.statement.icebergKey), - remoteFundingPubKey = PublicKey.fromHex(request.remoteFundingPubKey), - commitmentInput = CoSigningWire.inputInfo(request.input), - commitmentFormat = Transactions.CommitmentFormat.SimpleTaprootChannels, - spec = CoSigningWire.spec(context.spec ?: return "no commitment spec", params.channelId), - ) - return if (rebuilt.tx != tx) "the commitment its context rebuilds to is not the one it asks to sign" else null - } - - private suspend fun checkRemote( - database: GizaDatabase, - wallet: GroupLightningWalletManager.Wallet, - request: CoSigningWire.SigningRequest, - context: CoSigningWire.Context, - params: fr.acinq.lightning.channel.ChannelParams, - tx: Transaction, - pinned: IcebergChannelLedger?, - siblings: List, - ): String? { - rebuildsRemote(wallet, request, context, params, tx)?.let { return it } - val commitIndex = context.commitIndex ?: return "no commitment number" - val spec = CoSigningWire.spec(context.spec ?: return "no commitment spec", params.channelId) - - // The first commitment a device signs for a channel is where its floor starts; every later one - // answers to the ledger of the funding output it is on. - if (pinned == null) return null - val budgets = withSiblings(GroupLightningAuthorisations.budgets(database, wallet), spentBySiblings(siblings, commitIndex)) - val closed = GroupLightningAuthorisations.expired(database, wallet) - return when (val verdict = CoSignerPolicy.checkRemoteCommitment(load(pinned.ledger), commitIndex, tx.txid.toString(), spec, budgets, closed, wallet.statement.policy.inFlightCapSat * 1000)) { - is CoSignerPolicy.Verdict.Refuse -> verdict.reason - is CoSignerPolicy.Verdict.Sign -> null - } - } - - /** [budgets] with what a sibling commitment at the same number already spent given back, since this one spends it too. */ - private fun withSiblings(budgets: Map, spent: Map): Map = - (budgets.keys + spent.keys).associateWith { (budgets[it] ?: 0) + (spent[it] ?: 0) }.filterValues { it > 0 } - - /** Why the commitment's context does not rebuild to [tx], or null when it does. */ - private fun rebuildsRemote( - wallet: GroupLightningWalletManager.Wallet, - request: CoSigningWire.SigningRequest, - context: CoSigningWire.Context, - params: fr.acinq.lightning.channel.ChannelParams, - tx: Transaction, - ): String? { - val seed = wallet.seed ?: return "this device does not hold the node's seed, and cannot rebuild the commitment" - // On mainnet a channel holds at most the rollout's cap. Refusing its commitments means a bigger - // channel never opens, and a splice to a bigger one is never signed into. - GroupLightningRollout.channelCapFor(wallet.statement.chain)?.let { cap -> - val capacity = CoSigningWire.inputInfo(request.input).txOut.amount - if (capacity > cap) return "the channel holds ${capacity.sat} sats, over the ${cap.sat} a channel may hold on mainnet for now" - } - val commitParams = CoSigningWire.commit(context.commit ?: return "no commitment parameters") - val commitIndex = context.commitIndex ?: return "no commitment number" - val perCommitmentPoint = PublicKey.fromHex(context.remotePerCommitmentPoint ?: return "no per-commitment point") - val spec = CoSigningWire.spec(context.spec ?: return "no commitment spec", params.channelId) - val keys = keyManagerOf(ByteVector(seed.seed), wallet.statement.chain).channelKeys(params.localParams.fundingKeyPath) - .withGroupBasepoints(wallet.basepoints.forChannel) - val (rebuilt, _) = Commitments.makeRemoteTxs( - channelParams = params, - commitParams = commitParams, - commitKeys = keys.remoteCommitmentKeys(params, perCommitmentPoint), - commitTxNumber = commitIndex, - localFundingPubkey = PublicKey.fromHex(wallet.statement.icebergKey), - remoteFundingPubKey = PublicKey.fromHex(request.remoteFundingPubKey), - commitmentInput = CoSigningWire.inputInfo(request.input), - commitmentFormat = Transactions.CommitmentFormat.SimpleTaprootChannels, - spec = spec, - ) - return if (rebuilt.tx != tx) "the commitment its context rebuilds to is not the one it asks to sign" else null - } - - private fun checkClosing(statement: mobi.giza.compose.nostr.lightning.GroupLightningWalletStatementEvent.Statement, context: CoSigningWire.Context, tx: Transaction, closeTo: ByteVector): String? { - val local = ByteVector(context.localScript ?: return "no closing script") - val remote = ByteVector(context.remoteScript ?: return "no counterparty script") - if (local != closeTo) return "the close does not pay the group's onchain wallet" - if (tx.txOut.any { it.publicKeyScript != local && it.publicKeyScript != remote }) return "the close pays a script it did not name" - val ours = (context.spec ?: return "no commitment spec").toLocalMsat / 1000 - val paid = tx.txOut.filter { it.publicKeyScript == local }.sumOf { it.amount.sat } - val allowance = statement.policy.commitmentFeeAllowanceSat - return if (ours > allowance && paid < ours - allowance) "the close pays the group $paid sats of its $ours" else null - } - - /** Records what this device let the commitment do, at echo time: it is committed to it from here. */ - private suspend fun commitLedger(database: GizaDatabase, roomId: String, wallet: GroupLightningWalletManager.Wallet, request: CoSigningWire.SigningRequest) { - val context = request.context ?: return - if (context.type != "remote") return - val params = CoSigningWire.params(context.params) - val spec = CoSigningWire.spec(context.spec ?: return, params.channelId) - val tx = CoSigningWire.tx(request.tx) - val dao = database.icebergCoSigningDao() - val channelId = params.channelId.toHex() - val input = CoSigningWire.inputInfo(request.input) - val ledgers = dao.channelLedgers(request.wallet, channelId) - val pinned = ledgers.firstOrNull { it.fundingOutPoint == outPointOf(input) } - val commitIndex = context.commitIndex ?: return - val allowance = wallet.statement.policy.commitmentFeeAllowanceSat * 1000 - val row = when { - ledgers.isEmpty() -> IcebergChannelLedger(request.wallet, channelId, outPointOf(input), request.remoteFundingPubKey, store(CoSignerPolicy.open(commitIndex, tx.txid.toString(), spec, allowance)), fundingTxIndex = context.fundingTxIndex) - pinned == null -> when (val opening = openingOf(database, wallet, request, context, params, tx, ledgers)) { - is Opening.Refused -> return - is Opening.Opens -> IcebergChannelLedger( - request.wallet, channelId, outPointOf(input), request.remoteFundingPubKey, store(opening.ledger), - fundingTxIndex = context.fundingTxIndex, parentOutPoint = opening.parent.fundingOutPoint, purchaseId = opening.purchase.id, - ) - } - else -> { - val siblings = spentBySiblings(ledgers - pinned, commitIndex) - val budgets = withSiblings(GroupLightningAuthorisations.budgets(database, wallet), siblings) - when (val verdict = CoSignerPolicy.checkRemoteCommitment(load(pinned.ledger), commitIndex, tx.txid.toString(), spec, budgets, GroupLightningAuthorisations.expired(database, wallet), wallet.statement.policy.inFlightCapSat * 1000)) { - is CoSignerPolicy.Verdict.Refuse -> return - is CoSignerPolicy.Verdict.Sign -> { - // A sibling at this number already spent its share of each budget; spend only what is new. - GroupLightningAuthorisations.consume(database, wallet, verdict.consumed.mapValues { (hash, amount) -> amount - (siblings[hash] ?: 0) }.filterValues { it > 0 }) - pinned.copy(ledger = store(verdict.ledger, verdict.consumed), updatedAt = Clock.System.now()) - } - } - } - } - dao.upsertChannelLedger(row) - val next = load(row.ledger) - logger.i("Channel ${channelId.take(16)} in $roomId, funding output ${row.fundingTxIndex}: commitment ${next.commitIndex} leaves the group ${next.valueMsat} msat against a floor of ${next.floorMsat}") - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningDerivation.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningDerivation.kt deleted file mode 100644 index 1f93a665..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningDerivation.kt +++ /dev/null @@ -1,103 +0,0 @@ -package mobi.giza.compose.managers - -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.Crypto -import fr.acinq.bitcoin.DeterministicWallet -import fr.acinq.bitcoin.KeyPath -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.PublicKey -import fr.acinq.bitcoin.crypto.Pack -import fr.acinq.bitcoin.crypto.frost.TweakCache -import fr.acinq.bitcoin.utils.Either -import fr.acinq.lightning.crypto.GroupBasepoints - -/** - * The two commitment basepoints a group's Lightning wallet holds instead of its operator's node, derived - * from the group's ChillDKG threshold key -- the same key its on-chain wallet is. - * - * ``` - * I = HMAC-SHA512("bennu/group-lightning/basepoints/v1", serP(K) || chainHash || ser32(wallet)) - * K_b = K + I[0:32]·G, chain code I[32:64] - * payment basepoint = CKDpub((K_b, c_b), 0) - * delayed basepoint = CKDpub((K_b, c_b), 1) - * ``` - * - * Why these keys, and not the node's: whoever holds the node seed can make the LSP force-close, and in - * a stock channel the output that pays us after a force close is keyed from that seed. With these - * basepoints it is keyed from the group's key, so only a FROST quorum moves it. See constraint 7 in - * `docs/group-lightning-wallet.md`. - * - * The shape is [GroupWalletDerivation]'s account step with its own tag, so it is a different key that - * every member recomputes from what they already hold. It is not an account of the on-chain wallet: - * these keys sign tapscript leaves, never a key path, so a descriptor that found them would only - * mislead a watch-only wallet. - * - * ### Signing as them - * - * Both are script-path keys, used x-only inside a leaf. `to_remote`'s leaf key is the payment basepoint - * itself; `to_local`'s and an HTLC transaction's is the delayed basepoint plus - * `SHA256(per_commitment_point || basepoint)·G`. Each is a FROST session over [leafCache] with no - * TapTweak, because nothing commits a script tree to these keys -- they are the leaf. - */ -object GroupLightningDerivation { - /** Frozen once a channel exists under it, `bennu/` and all, for the reason [GroupWalletDerivation]'s account tag is. */ - private const val TAG = "bennu/group-lightning/basepoints/v1" - - const val PAYMENT: Long = 0L - const val DELAYED_PAYMENT: Long = 1L - - private const val MAX_INDEX: Long = 0x7FFFFFFFL - - /** One basepoint: the full point lightning-kmp puts in `open_channel`, and the cache that signs as it. */ - class Basepoint internal constructor(val which: Long, val publicKey: PublicKey, val cache: TweakCache) - - class Basepoints internal constructor(val chain: Chain, val wallet: Long, val payment: Basepoint, val delayedPayment: Basepoint) { - /** What a group node's channel keys take: [fr.acinq.lightning.crypto.ChannelKeys.withGroupBasepoints]. */ - val forChannel: GroupBasepoints get() = GroupBasepoints(payment.publicKey, delayedPayment.publicKey) - } - - /** - * @param wallet the Lightning wallet's number in the room, as its statement's `wallet` tag says; a - * re-keyed wallet is the next number, and gets unrelated basepoints. - */ - fun basepoints(thresholdPublicKey: HexKey, chain: Chain, wallet: Long): Basepoints { - require(wallet in 0L..MAX_INDEX) { "wallet $wallet is not an unhardened index" } - val root = PublicKey(ByteVector(thresholdPublicKey.hexToByteArray())) - require(root.isValid()) { "the threshold key is not a valid point" } - - val i = Crypto.hmac512(TAG.encodeToByteArray(), root.value.toByteArray() + chain.chainHash.value.toByteArray() + Pack.writeInt32BE(wallet.toInt())) - val tweak = ByteVector32(i.copyOfRange(0, 32)) - require(Crypto.isPrivKeyValid(tweak.toByteArray())) { "the basepoint step for wallet $wallet landed on an invalid scalar" } - val stepKey = root + PrivateKey(tweak).publicKey() - val stepCache = plainTweak(TweakCache.create(root), tweak, "the basepoint step") - require(stepCache.tweakedPublicKey == stepKey.xOnly()) { "the basepoint cache does not reach the step key" } - val step = DeterministicWallet.ExtendedPublicKey(publickeybytes = stepKey.value, chaincode = ByteVector32(i.copyOfRange(32, 64)), depth = 0, path = KeyPath.empty, parent = 0L) - - fun child(which: Long): Basepoint { - val key = step.derivePublicKey(which).publicKey - val childTweak = ByteVector32(Crypto.hmac512(step.chaincode.toByteArray(), step.publickeybytes.toByteArray() + Pack.writeInt32BE(which.toInt())).copyOfRange(0, 32)) - val cache = plainTweak(stepCache, childTweak, "basepoint $which") - require(cache.tweakedPublicKey == key.xOnly()) { "the cache does not reach basepoint $which" } - return Basepoint(which, key, cache) - } - return Basepoints(chain, wallet, child(PAYMENT), child(DELAYED_PAYMENT)) - } - - /** - * The cache a FROST session signs a leaf with: [basepoint] itself when [perCommitmentTweak] is null - * (`to_remote`), or the basepoint plus that tweak (`to_local`, an HTLC transaction's output) -- - * lightning-kmp's `GroupHeldOutputs.Output.tweak`. - */ - fun leafCache(basepoint: Basepoint, perCommitmentTweak: ByteVector32?): TweakCache = - if (perCommitmentTweak == null) basepoint.cache else plainTweak(basepoint.cache, perCommitmentTweak, "the per-commitment tweak") - - private fun plainTweak(cache: TweakCache, tweak: ByteVector32, step: String): TweakCache = - when (val tweaked = cache.tweak(tweak, isXonly = false)) { - is Either.Left -> throw IllegalArgumentException("Could not apply $step to the group's key", tweaked.value) - is Either.Right -> tweaked.value.first - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningLines.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningLines.kt deleted file mode 100644 index 164a0236..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningLines.kt +++ /dev/null @@ -1,83 +0,0 @@ -package mobi.giza.compose.managers - -import co.touchlab.kermit.Logger -import mobi.giza.compose.database.GizaDatabase -import mobi.giza.compose.database.model.ChatMessage -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlin.time.Instant - -/** - * Writes the group Lightning wallet's lines into its room's transcript ([ChatMessage.LIGHTNING_TYPES]). - * See docs/group-lightning-transcript.md, Phase 4. - * - * Each line hangs off the inner event it describes, which is what makes it one line: the device - * that sends a message writes it on the way out, every other device writes it on arrival, and a - * redelivery or a replay finds the line already there. The inner event row exists in both cases -- - * `GroupLightningWalletManager.queue` writes it on the way out, and the inbound path files every - * inner event before its manager sees it -- which the foreign key on [ChatMessage.marmotInnerEventId] - * needs. - */ -internal object GroupLightningLines { - private val logger = Logger.withTag("GroupLightningLines") - - suspend fun write( - database: GizaDatabase, - chatRoomId: String, - innerEventId: HexKey, - messageType: String, - actor: HexKey, - content: String, - createdAt: Instant, - ) { - if (database.chatMessageDao().getChatMessagesByMarmotInnerEventId(innerEventId) != null) return - if (database.marmotInnerEventDao().getById(innerEventId) == null) { - return logger.w("No inner event $innerEventId is stored to hang a $messageType line off; writing none") - } - val reader = database.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom?.userPublicKey - database.chatMessageDao().upsert( - ChatMessage( - senderPublicKey = actor, - isUserMessage = reader != null && reader.equals(actor, ignoreCase = true), - giftWrapPayloadId = null, - marmotGroupEventId = null, - marmotInnerEventId = innerEventId, - chatRoomId = chatRoomId, - content = content, - messageType = messageType, - createdAt = createdAt, - ) - ) - } - - /** - * Writes the line for one fact the operator's snapshots report, unless the room already has it. - * There is no message to hang it off: the same fact arrives in every snapshot until it stops - * being true, so [factKey] -- the channel, the payment -- is what makes it one line. - */ - suspend fun writeFact( - database: GizaDatabase, - chatRoomId: String, - messageType: String, - factKey: String, - reportedBy: HexKey, - content: String, - createdAt: Instant, - ) { - if (database.chatMessageDao().getLightningFactLine(chatRoomId, messageType, factKey) != null) return - val reader = database.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom?.userPublicKey - database.chatMessageDao().upsert( - ChatMessage( - senderPublicKey = reportedBy, - isUserMessage = reader != null && reader.equals(reportedBy, ignoreCase = true), - giftWrapPayloadId = null, - marmotGroupEventId = null, - marmotInnerEventId = null, - chatRoomId = chatRoomId, - content = content, - messageType = messageType, - lightningFactKey = factKey, - createdAt = createdAt, - ) - ) - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningNode.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningNode.kt deleted file mode 100644 index 56ce32e4..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningNode.kt +++ /dev/null @@ -1,697 +0,0 @@ -package mobi.giza.compose.managers - -import co.touchlab.kermit.Logger -import mobi.giza.compose.database.GizaDatabase -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.nostr.lightning.GroupLightningAuthorisationEvent -import mobi.giza.compose.nostr.lightning.GroupLightningEvents -import mobi.giza.compose.nostr.lightning.GroupLightningWalletStatementEvent -import mobi.giza.compose.wallet.GroupChainClients -import mobi.giza.compose.wallet.GroupLightningRollout -import mobi.giza.compose.wallet.lightning.GroupNodeKeyManager -import mobi.giza.compose.wallet.lightning.GroupSweep -import mobi.giza.compose.wallet.lightning.WalletWire -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.PublicKey -import fr.acinq.bitcoin.Satoshi -import fr.acinq.bitcoin.utils.Either -import fr.acinq.lightning.FeatureSupport -import fr.acinq.lightning.Features -import fr.acinq.lightning.Lightning -import fr.acinq.lightning.MilliSatoshi -import fr.acinq.lightning.NodeParams -import fr.acinq.lightning.PaymentEvents -import fr.acinq.lightning.PeerConnected -import fr.acinq.lightning.WalletParams -import fr.acinq.lightning.blockchain.Feerates -import fr.acinq.lightning.blockchain.electrum.ElectrumWatcher -import fr.acinq.lightning.blockchain.fee.FeeratePerByte -import fr.acinq.lightning.blockchain.fee.FeeratePerKw -import fr.acinq.lightning.blockchain.fee.OnChainFeerates -import fr.acinq.lightning.channel.ChannelCommand -import kotlinx.coroutines.flow.update -import mobi.giza.compose.wallet.lightning.CoSigningWire -import fr.acinq.lightning.channel.ChannelFundingResponse -import fr.acinq.lightning.channel.GroupHeldOutputs -import fr.acinq.lightning.channel.states.ChannelStateWithCommitments -import fr.acinq.lightning.channel.states.Closed -import fr.acinq.lightning.channel.states.Closing -import fr.acinq.lightning.crypto.RemoteIcebergFundingSigner -import fr.acinq.lightning.db.Databases -import fr.acinq.lightning.db.LightningIncomingPayment -import fr.acinq.lightning.db.LightningOutgoingPayment -import fr.acinq.lightning.db.WalletPayment -import fr.acinq.lightning.io.PaymentSent -import fr.acinq.lightning.io.Peer -import fr.acinq.lightning.io.TcpSocket -import fr.acinq.lightning.io.WrappedChannelCommand -import fr.acinq.lightning.logging.LoggerFactory -import fr.acinq.lightning.payment.Bolt11Invoice -import fr.acinq.lightning.payment.LiquidityPolicy -import fr.acinq.lightning.utils.Connection -import fr.acinq.lightning.utils.msat -import fr.acinq.lightning.wire.Init -import fr.acinq.phoenix.utils.extensions.isOnion -import kotlin.time.Clock -import kotlin.time.Duration -import kotlin.time.Duration.Companion.minutes -import kotlin.time.Duration.Companion.seconds -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Job -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.combine -import kotlinx.coroutines.flow.conflate -import kotlinx.coroutines.flow.distinctUntilChanged -import kotlinx.coroutines.flow.first -import kotlinx.coroutines.flow.filterNotNull -import kotlinx.coroutines.withTimeoutOrNull -import kotlinx.coroutines.isActive -import kotlinx.coroutines.launch -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock - -/** - * The group's Lightning node, on the operator's device (`docs/group-lightning-wallet.md`, Phase 8). - * - * A second lightning-kmp node beside the identity's own, built from the wallet's seed, with the group's - * funding key, basepoints and closing address ([GroupNodeKeyManager]), and a remote Iceberg signer whose - * transport ([GroupIcebergTransport]) reaches the members through the room. It runs only while this - * device is the elected operator and has heard from the room recently ([GroupLightningOperatorManager.mayRunNode]), - * and it stops itself the moment a newer term names somebody else -- telling the room where its - * channels were as it goes (kind 30366). - * - * The node itself is behind [PeerHandle], so the life cycle can be tested without an LSP to connect to. - */ -class GroupLightningNode( - private val database: GizaDatabase, - private val localChatRoom: LocalChatRoom, - private val userPublicKey: HexKey, - val wallet: GroupLightningWalletManager.Wallet, - private val scope: CoroutineScope, - private val peerFactory: suspend (NodeConfiguration) -> PeerHandle, - private val now: () -> kotlin.time.Instant = { Clock.System.now() }, - private val handoverCheck: Duration = HANDOVER_CHECK, - private val reportEvery: Duration = REPORT_EVERY, - /** How many pool counters must hold round one before the node connects; 0 for a test with no co-signers. */ - private val minimumPool: Int = MINIMUM_POOL, - private val poolWait: Duration = POOL_WAIT, - /** How long to wait before redialling the LSP after [failures] attempts in a row that did not hold. */ - private val reconnectAfter: (failures: Int) -> Duration = ::reconnectDelay, -) { - private val logger = Logger.withTag("GroupLightningNode") - private val chain = wallet.statement.chain - - /** What a node needs to be built, gathered here so a [peerFactory] can build a real one or a fake. */ - class NodeConfiguration( - val keyManager: GroupNodeKeyManager, - val chain: Chain, - val lspNodeId: PublicKey, - val transport: GroupIcebergTransport, - /** The most the group agreed to pay the LSP for the liquidity a payment needs: its statement's policy. */ - val maxLiquidityFee: Satoshi = Satoshi(GroupLightningWalletStatementEvent.Policy.DEFAULT.maxLiquidityFeeSat), - ) - - /** What this class needs of a running node. */ - interface PeerHandle { - /** - * Dials the LSP; true once the handshake is done, false when it could not be. [attempt] counts the tries - * in a row, from 1, for the timeouts to grow with as Phoenix's do. - */ - suspend fun connect(attempt: Int = 1): Boolean - fun disconnect() - /** Suspends until the connection to the LSP is down -- at once, when it is down already -- and says why. */ - suspend fun awaitDisconnect(): String - /** Each channel's local commitment number, by channel id: what the stopped message reports. */ - fun commitmentNumbers(): Map - /** The node's channels, as a snapshot reports them. */ - fun channels(): List - /** The payments the node has made or received while running, oldest first. */ - fun payments(): List - /** A Bolt11 invoice paying the node, for [amountMsat] or any amount. */ - suspend fun createInvoice(amountMsat: Long?, description: String): String - /** Whether the node has tried to pay [paymentHash] before, in this run or an earlier one. */ - suspend fun hasPaid(paymentHash: String): Boolean - /** Pays [bolt11] [amountMsat], through the LSP, and says how it went. */ - suspend fun pay(bolt11: String, amountMsat: Long): WalletWire.PaymentView - /** Starts a mutual close of [channelId] to [scriptPubKey]. */ - suspend fun close(channelId: String, scriptPubKey: ByteVector) - /** Publishes our own commitment of [channelId]. */ - suspend fun forceClose(channelId: String) - /** The outputs closing channels pay to the group's basepoints, for the group to sweep. */ - fun heldOutputs(): List - /** The node's reusable Bolt12 offer, through the LSP: every member recomputes it from the seed. */ - fun offer(): String? - /** The LSP's liquidity rates, as its `init` sent them, or null before it has. */ - fun fundingRates(): WalletWire.FundingRates? - /** The feerate the node would splice at, in sat/vbyte, or null while it has none. */ - fun feeratePerByte(): Long? - /** - * Buys [amountSat] of inbound liquidity for [channelId] from the LSP, by splicing, if its estimate is - * at most [maxFeeSat], and says what came of it, under the authorisation [id]. - */ - suspend fun buyLiquidity(id: String, channelId: String, amountSat: Long, maxFeeSat: Long): WalletWire.LiquidityPurchase - } - - sealed class State { - data object Stopped : State() - data class Running(val term: Long) : State() - data class Refused(val reason: String) : State() - } - - private val _state = MutableStateFlow(State.Stopped) - val state: StateFlow = _state - - private var peer: PeerHandle? = null - private var transport: GroupIcebergTransport? = null - private var watching: Job? = null - private var connecting: Job? = null - private var waking: Job? = null - /** Held while the node acts on what the room asked of it, so no two callers act on one request at once. */ - private val acting = Mutex() - private var lastReported: Triple, List, List>? = null - private var lastPurchases: List = emptyList() - /** What came of each liquidity purchase this node took on, by authorisation id. */ - private val purchases = MutableStateFlow>(emptyMap()) - private var lastReportedAt: kotlin.time.Instant? = null - - /** Starts the node if this device may run it now; otherwise says why not. */ - suspend fun start(): State { - if (_state.value is State.Running) return _state.value - val roomId = localChatRoom.chatRoom.id - val operator = GroupLightningOperatorManager.current(database, roomId, chain, wallet.statement.wallet) - val lastHeard = database.marmotGroupEventDao().newestSavedAt(roomId) - if (!GroupLightningOperatorManager.mayRunNode(database, roomId, chain, userPublicKey, lastHeard, now(), wallet.statement.wallet)) { - return State.Refused( - if (operator?.publicKey != userPublicKey) "this device is not the operator" else "this device has not heard from the room recently enough to be sure it still is" - ).also { _state.value = it } - } - val seed = wallet.seed ?: return State.Refused("this device does not hold the wallet's seed").also { _state.value = it } - val term = operator!!.term - - val transport = GroupIcebergTransport.create(database, localChatRoom, userPublicKey, wallet, term, scope).also { it.start() } - transport.provision(GroupLightningCoSigner.POOL_WINDOW) - // Round one is served synchronously from the pool, so the pool has to be there before the LSP can - // ask for anything: a channel that needs a label the pool lacks is aborted. - if (!transport.awaitPool(minimumPool, poolWait)) { - transport.stop() - return State.Refused("the group has not sent enough round one to sign with yet").also { _state.value = it } - } - val onchain = GroupWalletManager.walletFor(database, roomId, chain, wallet.statement.onchainAccount) - ?: return State.Refused("the onchain wallet it closes to is not open").also { _state.value = it } - val keyManager = GroupNodeKeyManager( - delegate = GroupLightningCoSigner.keyManagerOf(ByteVector(seed.seed), chain), - fundingSigner = RemoteIcebergFundingSigner(PublicKey.fromHex(wallet.statement.icebergKey), transport, SIGNING_DEADLINE), - basepoints = wallet.basepoints.forChannel, - finalScriptPubKey = GroupWalletDerivation.derive(onchain.account, GroupWalletDerivation.RECEIVE, 0).pubkeyScript, - ) - check(keyManager.nodeKeys.nodeKey.publicKey.toString() == wallet.statement.nodeId) { "the seed does not produce the statement's node" } - - val handle = peerFactory(NodeConfiguration(keyManager, chain, PublicKey.fromHex(wallet.statement.lspNodeId), transport, Satoshi(wallet.statement.policy.maxLiquidityFeeSat))) - this.transport = transport - peer = handle - _state.value = State.Running(term) - stayConnected(handle, runCatching { handle.connect(attempt = 1) }) - lastReported = null - report(term, force = true) - watchForHandover(term) - wakeOnRequests() - logger.i("The group's node ${wallet.statement.nodeId.take(16)} is running, term $term") - return _state.value - } - - /** Stops the node and tells the room where its channels were. Safe to call when it is not running. */ - suspend fun stop() { - watching?.cancel() - halt() - } - - /** [stop], minus cancelling the handover watch: the watch calls this itself, and must finish saying so. */ - private suspend fun halt() { - val running = _state.value as? State.Running ?: return - val numbers = peer?.commitmentNumbers().orEmpty() - // First, or the disconnect below would read as a drop and be redialled. - connecting?.cancel() - connecting = null - waking?.cancel() - waking = null - peer?.disconnect() - transport?.stop() - peer = null - transport = null - _state.value = State.Stopped - GroupLightningOperatorManager.announceStopped(database, localChatRoom, userPublicKey, chain, wallet.statement.wallet, running.term, numbers) - logger.i("The group's node stopped at the end of term ${running.term}") - } - - private val walletKey get() = GroupLightningCoSigner.walletKey(localChatRoom.chatRoom.id, chain, wallet.statement.wallet) - - /** Sends the room a snapshot when the channels or payments have changed, or when the last is [reportEvery] old. */ - internal suspend fun report(term: Long, force: Boolean = false) { - val handle = peer ?: return - val now = now() - val current = Triple(handle.channels(), handle.payments(), handle.heldOutputs()) - val bought = purchasesFor(current.first) - val due = force || current != lastReported || bought != lastPurchases || lastReportedAt.let { it == null || now - it >= reportEvery } - if (!due) return - val snapshot = WalletWire.Snapshot( - wallet = walletKey, term = term, nodeId = wallet.statement.nodeId, sentAt = now.epochSeconds, - channels = current.first, payments = current.second.takeLast(REPORTED_PAYMENTS), - assignments = transport?.assignments().orEmpty(), - heldOutputs = current.third, - offer = handle.offer(), - fundingRates = handle.fundingRates(), - feeratePerByte = handle.feeratePerByte(), - purchases = bought, - ) - GroupLightningReports.publishSnapshot(database, localChatRoom, userPublicKey, snapshot) - lastReported = current - lastPurchases = bought - lastReportedAt = now - } - - /** Makes an invoice for every request in the room that has none yet. */ - internal suspend fun answerInvoiceRequests() = acting.withLock { - val handle = peer ?: return@withLock - GroupLightningReports.unanswered(database, localChatRoom.chatRoom.id, walletKey).forEach { request -> - val bolt11 = handle.createInvoice(request.amountMsat, request.description) - GroupLightningReports.answer(database, localChatRoom, userPublicKey, request, bolt11) - } - } - - private val paying = mutableSetOf() - - /** - * Pays every payment the group has authorised and this node has not tried yet, each once. A payment - * that fails is not tried again: the group signs a new authorisation for another attempt, and the - * co-signers' budgets are what stop either from paying twice. - */ - internal suspend fun payAuthorised() = acting.withLock { - val handle = peer ?: return@withLock - GroupLightningAuthorisations.toPay(database, wallet, now()).forEach { pay -> - if (pay.paymentHash in paying || handle.hasPaid(pay.paymentHash)) return@forEach - paying += pay.paymentHash - scope.launch { - runCatching { handle.pay(pay.invoice, pay.amountMsat) } - .onSuccess { logger.i("Paid ${pay.paymentHash.take(16)}: ${if (it.succeeded) "sent" else "not sent"}") } - .onFailure { logger.e("Paying ${pay.paymentHash.take(16)} failed", it) } - } - } - } - - /** Every purchase this node took on, a pending one read as locked once its channel is on that output alone. */ - private fun purchasesFor(channels: List): List = purchases.value.values.map { p -> - val channel = channels.firstOrNull { it.channelId == p.channelId } - if (p.state == WalletWire.PENDING && channel != null && channel.fundingTxId == p.fundingTxId && channel.liveFundingOutputs == 1) p.copy(state = WalletWire.LOCKED) else p - }.sortedBy { it.id } - - /** - * Buys the inbound liquidity the group has authorised, once per authorisation - * (`docs/group-lightning-liquidity.md`, Phase 6). Not while the channel has a splice that has not - * locked: eclair refuses another until it does, so the purchase waits, and is tried at the next check - * after. A purchase that fails is not tried again by itself; the group signs a new one for another - * attempt, and every co-signer holds the fee to the cap whichever it is. - */ - internal suspend fun buyAuthorised() = acting.withLock { - val handle = peer ?: return@withLock - val channels = handle.channels().associateBy { it.channelId } - GroupLightningAuthorisations.liquidityPurchases(database, wallet, now()).forEach { buy -> - if (purchases.value[buy.id]?.state.let { it != null && it != WalletWire.WAITING }) return@forEach - val channel = channels[buy.channelId] ?: return@forEach - if (channel.liveFundingOutputs > 1) { - purchases.update { it + (buy.id to WalletWire.LiquidityPurchase(buy.id, buy.channelId, buy.amountSat, WalletWire.WAITING, fundingTxId = channel.fundingTxId)) } - return@forEach - } - purchases.update { it + (buy.id to WalletWire.LiquidityPurchase(buy.id, buy.channelId, buy.amountSat, WalletWire.PENDING)) } - scope.launch { - val outcome = runCatching { handle.buyLiquidity(buy.id, buy.channelId, buy.amountSat, buy.maxFeeSat) } - .getOrElse { WalletWire.LiquidityPurchase(buy.id, buy.channelId, buy.amountSat, WalletWire.FAILED, reason = it.message ?: it::class.simpleName) } - purchases.update { it + (buy.id to outcome) } - logger.i("Liquidity purchase ${buy.id}: ${outcome.state}${outcome.reason?.let { r -> ", $r" }.orEmpty()}") - } - } - } - - private val closing = mutableSetOf() - - /** - * Closes every channel the group has authorised closing, once per authorisation this run: mutually to - * the onchain wallet's first address, which is where the channel's own closing script already - * points, or by force. - */ - internal suspend fun closeAuthorised() = acting.withLock { - val handle = peer ?: return@withLock - val open = handle.channels().map { it.channelId }.toSet() - val actions = GroupLightningAuthorisations.channelActions(database, localChatRoom.chatRoom.id, wallet.statement, now()) - if (actions.isEmpty()) return@withLock - val onchain = GroupWalletManager.walletFor(database, localChatRoom.chatRoom.id, chain, wallet.statement.onchainAccount) ?: return@withLock - val closeTo = GroupWalletDerivation.derive(onchain.account, GroupWalletDerivation.RECEIVE, 0).pubkeyScript - actions.filter { it.channelId in open }.forEach { action -> - if (!closing.add("${action.action}:${action.channelId}")) return@forEach - when (action.action) { - GroupLightningAuthorisationEvent.FORCE_CLOSE -> handle.forceClose(action.channelId) - else -> handle.close(action.channelId, closeTo) - } - logger.i("${action.action} of ${action.channelId.take(16)}, as the group authorised") - } - } - - /** - * Redials the LSP each time the connection ends, logging why it ended, until the node stops. lightning-kmp - * does not reconnect by itself, and the identity's own node has Phoenix's connection daemon to do it; this - * one had nothing, so a single drop left it offline for the rest of the term. - * - * A connection that ends inside [STABLE_CONNECTION] counts against the backoff like one that never came - * up: an LSP that completes the handshake and hangs up on reading our features would otherwise be redialled - * every few seconds for as long as the term lasts. - */ - private fun stayConnected(handle: PeerHandle, first: Result) { - connecting?.cancel() - connecting = scope.launch { - var attempt = first - var since = now() - var failures = 0 - while (isActive) { - val reason = attempt.fold({ handle.awaitDisconnect() }, { it.message ?: it::class.simpleName.orEmpty() }) - val connected = attempt.getOrDefault(false) - val lasted = now() - since - failures = if (connected && lasted >= STABLE_CONNECTION) 1 else failures + 1 - val wait = reconnectAfter(failures) - logger.w( - if (connected) "The group's node lost the LSP after $lasted: $reason. Reconnecting in $wait" - else "The group's node could not reach the LSP: $reason. Trying again in $wait" - ) - delay(wait) - since = now() - attempt = runCatching { handle.connect(attempt = failures + 1) } - } - } - } - - /** Stops the node as soon as the room's newest operator statement names a later term. */ - private fun watchForHandover(term: Long) { - watching?.cancel() - watching = scope.launch { - while (isActive) { - delay(handoverCheck) - val current = GroupLightningOperatorManager.current(database, localChatRoom.chatRoom.id, chain, wallet.statement.wallet) - if (current == null || current.term != term || current.publicKey != userPublicKey) { - logger.i("Term $term is over; stopping the group's node") - halt() - return@launch - } - runCatching { report(term) }.onFailure { logger.e("Could not report the wallet to the room", it) } - act() - } - } - } - - /** - * Answers invoice requests, and makes the payments and channel actions the group has authorised. Each - * takes [acting] itself, so the poll, a wakeup and a direct call never pay or answer the same thing twice. - */ - private suspend fun act() { - runCatching { answerInvoiceRequests() }.onFailure { logger.e("Could not answer an invoice request", it) } - runCatching { payAuthorised() }.onFailure { logger.e("Could not make an authorised payment", it) } - runCatching { closeAuthorised() }.onFailure { logger.e("Could not close an authorised channel", it) } - if (GroupLightningRollout.LIQUIDITY_ENABLED) runCatching { buyAuthorised() }.onFailure { logger.e("Could not buy authorised liquidity", it) } - } - - /** - * Acts the moment the room's invoice requests or authorisations change, rather than at the next - * [handoverCheck]: on the first mainnet run that poll was most of the wait for an invoice and for a - * payment to leave once the group had signed it. The poll still runs, for expiries and snapshots. - */ - private fun wakeOnRequests() { - waking?.cancel() - val roomId = localChatRoom.chatRoom.id - waking = scope.launch { - combine( - database.marmotInnerEventDao().observeCountByChatRoomAndKinds(roomId, listOf(GroupLightningEvents.INVOICE_REQUEST)), - database.groupSignedEventDao().observeCountByChatRoomIdAndKind(roomId, GroupLightningAuthorisationEvent.KIND), - ) { requests, authorisations -> requests to authorisations } - .distinctUntilChanged() - .conflate() - .collect { act() } - } - } - - companion object { - /** A lightning-kmp payment as the room hears of it. */ - internal fun paymentView(payment: WalletPayment, incoming: Boolean) = WalletWire.PaymentView( - id = payment.id.toString(), - incoming = incoming, - amountMsat = payment.amount.msat, - feesMsat = payment.fees.msat, - paymentHash = (payment as? LightningIncomingPayment)?.paymentHash?.toHex() ?: (payment as? LightningOutgoingPayment)?.paymentHash?.toHex(), - description = ((payment as? LightningOutgoingPayment)?.details as? LightningOutgoingPayment.Details.Normal)?.paymentRequest?.description, - completedAt = payment.completedAt, - succeeded = payment.succeededAt != null, - ) - - /** How long a signature may take the group. Phase 0 was to measure what the LSP tolerates; until it is, a minute. */ - val SIGNING_DEADLINE: Duration = 60.seconds - val HANDOVER_CHECK: Duration = 10.seconds - /** Pool counters with round one in hand before the node connects: enough to open a channel and pay. */ - const val MINIMUM_POOL = 8 - /** How long a starting node waits for them before refusing; it is tried again at the next refresh. */ - val POOL_WAIT: Duration = 30.seconds - - val FEERATES_REFRESH: Duration = 10.minutes - val FEERATES_RETRY: Duration = 30.seconds - private val REGTEST_FEERATES = FeeratePerByte(Satoshi(2)).let { Feerates(it, it, it, it, it) } - - /** How stale a snapshot may grow while nothing changes. */ - val REPORT_EVERY: Duration = 5.minutes - /** How many of the newest payments a snapshot carries; members keep every one they have seen. */ - const val REPORTED_PAYMENTS = 50 - - /** How long a connection to the LSP has to last to reset the backoff. */ - val STABLE_CONNECTION: Duration = 1.minutes - val RECONNECT_FIRST: Duration = 2.seconds - val RECONNECT_MAX: Duration = 5.minutes - /** How long a drop's reason waits for the LSP's init, which can reach the node after the socket closes. */ - val INIT_GRACE: Duration = 1.seconds - - /** [RECONNECT_FIRST], doubling with each attempt in a row that did not hold, up to [RECONNECT_MAX]. */ - fun reconnectDelay(failures: Int): Duration = - if (failures >= 20) RECONNECT_MAX else (RECONNECT_FIRST * (1 shl (failures - 1).coerceAtLeast(0))).coerceAtMost(RECONNECT_MAX) - - /** - * Why a connection to the LSP ended, from the socket's reason and the features each side sent. The - * features come first when they explain it: an LSP that does not offer a feature we require hangs up - * after the Init exchange, and the socket only says it was closed. - */ - internal fun dropReason(ours: Features, theirs: Features?, closed: Connection.CLOSED): String { - val socket = closed.reason?.message ?: "closed by this node" - if (theirs == null) return "$socket, before the LSP sent its features" - val missing = ours.activated.filter { (feature, support) -> support == FeatureSupport.Mandatory && !theirs.hasFeature(feature) }.keys.map { it.rfcName } - val unknownToUs = theirs.unknown.filter { it.bitIndex % 2 == 0 }.map { "bit ${it.bitIndex}" } - return when { - missing.isNotEmpty() -> "$socket: the LSP does not offer ${missing.joinToString()}, which this node requires" - unknownToUs.isNotEmpty() -> "$socket: the LSP requires ${unknownToUs.joinToString()}, which this node does not know" - else -> socket - } - } - - /** - * Phoenix's connect and handshake timeouts for the [attempt]th try in a row (`AppConnectionsDaemon`), - * three times as long over Tor. - */ - fun connectTimeouts(attempt: Int, torIsEnabled: Boolean): Pair = when { - attempt <= 1 -> 1.seconds to 2.seconds - attempt <= 3 -> 2.seconds to 4.seconds - attempt <= 6 -> 4.seconds to 7.seconds - attempt <= 10 -> 7.seconds to 10.seconds - else -> 10.seconds to 15.seconds - }.let { (connect, handshake) -> if (torIsEnabled) connect * 3 to handshake * 3 else connect to handshake } - - /** - * Builds real lightning-kmp nodes, set up as Phoenix sets up its own (`NodeParamsManager`, `PeerManager`, - * `AppConnectionsDaemon`): lightning-kmp's default features, zero-conf with the LSP alone, the LSP reached - * at its onion address while the identity has Tor on, on the chain's Electrum connection, persisted in - * the databases [databasesFor] opens for the node's id. - * - * Simple taproot channels stay optional, as in Phoenix: lightning-kmp asks for that channel type in every - * channel it opens, and the co-signers rebuild every funding output and commitment as taproot, so the - * group never signs for another kind. Requiring the feature in `init` gained nothing and cost the - * connection: ACINQ's LSP does not list it in its own `init`, and a peer must hang up on a required - * feature it does not offer. - */ - fun lightningKmpPeers( - clients: GroupChainClients, - databasesFor: (nodeId: PublicKey, chain: Chain) -> Databases, - walletParamsFor: (chain: Chain, torIsEnabled: Boolean) -> WalletParams, - loggerFactory: LoggerFactory, - scope: CoroutineScope, - /** Whether the identity reaches the network over Tor, read as each node starts, as Phoenix reads it as its peer is made. */ - torIsEnabled: suspend () -> Boolean = { false }, - ): suspend (NodeConfiguration) -> PeerHandle = { configuration -> - val base = NodeParams(configuration.chain, loggerFactory, configuration.keyManager) - val nodeParams = base.copy( - zeroConfPeers = setOf(configuration.lspNodeId), - // Phoenix's default policy, except that the most one payment's liquidity may cost is the group's, - // from the statement it signed, rather than one member's setting. - liquidityPolicy = MutableStateFlow( - LiquidityPolicy.Auto( - inboundLiquidityTarget = null, - maxAbsoluteFee = configuration.maxLiquidityFee, - maxRelativeFeeBasisPoints = 50_00, - skipAbsoluteFeeCheck = false, - maxAllowedFeeCredit = 0.msat, - ) - ), - ) - val tor = torIsEnabled() - val walletParams = walletParamsFor(configuration.chain, tor) - require(walletParams.trampolineNode.id == configuration.lspNodeId) { "the wallet's LSP is not the node it would connect to" } - val client = clients.clientFor(configuration.chain) - val watcher = ElectrumWatcher(client, scope, loggerFactory) - val databases = databasesFor(nodeParams.nodeId, configuration.chain) - val peer = Peer(nodeParams, walletParams, client, watcher, databases, TcpSocket.Builder(), scope) - // The peer learns the chain's height only from header notifications, and a shared client that - // subscribed long ago sends the next one at the next block: until then the node can answer no - // invoice request and take no payment. So it is told the current height as it starts. - scope.launch { - runCatching { peer.currentTipFlow.value = client.startHeaderSubscription().blockHeight } - } - // lightning-kmp asks for feerates once, as Electrum connects, which suits a phone app that runs - // for minutes. The operator's node runs for days, and without feerates it cannot close a channel - // at all -- a force close waits for them, silently. So it asks again, often while it has none. - // Regtest has nothing to estimate from; there it takes a flat rate. - scope.launch { - while (isActive) { - val feerates = runCatching { client.getFeerates() }.getOrNull() - ?: REGTEST_FEERATES.takeIf { configuration.chain == Chain.Regtest } - feerates?.let { peer.onChainFeeratesFlow.value = OnChainFeerates(it) } - delay(if (feerates == null) FEERATES_RETRY else FEERATES_REFRESH) - } - } - val payments = mutableListOf() - // The LSP's features as it sent them on the current connection, for saying why one ended. - val lspInit = MutableStateFlow(null) - scope.launch { - nodeParams.nodeEvents.collect { event -> - when (event) { - is PeerConnected -> lspInit.value = event.theirInit - is PaymentEvents.PaymentReceived -> payments += paymentView(event.payment, incoming = true) - is PaymentEvents.PaymentSent -> payments += paymentView(event.payment, incoming = false) - else -> {} - } - } - } - object : PeerHandle { - override suspend fun connect(attempt: Int): Boolean { - // As Phoenix refuses to: over Tor, a clearnet address would leave Tor for the one connection - // that says the most about the group's money. - check(!tor || walletParams.trampolineNode.isOnion) { "Tor is on, and the LSP has no onion address on ${configuration.chain.name}" } - lspInit.value = null - val (connectTimeout, handshakeTimeout) = connectTimeouts(attempt, tor) - return peer.connect(connectTimeout = connectTimeout, handshakeTimeout = handshakeTimeout) - } - override fun disconnect() = peer.disconnect() - override suspend fun awaitDisconnect(): String { - val closed = peer.connectionState.first { it is Connection.CLOSED } as Connection.CLOSED - // An LSP that hangs up on our features does so milliseconds after its own init, and the - // socket reads as closed before the peer's event for that init has reached us: wait for it. - val theirs = withTimeoutOrNull(INIT_GRACE) { lspInit.filterNotNull().first() } - return dropReason(nodeParams.features.initFeatures(), theirs?.features, closed) - } - override fun commitmentNumbers(): Map = peer.channelsFlow.value.mapNotNull { (id, state) -> - (state as? ChannelStateWithCommitments)?.let { id.toHex() to it.commitments.localCommitIndex } - }.toMap() - override fun channels(): List = peer.channelsFlow.value.mapNotNull { (id, state) -> - (state as? ChannelStateWithCommitments)?.commitments?.latest?.let { latest -> - WalletWire.ChannelView( - channelId = id.toHex(), - state = state::class.simpleName ?: "", - capacitySat = latest.fundingAmount.sat, - oursMsat = latest.localCommit.spec.toLocal.msat, - theirsMsat = latest.localCommit.spec.toRemote.msat, - fundingTxId = latest.fundingTxId.toString(), - fundingIndex = latest.fundingInput.index, - commitIndex = latest.localCommit.index, - liveFundingOutputs = state.commitments.active.size, - ) - } - }.sortedBy { it.channelId } - override fun payments(): List = payments.toList() - override suspend fun createInvoice(amountMsat: Long?, description: String): String = - peer.createInvoice(Lightning.randomBytes32(), amountMsat?.let(::MilliSatoshi), Either.Left(description)).write() - override suspend fun hasPaid(paymentHash: String): Boolean = - databases.payments.listLightningOutgoingPayments(ByteVector32(paymentHash)).isNotEmpty() - override suspend fun close(channelId: String, scriptPubKey: ByteVector) { - peer.mutualClose(ByteVector32(channelId), scriptPubKey, peer.onChainFeeratesFlow.value?.mutualCloseFeerate ?: FeeratePerKw(FeeratePerByte(Satoshi(2)))) - } - override fun heldOutputs(): List = peer.channelsFlow.value.values.mapNotNull { state -> - when (state) { - is Closing -> state - is Closed -> state.state - else -> null - } - }.flatMap { closing -> - val latest = closing.commitments.latest - val keys = configuration.keyManager.channelKeys(closing.commitments.channelParams.localParams.fundingKeyPath) - buildList { - closing.localCommitPublished?.let { published -> - GroupHeldOutputs.inLocalCommit(keys, latest, published.commitTx)?.let(::add) - // Our HTLC transactions, once they spend our commitment: their delayed outputs are the group's too. - published.irrevocablySpent.values.filter { tx -> tx.txIn.any { it.outPoint.txid == published.commitTx.txid } } - .forEach { htlcTx -> GroupHeldOutputs.inHtlcTx(keys, latest, htlcTx)?.let(::add) } - } - closing.remoteCommitPublished?.let { GroupHeldOutputs.inRemoteCommit(keys, latest, latest.remoteCommit.remotePerCommitmentPoint, it.commitTx)?.let(::add) } - closing.nextRemoteCommitPublished?.let { published -> - latest.nextRemoteCommit?.let { next -> GroupHeldOutputs.inRemoteCommit(keys, latest, next.remotePerCommitmentPoint, published.commitTx)?.let(::add) } - } - } - }.map(GroupSweep::inputOf).distinctBy { it.txid to it.index } - override fun offer(): String = nodeParams.defaultOffer(walletParams.trampolineNode.id).offer.encode() - override fun fundingRates(): WalletWire.FundingRates? = peer.remoteFundingRates.value?.let { rates -> - WalletWire.FundingRates( - rates.fundingRates.map { WalletWire.FundingRate(it.minAmount.sat, it.maxAmount.sat, it.fundingWeight, it.feeProportional, it.feeBase.sat, it.channelCreationFee.sat) }, - rates.paymentTypes.map(CoSigningWire::paymentTypeName), - ) - } - override fun feeratePerByte(): Long? = peer.onChainFeeratesFlow.value?.fundingFeerate?.let { FeeratePerByte(it).feerate.sat } - override suspend fun buyLiquidity(id: String, channelId: String, amountSat: Long, maxFeeSat: Long): WalletWire.LiquidityPurchase { - fun failed(reason: String) = WalletWire.LiquidityPurchase(id, channelId, amountSat, WalletWire.FAILED, reason = reason) - val amount = Satoshi(amountSat) - val rate = peer.remoteFundingRates.value?.findRate(amount) ?: return failed("the LSP sells no liquidity in that amount") - val feerate = peer.onChainFeeratesFlow.value?.fundingFeerate ?: return failed("the node has no feerate yet") - // As Phoenix does: estimate, then buy at the feerate the estimate raised to, not the target. - val (actual, fees) = peer.estimateFeeForInboundLiquidity(amount, feerate, rate) ?: return failed("the channel is not ready") - if (fees.total.sat > maxFeeSat) return failed("it would cost ${fees.total.sat} sats, over the $maxFeeSat the group agreed to") - return when (val response = peer.requestInboundLiquidity(amount, actual, rate)) { - null -> failed("the channel is not ready") - is ChannelFundingResponse.Success -> WalletWire.LiquidityPurchase(id, channelId, amountSat, WalletWire.PENDING, response.fundingTxId.toString(), fees.total.sat).also { - payments += WalletWire.PaymentView( - id = "liquidity:${response.fundingTxId}", incoming = false, amountMsat = fees.total.sat * 1000, feesMsat = fees.total.sat * 1000, - completedAt = Clock.System.now().toEpochMilliseconds(), succeeded = true, kind = WalletWire.LIQUIDITY, liquiditySat = amountSat, - ) - } - is ChannelFundingResponse.Failure -> failed(response::class.simpleName ?: "the splice failed") - } - } - override suspend fun forceClose(channelId: String) { - peer.send(WrappedChannelCommand(ByteVector32(channelId), ChannelCommand.Close.ForceClose)) - } - override suspend fun pay(bolt11: String, amountMsat: Long): WalletWire.PaymentView { - val invoice = Bolt11Invoice.read(bolt11).get() - return when (val result = peer.payInvoice(MilliSatoshi(amountMsat), invoice)) { - // A payment that went is reported through the node's events, like every other. - is PaymentSent -> paymentView(result.payment, incoming = false) - else -> WalletWire.PaymentView( - id = result.request.paymentId.toString(), incoming = false, amountMsat = amountMsat, feesMsat = 0, - paymentHash = invoice.paymentHash.toHex(), description = invoice.description, - completedAt = Clock.System.now().toEpochMilliseconds(), succeeded = false, - ).also { payments += it } - } - } - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningOperatorManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningOperatorManager.kt deleted file mode 100644 index 05de7c32..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningOperatorManager.kt +++ /dev/null @@ -1,120 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import com.vitorpamplona.quartz.nip01Core.core.Event -import mobi.giza.compose.database.model.ChatMessage -import mobi.giza.compose.database.GizaDatabase -import mobi.giza.compose.database.model.FrostSigningSession -import mobi.giza.compose.database.model.GroupSignedEvent -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.network.serialization.CommonJson -import mobi.giza.compose.nostr.lightning.GroupLightningEvents -import mobi.giza.compose.nostr.lightning.GroupLightningOperatorStatementEvent -import mobi.giza.compose.nostr.lightning.GroupLightningWalletStatementEvent -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.Chain -import kotlinx.serialization.Serializable -import kotlin.time.Duration -import kotlin.time.Duration.Companion.minutes -import kotlin.time.Instant - -/** - * Who runs a group Lightning wallet's node, and how that changes hands (`docs/group-lightning-wallet.md`, - * Phase 7). - * - * An operator is elected the only way this group decides anything: a statement a quorum signs. The - * statement carries a term that only goes up, and [current] is the verified statement with the highest - * term -- two elections completing with the same term are settled by the lower event id, so every device - * picks the same one. - */ -object GroupLightningOperatorManager { - /** How fresh this device's view of the room must be before it may start the group's node. */ - val START_GATE: Duration = 5.minutes - - data class Operator(val statement: GroupLightningOperatorStatementEvent.Statement, val signedEvent: GroupSignedEvent) { - val publicKey: HexKey? get() = statement.operator - val term: Long get() = statement.term - } - - @Serializable - data class Stopped(val term: Long, val commitmentNumbers: Map) - - /** The operator of [chain]'s wallet [wallet] in [chatRoomId], or null when none has been elected. */ - suspend fun current(database: GizaDatabase, chatRoomId: String, chain: Chain, wallet: Long = 0L): Operator? = - terms(database, chatRoomId, chain, wallet).firstOrNull() - - /** The operator the group elected for [term], or null when it elected nobody for it. */ - suspend fun ofTerm(database: GizaDatabase, chatRoomId: String, chain: Chain, wallet: Long, term: Long): Operator? = - terms(database, chatRoomId, chain, wallet).firstOrNull { it.term == term } - - /** Every term's statement, newest first; of two for one term, the lower event id wins, as in [current]. */ - private suspend fun terms(database: GizaDatabase, chatRoomId: String, chain: Chain, wallet: Long): List = - database.groupSignedEventDao().getByChatRoomIdAndKind(chatRoomId, GroupLightningOperatorStatementEvent.KIND) - .filter { it.verifies() } - .mapNotNull { signed -> GroupLightningOperatorStatementEvent.read(signed.tags)?.let { Operator(it, signed) } } - .filter { it.statement.chain == chain && it.statement.wallet == wallet } - .sortedWith(compareByDescending { it.term }.thenBy { it.signedEvent.id }) - - /** - * Proposes [userPublicKey] as the operator, for the term after the current one. A member can only - * nominate themselves: the elected device has to run a node, and nobody is elected without agreeing. - */ - suspend fun nominateSelf(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain, wallet: Long = 0L): FrostSigningSession = - propose(database, localChatRoom, userPublicKey, chain, wallet, operator = userPublicKey) - - /** Proposes that nobody runs the node: the wallet stops until somebody is elected. Only the operator may. */ - suspend fun stepDown(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain, wallet: Long = 0L): FrostSigningSession { - val current = current(database, localChatRoom.chatRoom.id, chain, wallet) - require(current?.publicKey == userPublicKey) { "Only the operator can step down" } - return propose(database, localChatRoom, userPublicKey, chain, wallet, operator = null) - } - - private suspend fun propose(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain, wallet: Long, operator: HexKey?): FrostSigningSession { - requireNotNull(GroupLightningWalletManager.walletFor(database, localChatRoom.chatRoom.id, chain, wallet)) { "This group has no Lightning wallet on ${chain.name}" } - val current = current(database, localChatRoom.chatRoom.id, chain, wallet) - val template = GroupLightningOperatorStatementEvent.template( - GroupLightningOperatorStatementEvent.Statement(chain, wallet, operator, term = (current?.term ?: 0L) + 1, previous = current?.publicKey) - ) - return FrostSigningManager.proposeSigning(database, localChatRoom, userPublicKey, template.kind, template.tags, template.content) - } - - /** - * Whether this device may start the group's node: the newest operator statement it holds names - * [userPublicKey], and the room has synced within [START_GATE] of [now]. A phone that comes back after - * a week offline catches up on the room before its node can start. The co-signers are the real fence - * (they refuse anything from an older term); this gate keeps an old node from becoming the griefing - * case the plan's trust table describes. - */ - suspend fun mayRunNode(database: GizaDatabase, chatRoomId: String, chain: Chain, userPublicKey: HexKey, lastSyncedAt: Instant?, now: Instant, wallet: Long = 0L): Boolean { - if (lastSyncedAt == null || now - lastSyncedAt > START_GATE) return false - return current(database, chatRoomId, chain, wallet)?.publicKey == userPublicKey - } - - private const val STOPPED = "stopped running the group's Lightning node." - - /** Tells the room this device's node stopped, and where its channels were (kind 30366). */ - suspend fun announceStopped(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain, wallet: Long, term: Long, commitmentNumbers: Map) { - val queued = GroupLightningWalletManager.queue( - database, localChatRoom, userPublicKey, GroupLightningEvents.STOPPED, - CommonJson.encodeToString(Stopped.serializer(), Stopped(term, commitmentNumbers)), - tags = arrayOf(arrayOf("d", GroupLightningWalletStatementEvent.identifier(chain, wallet))), - ) - GroupLightningLines.write(database, localChatRoom.chatRoom.id, queued.id, ChatMessage.TYPE_LIGHTNING_OPERATOR_STOPPED, userPublicKey, STOPPED, queued.createdAt) - } - - /** - * An operator's stop, as its line: only from whoever ran that term's node. Their commitment - * numbers are read by the next operator's node from the stored event, not from here. - */ - suspend fun receiveStopped(database: GizaDatabase, localChatRoom: LocalChatRoom, innerEvent: Event) { - val identifier = innerEvent.tags.firstOrNull { it.size >= 2 && it[0] == "d" }?.get(1)?.split(':') ?: return - val chain = identifier.getOrNull(0)?.let(GroupWalletStatementEvent::chainNamed) ?: return - val wallet = identifier.getOrNull(1)?.toLongOrNull() ?: return - val stopped = runCatching { CommonJson.decodeFromString(Stopped.serializer(), innerEvent.content) }.getOrNull() ?: return - if (ofTerm(database, localChatRoom.chatRoom.id, chain, wallet, stopped.term)?.publicKey != innerEvent.pubKey) return - GroupLightningLines.write( - database, localChatRoom.chatRoom.id, innerEvent.id, ChatMessage.TYPE_LIGHTNING_OPERATOR_STOPPED, - innerEvent.pubKey, STOPPED, Instant.fromEpochSeconds(innerEvent.createdAt), - ) - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningReports.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningReports.kt deleted file mode 100644 index dd738010..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningReports.kt +++ /dev/null @@ -1,289 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.text.grouped -import fr.acinq.bitcoin.Satoshi -import mobi.giza.compose.database.model.ChatMessage -import co.touchlab.kermit.Logger -import mobi.giza.compose.database.GizaDatabase -import mobi.giza.compose.database.model.GroupLightningInvoiceRow -import mobi.giza.compose.database.model.GroupLightningPaymentRow -import mobi.giza.compose.database.model.GroupLightningSnapshotRow -import mobi.giza.compose.database.model.IcebergLabelAssignment -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.extensions.toHex -import mobi.giza.compose.network.serialization.CommonJson -import mobi.giza.compose.nostr.lightning.GroupLightningEvents -import mobi.giza.compose.wallet.lightning.WalletWire -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.utils.RandomInstance -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.PublicKey -import fr.acinq.lightning.payment.Bolt11Invoice -import fr.acinq.lightning.payment.OfferManager -import kotlin.time.Instant - -/** - * What the operator tells the room about the group's Lightning wallet, and how a member asks it for an - * invoice (`docs/group-lightning-wallet.md`, Phases 10 and 11). - * - * Everything here is the operator's claim. A member keeps it to show, checks what it can -- that the - * sender is the operator of the term it names, that an invoice pays the node the group signed for, that - * a channel's balance is what this device last co-signed -- and decides nothing with it: the co-signer - * reads its own ledgers, never a snapshot. - */ -object GroupLightningReports { - private val logger = Logger.withTag("GroupLightningReports") - - /** One channel as the snapshot reports it, beside what this device last co-signed for it. */ - data class ChannelCheck(val channel: WalletWire.ChannelView, val signedOursMsat: Long?) { - /** Whether the operator's figure is the one this device signed; null when it signed nothing for the channel. */ - val agrees: Boolean? get() = signedOursMsat?.let { it == channel.oursMsat } - } - - /** - * Whether a payment the node reports is a channel's close. lightning-kmp files a close as an - * outgoing payment, and gives it no payment hash: every Lightning payment has one. Read here - * for the wallet's payment list and the room's lines alike, so the two cannot disagree. - */ - fun isChannelClose(incoming: Boolean, paymentHash: String?): Boolean = !incoming && paymentHash == null - - /** What reached an outgoing payment's recipient: lightning-kmp reports its amount with the fee in it. */ - fun recipientMsat(amountMsat: Long, feesMsat: Long): Long = amountMsat - feesMsat - - /** Sends [snapshot] to the room, and files it here as every member would. */ - suspend fun publishSnapshot(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, snapshot: WalletWire.Snapshot) { - GroupLightningWalletManager.queue(database, localChatRoom, userPublicKey, GroupLightningEvents.SNAPSHOT, CommonJson.encodeToString(WalletWire.Snapshot.serializer(), snapshot)) - file(database, localChatRoom.chatRoom.id, userPublicKey, snapshot) - } - - /** Routes one inbound snapshot or invoice. Invoice requests are read by the running node, not here. */ - suspend fun process(database: GizaDatabase, localChatRoom: LocalChatRoom, innerEvent: Event) { - runCatching { - when (innerEvent.kind) { - GroupLightningEvents.SNAPSHOT -> receiveSnapshot(database, localChatRoom, innerEvent) - GroupLightningEvents.INVOICE -> receiveInvoice(database, localChatRoom, innerEvent) - GroupLightningEvents.INVOICE_REQUEST -> receiveInvoiceRequest(database, localChatRoom, innerEvent) - } - }.onFailure { logger.w("Could not read wallet report ${innerEvent.id}: ${it.message}") } - } - - private suspend fun receiveSnapshot(database: GizaDatabase, localChatRoom: LocalChatRoom, innerEvent: Event) { - val snapshot = CommonJson.decodeFromString(WalletWire.Snapshot.serializer(), innerEvent.content) - val wallet = GroupLightningCoSigner.walletOf(database, localChatRoom.chatRoom.id, snapshot.wallet) ?: return - if (snapshot.nodeId != wallet.statement.nodeId) return logger.w("Snapshot ${innerEvent.id} is for a node the group did not sign for") - // A snapshot from an earlier term's operator is still the truth about that term; one from - // anybody else is nobody's. - val operator = GroupLightningOperatorManager.ofTerm(database, localChatRoom.chatRoom.id, wallet.statement.chain, wallet.statement.wallet, snapshot.term) - if (operator?.publicKey != innerEvent.pubKey) return logger.w("Snapshot ${innerEvent.id} is not from the operator of term ${snapshot.term}") - // An offer is kept only if it is the one the group's node derives: the seed says which. - file(database, localChatRoom.chatRoom.id, innerEvent.pubKey, snapshot.copy(offer = snapshot.offer?.takeIf { it == offerOf(wallet) })) - // The round-one labels the operator handed out, so whoever operates next signs under them. - val dao = database.icebergCoSigningDao() - snapshot.assignments.forEach { (purpose, counter) -> - if (dao.assignmentFor(snapshot.wallet, purpose) == null) { - val label = GroupLightningCoSigner.poolLabel(wallet.statement.icebergKey, counter).toHex() - runCatching { dao.insertAssignment(IcebergLabelAssignment(snapshot.wallet, counter, label, purpose)) } - } - } - } - - /** - * The Bolt12 offer the group's node publishes, recomputed from the node seed the way lightning-kmp - * derives it ([OfferManager.deterministicOffer]); null on a device that does not hold the seed. - */ - fun offerOf(wallet: GroupLightningWalletManager.Wallet): String? { - val seed = wallet.seed ?: return null - val nodeKey = GroupLightningCoSigner.keyManagerOf(ByteVector(seed.seed), wallet.statement.chain).nodeKeys.nodeKey.privateKey - return OfferManager.deterministicOffer(wallet.statement.chain.chainHash, nodeKey, PublicKey.fromHex(wallet.statement.lspNodeId), null, null, null).offer.encode() - } - - private suspend fun file(database: GizaDatabase, chatRoomId: String, sentBy: HexKey, snapshot: WalletWire.Snapshot) { - val dao = database.groupLightningRecordsDao() - val held = dao.snapshot(snapshot.wallet) - val previous = held?.let { runCatching { CommonJson.decodeFromString(WalletWire.Snapshot.serializer(), it.content) }.getOrNull() } - val newer = held == null || snapshot.term > held.term || (snapshot.term == held.term && snapshot.sentAt >= held.sentAt.epochSeconds) - if (newer) { - dao.upsertSnapshot(GroupLightningSnapshotRow(snapshot.wallet, sentBy, snapshot.term, CommonJson.encodeToString(WalletWire.Snapshot.serializer(), snapshot), Instant.fromEpochSeconds(snapshot.sentAt))) - } - // Payments are kept whatever the snapshot's age: a list of what happened only grows. - snapshot.payments.forEach { p -> - dao.upsertPayment(GroupLightningPaymentRow(snapshot.wallet, p.id, p.incoming, p.amountMsat, p.feesMsat, p.paymentHash, p.description, p.completedAt?.let(Instant::fromEpochMilliseconds), p.succeeded, p.liquiditySat)) - } - sayWhatHappened(database, chatRoomId, sentBy, snapshot, previous.takeIf { newer }) - } - - /** lightning-kmp's channel states from the moment a close begins: what a snapshot says a closing channel is. */ - private val CLOSING_STATES = setOf("ShuttingDown", "Negotiating", "Closing", "Closed") - - /** - * The lines for what [snapshot] says happened (docs/group-lightning-transcript.md, Phase 5): a - * channel this room has not been told of, a channel that began to close, a payment that settled or - * failed. Each is written once whatever the number of snapshots that repeat it, because the line is - * keyed on the channel or the payment. [previous] is the snapshot this one replaces, when it does: - * a channel it held that this one does not is gone, and closed. - */ - private suspend fun sayWhatHappened( - database: GizaDatabase, - chatRoomId: String, - sentBy: HexKey, - snapshot: WalletWire.Snapshot, - previous: WalletWire.Snapshot?, - ) { - val sentAt = Instant.fromEpochSeconds(snapshot.sentAt) - fun sats(msat: Long) = "${Satoshi(msat / 1000).grouped()} sats" - - suspend fun closed(channel: WalletWire.ChannelView) = GroupLightningLines.writeFact( - database, chatRoomId, ChatMessage.TYPE_LIGHTNING_CHANNEL_CLOSED, channel.channelId, sentBy, - if (channel.oursMsat >= 1000) "A Lightning channel closed. Its ${sats(channel.oursMsat)} go to the onchain wallet." - else "A Lightning channel closed, with nothing of the group's in it.", - sentAt, - ) - - snapshot.channels.forEach { channel -> - if (channel.state in CLOSING_STATES) { - closed(channel) - } else { - GroupLightningLines.writeFact( - database, chatRoomId, ChatMessage.TYPE_LIGHTNING_CHANNEL_OPENED, channel.channelId, sentBy, - "The group's Lightning node opened a channel of ${Satoshi(channel.capacitySat).grouped()} sats.", - sentAt, - ) - } - } - previous?.channels - ?.filter { held -> snapshot.channels.none { it.channelId == held.channelId } } - ?.forEach { closed(it) } - - snapshot.payments.forEach { payment -> - val completedAt = payment.completedAt?.let(Instant::fromEpochMilliseconds) ?: return@forEach - // lightning-kmp files a channel's close as an outgoing payment, with no payment hash: every - // Lightning payment has one. The channel's closed line already says it, and a second line - // would read as the group having paid the money away. Found by the regtest run. - if (isChannelClose(payment.incoming, payment.paymentHash)) return@forEach - // A purchase of liquidity is said by its own line, below, as it locks or fails: it is not money sent. - if (payment.kind == WalletWire.LIQUIDITY) return@forEach - val (type, content) = when { - payment.incoming && payment.succeeded -> ChatMessage.TYPE_LIGHTNING_PAYMENT_RECEIVED to buildString { - append("The group's Lightning wallet received ${sats(payment.amountMsat)}") - payment.description?.takeIf { it.isNotBlank() }?.let { append(", for \u201c$it\u201d") } - append(".") - } - payment.incoming -> return@forEach - // An outgoing payment's amount is what left the wallet, its fee included; the line - // says what reached the recipient and the fee beside it. - payment.succeeded -> ChatMessage.TYPE_LIGHTNING_PAYMENT_SENT to buildString { - append("The group's Lightning wallet sent ${sats(recipientMsat(payment.amountMsat, payment.feesMsat))}") - if (payment.feesMsat > 0) append(", with ${Satoshi((payment.feesMsat + 999) / 1000).grouped()} sats in fees") - append(".") - } - else -> ChatMessage.TYPE_LIGHTNING_PAYMENT_FAILED to - "A Lightning payment of ${sats(recipientMsat(payment.amountMsat, payment.feesMsat))} failed. Nothing left the wallet." - } - GroupLightningLines.writeFact(database, chatRoomId, type, payment.id, sentBy, content, completedAt) - } - - // A liquidity purchase, once it has an outcome: the channel is on the splice's output, or it failed. - snapshot.purchases.forEach { purchase -> - when (purchase.state) { - WalletWire.LOCKED -> GroupLightningLines.writeFact( - database, chatRoomId, ChatMessage.TYPE_LIGHTNING_LIQUIDITY_ADDED, purchase.id, sentBy, - "The group's Lightning wallet can receive ${Satoshi(purchase.amountSat).grouped()} sats more" + - (purchase.feeSat?.let { ", for ${Satoshi(it).grouped()} sats in fees." } ?: "."), - sentAt, - ) - WalletWire.FAILED -> GroupLightningLines.writeFact( - database, chatRoomId, ChatMessage.TYPE_LIGHTNING_LIQUIDITY_FAILED, purchase.id, sentBy, - "Adding ${Satoshi(purchase.amountSat).grouped()} sats of inbound liquidity failed" + (purchase.reason?.let { ": $it." } ?: ". Nothing left the wallet."), - sentAt, - ) - } - } - } - - /** A snapshot, with each of its channels checked against this device's own ledger. */ - data class Report(val snapshot: WalletWire.Snapshot, val checks: List) - - /** The newest snapshot this device holds for [walletKey], with each channel checked against its own ledger. */ - suspend fun latest(database: GizaDatabase, walletKey: String): Report? { - val row = database.groupLightningRecordsDao().snapshot(walletKey) ?: return null - val snapshot = CommonJson.decodeFromString(WalletWire.Snapshot.serializer(), row.content) - return Report(snapshot, snapshot.channels.map { ChannelCheck(it, GroupLightningCoSigner.signedOursMsat(database, walletKey, it.channelId)) }) - } - - /** Asks the operator for an invoice; the answer arrives under the returned request id. */ - suspend fun requestInvoice( - database: GizaDatabase, - localChatRoom: LocalChatRoom, - userPublicKey: HexKey, - wallet: GroupLightningWalletManager.Wallet, - amountMsat: Long?, - description: String, - ): String { - val key = GroupLightningCoSigner.walletKey(localChatRoom.chatRoom.id, wallet.statement.chain, wallet.statement.wallet) - val requestId = RandomInstance.bytes(16).toHex() - val request = WalletWire.InvoiceRequest(key, requestId, amountMsat, description) - val queued = GroupLightningWalletManager.queue(database, localChatRoom, userPublicKey, GroupLightningEvents.INVOICE_REQUEST, CommonJson.encodeToString(WalletWire.InvoiceRequest.serializer(), request)) - GroupLightningLines.write(database, localChatRoom.chatRoom.id, queued.id, ChatMessage.TYPE_LIGHTNING_INVOICE_REQUESTED, userPublicKey, asked(request), queued.createdAt) - return requestId - } - - /** A member's invoice request, as its line: only for a wallet this room has. The operator's node answers it. */ - private suspend fun receiveInvoiceRequest(database: GizaDatabase, localChatRoom: LocalChatRoom, innerEvent: Event) { - val request = CommonJson.decodeFromString(WalletWire.InvoiceRequest.serializer(), innerEvent.content) - GroupLightningCoSigner.walletOf(database, localChatRoom.chatRoom.id, request.wallet) ?: return - GroupLightningLines.write( - database, localChatRoom.chatRoom.id, innerEvent.id, ChatMessage.TYPE_LIGHTNING_INVOICE_REQUESTED, - innerEvent.pubKey, asked(request), Instant.fromEpochSeconds(innerEvent.createdAt), - ) - } - - /** What a member asked for, to follow their name. The description is theirs and is quoted as it is. */ - private fun asked(request: WalletWire.InvoiceRequest): String = buildString { - append("asked the operator's node for an invoice") - request.amountMsat?.let { append(" of ${Satoshi(it / 1000).grouped()} sats") } - request.description.takeIf { it.isNotBlank() }?.let { append(", for \u201c$it\u201d") } - append(".") - } - - /** The node's answer to [requestId], as its line: naming whoever asked, when this device has their request. */ - private suspend fun invoiceIssued(database: GizaDatabase, chatRoomId: String, requestId: String): String { - val asker = database.marmotInnerEventDao().getByChatRoomAndKinds(chatRoomId, listOf(GroupLightningEvents.INVOICE_REQUEST)) - .firstOrNull { runCatching { CommonJson.decodeFromString(WalletWire.InvoiceRequest.serializer(), it.content) }.getOrNull()?.requestId == requestId } - ?.publicKey - return if (asker == null) "The operator's node made an invoice." else "The operator's node made @${ChatMessage.memberName(database, asker)}'s invoice." - } - - /** The invoice requests for [walletKey] in the room that no invoice answers yet, oldest first. */ - suspend fun unanswered(database: GizaDatabase, chatRoomId: String, walletKey: String): List = - database.marmotInnerEventDao().getByChatRoomAndKinds(chatRoomId, listOf(GroupLightningEvents.INVOICE_REQUEST)) - .sortedBy { it.createdAt } - .mapNotNull { runCatching { CommonJson.decodeFromString(WalletWire.InvoiceRequest.serializer(), it.content) }.getOrNull() } - .filter { it.wallet == walletKey && database.groupLightningRecordsDao().invoice(walletKey, it.requestId) == null } - - /** Sends the room the operator's invoice for [request], and files it here. */ - suspend fun answer(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, request: WalletWire.InvoiceRequest, bolt11: String) { - val reply = WalletWire.InvoiceReply(request.wallet, request.requestId, bolt11) - val queued = GroupLightningWalletManager.queue(database, localChatRoom, userPublicKey, GroupLightningEvents.INVOICE, CommonJson.encodeToString(WalletWire.InvoiceReply.serializer(), reply)) - database.groupLightningRecordsDao().upsertInvoice(GroupLightningInvoiceRow(request.wallet, request.requestId, bolt11)) - GroupLightningLines.write( - database, localChatRoom.chatRoom.id, queued.id, ChatMessage.TYPE_LIGHTNING_INVOICE_ISSUED, - userPublicKey, invoiceIssued(database, localChatRoom.chatRoom.id, request.requestId), queued.createdAt, - ) - } - - private suspend fun receiveInvoice(database: GizaDatabase, localChatRoom: LocalChatRoom, innerEvent: Event) { - val reply = CommonJson.decodeFromString(WalletWire.InvoiceReply.serializer(), innerEvent.content) - val wallet = GroupLightningCoSigner.walletOf(database, localChatRoom.chatRoom.id, reply.wallet) ?: return - val operator = GroupLightningOperatorManager.current(database, localChatRoom.chatRoom.id, wallet.statement.chain, wallet.statement.wallet) - if (operator?.publicKey != innerEvent.pubKey) return logger.w("Invoice ${innerEvent.id} is not from the operator") - // Whoever sent it, an invoice that pays some other node is not the group's. - val invoice = Bolt11Invoice.read(reply.bolt11).get() - if (invoice.nodeId.toString() != wallet.statement.nodeId) return logger.w("Invoice ${innerEvent.id} pays a node that is not the group's") - database.groupLightningRecordsDao().upsertInvoice(GroupLightningInvoiceRow(reply.wallet, reply.requestId, reply.bolt11)) - GroupLightningLines.write( - database, localChatRoom.chatRoom.id, innerEvent.id, ChatMessage.TYPE_LIGHTNING_INVOICE_ISSUED, - innerEvent.pubKey, invoiceIssued(database, localChatRoom.chatRoom.id, reply.requestId), Instant.fromEpochSeconds(innerEvent.createdAt), - ) - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningSweeps.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningSweeps.kt deleted file mode 100644 index 0f501747..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningSweeps.kt +++ /dev/null @@ -1,49 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.database.GizaDatabase -import mobi.giza.compose.database.model.FrostSigningSession -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.database.model.types.FrostSigningStage -import mobi.giza.compose.database.model.types.FrostSigningSubject -import mobi.giza.compose.network.serialization.CommonJson -import mobi.giza.compose.wallet.lightning.GroupSweep -import com.vitorpamplona.quartz.nip01Core.core.HexKey - -/** - * Which of what closed channels left the group is still to be swept, and the sweep that moves it - * (`docs/group-lightning-wallet.md`, Phase 13). The outputs come from the operator's snapshot; the - * sweep is checked by every member as [GroupSweep] says, so a snapshot that lies about an output only - * makes a sweep nobody can mine. - */ -object GroupLightningSweeps { - /** - * The feerate a sweep pays, in sats per virtual byte. A sweep is never urgent -- what it spends is - * the group's alone -- so it pays little, and the watcher keeps sending it until it confirms. - */ - const val FEERATE_SAT_PER_VBYTE: Long = 2 - - /** The held outputs [report] lists that no open or finished sweep in the room already spends. */ - suspend fun unswept(database: GizaDatabase, chatRoomId: String, report: GroupLightningReports.Report?): List { - val outputs = report?.snapshot?.heldOutputs.orEmpty() - if (outputs.isEmpty()) return outputs - val taken = database.groupTransactionDao().getByChatRoomId(chatRoomId) - .filter { row -> - val session = database.frostSigningSessionDao().getSessionById(row.frostSigningSessionId) - session?.subject == FrostSigningSubject.SWEEP && session.stage != FrostSigningStage.FAILED - } - .mapNotNull { runCatching { CommonJson.decodeFromString(GroupSweep.Sweep.serializer(), it.psbt) }.getOrNull() } - .flatMap { sweep -> sweep.inputs.map { it.txid to it.index } } - .toSet() - return outputs.filter { (it.txid to it.index) !in taken } - } - - /** Proposes sweeping [inputs] into the onchain wallet [wallet] closes to, at its first receive address. */ - suspend fun propose(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, inputs: List): FrostSigningSession { - val statement = wallet.statement - val onchain = GroupWalletManager.walletFor(database, localChatRoom.chatRoom.id, statement.chain, statement.onchainAccount) - ?: throw IllegalStateException("The onchain wallet this Lightning wallet closes to is not open") - val sweep = GroupSweep.build(statement.wallet, inputs, onchain.account, receiveIndex = 0, feeratePerVbyte = FEERATE_SAT_PER_VBYTE) - ?: throw IllegalArgumentException("There is too little to sweep to pay its fee") - return FrostSigningManager.proposeSweep(database, localChatRoom, userPublicKey, sweep, statement.chain, statement.onchainAccount) - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningWalletManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningWalletManager.kt deleted file mode 100644 index 2472d531..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupLightningWalletManager.kt +++ /dev/null @@ -1,238 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.database.model.ChatMessage -import co.touchlab.kermit.Logger -import mobi.giza.compose.database.GizaDatabase -import mobi.giza.compose.database.model.FrostSigningSession -import mobi.giza.compose.database.model.GroupLightningSeed -import mobi.giza.compose.database.model.GroupSignedEvent -import mobi.giza.compose.database.model.IcebergKeySession -import mobi.giza.compose.database.model.MarmotInnerEvent -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.database.model.types.IcebergRitualStage -import mobi.giza.compose.extensions.toHex -import mobi.giza.compose.network.serialization.CommonJson -import mobi.giza.compose.nostr.lightning.GroupLightningEvents -import mobi.giza.compose.nostr.lightning.GroupLightningWalletStatementEvent -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import mobi.giza.compose.wallet.GroupLightningRollout -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.EventHasher -import com.vitorpamplona.quartz.nip44Encryption.Nip44 -import com.vitorpamplona.quartz.utils.RandomInstance -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.DeterministicWallet -import fr.acinq.bitcoin.PublicKey -import fr.acinq.lightning.crypto.LocalKeyManager -import kotlinx.serialization.Serializable -import kotlin.time.Clock -import kotlin.time.Instant - -/** - * A group's Lightning wallet as the room has agreed it: the statement the group signed - * ([GroupLightningWalletStatementEvent]), checked against everything this device can recompute, and the - * node seed the members hold (`docs/group-lightning-wallet.md`, Phase 6). - */ -object GroupLightningWalletManager { - private val logger = Logger.withTag("GroupLightningWalletManager") - - /** - * A statement this device believes, with what it was checked against. - * - * @param ceremony this device's own record of the Iceberg ceremony, or null when this device is not - * one of its participants and reads the wallet without being able to sign for it. - * @param seed the node seed, when this device holds the one the statement names. - */ - data class Wallet( - val statement: GroupLightningWalletStatementEvent.Statement, - val signedEvent: GroupSignedEvent, - val basepoints: GroupLightningDerivation.Basepoints, - val ceremony: IcebergKeySession?, - val seed: GroupLightningSeed?, - ) - - @Serializable - private data class SeedMessage(val chain: String, val wallet: Long, val nodeId: String, val to: Map) - - /** The node id a group node running from [seed] on [chain] has: lightning-kmp's own derivation. */ - fun nodeIdOf(seed: ByteVector, chain: Chain): PublicKey = - DeterministicWallet.generate(seed).derivePrivateKey(LocalKeyManager.nodeKeyBasePath(chain)).publicKey - - /** - * Every Lightning wallet [chatRoomId] has opened on [chain] that this device believes, the newest - * statement for each wallet number, lowest number first. The last is the current one; the others are - * wallets a re-key left behind, whose channels are still to be closed (Phase 14). - */ - suspend fun wallets(database: GizaDatabase, chatRoomId: String, chain: Chain): List = - database.groupSignedEventDao().getByChatRoomIdAndKind(chatRoomId, GroupLightningWalletStatementEvent.KIND) - .sortedWith(compareByDescending { it.createdAt }.thenBy { it.id }) - .mapNotNull { verify(database, chatRoomId, it)?.takeIf { wallet -> wallet.statement.chain == chain } } - .distinctBy { it.statement.wallet } - .sortedBy { it.statement.wallet } - - /** The wallet a room uses on [chain] now: the highest-numbered one it has opened, or null. */ - suspend fun current(database: GizaDatabase, chatRoomId: String, chain: Chain): Wallet? = wallets(database, chatRoomId, chain).lastOrNull() - - /** The participants of [wallet] who are no longer in its room: each still holds a share and the seed. */ - suspend fun departed(database: GizaDatabase, wallet: Wallet): List { - val inRoom = database.participantDao().findParticipantsByChatRoomId(wallet.signedEvent.chatRoomId).filter { it.deletedAt == null }.map { it.participantPublicKey.lowercase() }.toSet() - return wallet.statement.participants.filter { it !in inRoom } - } - - /** - * A completed Iceberg key in [chatRoomId] that this device holds a share of and that no wallet the - * room opened uses yet: what a new wallet -- the first, or the one a re-key makes -- is opened under. - */ - suspend fun unusedKey(database: GizaDatabase, chatRoomId: String, chain: Chain): IcebergKeySession? { - val used = database.groupSignedEventDao().getByChatRoomIdAndKind(chatRoomId, GroupLightningWalletStatementEvent.KIND) - .mapNotNull { GroupLightningWalletStatementEvent.read(it.tags)?.ceremonyId }.toSet() - return database.icebergKeySessionDao().getSessionsForChatRoom(chatRoomId) - .firstOrNull { it.stage == IcebergRitualStage.COMPLETE && it.share != null && it.id !in used } - } - - /** The newest statement for [chain] and [wallet] in [chatRoomId] that this device believes, or null. */ - suspend fun walletFor(database: GizaDatabase, chatRoomId: String, chain: Chain, wallet: Long = 0L): Wallet? = - database.groupSignedEventDao().getByChatRoomIdAndKind(chatRoomId, GroupLightningWalletStatementEvent.KIND) - .sortedWith(compareByDescending { it.createdAt }.thenBy { it.id }) - .firstNotNullOfOrNull { signed -> - verify(database, chatRoomId, signed)?.takeIf { it.statement.chain == chain && it.statement.wallet == wallet } - } - - /** - * Whether [signed] is a Lightning wallet statement for [chatRoomId] that this device can stand behind: - * the room signed it, the onchain wallet it closes to is open, its Iceberg key is the one this - * device's ceremony made (when this device was in it), and its participants are the people who hold - * the onchain key (D1). Null otherwise, with the reason in the log. - */ - suspend fun verify(database: GizaDatabase, chatRoomId: String, signed: GroupSignedEvent): Wallet? { - if (signed.kind != GroupLightningWalletStatementEvent.KIND || !signed.verifies()) return null - val statement = GroupLightningWalletStatementEvent.read(signed.tags) ?: return null - val roomKey = GroupWalletManager.thresholdKeyFor(database, chatRoomId) ?: return null - if (GroupWalletManager.walletFor(database, chatRoomId, statement.chain, statement.onchainAccount) == null) { - logger.w("Lightning wallet ${signed.id} closes to an onchain wallet this room has not opened") - return null - } - // D1 as Phase 14 narrows it: every participant holds the onchain key. A wallet made after a member - // left names fewer of them; the one before still names everyone, and both stay believable. - FrostSigningManager.completedKey(database, chatRoomId)?.participantPublicKeySet()?.let { holders -> - if (!holders.map { it.lowercase() }.containsAll(statement.participants)) { - logger.w("Lightning wallet ${signed.id} names participants who do not hold the onchain key") - return null - } - } - val ceremony = database.icebergKeySessionDao().getSessionById(statement.ceremonyId) - val user = ceremony?.userPublicKey ?: database.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom?.userPublicKey - if (ceremony == null && user != null && user.lowercase() in statement.participants) { - logger.w("Lightning wallet ${signed.id} names a ceremony this participant has no record of") - return null - } - if (ceremony != null) { - val agrees = ceremony.stage == IcebergRitualStage.COMPLETE && - ceremony.groupPublicKey == statement.icebergKey && - ceremony.threshold == statement.threshold && - ceremony.participants() == statement.participants - if (!agrees) { - logger.w("Lightning wallet ${signed.id} disagrees with this device's ceremony ${ceremony.id}") - return null - } - } - val seed = database.groupLightningSeedDao().get(chatRoomId, statement.nodeId) - return Wallet(statement, signed, GroupLightningDerivation.basepoints(roomKey, statement.chain, statement.wallet), ceremony, seed) - } - - /** - * Proposes the wallet: makes its node seed, sends it to every other participant encrypted to them - * (kind 30357), and opens a signing session over the statement. The wallet exists once a quorum signs. - */ - suspend fun proposeWallet( - database: GizaDatabase, - localChatRoom: LocalChatRoom, - userPublicKey: HexKey, - nostrPrivateKey: ByteArray, - chain: Chain, - lspNodeId: HexKey, - wallet: Long? = null, - onchainAccount: Long = 0L, - policy: GroupLightningWalletStatementEvent.Policy = GroupLightningWalletStatementEvent.Policy.DEFAULT, - ): FrostSigningSession { - require(GroupLightningRollout.allows(chain)) { "A Lightning wallet cannot be opened on ${chain.name}" } - val roomId = localChatRoom.chatRoom.id - val ceremony = unusedKey(database, roomId, chain) - ?: throw IllegalStateException("This group has no Lightning wallet key that no wallet uses yet") - // The next number: a re-key opens a new wallet beside the old one, whose channels still need closing. - val wallet = wallet ?: ((wallets(database, roomId, chain).maxOfOrNull { it.statement.wallet } ?: -1L) + 1) - requireNotNull(GroupWalletManager.walletFor(database, roomId, chain, onchainAccount)) { - "Open a group onchain wallet on ${chain.name} first: it is where the Lightning wallet closes to" - } - - val seed = ByteVector(RandomInstance.bytes(32)) - val nodeId = nodeIdOf(seed, chain).value.toHex() - val chainName = GroupWalletStatementEvent.chainName(chain) - database.groupLightningSeedDao().insertIfAbsent(GroupLightningSeed(roomId, nodeId, chainName, wallet, seed.toHex(), userPublicKey)) - val to = ceremony.participants().filter { it != userPublicKey.lowercase() }.associateWith { recipient -> - Nip44.encrypt(seed.toHex(), nostrPrivateKey, recipient.hexToByteArray()).encodePayload() - } - val seedMessage = queue(database, localChatRoom, userPublicKey, GroupLightningEvents.NODE_SEED, CommonJson.encodeToString(SeedMessage.serializer(), SeedMessage(chainName, wallet, nodeId, to))) - GroupLightningLines.write(database, roomId, seedMessage.id, ChatMessage.TYPE_LIGHTNING_SEED_SHARED, userPublicKey, SEED_SHARED, seedMessage.createdAt) - - val statement = GroupLightningWalletStatementEvent.Statement( - chain = chain, - wallet = wallet, - onchainAccount = onchainAccount, - icebergKey = ceremony.groupPublicKey!!, - ceremonyId = ceremony.id, - threshold = ceremony.threshold, - participants = ceremony.participants(), - nodeId = nodeId, - lspNodeId = lspNodeId, - policy = policy, - ) - val template = GroupLightningWalletStatementEvent.template(statement) - return FrostSigningManager.proposeSigning(database, localChatRoom, userPublicKey, template.kind, template.tags, template.content) - } - - /** - * Files the seed a member sent this device, after checking it produces the node id the member - * claimed. The claim is all the sender gets to say: the node id is recomputed here, and a statement - * names a node, not a seed. - */ - suspend fun receiveSeed(database: GizaDatabase, localChatRoom: LocalChatRoom, innerEvent: Event, userPublicKey: HexKey, nostrPrivateKey: ByteArray) { - val message = runCatching { CommonJson.decodeFromString(SeedMessage.serializer(), innerEvent.content) }.getOrNull() ?: return - val chain = GroupWalletStatementEvent.chainNamed(message.chain) ?: return - suspend fun line() = GroupLightningLines.write( - database, localChatRoom.chatRoom.id, innerEvent.id, ChatMessage.TYPE_LIGHTNING_SEED_SHARED, - innerEvent.pubKey, SEED_SHARED, Instant.fromEpochSeconds(innerEvent.createdAt), - ) - // A member it was not sent to cannot check it, and is told it happened all the same: - // that the node has a seed, and who made it, is the group's business. A member it was - // sent to is told only once the seed proves to be the node's. - val ciphertext = message.to[userPublicKey.lowercase()] ?: return line() - val seedHex = runCatching { Nip44.decrypt(ciphertext, nostrPrivateKey, innerEvent.pubKey.hexToByteArray()) }.getOrNull() ?: return - val seed = runCatching { ByteVector(seedHex) }.getOrNull()?.takeIf { it.size() == 32 } ?: return - val nodeId = nodeIdOf(seed, chain).value.toHex() - if (nodeId != message.nodeId) { - logger.w("A node seed from ${innerEvent.pubKey.take(8)} does not produce the node it claims; dropping") - return - } - database.groupLightningSeedDao().insertIfAbsent(GroupLightningSeed(localChatRoom.chatRoom.id, nodeId, message.chain, message.wallet, seed.toHex(), innerEvent.pubKey)) - line() - } - - /** - * Queues one of this device's messages as a Marmot inner event for the room, as the ritual managers do, - * and returns the row: a message worth a line gets it from here, since this device never reads its own back. - */ - internal suspend fun queue(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, kind: Int, content: String, tags: Array> = emptyArray()): MarmotInnerEvent { - val createdAt = Clock.System.now().epochSeconds - val id = EventHasher.hashId(pubKey = userPublicKey, createdAt = createdAt, kind = kind, tags = tags, content = content) - val queued = MarmotInnerEvent(id = id, publicKey = userPublicKey, kind = kind, createdAt = Instant.fromEpochSeconds(createdAt), tags = tags, content = content, chatRoomId = localChatRoom.chatRoom.id) - database.marmotInnerEventDao().upsert(queued) - return queued - } - - private const val SEED_SHARED = "gave each key holder the Lightning node's seed, encrypted to each of them." - -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/IcebergDkg.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/IcebergDkg.kt deleted file mode 100644 index 06f3668b..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/IcebergDkg.kt +++ /dev/null @@ -1,330 +0,0 @@ -package mobi.giza.compose.managers - -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Crypto -import fr.acinq.bitcoin.PublicKey -import fr.acinq.bitcoin.crypto.Pack -import fr.acinq.bitcoin.crypto.iceberg.Iceberg -import fr.acinq.bitcoin.crypto.iceberg.PublicShare -import fr.acinq.bitcoin.crypto.iceberg.Share -import fr.acinq.bitcoin.utils.Either - -/** - * A distributed key generation for Iceberg, which ships only a trusted dealer. - * - * An Iceberg share is replicated secret sharing, not a Shamir point: every - * `(t-1)`-subset `T` of the participants has its own 32-byte seed, held by every - * participant *outside* `T`, and a participant's share is the seeds of the - * subsets it is outside of, in the lexicographic rank order `rss.h` fixes. So a - * DKG only has to agree each seed among its holders without any member of `T` - * learning it: - * - * ``` - * round 1 each holder j of each T: c[j,T] = random, publish h[j,T] = H(commit, sid, T, j, c[j,T]) - * round 2 send c[j,T] to every other holder of T, encrypted to them - * round 3 each k checks every c[j,T] it was sent against h[j,T], then - * s[T] = H(seed, sid, T, c[j,T] for each holder j, ascending) - * share = 1 | n | t | k | s[T] for each T not containing k, in rank order - * and publishes its public share and a signature over the transcript - * done Iceberg.groupPublicKey over all n public shares - * ``` - * - * Why it is safe, in the three sentences it takes: - * - * - **Every seed is random.** `T` has `n - t + 1 >= t` holders and at most - * `t - 1` members are corrupt, so some holder's contribution is honest. - * - **Every seed is secret from `T`.** Its contributions only go to its holders, - * so a coalition of `t - 1` lacks exactly the seed named after itself, which - * is the scheme's whole margin (`rss.h`). - * - **Nobody chooses last.** Contributions are committed before any is revealed, - * so a contributor cannot grind the group key. - * - * A contributor who reveals something other than what it committed to is named - * ([Fault.BadReveal]). One who commits to two different values in front of two - * different members is not caught here; the transcript signature is what catches - * that, because the two members then publish different transcript hashes. - * - * ### Repair, which RSS gives away - * - * Every seed a participant holds is also held by `n - t` others. A participant - * that has lost its share can be sent its seeds again ([repairSeeds]); the share - * it rebuilds ([repair]) must reproduce the public share it published, which is - * the check on what it was sent. That replaces ChillDKG's recovery data. - * - * ### What this is not - * - * Reviewed. `iceberg.md` says the scheme must not protect anything of value, and - * this protocol is newer than the scheme. It lives in the app rather than in the - * bitcoin-kmp fork beside [Iceberg] only because it needs nothing from inside - * the library; see the build table in `docs/group-lightning-wallet.md`. - * - * Every function here is pure over inputs the ritual has stored, as - * [fr.acinq.bitcoin.crypto.dkg.chill.ChillDKG]'s are, so a ceremony resumes from - * its persisted messages after the app is killed. - */ -object IcebergDkg { - /** `SECP256K1_ICEBERG_MAX_PARTICIPANTS`, which sizes the library's ABI. */ - const val MAX_PARTICIPANTS = 10 - - // Inputs to every hash of the ceremony. `bennu/` is not a brand string: a Bennu - // member and a Giza member run one ceremony together, so the tags stayed when the app - // was forked (docs/giza-rebrand.md). - private const val TAG_SESSION = "bennu/iceberg-dkg/session/v1" - private const val TAG_CONTRIBUTION = "bennu/iceberg-dkg/contribution/v1" - private const val TAG_COMMIT = "bennu/iceberg-dkg/commit/v1" - private const val TAG_SEED = "bennu/iceberg-dkg/seed/v1" - private const val TAG_TRANSCRIPT = "bennu/iceberg-dkg/transcript/v1" - - /** The share format version `secp256k1_iceberg_share_parse` accepts. */ - private const val SHARE_VERSION: Byte = 1 - - /** - * Whether a group of [n] with threshold [t] can be *expressed* by Iceberg: - * a round-one quorum of `2t-1` has to exist. - */ - fun isExpressible(n: Int, t: Int): Boolean = n in 1..MAX_PARTICIPANTS && t >= 1 && t <= (n + 1) / 2 - - /** - * Whether it can be *deployed*: expressible, a real threshold, and big - * enough for the group to agree what it signs while `t - 1` members - * misbehave, `n >= 3t - 2` (`secp256k1_iceberg.h`, constraint 3). 2-of-4 is - * the smallest group this admits, and 4-of-10 the largest threshold. - */ - fun isDeployable(n: Int, t: Int): Boolean = isExpressible(n, t) && t >= 2 && n >= 3 * t - 2 - - /** Every threshold a group of [n] could deploy, smallest first. */ - fun deployableThresholds(n: Int): List = (2..n).filter { isDeployable(n, it) } - - /** - * A ceremony's parameters, the same on every device. - * - * [hostKeys] are sorted bytewise and participant `k` is `hostKeys[k - 1]`, - * for the reason the ChillDKG ritual sorts its own: an order every device - * reaches without being told. [sessionId] binds all of it, so a device - * that ordered the participants differently computes another session and - * gets no key rather than a weaker one. - */ - class Params private constructor( - val n: Int, - val t: Int, - val hostKeys: List, - val sessionId: ByteVector32, - ) { - /** The `(t-1)`-subsets, as bitmasks over participants 1..n, in rank order. */ - val subsets: List = subsetsInRankOrder(n, t - 1) - - fun holders(subset: Int): List = (1..n).filter { subset and (1 shl it) == 0 } - - fun isHolder(participant: Int, subset: Int): Boolean = subset and (1 shl participant) == 0 - - /** The ranks whose seeds [participant] holds, ascending: its share's layout. */ - fun heldRanks(participant: Int): List = subsets.indices.filter { isHolder(participant, subsets[it]) } - - fun indexOf(hostKey: PublicKey): Int? = hostKeys.indexOf(hostKey).takeIf { it >= 0 }?.plus(1) - - companion object { - /** - * @param ceremonyId the proposal's own id, so two ceremonies over the - * same people and threshold are two sessions. - */ - fun of(t: Int, hostKeys: Collection, ceremonyId: ByteVector32): Params { - val sorted = hostKeys.distinct().sortedWith { a, b -> compareBytes(a.value.toByteArray(), b.value.toByteArray()) } - require(sorted.size == hostKeys.size) { "a participant appears twice" } - require(isDeployable(sorted.size, t)) { "$t-of-${sorted.size} is not a deployable Iceberg group" } - val sid = Crypto.taggedHash( - byteArrayOf(sorted.size.toByte(), t.toByte()) + sorted.flatMap { it.value.toByteArray().asList() } + ceremonyId.toByteArray(), - TAG_SESSION, - ) - return Params(sorted.size, t, sorted, sid) - } - } - } - - /** What went wrong, as a value: a faulty participant is an outcome of a DKG, not a bug in it. */ - sealed class Fault(val participant: Int?, message: String) : Exception(message) { - class MissingCommitment(participant: Int) : Fault(participant, "participant $participant sent no commitment") - class MissingReveal(participant: Int) : Fault(participant, "participant $participant revealed nothing to us") - class BadReveal(participant: Int) : Fault(participant, "participant $participant revealed a value it had not committed to") - class MalformedMessage(participant: Int, reason: String) : Fault(participant, "participant $participant sent a malformed message: $reason") - class InconsistentShares(reason: String) : Fault(null, "the public shares do not lie on one polynomial: $reason") - class RepairMismatch(reason: String) : Fault(null, "the repaired share does not reproduce the published public share: $reason") - } - - /** One participant's round-1 message: a commitment per subset it holds, by rank. */ - data class Commitments(val participant: Int, val byRank: Map) - - /** - * [participant]'s contribution to the seed at [rank], derived from the - * 32 random bytes it stored when it joined. Storing the root rather than the - * contributions is what lets a ritual stay a function of its stored inputs. - * The root is as secret as the share it becomes; drop it once the share is - * assembled. - */ - fun contribution(params: Params, participant: Int, root: ByteVector32, rank: Int): ByteVector32 { - require(params.isHolder(participant, params.subsets[rank])) { "participant $participant does not hold the seed at rank $rank" } - return Crypto.taggedHash(root.toByteArray() + params.sessionId.toByteArray() + Pack.writeInt32BE(rank) + byteArrayOf(participant.toByte()), TAG_CONTRIBUTION) - } - - fun commitment(params: Params, participant: Int, rank: Int, contribution: ByteVector32): ByteVector32 = - Crypto.taggedHash(params.sessionId.toByteArray() + Pack.writeInt32BE(rank) + byteArrayOf(participant.toByte()) + contribution.toByteArray(), TAG_COMMIT) - - /** Round 1: commit to every contribution, to be published to everyone. */ - fun round1(params: Params, participant: Int, root: ByteVector32): Commitments = - Commitments(participant, params.heldRanks(participant).associateWith { commitment(params, participant, it, contribution(params, participant, root, it)) }) - - /** - * Round 2: what [participant] reveals to [recipient], by rank -- its - * contributions to the seeds they both hold, and nothing else. The caller - * encrypts it to the recipient; it must never travel in the clear. - */ - fun round2(params: Params, participant: Int, root: ByteVector32, recipient: Int): Map { - require(participant != recipient) { "a participant does not reveal to itself" } - return params.heldRanks(participant) - .filter { params.isHolder(recipient, params.subsets[it]) } - .associateWith { contribution(params, participant, root, it) } - } - - /** - * Round 3: check every reveal against its commitment and assemble this - * participant's share. - * - * @param commitments every participant's round-1 message, own included. - * @param reveals what every other participant revealed to this one, by sender. - */ - fun assemble( - params: Params, - participant: Int, - root: ByteVector32, - commitments: Map, - reveals: Map>, - ): Either { - for (j in 1..params.n) { - val c = commitments[j] ?: return Either.Left(Fault.MissingCommitment(j)) - if (c.byRank.keys != params.heldRanks(j).toSet()) return Either.Left(Fault.MalformedMessage(j, "commitments for the wrong subsets")) - } - val seeds = params.heldRanks(participant).map { rank -> - val contributions = params.holders(params.subsets[rank]).map { j -> - val value = if (j == participant) { - contribution(params, participant, root, rank) - } else { - reveals[j]?.get(rank) ?: return Either.Left(Fault.MissingReveal(j)) - } - if (commitment(params, j, rank, value) != commitments.getValue(j).byRank.getValue(rank)) return Either.Left(Fault.BadReveal(j)) - value - } - seed(params, rank, contributions) - } - return Either.Right(share(params.n, params.t, participant, seeds)) - } - - /** The seed at [rank], from its holders' contributions in ascending participant order. */ - fun seed(params: Params, rank: Int, contributions: List): ByteVector32 = - Crypto.taggedHash(params.sessionId.toByteArray() + Pack.writeInt32BE(rank) + contributions.flatMap { it.toByteArray().asList() }, TAG_SEED) - - /** - * A share in `secp256k1_iceberg_share_serialize`'s encoding: version, n, t, - * the participant's index, then its seeds in rank order. Which seed is which - * follows from n, t and the index, so the order of [seeds] is the whole of - * the layout and has to be [Params.heldRanks]'s. - */ - fun share(n: Int, t: Int, participant: Int, seeds: List): Share { - require(isExpressible(n, t) && participant in 1..n) - require(seeds.size == binomial(n - 1, t - 1)) { "a share holds C(n-1, t-1) seeds" } - return Share(byteArrayOf(SHARE_VERSION, n.toByte(), t.toByte(), participant.toByte()) + seeds.flatMap { it.toByteArray().asList() }) - } - - /** - * The hash every participant publishes beside its public share: the parameters and every - * commitment. Two members who were shown different commitments publish different hashes, and the - * ritual refuses to finish on hashes that do not all agree. - * - * It cannot cover the public shares, which are published in the same message. Those are held - * together by [groupPublicKey], which refuses a set that does not lie on one polynomial, and by - * the wallet statement the group signs over the key they make (Phase 6), which a member whose - * device computed a different key refuses to sign. - */ - fun transcriptHash(params: Params, commitments: Map): ByteVector32 { - require(commitments.size == params.n) - val bytes = buildList { - addAll(params.sessionId.toByteArray().asList()) - for (j in 1..params.n) { - val c = commitments.getValue(j) - for (rank in params.heldRanks(j)) addAll(c.byRank.getValue(rank).toByteArray().asList()) - } - } - return Crypto.taggedHash(bytes.toByteArray(), TAG_TRANSCRIPT) - } - - /** - * The group key, from every participant's public share in participant - * order. Using all `n` rather than a quorum is the point: `groupPublicKey` - * checks the shares lie on one polynomial of degree `t-1`, and every share - * past `t` is one more constraint a wrong one has to satisfy. - */ - fun groupPublicKey(params: Params, publicShares: List): Either { - if (publicShares.size != params.n) return Either.Left(Fault.InconsistentShares("expected ${params.n} public shares, got ${publicShares.size}")) - return when (val key = Iceberg.groupPublicKey(publicShares, params.n, params.t)) { - is Either.Right -> Either.Right(key.value) - is Either.Left -> Either.Left(Fault.InconsistentShares(key.value.message ?: "rejected")) - } - } - - /** - * What [helper] sends [participant] to repair its share: the seeds they - * both hold. Encrypted to the participant, like a round-2 reveal. - */ - fun repairSeeds(params: Params, helper: Int, helperShare: Share, participant: Int): Map { - require(helper != participant) - val bytes = helperShare.toByteArray() - require(bytes[3].toInt() == helper) { "that is not the helper's share" } - return params.heldRanks(helper).withIndex() - .filter { (_, rank) -> params.isHolder(participant, params.subsets[rank]) } - .associate { (i, rank) -> rank to ByteVector32(bytes.copyOfRange(4 + 32 * i, 36 + 32 * i)) } - } - - /** - * Rebuild [participant]'s share from what helpers sent ([repairSeeds]). - * Where several helpers sent one seed they must agree, and the result must - * reproduce [publishedPublicShare] -- a wrong seed from anybody fails here - * rather than at a signature. - */ - fun repair(params: Params, participant: Int, received: Map>, publishedPublicShare: PublicShare): Either { - val seeds = params.heldRanks(participant).map { rank -> - val offered = received.values.mapNotNull { it[rank] }.toSet() - when (offered.size) { - 0 -> return Either.Left(Fault.RepairMismatch("nobody sent the seed at rank $rank")) - 1 -> offered.single() - else -> return Either.Left(Fault.RepairMismatch("helpers disagree on the seed at rank $rank")) - } - } - val share = share(params.n, params.t, participant, seeds) - if (Iceberg.publicShare(share, null) != publishedPublicShare) return Either.Left(Fault.RepairMismatch("public share differs")) - return Either.Right(share) - } - - /** All [size]-subsets of 1..[n] as bitmasks (bit j for participant j), in `rss.h`'s lexicographic rank order. */ - fun subsetsInRankOrder(n: Int, size: Int): List { - val out = mutableListOf() - fun walk(next: Int, remaining: Int, mask: Int) { - if (remaining == 0) { out += mask; return } - for (j in next..(n - remaining + 1)) walk(j + 1, remaining - 1, mask or (1 shl j)) - } - walk(1, size, 0) - return out - } - - fun binomial(n: Int, k: Int): Int { - if (k < 0 || k > n) return 0 - var r = 1L - for (i in 0 until k) r = r * (n - i) / (i + 1) - return r.toInt() - } - - private fun compareBytes(a: ByteArray, b: ByteArray): Int { - for (i in 0 until minOf(a.size, b.size)) { - val c = (a[i].toInt() and 0xff) - (b[i].toInt() and 0xff) - if (c != 0) return c - } - return a.size - b.size - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/IcebergRitualManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/IcebergRitualManager.kt deleted file mode 100644 index e9d4d25c..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/IcebergRitualManager.kt +++ /dev/null @@ -1,669 +0,0 @@ -package mobi.giza.compose.managers - -import co.touchlab.kermit.Logger -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.IcebergKeySession -import mobi.giza.compose.database.model.IcebergParticipantMessage -import mobi.giza.compose.database.model.MarmotInnerEvent -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.database.model.types.IcebergApprovalStep -import mobi.giza.compose.database.model.types.IcebergRitualStage -import mobi.giza.compose.extensions.toHex -import mobi.giza.compose.network.serialization.CommonJson -import mobi.giza.compose.nostr.lightning.GroupLightningEvents -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.nip01Core.tags.people.PTag -import com.vitorpamplona.quartz.nip01Core.tags.people.taggedUsers -import com.vitorpamplona.quartz.nip44Encryption.Nip44 -import com.vitorpamplona.quartz.utils.RandomInstance -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.PublicKey -import fr.acinq.bitcoin.crypto.iceberg.Iceberg -import fr.acinq.bitcoin.crypto.iceberg.PublicShare -import fr.acinq.bitcoin.crypto.iceberg.Share -import fr.acinq.bitcoin.utils.Either -import kotlinx.coroutines.CancellationException -import kotlinx.serialization.Serializable -import kotlin.time.Clock -import kotlin.time.Duration -import kotlin.time.Duration.Companion.hours -import kotlin.time.Instant - -/** - * Runs an Iceberg key ceremony ([IcebergDkg]) in a group's Marmot room: the key a group Lightning - * wallet signs its channels with (`docs/group-lightning-wallet.md`, Phase 5). - * - * Built like [ChillDkgRitualManager], and following its rules: every step is a pure function of what - * this device has stored, so a ceremony survives the app being killed; faults are values with one - * failure path; and each device writes the ceremony's transcript lines from what it has received. - * - * ### One approval, then the device - * - * Nothing of this device's own is published until its owner agrees to join. After that the device takes - * the other two rounds by itself, because every check in them is one the code makes and the person - * could not: whether a contribution matches its commitment, whether everyone saw the same commitments, - * whether the public shares make one key. Asking a person to tap through them added nothing but the - * chance that a member who joined would not come back, holding the ceremony open for everybody. - * - * A ceremony ends without anyone deciding to end it in two ways. A fault any device detects stops it on - * that device, and the failure it broadcasts stops it on every other. A ceremony that has not finished - * [DEADLINE] after its proposal is abandoned by the device of whichever participant notices first - * ([abandonOverdue]), naming who had not taken their part. Any participant can also [abandon] it. - * - * ### Two things it does not need, that ChillDKG does - * - * **No host keys.** ChillDKG's first round exists to fix the participant set and its order. Here the - * set is fixed before anyone speaks -- it is the people who hold the room's onchain wallet key - * (decision D1), which the proposal names and every device checks against its own record of that - * ceremony -- and the order is the bytewise order of their nostr keys. - * - * **No coordinator aggregation.** Every round is broadcast and every device assembles its own share, so - * the member who opens the ceremony does nothing the others do not. - * - * ### What travels in the clear, inside MLS - * - * Commitments, public shares and transcript hashes are public by construction. Contributions are not: - * each one goes only to the other holders of its seed, NIP-44 encrypted from the sender's nostr key to - * each recipient's, inside the MLS message the whole room can read. A member who is in the room but - * outside a seed's holders sees ciphertext. - * - * The room must be a Marmot room: that is where the onchain wallet's statement and every signing - * session already are. - */ -object IcebergRitualManager { - private val logger = Logger.withTag("IcebergRitualManager") - - private const val SESSION_TAG = "iceberg_session" - private const val THRESHOLD_TAG = "threshold" - private const val ONCHAIN_TAG = "onchain_dkg" - - /** - * How long a ceremony has, from its proposal, before any participant's device abandons it. Long - * enough for a member to see the request and open the app once; short enough that a member who - * never does stops blocking the room, which can only run one ceremony at a time. - */ - val DEADLINE: Duration = 24.hours - - /** When [session] is abandoned if it has not finished: [DEADLINE] after it was proposed. */ - fun deadlineOf(session: IcebergKeySession): Instant = session.createdAt + DEADLINE - - @Serializable - private data class Round1(val commitments: Map) - - @Serializable - private data class Round2(val to: Map) - - @Serializable - private data class Round2Plain(val contributions: Map) - - @Serializable - private data class Round3(val publicShare: String, val transcript: String) - - /** The thresholds a group whose onchain key is [onchainKey] could choose, smallest first; empty if none. */ - fun thresholdsFor(onchainKey: DkgSession): List = - onchainKey.participantPublicKeySet()?.let { IcebergDkg.deployableThresholds(it.size) }.orEmpty() - - /** The thresholds a ceremony in [chatRoomId] could use now, over [holdersInRoom]; empty if none. */ - suspend fun thresholds(database: GizaDatabase, chatRoomId: String): List { - val onchainKey = FrostSigningManager.completedKey(database, chatRoomId) ?: return emptyList() - return IcebergDkg.deployableThresholds(holdersInRoom(database, chatRoomId, onchainKey).size) - } - - /** - * Who a ceremony in [chatRoomId] is over (decision D1, as Phase 14 narrows it): the holders of the - * onchain key [onchainKey] who are still in the room, as this device's MLS state has it. A member - * who was removed keeps their onchain share, but a new Lightning wallet is made without them. - * - * The removal commit is an earlier epoch than any proposal sent after it, so a device reading a - * proposal has already applied it, and every device computes the same set. - */ - suspend fun holdersInRoom(database: GizaDatabase, chatRoomId: String, onchainKey: DkgSession): Set { - val holders = onchainKey.participantPublicKeySet()?.map { it.lowercase() }?.toSet().orEmpty() - val inRoom = database.participantDao().findParticipantsByChatRoomId(chatRoomId).filter { it.deletedAt == null }.map { it.participantPublicKey.lowercase() }.toSet() - return holders intersect inRoom - } - - /** A participant's nostr key as the compressed point [IcebergDkg.Params] orders and binds. */ - private fun asPoint(nostrKey: HexKey): PublicKey = PublicKey(ByteVector("02$nostrKey")) - - fun paramsOf(session: IcebergKeySession): IcebergDkg.Params = - IcebergDkg.Params.of(session.threshold, session.participants().map(::asPoint), ByteVector32(session.id)) - - private fun indexOf(session: IcebergKeySession, nostrKey: HexKey): Int? = - session.participants().indexOf(nostrKey.lowercase()).takeIf { it >= 0 }?.plus(1) - - /** - * Opens a ceremony over the people who hold [localChatRoom]'s onchain wallet key, at [threshold]. - * A ceremony already running in the room is returned instead of a second. - * - * @param chain the network the Lightning wallet is for. The room must have opened an onchain - * wallet there first (decision D2), because that wallet is where the Lightning wallet closes to. - */ - suspend fun proposeCeremony( - database: GizaDatabase, - localChatRoom: LocalChatRoom, - userPublicKey: HexKey, - nostrPrivateKey: ByteArray, - threshold: Int, - chain: Chain, - ): IcebergKeySession { - val roomId = localChatRoom.chatRoom.id - require(localChatRoom.chatRoom.mlsGroupState != null) { "An Iceberg ceremony runs in a Marmot room" } - - database.icebergKeySessionDao().getSessionsForChatRoom(roomId) - .firstOrNull { it.stage != IcebergRitualStage.FAILED && it.stage != IcebergRitualStage.COMPLETE } - ?.let { return it } - - val onchainKey = FrostSigningManager.completedKey(database, roomId) - ?: throw IllegalStateException("This group has no onchain key whose holders could sign a Lightning wallet") - requireNotNull(GroupWalletManager.walletFor(database, roomId, chain)) { - "Open a group onchain wallet on ${chain.name} before a Lightning wallet: it is where the Lightning wallet closes to" - } - val members = holdersInRoom(database, roomId, onchainKey) - require(userPublicKey.lowercase() in members) { "This device does not hold the onchain key" } - require(IcebergDkg.isDeployable(members.size, threshold)) { "$threshold-of-${members.size} is not a deployable Iceberg group" } - - val session = IcebergKeySession( - id = RandomInstance.bytes(32).toHex(), - chatRoomId = roomId, - coordinatorPublicKey = userPublicKey, - userPublicKey = userPublicKey, - threshold = threshold, - participantCount = members.size, - participantPublicKeys = IcebergKeySession.formatParticipants(members), - onchainDkgSessionId = onchainKey.id, - root = RandomInstance.bytes(32).toHex(), - // Opening a ceremony is agreeing to be in it, as with ChillDKG's host key. - joinApprovedAt = Clock.System.now(), - ) - database.icebergKeySessionDao().upsert(session) - announce( - database, session, ChatMessage.TYPE_ICEBERG_STARTED, - "started a key ceremony for a Lightning wallet. It will take ${session.threshold} of ${session.participantCount} " + - "of the people who hold the onchain wallet's key to sign for it, and ${2 * session.threshold - 1} of their devices " + - "to be online for every payment.", - session.coordinatorPublicKey, - ) - broadcast(database, localChatRoom, session, GroupLightningEvents.CEREMONY_PROPOSAL, "", includeProposalTags = true) - advance(database, localChatRoom, session.id, nostrPrivateKey) - return database.icebergKeySessionDao().getSessionById(session.id) ?: session - } - - /** Feeds one inbound ceremony message in and advances as far as it will go. Safe to call twice. */ - suspend fun processCeremonyPayload( - database: GizaDatabase, - localChatRoom: LocalChatRoom, - innerEvent: Event, - userPublicKey: HexKey, - nostrPrivateKey: ByteArray, - ) { - val sessionId = innerEvent.tags.firstOrNull { it.size >= 2 && it[0] == SESSION_TAG }?.get(1) - if (sessionId == null) { - logger.w("Iceberg payload ${innerEvent.id} has no session tag; dropping") - return - } - val session = if (innerEvent.kind == GroupLightningEvents.CEREMONY_PROPOSAL) { - acceptProposal(database, localChatRoom, innerEvent, sessionId, userPublicKey) - } else { - database.icebergKeySessionDao().getSessionById(sessionId) - } ?: return - if (session.stage == IcebergRitualStage.FAILED || session.stage == IcebergRitualStage.COMPLETE) 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, - ): IcebergKeySession? { - database.icebergKeySessionDao().getSessionById(sessionId)?.let { return it } - - val members = innerEvent.tags.taggedUsers().map { it.pubKey.lowercase() }.toSet() + innerEvent.pubKey.lowercase() - val threshold = innerEvent.tags.firstOrNull { it.size >= 2 && it[0] == THRESHOLD_TAG }?.get(1)?.toIntOrNull() - val onchainId = innerEvent.tags.firstOrNull { it.size >= 2 && it[0] == ONCHAIN_TAG }?.get(1) - if (userPublicKey.lowercase() !in members) return null - // A proposal read after its deadline is over on every device that took part in it, finished or - // not: one that could still be running would need this device, which has not joined. Filing it - // would ask its owner to join a ceremony that is about to be abandoned -- or, on a device - // reading the room again after a restore, abandon one the group finished long ago. - val proposedAt = Instant.fromEpochSeconds(innerEvent.createdAt) - if (Clock.System.now() >= proposedAt + DEADLINE) { - logger.i("Iceberg proposal $sessionId is past its deadline; not filing it") - return null - } - if (threshold == null || !IcebergDkg.isDeployable(members.size, threshold)) { - logger.w("Iceberg proposal $sessionId asks for $threshold-of-${members.size}, which is not deployable; dropping") - return null - } - // D1, checked rather than trusted: the people the proposal names must be exactly the people - // who hold the onchain key it names and are still in the room, as this device's own records say. - val onchainKey = onchainId?.let { database.dkgSessionDao().getSessionById(it) } - if (onchainKey == null || holdersInRoom(database, localChatRoom.chatRoom.id, onchainKey) != members) { - logger.w("Iceberg proposal $sessionId names people who are not the holders of onchain key $onchainId; dropping") - return null - } - // The id is the ceremony id the key is bound to (IcebergDkg.Params), so it has to be 32 bytes. - if (runCatching { ByteVector32(sessionId) }.isFailure) { - logger.w("Iceberg proposal $sessionId has an id that is not 32 bytes; dropping") - return null - } - - val session = IcebergKeySession( - id = sessionId, - chatRoomId = localChatRoom.chatRoom.id, - coordinatorPublicKey = innerEvent.pubKey, - userPublicKey = userPublicKey, - threshold = threshold, - participantCount = members.size, - participantPublicKeys = IcebergKeySession.formatParticipants(members), - onchainDkgSessionId = onchainKey.id, - root = RandomInstance.bytes(32).toHex(), - // When it was proposed, not when this device heard of it: the deadline runs from here, - // and every device has to agree on it. - createdAt = proposedAt, - ) - database.icebergKeySessionDao().upsert(session) - announce( - database, session, ChatMessage.TYPE_ICEBERG_STARTED, - "started a key ceremony for a Lightning wallet. It will take ${session.threshold} of ${session.participantCount} " + - "of the people who hold the onchain wallet's key to sign for it, and ${2 * session.threshold - 1} of their devices " + - "to be online for every payment.", - session.coordinatorPublicKey, - ) - announceApprovalNeeded(database, session, IcebergApprovalStep.JOIN) - replayStoredMessages(database, session) - return session - } - - private suspend fun replayStoredMessages(database: GizaDatabase, session: IcebergKeySession) { - database.marmotInnerEventDao() - .getByChatRoomAndKinds(chatRoomId = session.chatRoomId, kinds = GroupLightningEvents.CEREMONY.toList()) - .filter { it.kind != GroupLightningEvents.CEREMONY_PROPOSAL && it.tags.any { t -> t.size >= 2 && t[0] == SESSION_TAG && t[1] == session.id } } - .forEach { stored -> - val event = Event(stored.id, stored.publicKey, stored.createdAt.epochSeconds, stored.kind, stored.tags, stored.content, "") - if (!record(database, session, event)) return - } - } - - /** Files one message, first copy wins. False when the message ends the ceremony. */ - private suspend fun record(database: GizaDatabase, session: IcebergKeySession, innerEvent: Event): Boolean { - val sender = innerEvent.pubKey.lowercase() - when (innerEvent.kind) { - GroupLightningEvents.CEREMONY_PROPOSAL -> Unit - GroupLightningEvents.DKG_ROUND_1, GroupLightningEvents.DKG_ROUND_2, GroupLightningEvents.DKG_ROUND_3 -> { - if (indexOf(session, sender) == null) { - logger.w("Ceremony ${session.id}: kind ${innerEvent.kind} from ${sender.take(8)}, who is not in it; ignoring") - return true - } - val dao = database.icebergKeySessionDao() - if (dao.getMessage(session.id, innerEvent.kind, sender) == null) { - dao.upsert(IcebergParticipantMessage(session.id, sender, innerEvent.kind, innerEvent.content)) - announceStep(database, session, innerEvent.kind, sender) - } - } - GroupLightningEvents.CEREMONY_FAILURE -> { - // The sender's own account of why, which is a sentence from any build - // with [describe]. The line names the sender; the reason is not the - // place for a key prefix. - fail(database, session, innerEvent.content.ifBlank { "Something went wrong on their device." }, sender) - return false - } - } - return true - } - - /** - * 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, as [ChillDkgRitualManager.advance] does. - */ - private suspend fun advance(database: GizaDatabase, localChatRoom: LocalChatRoom, sessionId: String, nostrPrivateKey: ByteArray) { - var session = database.icebergKeySessionDao().getSessionById(sessionId) ?: return - if (session.stage == IcebergRitualStage.COMPLETE || session.stage == IcebergRitualStage.FAILED) return - val dao = database.icebergKeySessionDao() - try { - val params = paramsOf(session) - val me = indexOf(session, session.userPublicKey) ?: error("this device is not in ceremony ${session.id}") - val root = ByteVector32(session.root ?: error("ceremony ${session.id} has lost its random root")) - - if (session.joinApprovedAt == null) return - if (own(database, session, GroupLightningEvents.DKG_ROUND_1) == null) { - val commitments = IcebergDkg.round1(params, me, root) - publishOwn(database, localChatRoom, session, GroupLightningEvents.DKG_ROUND_1, CommonJson.encodeToString(Round1.serializer(), Round1(commitments.byRank.entries.associate { (rank, c) -> rank.toString() to c.toHex() }))) - } - val commitments = commitmentsOf(database, session, params) ?: return - session = moveTo(database, session, IcebergRitualStage.COLLECTING_REVEALS) - - if (own(database, session, GroupLightningEvents.DKG_ROUND_2) == null) { - val to = (1..params.n).filter { it != me }.associate { k -> - val recipient = session.participants()[k - 1] - val plain = Round2Plain(IcebergDkg.round2(params, me, root, k).entries.associate { (rank, c) -> rank.toString() to c.toHex() }) - recipient to Nip44.encrypt(CommonJson.encodeToString(Round2Plain.serializer(), plain), nostrPrivateKey, recipient.hexToByteArray()).encodePayload() - } - publishOwn(database, localChatRoom, session, GroupLightningEvents.DKG_ROUND_2, CommonJson.encodeToString(Round2.serializer(), Round2(to))) - } - val reveals = revealsTo(database, session, me, nostrPrivateKey) ?: return - val share = when (val assembled = IcebergDkg.assemble(params, me, root, commitments, reveals)) { - is Either.Left -> throw assembled.value - is Either.Right -> assembled.value - } - session = moveTo(database, session, IcebergRitualStage.COLLECTING_CONFIRMATIONS) - - val transcript = IcebergDkg.transcriptHash(params, commitments) - val myPublicShare = Iceberg.publicShare(share, null) - if (own(database, session, GroupLightningEvents.DKG_ROUND_3) == null) { - publishOwn(database, localChatRoom, session, GroupLightningEvents.DKG_ROUND_3, CommonJson.encodeToString(Round3.serializer(), Round3(myPublicShare.toByteArray().toHex(), transcript.toHex()))) - } - val confirmations = dao.getMessagesByKind(session.id, GroupLightningEvents.DKG_ROUND_3) - if (confirmations.size < params.n) return - val byIndex = confirmations.associate { m -> indexOf(session, m.participantPublicKey)!! to CommonJson.decodeFromString(Round3.serializer(), m.payload) } - val disagreeing = byIndex.filterValues { it.transcript != transcript.toHex() }.keys - if (disagreeing.isNotEmpty()) throw Disagreement(disagreeing.sorted()) - val publicShares = (1..params.n).map { PublicShare(byIndex.getValue(it).publicShare) } - if (publicShares[me - 1] != myPublicShare) throw WrongPublicShare() - val groupKey = when (val key = IcebergDkg.groupPublicKey(params, publicShares)) { - is Either.Left -> throw key.value - is Either.Right -> key.value - } - update(database, session) { - it.copy( - stage = IcebergRitualStage.COMPLETE, - share = share.toByteArray().toHex(), - root = null, - groupPublicKey = groupKey.value.toHex(), - publicShares = publicShares.joinToString(",") { p -> p.toByteArray().toHex() }, - ) - } - announce( - database, session, ChatMessage.TYPE_ICEBERG_COMPLETE, - "The group has a key for a Lightning wallet. It takes ${session.threshold} of ${session.participantCount} to sign for it.", - session.coordinatorPublicKey, - ) - logger.i("Iceberg ceremony ${session.id} complete") - } catch (e: CancellationException) { - throw e - } catch (e: Throwable) { - logger.e("Iceberg ceremony ${session.id} failed", e) - // Said, not thrown: the exception is in the log, and what the group is told - // -- here, and on every other device through the failure message -- is a - // sentence naming the member at fault where the fault names one. - val reason = describe(database, session, e) - fail(database, session, reason) - broadcast(database, localChatRoom, session, GroupLightningEvents.CEREMONY_FAILURE, reason) - } - } - - /** Some participants' transcript hashes are not this device's: they saw different commitments. */ - private class Disagreement(val participants: List) : Exception("participants $participants saw a different set of commitments") - - private class WrongPublicShare : Exception("the public share published for this device is not the one its share gives") - - /** - * Why a ceremony stopped on this device, as a sentence for the group: in its failure line's - * reason, on its screen, and in the failure message the other devices read. Shaped like - * ChillDKG's blame -- the member at fault is the actionable part -- but with their name rather - * than their index, since the index is an order of keys nobody sees. - */ - internal suspend fun describe(database: GizaDatabase, session: IcebergKeySession, failure: Throwable): String { - suspend fun named(index: Int?): String = index - ?.let { session.participants().getOrNull(it - 1) } - ?.let { "@" + ChatMessage.memberName(database, it) } - ?: "A member" - - return when (failure) { - is IcebergDkg.Fault.MissingCommitment -> "${named(failure.participant)} sent no commitment to their contributions." - is IcebergDkg.Fault.MissingReveal -> "${named(failure.participant)} sent this device nothing in the second round." - is IcebergDkg.Fault.BadReveal -> "${named(failure.participant)} sent a contribution that does not match what they committed to." - is IcebergDkg.Fault.MalformedMessage -> "${named(failure.participant)} sent a message this device could not read." - is IcebergDkg.Fault.InconsistentShares -> "The members' public shares do not make one key." - is IcebergDkg.Fault.RepairMismatch -> "A repaired share does not match the public share published for it." - is Disagreement -> failure.participants.map { named(it) }.joinToString(", ") + - " saw a different set of commitments from this device." - is WrongPublicShare -> "The public share published for this device is not the one its share gives." - else -> "Something went wrong on this device." - } - } - - /** Every participant's commitments, or null while any are missing. */ - private suspend fun commitmentsOf(database: GizaDatabase, session: IcebergKeySession, params: IcebergDkg.Params): Map? { - val messages = database.icebergKeySessionDao().getMessagesByKind(session.id, GroupLightningEvents.DKG_ROUND_1) - if (messages.size < params.n) return null - return messages.associate { m -> - val j = indexOf(session, m.participantPublicKey)!! - val body = CommonJson.decodeFromString(Round1.serializer(), m.payload) - j to IcebergDkg.Commitments(j, body.commitments.entries.associate { (rank, c) -> rank.toInt() to ByteVector32(c) }) - } - } - - /** What every other participant revealed to this device, decrypted, or null while any are missing. */ - private suspend fun revealsTo(database: GizaDatabase, session: IcebergKeySession, me: Int, nostrPrivateKey: ByteArray): Map>? { - val messages = database.icebergKeySessionDao().getMessagesByKind(session.id, GroupLightningEvents.DKG_ROUND_2) - .filter { it.participantPublicKey != session.userPublicKey.lowercase() } - if (messages.size < session.participantCount - 1) return null - val myKey = session.userPublicKey.lowercase() - return messages.associate { m -> - val j = indexOf(session, m.participantPublicKey)!! - val ciphertext = CommonJson.decodeFromString(Round2.serializer(), m.payload).to[myKey] - ?: throw IcebergDkg.Fault.MissingReveal(j) - val plain = try { - Nip44.decrypt(ciphertext, nostrPrivateKey, m.participantPublicKey.hexToByteArray()) - } catch (e: Throwable) { - throw IcebergDkg.Fault.MalformedMessage(j, "its contributions could not be decrypted") - } - j to CommonJson.decodeFromString(Round2Plain.serializer(), plain).contributions.entries.associate { (rank, c) -> rank.toInt() to ByteVector32(c) } - } - } - - /** - * What this ceremony is waiting on its owner for, or null. Only ever [IcebergApprovalStep.JOIN]: it - * is the one gate in [advance]. - */ - suspend fun pendingApproval(database: GizaDatabase, session: IcebergKeySession): IcebergApprovalStep? { - if (session.stage == IcebergRitualStage.COMPLETE || session.stage == IcebergRitualStage.FAILED) return null - return if (session.joinApprovedAt == null) IcebergApprovalStep.JOIN else null - } - - /** Records that this device's owner agreed to [step] and runs on. A step it is not waiting on is a no-op. */ - suspend fun approve(database: GizaDatabase, localChatRoom: LocalChatRoom, sessionId: String, step: IcebergApprovalStep, nostrPrivateKey: ByteArray) { - val session = database.icebergKeySessionDao().getSessionById(sessionId) ?: return - if (pendingApproval(database, session) != step) { - logger.i("Ceremony $sessionId is not waiting on $step; ignoring the approval") - return - } - val now = Clock.System.now() - update(database, session) { - when (step) { - IcebergApprovalStep.JOIN -> it.copy(joinApprovedAt = now) - IcebergApprovalStep.REVEAL -> it.copy(revealApprovedAt = now) - IcebergApprovalStep.CONFIRM -> it.copy(confirmApprovedAt = now) - } - } - advance(database, localChatRoom, sessionId, nostrPrivateKey) - } - - /** - * Takes whatever steps [sessionId] can take now. Messages arriving and approvals already do this; - * this is for a ceremony that stopped at a gate a build before this one had, and that nothing will - * arrive to move, since the others are waiting on this device. - */ - suspend fun resume(database: GizaDatabase, localChatRoom: LocalChatRoom, sessionId: String, nostrPrivateKey: ByteArray) = - advance(database, localChatRoom, sessionId, nostrPrivateKey) - - /** - * Ends [sessionId] for everyone in it, at its owner's word. Open to any participant, as the shared - * key's is (`docs/ceremony-creation.md`, decision 3): any of them could already end it by going - * quiet, and saying so lets the others stop waiting. False when it is already over. - */ - suspend fun abandon(database: GizaDatabase, localChatRoom: LocalChatRoom, sessionId: String): Boolean { - val session = database.icebergKeySessionDao().getSessionById(sessionId) ?: return false - if (session.stage == IcebergRitualStage.COMPLETE || session.stage == IcebergRitualStage.FAILED) return false - val reason = "@${ChatMessage.memberName(database, session.userPublicKey)} abandoned it." - fail(database, session, reason) - broadcast(database, localChatRoom, session, GroupLightningEvents.CEREMONY_FAILURE, reason) - return true - } - - /** - * Abandons every ceremony [userPublicKey] is in that has passed its [deadlineOf] without finishing, - * telling the group who had not taken their part. Every participant's device does this, so several - * may say it; the first failure each device files is the one it keeps. - */ - suspend fun abandonOverdue(database: GizaDatabase, userPublicKey: HexKey, now: Instant = Clock.System.now()) { - for (session in database.icebergKeySessionDao().getRunningSessions()) { - if (session.userPublicKey != userPublicKey || now < deadlineOf(session)) continue - val localChatRoom = database.chatRoomDao().findChatRoomById(session.chatRoomId) ?: continue - val reason = overdueReason(database, session) - logger.i("Iceberg ceremony ${session.id} is past its deadline; abandoning it") - fail(database, session, reason) - broadcast(database, localChatRoom, session, GroupLightningEvents.CEREMONY_FAILURE, reason) - } - } - - /** - * Why an overdue ceremony stopped: the members missing from the first round this device does not - * have from everyone, which is who the ceremony was waiting on. - */ - internal suspend fun overdueReason(database: GizaDatabase, session: IcebergKeySession): String { - val dao = database.icebergKeySessionDao() - val missing = listOf(GroupLightningEvents.DKG_ROUND_1, GroupLightningEvents.DKG_ROUND_2, GroupLightningEvents.DKG_ROUND_3) - .firstNotNullOfOrNull { kind -> - val sent = dao.getMessagesByKind(session.id, kind).map { it.participantPublicKey.lowercase() }.toSet() - session.participants().filter { it !in sent }.takeIf { it.isNotEmpty() } - } - .orEmpty() - val hours = DEADLINE.inWholeHours - if (missing.isEmpty()) return "It didn't finish within $hours hours of being proposed." - val names = missing.map { "@" + ChatMessage.memberName(database, it) } - return "${names.joinToString(", ")} didn't take their part within $hours hours of it being proposed." - } - - /** The share this device holds for the room's newest completed ceremony, with what it is a share of. */ - suspend fun completedKey(database: GizaDatabase, chatRoomId: String): IcebergKeySession? = - database.icebergKeySessionDao().getSessionsForChatRoom(chatRoomId).firstOrNull { it.stage == IcebergRitualStage.COMPLETE && it.share != null } - - fun shareOf(session: IcebergKeySession): Share? = session.share?.let { Share(it.hexToByteArray()) } - - private suspend fun own(database: GizaDatabase, session: IcebergKeySession, kind: Kind): IcebergParticipantMessage? = - database.icebergKeySessionDao().getMessage(session.id, kind, session.userPublicKey.lowercase()) - - private suspend fun update(database: GizaDatabase, session: IcebergKeySession, transform: (IcebergKeySession) -> IcebergKeySession): IcebergKeySession { - val current = database.icebergKeySessionDao().getSessionById(session.id) ?: session - val updated = transform(current) - if (updated == current) return current - val stamped = updated.copy(updatedAt = Clock.System.now()) - database.icebergKeySessionDao().upsert(stamped) - return stamped - } - - private suspend fun moveTo(database: GizaDatabase, session: IcebergKeySession, stage: IcebergRitualStage): IcebergKeySession = update(database, session) { current -> - val settled = current.stage == IcebergRitualStage.COMPLETE || current.stage == IcebergRitualStage.FAILED - if (settled || current.stage.ordinal >= stage.ordinal) current else current.copy(stage = stage) - } - - private suspend fun fail(database: GizaDatabase, session: IcebergKeySession, reason: String, culprit: HexKey = session.userPublicKey) { - val current = database.icebergKeySessionDao().getSessionById(session.id) ?: session - if (current.stage == IcebergRitualStage.FAILED) return - update(database, current) { it.copy(stage = IcebergRitualStage.FAILED, failureReason = reason, root = null) } - announce(database, current, ChatMessage.TYPE_ICEBERG_FAILED, "abandoned the Lightning wallet's key ceremony. No key was created, and it is safe to run it again.", culprit) - } - - private suspend fun announceApprovalNeeded(database: GizaDatabase, session: IcebergKeySession, step: IcebergApprovalStep) { - val asked = (database.icebergKeySessionDao().getSessionById(session.id) ?: session).approvalRequestedThrough - if (asked != null && asked.ordinal >= step.ordinal) return - update(database, session) { it.copy(approvalRequestedThrough = step) } - val (type, content) = when (step) { - IcebergApprovalStep.JOIN -> ChatMessage.TYPE_ICEBERG_APPROVAL_NEEDED_JOIN to - "Your approval is needed to join the Lightning wallet's key ceremony. Nothing has been published from this device yet." - IcebergApprovalStep.REVEAL -> ChatMessage.TYPE_ICEBERG_APPROVAL_NEEDED_REVEAL to - "Everyone has joined the Lightning wallet's key ceremony. Your approval is needed to send your contributions to the key." - IcebergApprovalStep.CONFIRM -> ChatMessage.TYPE_ICEBERG_APPROVAL_NEEDED_CONFIRM to - "Your share of the Lightning wallet's key is assembled. Your approval is needed to publish what you saw, so the group can check it agrees." - } - announce(database, session, type, content, session.userPublicKey) - } - - private suspend fun announceStep(database: GizaDatabase, session: IcebergKeySession, kind: Kind, actor: HexKey) { - val (type, content) = when (kind) { - GroupLightningEvents.DKG_ROUND_1 -> ChatMessage.TYPE_ICEBERG_COMMITTED to - "joined the Lightning wallet's key ceremony, committing to their contributions before anyone reveals one." - GroupLightningEvents.DKG_ROUND_2 -> ChatMessage.TYPE_ICEBERG_REVEALED to - "sent their contributions to the key, each one only to the members who will hold it." - GroupLightningEvents.DKG_ROUND_3 -> ChatMessage.TYPE_ICEBERG_CONFIRMED to - "assembled their share and published what they saw, for the group to check it agrees." - else -> return - } - announce(database, session, type, content, actor) - } - - private suspend fun announce(database: GizaDatabase, session: IcebergKeySession, messageType: String, content: String, actor: HexKey) { - database.chatMessageDao().upsert( - ChatMessage( - senderPublicKey = actor, - isUserMessage = actor.lowercase() == session.userPublicKey.lowercase(), - giftWrapPayloadId = null, - marmotGroupEventId = null, - marmotInnerEventId = null, - chatRoomId = session.chatRoomId, - content = content, - messageType = messageType, - dkgSessionId = session.id, - ) - ) - } - - private suspend fun publishOwn(database: GizaDatabase, localChatRoom: LocalChatRoom, session: IcebergKeySession, kind: Kind, content: String) { - broadcast(database, localChatRoom, session, kind, content) - val dao = database.icebergKeySessionDao() - val me = session.userPublicKey.lowercase() - val known = dao.getMessage(session.id, kind, me) != null - dao.upsert(IcebergParticipantMessage(session.id, me, kind, content)) - if (!known) announceStep(database, session, kind, me) - } - - /** - * Queues one of this device's messages as a Marmot inner event for the room. The p-tags name the - * participants on every message, as the ChillDKG ritual's do: they are the set the proposal is - * checked against, and inside MLS naming them leaks nothing. - */ - private suspend fun broadcast( - database: GizaDatabase, - localChatRoom: LocalChatRoom, - session: IcebergKeySession, - kind: Kind, - content: String, - includeProposalTags: Boolean = false, - ) { - val pTags = session.participants().filterNot { it == session.userPublicKey.lowercase() }.map { PTag.assemble(it, null) } - val ownTags = buildList { - add(arrayOf(SESSION_TAG, session.id)) - if (includeProposalTags) { - add(arrayOf(THRESHOLD_TAG, session.threshold.toString())) - add(arrayOf(ONCHAIN_TAG, session.onchainDkgSessionId)) - } - } - val tags = pTags.toTypedArray() + ownTags.toTypedArray() - val createdAt = Clock.System.now().epochSeconds - val id = EventHasher.hashId(pubKey = session.userPublicKey, createdAt = createdAt, tags = tags, content = content, kind = kind) - database.marmotInnerEventDao().upsert( - MarmotInnerEvent( - id = id, - publicKey = session.userPublicKey, - kind = kind, - createdAt = Instant.fromEpochSeconds(createdAt), - tags = tags, - content = content, - chatRoomId = localChatRoom.chatRoom.id, - ) - ) - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/lightning/GroupLightningAuthorisationEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/lightning/GroupLightningAuthorisationEvent.kt deleted file mode 100644 index 1c5a16ef..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/lightning/GroupLightningAuthorisationEvent.kt +++ /dev/null @@ -1,183 +0,0 @@ -package mobi.giza.compose.nostr.lightning - -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import com.vitorpamplona.quartz.nip01Core.core.Kind -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import fr.acinq.bitcoin.Chain -import fr.acinq.lightning.payment.Bolt11Invoice -import kotlin.time.Clock - -/** - * Something the group lets its Lightning wallet do: kind 30363, FROST-signed, never broadcast - * (`docs/group-lightning-wallet.md`, Phase 12). - * - * The operator's node acts on an authorisation, and every co-signer reads it as a budget: an HTLC the - * group's commitment offers must pay a hash some authorisation names, within its amount and fee cap. - * So the operator cannot add a payment, only make one the group signed for. - * - * `pay` is a payment ([Pay]); `close` and `force-close` act on one channel ([ChannelAction]); - * `buy-liquidity` buys inbound liquidity for one channel by splicing it ([BuyLiquidity], - * `docs/group-lightning-liquidity.md`, Phase 4). An action this device does not know reads as null, - * which every caller treats as no authorisation at all. - */ -object GroupLightningAuthorisationEvent { - val KIND: Kind = GroupLightningEvents.AUTHORISATION - - private const val D_TAG = "d" - private const val ACTION_TAG = "action" - private const val INVOICE_TAG = "invoice" - private const val AMOUNT_TAG = "amount" - private const val MAX_FEE_TAG = "maxfee" - private const val HASH_TAG = "hash" - private const val EXPIRES_TAG = "expires" - - private const val CHANNEL_TAG = "channel" - private const val ID_TAG = "id" - - const val PAY = "pay" - /** A mutual close of one channel, to the onchain wallet the statement names. */ - const val CLOSE = "close" - /** Publishing our own commitment of one channel: what the group does when the LSP has gone away. */ - const val FORCE_CLOSE = "force-close" - /** Buying inbound liquidity for one channel from the LSP, by splicing it. */ - const val BUY_LIQUIDITY = "buy-liquidity" - - /** - * A payment the group authorises, at most [amountMsat] plus [maxFeeMsat], until [expiresAt] (epoch - * seconds). After that no new HTLC for it is signed; one already in flight still settles against it. - */ - data class Pay( - val chain: Chain, - val wallet: Long, - val invoice: String, - val amountMsat: Long, - val maxFeeMsat: Long, - val paymentHash: String, - val expiresAt: Long, - ) { - val budgetMsat: Long get() = amountMsat + maxFeeMsat - } - - fun template(pay: Pay, createdAt: Long = Clock.System.now().epochSeconds): EventTemplate<*> = - EventTemplate( - createdAt = createdAt, - kind = KIND, - tags = arrayOf( - arrayOf(D_TAG, "${GroupLightningWalletStatementEvent.identifier(pay.chain, pay.wallet)}:${pay.paymentHash}"), - arrayOf(ACTION_TAG, PAY), - arrayOf(INVOICE_TAG, pay.invoice), - arrayOf(AMOUNT_TAG, pay.amountMsat.toString()), - arrayOf(MAX_FEE_TAG, pay.maxFeeMsat.toString()), - arrayOf(HASH_TAG, pay.paymentHash), - arrayOf(EXPIRES_TAG, pay.expiresAt.toString()), - ), - content = "", - ) - - /** - * The payment [tags] authorise, or null for anything this device cannot stand behind: an action it - * does not know, an invoice it cannot read, or one that disagrees with what the tags say it is -- - * another network, another hash, another amount, or an expiry past the invoice's own. - */ - fun read(tags: Array>): Pay? { - fun value(name: String): String? = tags.firstOrNull { it.size >= 2 && it[0] == name }?.get(1) - if (value(ACTION_TAG) != PAY) return null - val d = value(D_TAG) ?: return null - val parts = d.split(':') - if (parts.size != 3) return null - val chain = GroupWalletStatementEvent.chainNamed(parts[0]) ?: return null - val wallet = parts[1].toLongOrNull() ?: return null - val bolt11 = value(INVOICE_TAG) ?: return null - val invoice = runCatching { Bolt11Invoice.read(bolt11).get() }.getOrNull() ?: return null - val amount = value(AMOUNT_TAG)?.toLongOrNull()?.takeIf { it > 0 } ?: return null - val maxFee = value(MAX_FEE_TAG)?.toLongOrNull()?.takeIf { it >= 0 } ?: return null - val hash = value(HASH_TAG) ?: return null - val expires = value(EXPIRES_TAG)?.toLongOrNull() ?: return null - if (invoice.chain != chain) return null - if (parts[2] != hash || invoice.paymentHash.toHex() != hash) return null - if (invoice.amount != null && invoice.amount!!.msat != amount) return null - if (expires > invoice.timestampSeconds + (invoice.expirySeconds ?: Bolt11Invoice.DEFAULT_EXPIRY_SECONDS.toLong())) return null - return Pay(chain, wallet, bolt11, amount, maxFee, hash, expires) - } - - /** A [CLOSE] or [FORCE_CLOSE] of [channelId], open until [expiresAt] (epoch seconds). */ - data class ChannelAction(val action: String, val chain: Chain, val wallet: Long, val channelId: String, val expiresAt: Long) { - init { - require(action == CLOSE || action == FORCE_CLOSE) { "not a channel action: $action" } - } - } - - fun template(channelAction: ChannelAction, createdAt: Long = Clock.System.now().epochSeconds): EventTemplate<*> = - EventTemplate( - createdAt = createdAt, - kind = KIND, - tags = arrayOf( - arrayOf(D_TAG, "${GroupLightningWalletStatementEvent.identifier(channelAction.chain, channelAction.wallet)}:${channelAction.action}:${channelAction.channelId}"), - arrayOf(ACTION_TAG, channelAction.action), - arrayOf(CHANNEL_TAG, channelAction.channelId), - arrayOf(EXPIRES_TAG, channelAction.expiresAt.toString()), - ), - content = "", - ) - - /** The channel action [tags] authorise, or null for a payment, an unknown action, or tags that disagree. */ - fun readChannelAction(tags: Array>): ChannelAction? { - fun value(name: String): String? = tags.firstOrNull { it.size >= 2 && it[0] == name }?.get(1) - val action = value(ACTION_TAG)?.takeIf { it == CLOSE || it == FORCE_CLOSE } ?: return null - val parts = value(D_TAG)?.split(':') ?: return null - if (parts.size != 4 || parts[2] != action) return null - val chain = GroupWalletStatementEvent.chainNamed(parts[0]) ?: return null - val wallet = parts[1].toLongOrNull() ?: return null - val channelId = value(CHANNEL_TAG)?.takeIf { it.length == 64 && it == parts[3] } ?: return null - val expires = value(EXPIRES_TAG)?.toLongOrNull() ?: return null - return ChannelAction(action, chain, wallet, channelId, expires) - } - - /** - * Buying [amountSat] of inbound liquidity for [channelId] from the LSP, by splicing the channel, for - * at most [maxFeeSat] in fees -- our share of the splice's mining fee and the purchase's own, mining - * and service, together -- until [expiresAt] (epoch seconds). The fee comes out of the group's - * balance in the channel. [id] tells two purchases for one channel apart. - */ - data class BuyLiquidity( - val chain: Chain, - val wallet: Long, - val channelId: String, - val amountSat: Long, - val maxFeeSat: Long, - val expiresAt: Long, - val id: String, - ) - - fun template(buy: BuyLiquidity, createdAt: Long = Clock.System.now().epochSeconds): EventTemplate<*> = - EventTemplate( - createdAt = createdAt, - kind = KIND, - tags = arrayOf( - arrayOf(D_TAG, "${GroupLightningWalletStatementEvent.identifier(buy.chain, buy.wallet)}:$BUY_LIQUIDITY:${buy.channelId}:${buy.id}"), - arrayOf(ACTION_TAG, BUY_LIQUIDITY), - arrayOf(CHANNEL_TAG, buy.channelId), - arrayOf(AMOUNT_TAG, buy.amountSat.toString()), - arrayOf(MAX_FEE_TAG, buy.maxFeeSat.toString()), - arrayOf(EXPIRES_TAG, buy.expiresAt.toString()), - arrayOf(ID_TAG, buy.id), - ), - content = "", - ) - - /** The liquidity purchase [tags] authorise, or null for any other action, or tags that disagree. */ - fun readBuyLiquidity(tags: Array>): BuyLiquidity? { - fun value(name: String): String? = tags.firstOrNull { it.size >= 2 && it[0] == name }?.get(1) - if (value(ACTION_TAG) != BUY_LIQUIDITY) return null - val parts = value(D_TAG)?.split(':') ?: return null - if (parts.size != 5 || parts[2] != BUY_LIQUIDITY) return null - val chain = GroupWalletStatementEvent.chainNamed(parts[0]) ?: return null - val wallet = parts[1].toLongOrNull() ?: return null - val channelId = value(CHANNEL_TAG)?.takeIf { it.length == 64 && it == parts[3] } ?: return null - val id = value(ID_TAG)?.takeIf { it.isNotEmpty() && it == parts[4] } ?: return null - val amount = value(AMOUNT_TAG)?.toLongOrNull()?.takeIf { it > 0 } ?: return null - val maxFee = value(MAX_FEE_TAG)?.toLongOrNull()?.takeIf { it >= 0 } ?: return null - val expires = value(EXPIRES_TAG)?.toLongOrNull() ?: return null - return BuyLiquidity(chain, wallet, channelId, amount, maxFee, expires, id) - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/lightning/GroupLightningEvents.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/lightning/GroupLightningEvents.kt deleted file mode 100644 index 4a2d793b..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/lightning/GroupLightningEvents.kt +++ /dev/null @@ -1,90 +0,0 @@ -package mobi.giza.compose.nostr.lightning - -import com.vitorpamplona.quartz.nip01Core.core.Kind - -/** - * The nostr kinds a group Lightning wallet is carried on: its Iceberg key - * ceremony, its two group-signed statements, and the traffic between the - * operator's node and the members' co-signers. See - * `docs/group-lightning-wallet.md`. - * - * These are **rumor** kinds, like every other family here: each one only ever - * exists as a Marmot inner event, MLS-encrypted to the room, and none is ever - * broadcast to a relay. The replaceable semantics the 3xxxx range implies never - * apply. - * - * ``` - * proposer --[ 30350 ceremony proposal ]-> everyone "let's make a t-of-n Iceberg key" - * participant --[ 30351 DKG round 1 ]-> everyone commitments to seed contributions - * participant --[ 30352 DKG round 2 ]-> everyone contributions, each encrypted to its holder - * participant --[ 30353 DKG round 3 ]-> everyone public share + transcript signature - * anyone --[ 30354 ceremony failure ]-> everyone abort + blame - * group --[ 30355 wallet statement ] FROST-signed, never broadcast - * group --[ 30356 operator statement] FROST-signed, never broadcast - * opener --[ 30357 node seed ]-> each participant, encrypted to them - * operator --[ 30358 signing request ]-> everyone - * participant --[ 30359 echo ]-> everyone (label, message hash) - * participant --[ 30360 nonce batch ]-> everyone round-one contributions - * participant --[ 30361 signature share ]-> everyone round two - * operator --[ 30362 snapshot ]-> everyone balance, channels, payments - * group --[ 30363 authorisation ] FROST-signed: pay, close, force-close, splice-out - * member --[ 30364 invoice request ]-> everyone - * operator --[ 30365 invoice ]-> everyone - * old operator--[ 30366 stopped ]-> everyone its last commitment numbers - * ``` - * - * ### Why 30350 - * - * This family was first reserved at 30333-30349, the run after the highest - * kinds then in use. The guarded-wallet family took 30333-30337 on the main - * branch while this one was being built, and the two met at the merge, where - * nothing would have failed: each reads the other's events by kind. Rumor kinds - * are never published and nothing had shipped, so this family moved to a fresh - * run past the guarded wallets' with room before it. The note on - * `FrostSigningEvents` asks the next family not to rely on routing to keep it - * apart from the others; `GroupLightningEventsTest` asserts both that none of it - * overlaps a kind the app uses and that it starts past all of them. - */ -object GroupLightningEvents { - val CEREMONY_PROPOSAL: Kind = 30350 - val DKG_ROUND_1: Kind = 30351 - val DKG_ROUND_2: Kind = 30352 - val DKG_ROUND_3: Kind = 30353 - val CEREMONY_FAILURE: Kind = 30354 - - val WALLET_STATEMENT: Kind = 30355 - val OPERATOR_STATEMENT: Kind = 30356 - val NODE_SEED: Kind = 30357 - - val SIGNING_REQUEST: Kind = 30358 - val ECHO: Kind = 30359 - val NONCE_BATCH: Kind = 30360 - val SIGNATURE_SHARE: Kind = 30361 - - val SNAPSHOT: Kind = 30362 - val AUTHORISATION: Kind = 30363 - val INVOICE_REQUEST: Kind = 30364 - val INVOICE: Kind = 30365 - val STOPPED: Kind = 30366 - - /** The Iceberg ceremony's kinds, for routing to its ritual manager. */ - val CEREMONY: Set = setOf(CEREMONY_PROPOSAL, DKG_ROUND_1, DKG_ROUND_2, DKG_ROUND_3, CEREMONY_FAILURE) - - /** The co-signing protocol's kinds, for routing to the co-signer. */ - val CO_SIGNING: Set = setOf(SIGNING_REQUEST, ECHO, NONCE_BATCH, SIGNATURE_SHARE) - - /** Everything the operator and the members tell each other outside the two protocols. */ - val WALLET_TRAFFIC: Set = setOf(NODE_SEED, SNAPSHOT, INVOICE_REQUEST, INVOICE, STOPPED) - - /** The three kinds the group signs with its FROST key, filed as `GroupSignedEvent`s. */ - val GROUP_SIGNED: Set = setOf(WALLET_STATEMENT, OPERATOR_STATEMENT, AUTHORISATION) - - /** - * What members' devices say to each other, as opposed to what the group signs. Never a chat - * line as it arrives: the manager that acts on one writes the line, if it is worth one - * (`docs/group-lightning-transcript.md`). - */ - val PROTOCOL: Set = CEREMONY + CO_SIGNING + WALLET_TRAFFIC - - val ALL: Set = PROTOCOL + GROUP_SIGNED -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/lightning/GroupLightningOperatorStatementEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/lightning/GroupLightningOperatorStatementEvent.kt deleted file mode 100644 index 943e8556..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/lightning/GroupLightningOperatorStatementEvent.kt +++ /dev/null @@ -1,60 +0,0 @@ -package mobi.giza.compose.nostr.lightning - -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.Kind -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import fr.acinq.bitcoin.Chain -import kotlin.time.Clock - -/** - * Who runs the group's Lightning node: kind 30356, FROST-signed, never broadcast - * (`docs/group-lightning-wallet.md`, Phase 7). - * - * The term is what every co-signer fences on. It only goes up, and a request from anyone but the - * newest term's operator is refused, so an old node that keeps running cannot sign anything -- which - * is the whole of "only one operator at a time" that does not depend on the old device behaving. - */ -object GroupLightningOperatorStatementEvent { - val KIND: Kind = GroupLightningEvents.OPERATOR_STATEMENT - - private const val D_TAG = "d" - private const val OPERATOR_TAG = "operator" - private const val TERM_TAG = "term" - private const val PREVIOUS_TAG = "previous" - - /** Written in place of a key when the operator steps down and nobody replaces them. */ - const val NOBODY = "none" - - data class Statement( - val chain: Chain, - val wallet: Long, - /** The operator's nostr key, or null when the statement names nobody. */ - val operator: HexKey?, - val term: Long, - val previous: HexKey?, - ) - - fun template(statement: Statement, createdAt: Long = Clock.System.now().epochSeconds): EventTemplate<*> = - EventTemplate( - createdAt = createdAt, - kind = KIND, - tags = buildList { - add(arrayOf(D_TAG, GroupLightningWalletStatementEvent.identifier(statement.chain, statement.wallet))) - add(arrayOf(OPERATOR_TAG, statement.operator ?: NOBODY)) - add(arrayOf(TERM_TAG, statement.term.toString())) - statement.previous?.let { add(arrayOf(PREVIOUS_TAG, it)) } - }.toTypedArray(), - content = "", - ) - - fun read(tags: Array>): Statement? { - fun value(name: String): String? = tags.firstOrNull { it.size >= 2 && it[0] == name }?.get(1) - val d = value(D_TAG) ?: return null - val chainName = d.substringBefore(':', "").takeIf { it.isNotEmpty() } ?: return null - val chain = mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent.chainNamed(chainName) ?: return null - val wallet = d.substringAfter(':', "").toLongOrNull() ?: return null - val term = value(TERM_TAG)?.toLongOrNull()?.takeIf { it >= 1 } ?: return null - val operator = value(OPERATOR_TAG) ?: return null - return Statement(chain, wallet, operator.takeIf { it != NOBODY }, term, value(PREVIOUS_TAG)) - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/lightning/GroupLightningWalletStatementEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/lightning/GroupLightningWalletStatementEvent.kt deleted file mode 100644 index 5666deae..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/lightning/GroupLightningWalletStatementEvent.kt +++ /dev/null @@ -1,107 +0,0 @@ -package mobi.giza.compose.nostr.lightning - -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.Kind -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import fr.acinq.bitcoin.Chain -import kotlin.time.Clock - -/** - * The group's statement that it keeps a Lightning wallet: kind 30355, FROST-signed by the room through - * the ordinary proposal flow, never broadcast (`docs/group-lightning-wallet.md`, Phase 6). - * - * It binds together everything a co-signer checks before it answers for a channel: which onchain wallet - * the Lightning wallet closes to, which Iceberg key funds its channels and who holds it, which node the - * wallet's seed produces, which LSP the node opens channels with, and the policy that bounds what the - * node can put at risk. Like the onchain statement it is a record that the group agreed, and every - * value a reader can recompute it recomputes rather than believes. - */ -object GroupLightningWalletStatementEvent { - val KIND: Kind = GroupLightningEvents.WALLET_STATEMENT - - private const val D_TAG = "d" - private const val CHAIN_TAG = "chain" - private const val WALLET_TAG = "wallet" - private const val ONCHAIN_TAG = "onchain" - private const val ICEBERG_TAG = "iceberg" - private const val PARTICIPANTS_TAG = "participants" - private const val NODE_TAG = "node" - private const val LSP_TAG = "lsp" - private const val POLICY_TAG = "policy" - - /** - * What bounds the node, in sats. [inFlightCapSat] is the most that can be in HTLCs at once, which is - * the most the node seed is ever worth (the trust table in the plan); [commitmentFeeAllowanceSat] is - * how far our balance may fall to commitment fees between authorisations; [maxLiquidityFeeSat] is the - * most the LSP may take from one incoming payment to open or grow a channel. - */ - data class Policy(val inFlightCapSat: Long, val commitmentFeeAllowanceSat: Long, val maxLiquidityFeeSat: Long) { - companion object { - val DEFAULT = Policy(inFlightCapSat = 200_000, commitmentFeeAllowanceSat = 5_000, maxLiquidityFeeSat = 10_000) - } - } - - data class Statement( - val chain: Chain, - val wallet: Long, - /** The onchain account on [chain] the wallet closes to. */ - val onchainAccount: Long, - /** The Iceberg group key, compressed hex. */ - val icebergKey: HexKey, - val ceremonyId: String, - val threshold: Int, - /** The Iceberg participants' nostr keys, sorted. */ - val participants: List, - val nodeId: HexKey, - val lspNodeId: HexKey, - val policy: Policy, - ) - - /** One statement per network and wallet number, the newest winning. */ - fun identifier(chain: Chain, wallet: Long): String = "${GroupWalletStatementEvent.chainName(chain)}:$wallet" - - fun template(statement: Statement, createdAt: Long = Clock.System.now().epochSeconds): EventTemplate<*> = - EventTemplate( - createdAt = createdAt, - kind = KIND, - tags = arrayOf( - arrayOf(D_TAG, identifier(statement.chain, statement.wallet)), - arrayOf(CHAIN_TAG, GroupWalletStatementEvent.chainName(statement.chain)), - arrayOf(WALLET_TAG, statement.wallet.toString()), - arrayOf(ONCHAIN_TAG, statement.onchainAccount.toString()), - arrayOf(ICEBERG_TAG, statement.icebergKey, statement.ceremonyId, statement.threshold.toString()), - arrayOf(PARTICIPANTS_TAG) + statement.participants.toTypedArray(), - arrayOf(NODE_TAG, statement.nodeId), - arrayOf(LSP_TAG, statement.lspNodeId), - arrayOf(POLICY_TAG, statement.policy.inFlightCapSat.toString(), statement.policy.commitmentFeeAllowanceSat.toString(), statement.policy.maxLiquidityFeeSat.toString()), - ), - content = "", - ) - - /** The statement's fields, or null when any is missing or unreadable. Nothing is verified here. */ - fun read(tags: Array>): Statement? { - fun tag(name: String): Array? = tags.firstOrNull { it.isNotEmpty() && it[0] == name } - val chain = tag(CHAIN_TAG)?.getOrNull(1)?.let(GroupWalletStatementEvent::chainNamed) ?: return null - val wallet = tag(WALLET_TAG)?.getOrNull(1)?.toLongOrNull() ?: return null - if (tag(D_TAG)?.getOrNull(1) != identifier(chain, wallet)) return null - val iceberg = tag(ICEBERG_TAG)?.takeIf { it.size >= 4 } ?: return null - val policy = tag(POLICY_TAG)?.takeIf { it.size >= 4 }?.let { p -> - Policy(p[1].toLongOrNull() ?: return null, p[2].toLongOrNull() ?: return null, p[3].toLongOrNull() ?: return null) - } ?: return null - val participants = tag(PARTICIPANTS_TAG)?.drop(1)?.takeIf { it.isNotEmpty() } ?: return null - if (participants != participants.sorted()) return null - return Statement( - chain = chain, - wallet = wallet, - onchainAccount = tag(ONCHAIN_TAG)?.getOrNull(1)?.toLongOrNull() ?: return null, - icebergKey = iceberg[1], - ceremonyId = iceberg[2], - threshold = iceberg[3].toIntOrNull() ?: return null, - participants = participants, - nodeId = tag(NODE_TAG)?.getOrNull(1) ?: return null, - lspNodeId = tag(LSP_TAG)?.getOrNull(1) ?: return null, - policy = policy, - ) - } -} 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 adfbedec..ce7a228d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -106,11 +106,6 @@ interface ChatRepository { */ suspend fun groupWallet(chatRoomId: String, chain: Chain): GroupWallet? - /** - * Who holds a share of the key of the Lightning wallet this group uses on [chain], and its node's - * seed: the people a removal leaves able to grief it until a new wallet replaces it (Phase 14). - */ - suspend fun lightningParticipants(chatRoomId: String, chain: Chain): Set = emptySet() /** * The account this group *would* open on [chain], whether or not it has, or diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/FrostSigningRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/FrostSigningRepository.kt index cc6c2bf7..69af4af4 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/FrostSigningRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/FrostSigningRepository.kt @@ -3,7 +3,6 @@ package mobi.giza.compose.repository import mobi.giza.compose.database.model.GroupTransaction import mobi.giza.compose.managers.GroupWalletDerivation import mobi.giza.compose.wallet.GroupSpend -import mobi.giza.compose.wallet.lightning.GroupSweep import fr.acinq.bitcoin.Chain import fr.acinq.bitcoin.OutPoint import fr.acinq.bitcoin.psbt.Psbt @@ -258,8 +257,6 @@ interface FrostSigningRepository { /** The spend a transaction session signs, checked again; null for anything else. */ suspend fun checkedSpend(sessionId: String): GroupSpend.Checked? - /** The sweep a sweep session signs, checked again; null for anything else. */ - suspend fun checkedSweep(sessionId: String): GroupSweep.Checked? = null /** The coins the room's open spends are already spending. */ suspend fun reservedOutPoints(chatRoomId: String): Set diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupLightningRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupLightningRepository.kt deleted file mode 100644 index 9ebb62e7..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupLightningRepository.kt +++ /dev/null @@ -1,152 +0,0 @@ -package mobi.giza.compose.repository - -import mobi.giza.compose.database.model.FrostSigningSession -import mobi.giza.compose.database.model.IcebergKeySession -import mobi.giza.compose.database.model.GroupLightningInvoiceRow -import mobi.giza.compose.database.model.GroupLightningPaymentRow -import mobi.giza.compose.managers.GroupLightningOperatorManager -import mobi.giza.compose.managers.GroupLightningReports -import mobi.giza.compose.managers.GroupLightningWalletManager -import mobi.giza.compose.nostr.lightning.GroupLightningAuthorisationEvent -import mobi.giza.compose.database.model.IcebergParticipantMessage -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.database.model.types.IcebergApprovalStep -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.Chain -import mobi.giza.compose.wallet.lightning.GroupSweep -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.flowOf - -/** - * Reads, opens and approves a group's Lightning wallet: for now, the Iceberg ceremony its key comes - * from (`docs/group-lightning-wallet.md`, Phase 5). Advancing a ceremony is the inbound path's job, - * except that a step waiting on this device's owner waits until [approveCeremony]. - */ -interface GroupLightningRepository { - fun observeCeremony(sessionId: String): Flow - - fun observeCeremonies(chatRoomId: String): Flow> - - suspend fun ceremonyMessages(sessionId: String): List - - suspend fun pendingApproval(session: IcebergKeySession): IcebergApprovalStep? - - /** The thresholds a ceremony in [chatRoomId] could use, smallest first; empty when the room cannot have one. */ - suspend fun ceremonyThresholds(chatRoomId: String): List - - /** How many people hold the onchain wallet's key, and so would be in a ceremony; 0 for a room without one. */ - suspend fun keyHolderCount(chatRoomId: String): Int - - /** Whether [chatRoomId] has opened the onchain wallet a Lightning wallet on [chain] would close to. */ - suspend fun hasOnchainWallet(chatRoomId: String, chain: Chain): Boolean - - suspend fun proposeCeremony(localChatRoom: LocalChatRoom, userPublicKey: HexKey, nostrPrivateKey: ByteArray, threshold: Int, chain: Chain): IcebergKeySession - - suspend fun approveCeremony(localChatRoom: LocalChatRoom, sessionId: String, step: IcebergApprovalStep, nostrPrivateKey: ByteArray) - - /** Takes whatever steps the ceremony can take now, for one a gate of an earlier build left waiting. */ - suspend fun resumeCeremony(localChatRoom: LocalChatRoom, sessionId: String, nostrPrivateKey: ByteArray) - - /** Ends the ceremony for everyone in it; false when it is already over. */ - suspend fun abandonCeremony(localChatRoom: LocalChatRoom, sessionId: String): Boolean - - /** The newest completed Lightning wallet key this device holds a share of, or null. */ - suspend fun completedCeremony(chatRoomId: String): IcebergKeySession? - - /** The wallet the room uses on [chain] now -- the highest-numbered it agreed -- as this device can check it, or null. */ - suspend fun lightningWallet(chatRoomId: String, chain: Chain): GroupLightningWalletManager.Wallet? - - /** The wallets a re-key left behind on [chain], lowest number first: their channels are still to close. */ - suspend fun earlierWallets(chatRoomId: String, chain: Chain): List - - /** The participants of [wallet] who have left its room, and still hold a share of its key and its seed. */ - suspend fun departed(wallet: GroupLightningWalletManager.Wallet): List - - /** Whether the room has a completed Lightning wallet key no wallet uses yet, for a new wallet to open under. */ - suspend fun hasUnusedKey(chatRoomId: String, chain: Chain): Boolean - - /** That key itself, the newest of them, or null: what the chat's standing notice names. */ - suspend fun unusedKey(chatRoomId: String, chain: Chain): IcebergKeySession? - - suspend fun operator(chatRoomId: String, chain: Chain, wallet: Long): GroupLightningOperatorManager.Operator? - - /** The LSP a Lightning wallet on [chain] opens channels with, or null for a network with none. */ - fun lspNodeId(chain: Chain): HexKey? - - suspend fun proposeWallet(localChatRoom: LocalChatRoom, userPublicKey: HexKey, nostrPrivateKey: ByteArray, chain: Chain): FrostSigningSession - - suspend fun nominateSelf(localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain, wallet: Long): FrostSigningSession - - suspend fun stepDown(localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain, wallet: Long): FrostSigningSession - - /** The operator's newest snapshot of the wallet on [chain], each channel checked against this device's ledger. */ - fun observeReport(chatRoomId: String, chain: Chain, wallet: Long): Flow - - /** Every payment any snapshot has reported, newest first. */ - fun observePayments(chatRoomId: String, chain: Chain, wallet: Long): Flow> - - /** Asks the operator's node for an invoice; returns the request id its answer will carry. */ - suspend fun requestInvoice(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, amountMsat: Long?, description: String): String - - /** The operator's invoice for [requestId], once it has arrived and been checked. */ - fun observeInvoice(chatRoomId: String, chain: Chain, wallet: Long, requestId: String): Flow - - /** Proposes [pay] to the group; the operator's node pays it once a quorum signs. */ - suspend fun proposePayment(localChatRoom: LocalChatRoom, userPublicKey: HexKey, pay: GroupLightningAuthorisationEvent.Pay): FrostSigningSession - - /** Proposes [buy] to the group; the operator's node buys the liquidity once a quorum signs. */ - suspend fun proposeLiquidity(localChatRoom: LocalChatRoom, userPublicKey: HexKey, buy: GroupLightningAuthorisationEvent.BuyLiquidity): FrostSigningSession - - /** Proposes closing [channelId] to the onchain wallet, or force-closing it when [force]. */ - suspend fun proposeClose(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelId: String, force: Boolean): FrostSigningSession - - /** Proposes closing every one of [channelIds] to the onchain wallet, in one signing session. */ - suspend fun proposeCloseAll(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelIds: List): FrostSigningSession - - /** What closed channels left the group that no sweep spends yet, from [report]. */ - suspend fun unswept(chatRoomId: String, report: GroupLightningReports.Report?): List - - /** Proposes sweeping [inputs] into the onchain wallet. */ - suspend fun proposeSweep(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, inputs: List): FrostSigningSession - - companion object { - /** - * For previews and for screens that only read: every flow empty, every read empty or - * null, and every proposal refused, since there is no room behind it to propose in. - */ - val NO_OP_GROUP_LIGHTNING_REPOSITORY: GroupLightningRepository = object : GroupLightningRepository { - override fun observeCeremony(sessionId: String): Flow = flowOf(null) - override fun observeCeremonies(chatRoomId: String): Flow> = flowOf(emptyList()) - override suspend fun ceremonyMessages(sessionId: String): List = emptyList() - override suspend fun pendingApproval(session: IcebergKeySession): IcebergApprovalStep? = null - override suspend fun ceremonyThresholds(chatRoomId: String): List = emptyList() - override suspend fun keyHolderCount(chatRoomId: String): Int = 0 - override suspend fun hasOnchainWallet(chatRoomId: String, chain: Chain): Boolean = false - override suspend fun proposeCeremony(localChatRoom: LocalChatRoom, userPublicKey: HexKey, nostrPrivateKey: ByteArray, threshold: Int, chain: Chain): IcebergKeySession = error("No room to propose in") - override suspend fun approveCeremony(localChatRoom: LocalChatRoom, sessionId: String, step: IcebergApprovalStep, nostrPrivateKey: ByteArray) = Unit - override suspend fun resumeCeremony(localChatRoom: LocalChatRoom, sessionId: String, nostrPrivateKey: ByteArray) = Unit - override suspend fun abandonCeremony(localChatRoom: LocalChatRoom, sessionId: String): Boolean = false - override suspend fun completedCeremony(chatRoomId: String): IcebergKeySession? = null - override suspend fun lightningWallet(chatRoomId: String, chain: Chain): GroupLightningWalletManager.Wallet? = null - override suspend fun earlierWallets(chatRoomId: String, chain: Chain): List = emptyList() - override suspend fun departed(wallet: GroupLightningWalletManager.Wallet): List = emptyList() - override suspend fun hasUnusedKey(chatRoomId: String, chain: Chain): Boolean = false - override suspend fun unusedKey(chatRoomId: String, chain: Chain): IcebergKeySession? = null - override suspend fun operator(chatRoomId: String, chain: Chain, wallet: Long): GroupLightningOperatorManager.Operator? = null - override fun lspNodeId(chain: Chain): HexKey? = null - override suspend fun proposeWallet(localChatRoom: LocalChatRoom, userPublicKey: HexKey, nostrPrivateKey: ByteArray, chain: Chain): FrostSigningSession = error("No room to propose in") - override suspend fun nominateSelf(localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain, wallet: Long): FrostSigningSession = error("No room to propose in") - override suspend fun stepDown(localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain, wallet: Long): FrostSigningSession = error("No room to propose in") - override fun observeReport(chatRoomId: String, chain: Chain, wallet: Long): Flow = flowOf(null) - override fun observePayments(chatRoomId: String, chain: Chain, wallet: Long): Flow> = flowOf(emptyList()) - override suspend fun requestInvoice(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, amountMsat: Long?, description: String): String = error("No room to ask in") - override fun observeInvoice(chatRoomId: String, chain: Chain, wallet: Long, requestId: String): Flow = flowOf(null) - override suspend fun proposePayment(localChatRoom: LocalChatRoom, userPublicKey: HexKey, pay: GroupLightningAuthorisationEvent.Pay): FrostSigningSession = error("No room to propose in") - override suspend fun proposeLiquidity(localChatRoom: LocalChatRoom, userPublicKey: HexKey, buy: GroupLightningAuthorisationEvent.BuyLiquidity): FrostSigningSession = error("No room to propose in") - override suspend fun proposeClose(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelId: String, force: Boolean): FrostSigningSession = error("No room to propose in") - override suspend fun proposeCloseAll(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelIds: List): FrostSigningSession = error("No room to propose in") - override suspend fun unswept(chatRoomId: String, report: GroupLightningReports.Report?): List = emptyList() - override suspend fun proposeSweep(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, inputs: List): FrostSigningSession = error("No room to propose in") - } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt index 62a35da7..116691c2 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt @@ -8,14 +8,12 @@ import com.vitorpamplona.quartz.nip01Core.core.HexKey import mobi.giza.compose.nostr.wallet.MemberWalletCertificateEvent import mobi.giza.compose.nostr.wallet.MemberWalletRequestEvent import mobi.giza.compose.managers.SharedKeyDerivation +import mobi.giza.compose.managers.WalletRefusal +import mobi.giza.compose.nostr.RetiredKinds import mobi.giza.compose.nostr.frost.GroupKeyStateEvent -import mobi.giza.compose.nostr.lightning.GroupLightningAuthorisationEvent -import mobi.giza.compose.nostr.lightning.GroupLightningOperatorStatementEvent -import mobi.giza.compose.nostr.lightning.GroupLightningWalletStatementEvent import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent import fr.acinq.bitcoin.Satoshi -import fr.acinq.lightning.payment.Bolt11Invoice /** * An event a group is being asked to sign, said in words. @@ -111,56 +109,6 @@ object ProposedEvent { } ?: "A wallet statement this device cannot read" ) - // The group keeping a Lightning wallet. What a member agrees to is a key, a node and an LSP - // holding money under a policy, so the summary names the network, the threshold and the cap - // on what can be in flight at once. - GroupLightningWalletStatementEvent.KIND -> Summary( - label = "Open a Lightning wallet", - detail = GroupLightningWalletStatementEvent.read(event.tags)?.let { statement -> - "On ${GroupWalletStatementEvent.chainName(statement.chain)}, ${statement.threshold} of ${statement.participants.size} to sign, " + - "at most ${statement.policy.inFlightCapSat} sats in flight" - } ?: "A Lightning wallet statement this device cannot read" - ) - - GroupLightningOperatorStatementEvent.KIND -> Summary( - label = "Choose who runs the Lightning wallet", - detail = GroupLightningOperatorStatementEvent.read(event.tags)?.let { statement -> - statement.operator?.let { "Term ${statement.term}: ${it.take(8)} runs the node" } ?: "Term ${statement.term}: nobody runs the node" - } ?: "An operator statement this device cannot read" - ) - - // A payment from the Lightning wallet. What a member agrees to is money leaving, so the - // summary leads with the amount and the most the fee can be, then who is paid and for what as - // the invoice says; the payee is a node key, shortened, since nobody checks one by eye. - GroupLightningAuthorisationEvent.KIND -> GroupLightningAuthorisationEvent.read(event.tags)?.let { pay -> - val invoice = runCatching { Bolt11Invoice.read(pay.invoice).get() }.getOrNull() - Summary( - label = "Pay ${Satoshi(pay.amountMsat / 1000).grouped()} sats", - detail = buildString { - append("To ${invoice?.nodeId?.toString()?.take(16) ?: "a node"}, with a fee of at most ${Satoshi(pay.maxFeeMsat / 1000).grouped()} sats") - invoice?.description?.takeIf { it.isNotBlank() }?.let { append(", for \"$it\"") } - }, - ) - } ?: GroupLightningAuthorisationEvent.readChannelAction(event.tags)?.let { action -> - // Closing moves the channel's money to the onchain wallet; forcing it does so slowly, at a - // cost, and is for when the LSP has gone. The summary says which, because that is the choice. - if (action.action == GroupLightningAuthorisationEvent.FORCE_CLOSE) Summary( - label = "Force-close a Lightning channel", - detail = "Channel ${action.channelId.take(16)}: the group's own commitment is published, and its money reaches the onchain wallet after a delay", - ) else Summary( - label = "Close a Lightning channel", - detail = "Channel ${action.channelId.take(16)}: its money goes to the group's onchain wallet", - ) - } ?: GroupLightningAuthorisationEvent.readBuyLiquidity(event.tags)?.let { buy -> - // Buying liquidity spends the group's money on room to be paid. A signer weighs how much - // room, what it costs at most, and that the LSP may take back what is unused after a year - // (docs/group-lightning-liquidity.md, Phase 4). - Summary( - label = "Add ${Satoshi(buy.amountSat).grouped()} sats of inbound liquidity", - detail = "Channel ${buy.channelId.take(16)}: for at most ${Satoshi(buy.maxFeeSat).grouped()} sats in fees, from the group's balance. The LSP may reclaim what is unused after a year", - ) - } ?: Summary(label = "Authorise the Lightning wallet", detail = "An authorisation this device cannot read") - // The group agreeing to guard one member's wallet. What a signer weighs // is whose wallet, and what the group can do with it: take any coin that // has sat for its leaf's delay, alongside every group above it after @@ -205,6 +153,11 @@ object ProposedEvent { ?: "A member wallet this device cannot read" ) + // A Bennu wallet's: declined on arrival, and said as what it is rather than + // as a number. docs/giza-wallet-removal.md. + in RetiredKinds.WALLET, in RetiredKinds.GROUP_LIGHTNING -> + Summary(label = "A wallet's to sign", detail = WalletRefusal.REASON) + else -> Summary(label = "Event of kind ${event.kind}", detail = event.content) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedSpend.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedSpend.kt index e174d15c..8111f073 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedSpend.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedSpend.kt @@ -1,7 +1,8 @@ package mobi.giza.compose.text +import mobi.giza.compose.managers.WalletRefusal + import mobi.giza.compose.wallet.GroupSpend -import mobi.giza.compose.wallet.lightning.GroupSweep import fr.acinq.bitcoin.Bitcoin import fr.acinq.bitcoin.ByteVector import fr.acinq.bitcoin.Chain @@ -53,16 +54,10 @@ object ProposedSpend { fun addressOf(script: ByteVector, chain: Chain): String = Bitcoin.addressFromPublicKeyScript(chain.chainHash, script.toByteArray()).right ?: script.toHex() - /** A sweep from the Lightning wallet: what reaches the onchain wallet, which is all a member is agreeing to. */ - fun summarize(sweep: GroupSweep.Checked): ProposedEvent.Summary = - ProposedEvent.Summary( - label = "Sweep into the group's onchain wallet", - detail = "${sweep.amount.grouped()} sats a closed Lightning channel left the group, after ${sweep.fee.grouped()} sats in fees" - ) - - val UNREADABLE_SWEEP = ProposedEvent.Summary( + /** A sweep from a Bennu group's Lightning wallet, which this device declined on arrival. */ + val SWEEP = ProposedEvent.Summary( label = "Sweep into the group's onchain wallet", - detail = "A sweep this device cannot check" + detail = WalletRefusal.REASON ) /** What a summary says for a spend this device cannot check: nothing a member could sign on. */ diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt index 583bf1cc..45ac06e2 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomMessagingScreen.kt @@ -1,8 +1,5 @@ package mobi.giza.compose.ui.composable -import mobi.giza.compose.ui.composable.navigation.routes.IcebergCeremonyRoute -import mobi.giza.compose.ui.composable.navigation.routes.GroupLightningWalletRoute -import mobi.giza.compose.repository.GroupLightningRepository import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box @@ -51,7 +48,6 @@ import mobi.giza.compose.repository.FrostSigningRepository import mobi.giza.compose.repository.NostrRepository import mobi.giza.compose.ui.composable.navigation.routes.ChatRoomDetailRoute import mobi.giza.compose.ui.composable.navigation.routes.DkgRitualRoute -import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute import mobi.giza.compose.ui.composable.navigation.routes.ProposalListRoute import mobi.giza.compose.ui.composable.navigation.routes.proposalDestination import mobi.giza.compose.ui.composable.navigation.routes.Route @@ -90,7 +86,6 @@ fun ChatRoomMessagingScreen( chatRepository: ChatRepository, frostSigningRepository: FrostSigningRepository, dkgRepository: DkgRepository, - lightningRepository: GroupLightningRepository, onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, onNavigateToRoute: (Route) -> Unit, /** @@ -137,7 +132,6 @@ fun ChatRoomMessagingScreen( chatRepository = chatRepository, frostSigningRepository = frostSigningRepository, dkgRepository = dkgRepository, - lightningRepository = lightningRepository, ) ) @@ -191,23 +185,6 @@ fun ChatRoomMessagingScreen( ) ) }, - onOpenIcebergCeremony = { sessionId -> - onNavigateToRoute.invoke( - IcebergCeremonyRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - ) - }, - onOpenLightningWallet = { - onNavigateToRoute.invoke( - GroupLightningWalletRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - ) - ) - }, onOpenSigning = { sessionId -> onNavigateToRoute.invoke( proposalDestination( @@ -513,7 +490,6 @@ private fun ChatRoomMessagingScreenPreview() { chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, dkgRepository = DkgRepository.NO_OP_DKG_REPOSITORY, - lightningRepository = GroupLightningRepository.NO_OP_GROUP_LIGHTNING_REPOSITORY, onNavigateToRouteAndPopUpInclusive = {}, onNavigateToRoute = {}, onNavigateBack = {}, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/FrostSigningScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/FrostSigningScreen.kt index 76d10b0e..8b011060 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/FrostSigningScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/FrostSigningScreen.kt @@ -1,5 +1,7 @@ package mobi.giza.compose.ui.composable +import mobi.giza.compose.managers.WalletRefusal + import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row @@ -16,7 +18,6 @@ import androidx.compose.material.icons.filled.Block import androidx.compose.material.icons.filled.Campaign import androidx.compose.material.icons.filled.CheckCircle import androidx.compose.material.icons.filled.Draw -import androidx.compose.material.icons.filled.ErrorOutline import androidx.compose.material.icons.filled.HourglassEmpty import androidx.compose.material.icons.filled.RadioButtonUnchecked import androidx.compose.material3.Button @@ -41,7 +42,6 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import mobi.giza.compose.resources.Res import mobi.giza.compose.resources.ask_again @@ -70,10 +70,7 @@ import mobi.giza.compose.resources.signed_their_part import mobi.giza.compose.resources.signers_have_not_signed import mobi.giza.compose.resources.spend_from_the_group_s_wallet import mobi.giza.compose.resources.spends_s_of_the_group_s_coins -import mobi.giza.compose.resources.sweep_into_the_group_s_onchain_wallet -import mobi.giza.compose.resources.sweeps_s_outputs_a_closed_channel_left_the_group import mobi.giza.compose.resources.this_spend_could_not_be_checked -import mobi.giza.compose.resources.this_sweep_could_not_be_checked import mobi.giza.compose.database.model.ChatRoom import mobi.giza.compose.database.model.FrostSigningSession import mobi.giza.compose.database.model.intermdiate.LocalChatRoom @@ -97,7 +94,6 @@ import mobi.giza.compose.ui.theme.spacing import mobi.giza.compose.ui.view.model.FrostSigningViewModel import mobi.giza.compose.ui.view.state.FrostSigningUIState import mobi.giza.compose.wallet.GroupSpend -import mobi.giza.compose.wallet.lightning.GroupSweep import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import org.jetbrains.compose.resources.stringResource @@ -204,7 +200,8 @@ fun FrostSigningScreen( val readable = state.items.isNotEmpty() && if (isSpend) { state.spend?.inputs?.size == state.items.size } else if (isSweep) { - state.sweep?.inputs?.size == state.items.size + // Declined on arrival: a sweep is never put to this device. + false } else { proposed.size == state.items.size } @@ -226,7 +223,7 @@ fun FrostSigningScreen( ) { when { isSpend -> WhatIsBeingSpent(state.spend) - isSweep -> WhatIsBeingSwept(state.sweep) + isSweep -> Text(text = WalletRefusal.REASON, color = MaterialTheme.colorScheme.error) else -> WhatIsBeingSigned(proposed, state.items.size) } @@ -524,36 +521,6 @@ private fun WhatIsBeingSigned(events: List, expected: Int) { } } -/** - * The spend, every output of it: what leaves the group and where to, what comes - * back as change, and the fee. The batch rule holds with more force here -- a - * member who cannot see every output must not be able to approve one -- so - * every output is a row, change included, and nothing is behind a disclosure - * but the coins being spent, which are the group's own and were each checked - * against the wallet before this was drawn. - */ -/** A sweep: the address it pays, which is the group's own, and what reaches it. */ -@Composable -private fun WhatIsBeingSwept(sweep: GroupSweep.Checked?) { - if (sweep == null) { - Text(text = stringResource(Res.string.this_sweep_could_not_be_checked), color = MaterialTheme.colorScheme.error) - return - } - Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space200)) { - Text(text = stringResource(Res.string.sweep_into_the_group_s_onchain_wallet), style = MaterialTheme.typography.labelMedium) - Text(text = stringResource(Res.string.s_sats, sweep.amount.grouped()), style = MaterialTheme.typography.titleMedium) - Text( - text = stringResource(Res.string.fee_s_sats_at_s_sats_per_byte, sweep.fee.grouped(), sweep.feeratePerVbyte.toString()), - style = MaterialTheme.typography.bodyMedium - ) - Text( - text = stringResource(Res.string.sweeps_s_outputs_a_closed_channel_left_the_group, sweep.inputs.size.toString()), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } -} - @Composable private fun WhatIsBeingSpent(spend: GroupSpend.Checked?) { if (spend == null) { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupLightningLiquidityScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupLightningLiquidityScreen.kt deleted file mode 100644 index fa0a5d9a..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupLightningLiquidityScreen.kt +++ /dev/null @@ -1,275 +0,0 @@ -package mobi.giza.compose.ui.composable - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.selection.toggleable -import androidx.compose.foundation.text.KeyboardOptions -import androidx.compose.foundation.text.input.TextFieldLineLimits -import androidx.compose.foundation.verticalScroll -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Bolt -import androidx.compose.material3.Button -import androidx.compose.material3.Card -import androidx.compose.material3.Checkbox -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.ModalBottomSheet -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Slider -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.material3.minimumInteractiveComponentSize -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.semantics.Role -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.input.ImeAction -import androidx.compose.ui.text.input.KeyboardType -import androidx.compose.ui.text.style.TextOverflow -import androidx.lifecycle.viewmodel.compose.viewModel -import mobi.giza.compose.resources.Res -import mobi.giza.compose.resources.add_liquidity -import mobi.giza.compose.resources.after_a_year_the_lsp_may_reclaim -import mobi.giza.compose.resources.ask_the_group -import mobi.giza.compose.resources.buying_liquidity_asks_the_group_to_sign -import mobi.giza.compose.resources.couldn_t_propose_this -import mobi.giza.compose.resources.current_liquidity_s_sats -import mobi.giza.compose.resources.duration -import mobi.giza.compose.resources.fee_limit_in_sats -import mobi.giza.compose.resources.i_understand -import mobi.giza.compose.resources.left_empty_s_sats -import mobi.giza.compose.resources.liquidity_is_an_initial_amount -import mobi.giza.compose.resources.liquidity_lets_the_group_receive_more -import mobi.giza.compose.resources.liquidity_to_add_s_sats -import mobi.giza.compose.resources.miner_fee -import mobi.giza.compose.resources.nobody_runs_this_wallet -import mobi.giza.compose.resources.one_year -import mobi.giza.compose.resources.plan_ahead_your_liquidity -import mobi.giza.compose.resources.priced_at_s_sat_vbyte_in_term_s -import mobi.giza.compose.resources.receive_a_payment_first_it_opens_the_channel -import mobi.giza.compose.resources.review_the_purchase -import mobi.giza.compose.resources.s_sats -import mobi.giza.compose.resources.sats -import mobi.giza.compose.resources.service_fee -import mobi.giza.compose.resources.the_channel_grows_from_s_to_s_sats -import mobi.giza.compose.resources.the_channel_holds_the_most_it_may_for_now -import mobi.giza.compose.resources.the_fee_is_a_quarter_of_the_amount_or_more -import mobi.giza.compose.resources.the_fee_is_more_than_the_group_s_balance -import mobi.giza.compose.resources.the_lsp_sells_none_of_these_amounts -import mobi.giza.compose.resources.the_operator_hasn_t_reported_what_the_lsp_sells -import mobi.giza.compose.resources.total -import mobi.giza.compose.repository.ChatRepository -import mobi.giza.compose.repository.GroupLightningRepository -import mobi.giza.compose.text.GroupedSats -import mobi.giza.compose.text.grouped -import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute -import mobi.giza.compose.ui.composable.navigation.routes.Route -import mobi.giza.compose.ui.composable.widgets.Decorative -import mobi.giza.compose.ui.composable.widgets.EmptyState -import mobi.giza.compose.ui.composable.widgets.ErrorState -import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator -import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState -import mobi.giza.compose.ui.composable.widgets.NavigateBackButton -import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition -import mobi.giza.compose.ui.composable.widgets.rememberNotifier -import mobi.giza.compose.ui.theme.readableContent -import mobi.giza.compose.ui.theme.spacing -import mobi.giza.compose.ui.view.model.GroupLightningLiquidityViewModel -import mobi.giza.compose.ui.view.state.GroupLightningLiquidityUIState -import mobi.giza.compose.wallet.GroupLightningRollout -import mobi.giza.compose.wallet.lightning.LiquidityPrice -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.Satoshi -import kotlin.math.roundToInt -import org.jetbrains.compose.resources.stringResource - -/** - * Asking the group to buy inbound liquidity, as Phoenix asks its owner (`docs/group-lightning-liquidity.md`, - * Phase 7): an amount on Phoenix's slider, its price worked out on this device, a review with the - * acknowledgement Phoenix asks for, and then a proposal rather than a purchase. The group signs it; the - * operator's node buys; every member's device checks the splice. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun GroupLightningLiquidityScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - chatRepository: ChatRepository, - lightningRepository: GroupLightningRepository, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val viewModel: GroupLightningLiquidityViewModel = viewModel( - factory = GroupLightningLiquidityViewModel.factory(activeUserPublicKey, chatRoomId, GroupLightningRollout.NETWORK, chatRepository, lightningRepository) - ) - LaunchedEffect(true) { viewModel.initiate() } - - val notify = rememberNotifier(rememberCoroutineScope()) - val couldNotPropose = stringResource(Res.string.couldn_t_propose_this) - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { Text(stringResource(Res.string.add_liquidity), maxLines = 1, overflow = TextOverflow.Ellipsis) }, - navigationIcon = { NavigateBackButton(onNavigateBack) } - ) - } - ) { padding -> - ScreenStateTransition(viewModel.uiState) { uiState -> - when (val state = uiState) { - GroupLightningLiquidityUIState.Loading -> LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding)) - - is GroupLightningLiquidityUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = state.message, onRetry = null) - - is GroupLightningLiquidityUIState.Unavailable -> EmptyState( - modifier = Modifier.padding(padding).readableContent(), - message = unavailableBecause(state.why), - icon = Icons.Default.Bolt, - ) - - is GroupLightningLiquidityUIState.Form -> LiquidityForm( - modifier = Modifier.padding(padding), - form = state, - viewModel = viewModel, - onAsk = { - viewModel.propose( - onSession = { sessionId -> onNavigateToRoute(FrostSigningRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, sessionId = sessionId)) }, - onFailure = { notify(couldNotPropose) }, - ) - }, - ) - } - } - } -} - -/** Why nothing can be asked for now, in a sentence; the wallet screen says the same where its button would be. */ -@Composable -internal fun unavailableBecause(why: LiquidityPrice.Availability): String = when (why) { - LiquidityPrice.Availability.NoOperator -> stringResource(Res.string.nobody_runs_this_wallet) - LiquidityPrice.Availability.NoPrices -> stringResource(Res.string.the_operator_hasn_t_reported_what_the_lsp_sells) - LiquidityPrice.Availability.NoChannel -> stringResource(Res.string.receive_a_payment_first_it_opens_the_channel) - LiquidityPrice.Availability.AtTheCap -> stringResource(Res.string.the_channel_holds_the_most_it_may_for_now) - LiquidityPrice.Availability.NothingSold -> stringResource(Res.string.the_lsp_sells_none_of_these_amounts) - is LiquidityPrice.Availability.Available -> "" -} - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -private fun LiquidityForm(modifier: Modifier, form: GroupLightningLiquidityUIState.Form, viewModel: GroupLightningLiquidityViewModel, onAsk: () -> Unit) { - val channel = form.available.channel - val offered = form.available.offered - val amount = viewModel.amountSat(form) - val price = viewModel.price(form) - val cap = viewModel.maxFeeSat(form) - val overBalance = price != null && price.totalSat > form.snapshot.spendableMsat / 1000 - Column( - modifier = modifier.readableContent().fillMaxSize().verticalScroll(rememberScrollState()).padding(MaterialTheme.spacing.screenMargin), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - ) { - Text(stringResource(Res.string.plan_ahead_your_liquidity), style = MaterialTheme.typography.titleMedium) - Text(stringResource(Res.string.liquidity_lets_the_group_receive_more), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) - Text(stringResource(Res.string.current_liquidity_s_sats, Satoshi(form.snapshot.inboundMsat / 1000).grouped()), style = MaterialTheme.typography.bodyLarge) - Text(stringResource(Res.string.liquidity_to_add_s_sats, Satoshi(amount).grouped()), style = MaterialTheme.typography.titleLarge) - // Phoenix's discrete slider, over the amounts the LSP sells and the channel has room for. - if (offered.size > 1) { - Slider( - value = viewModel.choice.toFloat(), - onValueChange = { viewModel.choice = it.roundToInt() }, - valueRange = 0f..offered.lastIndex.toFloat(), - steps = (offered.size - 2).coerceAtLeast(0), - ) - } - Text(stringResource(Res.string.the_channel_grows_from_s_to_s_sats, Satoshi(channel.capacitySat).grouped(), Satoshi(channel.capacitySat + amount).grouped()), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - - price?.let { p -> - Card(modifier = Modifier.fillMaxWidth()) { - Column(modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { - FeeLine(stringResource(Res.string.miner_fee), stringResource(Res.string.s_sats, Satoshi(p.miningSat).grouped())) - FeeLine(stringResource(Res.string.service_fee), stringResource(Res.string.s_sats, Satoshi(p.serviceSat).grouped())) - FeeLine(stringResource(Res.string.duration), stringResource(Res.string.one_year)) - Text(stringResource(Res.string.after_a_year_the_lsp_may_reclaim), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - HorizontalDivider() - FeeLine(stringResource(Res.string.total), stringResource(Res.string.s_sats, Satoshi(p.totalSat).grouped()), emphasised = true) - Text(stringResource(Res.string.priced_at_s_sat_vbyte_in_term_s, form.available.feeratePerByte.toString(), form.term.toString()), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - } - } - // Phoenix's two checks: a warning that does not stop anyone, and a balance that does. - if (LiquidityPrice.expensive(p, amount)) { - Text(stringResource(Res.string.the_fee_is_a_quarter_of_the_amount_or_more), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.error) - } - if (overBalance) { - Text(stringResource(Res.string.the_fee_is_more_than_the_group_s_balance), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.error) - } - } - - OutlinedTextField( - modifier = Modifier.fillMaxWidth(), - state = viewModel.maxFeeField, - outputTransformation = GroupedSats, - lineLimits = TextFieldLineLimits.SingleLine, - keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Done), - label = { Text(stringResource(Res.string.fee_limit_in_sats)) }, - suffix = { Text(stringResource(Res.string.sats)) }, - isError = cap == null, - supportingText = price?.let { p -> { Text(stringResource(Res.string.left_empty_s_sats, Satoshi(LiquidityPrice.defaultCap(p)).grouped())) } }, - ) - Text(stringResource(Res.string.buying_liquidity_asks_the_group_to_sign), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) - Button( - modifier = Modifier.fillMaxWidth(), - onClick = { viewModel.acknowledged = false; viewModel.reviewing = true }, - enabled = price != null && cap != null && !overBalance && !viewModel.isActionPending.value, - ) { - Text(stringResource(Res.string.review_the_purchase)) - } - } - - if (viewModel.reviewing) { - ModalBottomSheet(onDismissRequest = { viewModel.reviewing = false }) { - Column( - modifier = Modifier.readableContent().padding(MaterialTheme.spacing.screenMargin), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - ) { - Text(stringResource(Res.string.review_the_purchase), style = MaterialTheme.typography.titleMedium) - Text(stringResource(Res.string.liquidity_to_add_s_sats, Satoshi(amount).grouped()), style = MaterialTheme.typography.bodyLarge) - Text(stringResource(Res.string.liquidity_is_an_initial_amount), style = MaterialTheme.typography.bodyMedium) - Row( - modifier = Modifier.fillMaxWidth().toggleable(value = viewModel.acknowledged, role = Role.Checkbox, onValueChange = { viewModel.acknowledged = it }).minimumInteractiveComponentSize(), - verticalAlignment = Alignment.CenterVertically, - ) { - Checkbox(checked = viewModel.acknowledged, onCheckedChange = null) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.i_understand)) - } - Button(modifier = Modifier.fillMaxWidth(), onClick = onAsk, enabled = viewModel.acknowledged && !viewModel.isActionPending.value) { - Icon(Icons.Default.Bolt, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.ask_the_group)) - } - } - } - } -} - -@Composable -private fun FeeLine(label: String, value: String, emphasised: Boolean = false) { - Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { - Text(label, style = MaterialTheme.typography.bodyMedium, fontWeight = if (emphasised) FontWeight.SemiBold else null) - Text(value, style = MaterialTheme.typography.bodyMedium, fontWeight = if (emphasised) FontWeight.SemiBold else null) - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupLightningReceiveScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupLightningReceiveScreen.kt deleted file mode 100644 index 807dc660..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupLightningReceiveScreen.kt +++ /dev/null @@ -1,212 +0,0 @@ -package mobi.giza.compose.ui.composable - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.text.KeyboardOptions -import androidx.compose.foundation.text.input.TextFieldLineLimits -import androidx.compose.foundation.text.selection.SelectionContainer -import androidx.compose.foundation.verticalScroll -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Bolt -import androidx.compose.material.icons.filled.ContentCopy -import androidx.compose.material3.Button -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalClipboardManager -import androidx.compose.ui.text.buildAnnotatedString -import androidx.compose.ui.text.input.ImeAction -import androidx.compose.ui.text.input.KeyboardType -import androidx.compose.ui.text.style.TextOverflow -import androidx.lifecycle.viewmodel.compose.viewModel -import mobi.giza.compose.resources.Res -import mobi.giza.compose.resources.amount_in_sats -import mobi.giza.compose.resources.anyone_can_pay_this_offer -import mobi.giza.compose.resources.ask_for_an_invoice -import mobi.giza.compose.resources.copy_invoice -import mobi.giza.compose.resources.copy_offer -import mobi.giza.compose.resources.couldn_t_ask_for_an_invoice -import mobi.giza.compose.resources.invoice_copied -import mobi.giza.compose.resources.leave_the_amount_empty_to_let_the_payer_choose -import mobi.giza.compose.resources.nobody_runs_this_wallet_to_make_an_invoice -import mobi.giza.compose.resources.offer_copied -import mobi.giza.compose.resources.receive -import mobi.giza.compose.resources.sats -import mobi.giza.compose.resources.sats_are_whole_numbers -import mobi.giza.compose.resources.that_is_more_sats_than_there_will_ever_be -import mobi.giza.compose.resources.that_isn_t_an_amount_in_sats -import mobi.giza.compose.resources.the_group_s_offer -import mobi.giza.compose.resources.this_invoice_pays_the_group_s_node -import mobi.giza.compose.resources.waiting_for_the_operator_s_device -import mobi.giza.compose.resources.what_it_is_for -import mobi.giza.compose.repository.ChatRepository -import mobi.giza.compose.repository.GroupLightningRepository -import mobi.giza.compose.text.GroupedSats -import mobi.giza.compose.text.SatsInput -import mobi.giza.compose.ui.composable.widgets.Decorative -import mobi.giza.compose.ui.composable.widgets.EmptyState -import mobi.giza.compose.ui.composable.widgets.ErrorState -import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator -import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState -import mobi.giza.compose.ui.composable.widgets.NavigateBackButton -import mobi.giza.compose.ui.composable.widgets.QRCodeView -import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition -import mobi.giza.compose.ui.composable.widgets.rememberNotifier -import mobi.giza.compose.ui.theme.readableContent -import mobi.giza.compose.ui.theme.spacing -import mobi.giza.compose.ui.view.model.GroupLightningReceiveViewModel -import mobi.giza.compose.ui.view.state.GroupLightningReceiveUIState -import mobi.giza.compose.wallet.GroupLightningRollout -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import org.jetbrains.compose.resources.stringResource - -/** - * Receiving into the group's Lightning wallet: a member asks, the operator's node makes the invoice, and - * it is shown once this device has checked it pays the group's node (`docs/group-lightning-wallet.md`, - * Phase 11). - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun GroupLightningReceiveScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - chatRepository: ChatRepository, - lightningRepository: GroupLightningRepository, - onNavigateBack: () -> Unit, -) { - val viewModel: GroupLightningReceiveViewModel = viewModel( - factory = GroupLightningReceiveViewModel.factory(activeUserPublicKey, chatRoomId, GroupLightningRollout.NETWORK, chatRepository, lightningRepository) - ) - LaunchedEffect(true) { viewModel.initiate() } - - val notify = rememberNotifier(rememberCoroutineScope()) - val couldNotAsk = stringResource(Res.string.couldn_t_ask_for_an_invoice) - val copied = stringResource(Res.string.invoice_copied) - val offerCopied = stringResource(Res.string.offer_copied) - val clipboardManager = LocalClipboardManager.current - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { Text(stringResource(Res.string.receive), maxLines = 1, overflow = TextOverflow.Ellipsis) }, - navigationIcon = { NavigateBackButton(onNavigateBack) } - ) - } - ) { padding -> - ScreenStateTransition(viewModel.uiState) { uiState -> - when (val state = uiState) { - GroupLightningReceiveUIState.Loading -> LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding)) - - is GroupLightningReceiveUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = state.message, onRetry = null) - - GroupLightningReceiveUIState.Unavailable -> EmptyState( - modifier = Modifier.padding(padding).readableContent(), - message = stringResource(Res.string.nobody_runs_this_wallet_to_make_an_invoice), - icon = Icons.Default.Bolt, - ) - - is GroupLightningReceiveUIState.Form -> { - val amountProblem = when (viewModel.amount()) { - SatsInput.Empty, is SatsInput.Sats -> null - SatsInput.NotWhole -> stringResource(Res.string.sats_are_whole_numbers) - SatsInput.TooLarge -> stringResource(Res.string.that_is_more_sats_than_there_will_ever_be) - else -> stringResource(Res.string.that_isn_t_an_amount_in_sats) - } - Column( - modifier = Modifier.padding(padding).readableContent().fillMaxSize().verticalScroll(rememberScrollState()).padding(MaterialTheme.spacing.screenMargin), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - ) { - OutlinedTextField( - modifier = Modifier.fillMaxWidth(), - state = viewModel.amountField, - outputTransformation = GroupedSats, - lineLimits = TextFieldLineLimits.SingleLine, - keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Next), - label = { Text(stringResource(Res.string.amount_in_sats)) }, - suffix = { Text(stringResource(Res.string.sats)) }, - isError = amountProblem != null, - supportingText = { Text(amountProblem ?: stringResource(Res.string.leave_the_amount_empty_to_let_the_payer_choose)) }, - ) - OutlinedTextField( - modifier = Modifier.fillMaxWidth(), - state = viewModel.descriptionField, - lineLimits = TextFieldLineLimits.SingleLine, - label = { Text(stringResource(Res.string.what_it_is_for)) }, - ) - Button( - modifier = Modifier.fillMaxWidth(), - onClick = { viewModel.request(onFailure = { notify(couldNotAsk) }) }, - enabled = amountProblem == null && !viewModel.isActionPending.value, - ) { - Icon(Icons.Default.Bolt, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.ask_for_an_invoice)) - } - // The offer needs no operator online to ask: the node answers payers itself. - state.offer?.let { offer -> - HorizontalDivider() - Text(stringResource(Res.string.the_group_s_offer), style = MaterialTheme.typography.titleSmall) - Text(stringResource(Res.string.anyone_can_pay_this_offer), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) - SelectionContainer { Text(offer, style = MaterialTheme.typography.bodySmall, maxLines = 3, overflow = TextOverflow.Ellipsis) } - TextButton(onClick = { - clipboardManager.setText(buildAnnotatedString { append(offer) }) - notify(offerCopied) - }) { - Icon(Icons.Default.ContentCopy, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.copy_offer)) - } - } - } - } - - is GroupLightningReceiveUIState.Waiting -> Column( - modifier = Modifier.padding(padding).readableContent().fillMaxSize().padding(MaterialTheme.spacing.screenMargin), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - ) { - LoadingDataIndicator(modifier = Modifier.fillMaxWidth()) - Text(stringResource(Res.string.waiting_for_the_operator_s_device), style = MaterialTheme.typography.bodyLarge) - } - - is GroupLightningReceiveUIState.Invoice -> Column( - modifier = Modifier.padding(padding).readableContent().fillMaxSize().verticalScroll(rememberScrollState()).padding(MaterialTheme.spacing.screenMargin), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - ) { - // The URI scheme, so a scanning wallet knows what the text is. - QRCodeView("lightning:${state.bolt11}") - Text(stringResource(Res.string.this_invoice_pays_the_group_s_node), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) - SelectionContainer { Text(state.bolt11, style = MaterialTheme.typography.bodySmall) } - TextButton(onClick = { - clipboardManager.setText(buildAnnotatedString { append(state.bolt11) }) - notify(copied) - }) { - Icon(Icons.Default.ContentCopy, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.copy_invoice)) - } - } - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupLightningSendScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupLightningSendScreen.kt deleted file mode 100644 index 75f2c5e7..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupLightningSendScreen.kt +++ /dev/null @@ -1,207 +0,0 @@ -package mobi.giza.compose.ui.composable - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.text.KeyboardOptions -import androidx.compose.foundation.text.input.TextFieldLineLimits -import androidx.compose.foundation.verticalScroll -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Bolt -import androidx.compose.material3.Button -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.input.ImeAction -import androidx.compose.ui.text.input.KeyboardType -import androidx.compose.ui.text.style.TextOverflow -import androidx.lifecycle.viewmodel.compose.viewModel -import mobi.giza.compose.resources.Res -import mobi.giza.compose.resources.amount_in_sats -import mobi.giza.compose.resources.ask_the_group_to_pay -import mobi.giza.compose.resources.couldn_t_propose_this -import mobi.giza.compose.resources.fee_limit_in_sats -import mobi.giza.compose.resources.left_empty_s_sats -import mobi.giza.compose.resources.lightning_invoice -import mobi.giza.compose.resources.nobody_runs_this_wallet -import mobi.giza.compose.resources.paying_asks_the_group_to_sign -import mobi.giza.compose.resources.sats -import mobi.giza.compose.resources.sats_are_whole_numbers -import mobi.giza.compose.resources.send -import mobi.giza.compose.resources.that_invoice_has_expired -import mobi.giza.compose.resources.that_invoice_is_for_another_network -import mobi.giza.compose.resources.that_invoice_names_no_amount -import mobi.giza.compose.resources.that_invoice_pays_this_wallet -import mobi.giza.compose.resources.that_is_more_sats_than_there_will_ever_be -import mobi.giza.compose.resources.that_isn_t_a_lightning_invoice -import mobi.giza.compose.resources.that_isn_t_an_amount_in_sats -import mobi.giza.compose.resources.the_invoice_names_the_amount_s_sats -import mobi.giza.compose.managers.GroupLightningAuthorisations -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import mobi.giza.compose.repository.ChatRepository -import mobi.giza.compose.repository.GroupLightningRepository -import mobi.giza.compose.text.GroupedSats -import mobi.giza.compose.text.SatsInput -import mobi.giza.compose.text.grouped -import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute -import mobi.giza.compose.ui.composable.navigation.routes.Route -import mobi.giza.compose.ui.composable.widgets.Decorative -import mobi.giza.compose.ui.composable.widgets.EmptyState -import mobi.giza.compose.ui.composable.widgets.ErrorState -import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator -import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState -import mobi.giza.compose.ui.composable.widgets.NavigateBackButton -import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition -import mobi.giza.compose.ui.composable.widgets.rememberNotifier -import mobi.giza.compose.ui.theme.readableContent -import mobi.giza.compose.ui.theme.spacing -import mobi.giza.compose.ui.view.model.GroupLightningSendViewModel -import mobi.giza.compose.ui.view.state.GroupLightningSendUIState -import mobi.giza.compose.wallet.GroupLightningRollout -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.Satoshi -import org.jetbrains.compose.resources.stringResource - -/** - * Proposing a payment from the group's Lightning wallet (`docs/group-lightning-wallet.md`, Phase 12). The - * proposal opens a signing session; the operator's node pays once the group has signed. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun GroupLightningSendScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - chatRepository: ChatRepository, - lightningRepository: GroupLightningRepository, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val viewModel: GroupLightningSendViewModel = viewModel( - factory = GroupLightningSendViewModel.factory(activeUserPublicKey, chatRoomId, GroupLightningRollout.NETWORK, chatRepository, lightningRepository) - ) - LaunchedEffect(true) { viewModel.initiate() } - - val notify = rememberNotifier(rememberCoroutineScope()) - val couldNotPropose = stringResource(Res.string.couldn_t_propose_this) - val network = GroupWalletStatementEvent.chainName(GroupLightningRollout.NETWORK) - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { Text(stringResource(Res.string.send), maxLines = 1, overflow = TextOverflow.Ellipsis) }, - navigationIcon = { NavigateBackButton(onNavigateBack) } - ) - } - ) { padding -> - ScreenStateTransition(viewModel.uiState) { uiState -> - when (val state = uiState) { - GroupLightningSendUIState.Loading -> LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding)) - - is GroupLightningSendUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = state.message, onRetry = null) - - GroupLightningSendUIState.Unavailable -> EmptyState( - modifier = Modifier.padding(padding).readableContent(), - message = stringResource(Res.string.nobody_runs_this_wallet), - icon = Icons.Default.Bolt, - ) - - is GroupLightningSendUIState.Form -> { - val preview = viewModel.preview() - val pay = preview?.getOrNull() - val invoiceProblem = (preview?.exceptionOrNull() as? GroupLightningAuthorisations.ProblemException)?.problem - val invoiceNamesAmount = viewModel.invoiceAmountMsat() != null - Column( - modifier = Modifier.padding(padding).readableContent().fillMaxSize().verticalScroll(rememberScrollState()).padding(MaterialTheme.spacing.screenMargin), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - ) { - OutlinedTextField( - modifier = Modifier.fillMaxWidth(), - state = viewModel.invoiceField, - lineLimits = TextFieldLineLimits.MultiLine(maxHeightInLines = 4), - label = { Text(stringResource(Res.string.lightning_invoice)) }, - isError = invoiceProblem != null && invoiceProblem != GroupLightningAuthorisations.Problem.NeedsAmount, - supportingText = invoiceProblem?.let { problem -> { Text(problemWith(problem, network)) } } - ?: pay?.takeIf { invoiceNamesAmount }?.let { { Text(stringResource(Res.string.the_invoice_names_the_amount_s_sats, Satoshi(it.amountMsat / 1000).grouped())) } }, - ) - if (!invoiceNamesAmount) { - OutlinedTextField( - modifier = Modifier.fillMaxWidth(), - state = viewModel.amountField, - outputTransformation = GroupedSats, - lineLimits = TextFieldLineLimits.SingleLine, - keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Next), - label = { Text(stringResource(Res.string.amount_in_sats)) }, - suffix = { Text(stringResource(Res.string.sats)) }, - isError = amountProblem(viewModel.amount()) != null, - supportingText = amountProblem(viewModel.amount())?.let { { Text(it) } }, - ) - } - OutlinedTextField( - modifier = Modifier.fillMaxWidth(), - state = viewModel.maxFeeField, - outputTransformation = GroupedSats, - lineLimits = TextFieldLineLimits.SingleLine, - keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Done), - label = { Text(stringResource(Res.string.fee_limit_in_sats)) }, - suffix = { Text(stringResource(Res.string.sats)) }, - isError = amountProblem(viewModel.maxFee()) != null, - supportingText = { - Text( - amountProblem(viewModel.maxFee()) - ?: stringResource(Res.string.left_empty_s_sats, Satoshi(viewModel.defaultMaxFeeSat((pay?.amountMsat ?: 0) / 1000)).grouped()) - ) - }, - ) - Text(stringResource(Res.string.paying_asks_the_group_to_sign), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) - Button( - modifier = Modifier.fillMaxWidth(), - onClick = { - viewModel.propose( - onSession = { sessionId -> onNavigateToRoute(FrostSigningRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, sessionId = sessionId)) }, - onFailure = { notify(couldNotPropose) }, - ) - }, - enabled = pay != null && !viewModel.isActionPending.value, - ) { - Icon(Icons.Default.Bolt, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.ask_the_group_to_pay)) - } - } - } - } - } - } -} - -@Composable -private fun problemWith(problem: GroupLightningAuthorisations.Problem, network: String): String = when (problem) { - GroupLightningAuthorisations.Problem.Unreadable -> stringResource(Res.string.that_isn_t_a_lightning_invoice) - GroupLightningAuthorisations.Problem.OtherNetwork -> stringResource(Res.string.that_invoice_is_for_another_network, network) - GroupLightningAuthorisations.Problem.Expired -> stringResource(Res.string.that_invoice_has_expired) - GroupLightningAuthorisations.Problem.NeedsAmount -> stringResource(Res.string.that_invoice_names_no_amount) - GroupLightningAuthorisations.Problem.PaysTheGroup -> stringResource(Res.string.that_invoice_pays_this_wallet) -} - -@Composable -private fun amountProblem(input: SatsInput): String? = when (input) { - SatsInput.Empty, is SatsInput.Sats -> null - SatsInput.NotWhole -> stringResource(Res.string.sats_are_whole_numbers) - SatsInput.TooLarge -> stringResource(Res.string.that_is_more_sats_than_there_will_ever_be) - else -> stringResource(Res.string.that_isn_t_an_amount_in_sats) -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupLightningWalletScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupLightningWalletScreen.kt deleted file mode 100644 index a7cb5756..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupLightningWalletScreen.kt +++ /dev/null @@ -1,539 +0,0 @@ -package mobi.giza.compose.ui.composable - -import androidx.compose.material.icons.filled.AddLink -import androidx.compose.material3.TextButton -import mobi.giza.compose.resources.add_liquidity -import mobi.giza.compose.resources.adding_s_sats_of_inbound_liquidity -import mobi.giza.compose.resources.couldn_t_add_liquidity_s -import mobi.giza.compose.resources.inbound_liquidity_added_s_sats_for_s_sats -import mobi.giza.compose.resources.waiting_for_the_last_splice_before_adding_s_sats -import mobi.giza.compose.ui.composable.navigation.routes.GroupLightningLiquidityRoute -import mobi.giza.compose.wallet.lightning.LiquidityPrice -import mobi.giza.compose.wallet.lightning.WalletWire - -import mobi.giza.compose.resources.a_channel_closed_s_sats_to_the_onchain_wallet -import mobi.giza.compose.resources.a_channel_is_closing_s_sats_to_the_onchain_wallet -import androidx.compose.material.icons.filled.LinkOff -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.text.selection.SelectionContainer -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.filled.CallMade -import androidx.compose.material.icons.automirrored.filled.CallReceived -import androidx.compose.material.icons.filled.AccountBalanceWallet -import androidx.compose.material.icons.filled.Bolt -import androidx.compose.material.icons.filled.Key -import androidx.compose.material.icons.filled.MoreVert -import androidx.compose.material.icons.filled.Router -import androidx.compose.material.icons.filled.Warning -import androidx.compose.material3.Button -import androidx.compose.material3.Card -import androidx.compose.material3.DropdownMenu -import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.ListItem -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedButton -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextOverflow -import androidx.lifecycle.viewmodel.compose.viewModel -import mobi.giza.compose.resources.Res -import mobi.giza.compose.resources.a_closed_channel_s_outputs_go_to_the_onchain_wallet -import mobi.giza.compose.resources.a_lightning_wallet_needs_four_signers -import mobi.giza.compose.resources.at_most_s_sats_in_flight -import mobi.giza.compose.resources.balance -import mobi.giza.compose.resources.channel_actions -import mobi.giza.compose.resources.channels -import mobi.giza.compose.resources.close_its_channels -import mobi.giza.compose.resources.close_to_the_onchain_wallet -import mobi.giza.compose.resources.couldn_t_propose_this -import mobi.giza.compose.resources.couldn_t_send_s_sats -import mobi.giza.compose.resources.earlier_wallet_s -import mobi.giza.compose.resources.force_close -import mobi.giza.compose.resources.group_wallet -import mobi.giza.compose.resources.lightning_wallet -import mobi.giza.compose.resources.lsp_s -import mobi.giza.compose.resources.make_a_key -import mobi.giza.compose.resources.matches_what_your_device_signed -import mobi.giza.compose.resources.no_payments_yet -import mobi.giza.compose.resources.nobody_runs_this_wallet -import mobi.giza.compose.resources.nobody_runs_this_wallet_s_node -import mobi.giza.compose.resources.node_s -import mobi.giza.compose.resources.open_a_lightning_wallet -import mobi.giza.compose.resources.open_a_new_lightning_wallet -import mobi.giza.compose.resources.open_the_group_s_onchain_wallet_first -import mobi.giza.compose.resources.opening_a_lightning_wallet_asks -import mobi.giza.compose.resources.payments -import mobi.giza.compose.resources.receive -import mobi.giza.compose.resources.received_s_sats -import mobi.giza.compose.resources.reported_by_the_operator_in_term_s -import mobi.giza.compose.resources.run_by_s_term_s -import mobi.giza.compose.resources.run_this_wallet_on_my_device -import mobi.giza.compose.resources.s_of_s_sats_are_the_group_s -import mobi.giza.compose.resources.s_people_who_left_still_hold_a_share -import mobi.giza.compose.resources.s_sats -import mobi.giza.compose.resources.s_sats_can_be_received -import mobi.giza.compose.resources.s_sats_in_s_channels -import mobi.giza.compose.resources.s_sats_wait_in_closed_channels -import mobi.giza.compose.resources.see_the_key_ceremony -import mobi.giza.compose.resources.send -import mobi.giza.compose.resources.sent_s_sats_with_a_fee_of_s_sats -import mobi.giza.compose.resources.signers_needed_s_of_s -import mobi.giza.compose.resources.step_down -import mobi.giza.compose.resources.sweep_into_the_onchain_wallet -import mobi.giza.compose.resources.sweep_s_sats -import mobi.giza.compose.resources.the_group_is_making_its_lightning_wallet_key -import mobi.giza.compose.resources.the_operator_hasn_t_reported_the_wallet_yet -import mobi.giza.compose.resources.the_operator_s_device_runs_the_node -import mobi.giza.compose.resources.this_group_has_no_lightning_wallet_key_yet -import mobi.giza.compose.resources.you -import mobi.giza.compose.resources.your_device_hasn_t_signed_for_this_channel -import mobi.giza.compose.resources.your_device_signed_for_s_sats -import mobi.giza.compose.resources.your_share_of_this_key_is_stored_unencrypted -import mobi.giza.compose.database.model.GroupLightningPaymentRow -import mobi.giza.compose.identity.Identity -import mobi.giza.compose.managers.GroupLightningReports -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import mobi.giza.compose.repository.ChatRepository -import mobi.giza.compose.repository.GroupLightningRepository -import mobi.giza.compose.text.grouped -import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute -import mobi.giza.compose.ui.composable.navigation.routes.GroupLightningReceiveRoute -import mobi.giza.compose.ui.composable.navigation.routes.GroupLightningSendRoute -import mobi.giza.compose.ui.composable.navigation.routes.GroupWalletRoute -import mobi.giza.compose.ui.composable.navigation.routes.IcebergCeremonyRoute -import mobi.giza.compose.ui.composable.navigation.routes.Route -import mobi.giza.compose.ui.composable.widgets.Decorative -import mobi.giza.compose.ui.composable.widgets.EmptyState -import mobi.giza.compose.ui.composable.widgets.ErrorState -import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator -import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState -import mobi.giza.compose.ui.composable.widgets.NavigateBackButton -import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition -import mobi.giza.compose.ui.composable.widgets.rememberNotifier -import mobi.giza.compose.ui.theme.readableContent -import mobi.giza.compose.ui.theme.spacing -import mobi.giza.compose.ui.view.model.GroupLightningWalletViewModel -import mobi.giza.compose.ui.view.state.GroupLightningWalletUIState -import mobi.giza.compose.wallet.GroupLightningRollout -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.Satoshi -import kotlinx.coroutines.flow.StateFlow -import org.jetbrains.compose.resources.stringResource - -/** - * The group's Lightning wallet: what it needs before it can exist, the statement that opened it, and - * who runs its node. Balance, channels and payments are the operator's snapshot - * (Phase 10), each channel checked against what this device last co-signed. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun GroupLightningWalletScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - activeIdentityStateFlow: StateFlow, - chatRepository: ChatRepository, - lightningRepository: GroupLightningRepository, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val viewModel: GroupLightningWalletViewModel = viewModel( - factory = GroupLightningWalletViewModel.factory( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - chain = GroupLightningRollout.NETWORK, - activeIdentityStateFlow = activeIdentityStateFlow, - chatRepository = chatRepository, - lightningRepository = lightningRepository, - ) - ) - LaunchedEffect(true) { viewModel.initiate() } - - val notify = rememberNotifier(rememberCoroutineScope()) - val couldNotPropose = stringResource(Res.string.couldn_t_propose_this) - val toSession = { sessionId: String -> onNavigateToRoute(FrostSigningRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, sessionId = sessionId)) } - val toCeremony = { sessionId: String? -> onNavigateToRoute(IcebergCeremonyRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, sessionId = sessionId)) } - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { Text(stringResource(Res.string.lightning_wallet), maxLines = 1, overflow = TextOverflow.Ellipsis) }, - navigationIcon = { NavigateBackButton(onNavigateBack) } - ) - } - ) { padding -> - ScreenStateTransition(viewModel.uiState) { uiState -> - when (val state = uiState) { - is GroupLightningWalletUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = state.message, onRetry = null) - - GroupLightningWalletUIState.Loading -> LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding)) - - is GroupLightningWalletUIState.NeedsOnchainWallet -> EmptyState( - modifier = Modifier.padding(padding).readableContent(), - message = stringResource(Res.string.open_the_group_s_onchain_wallet_first), - icon = Icons.Default.AccountBalanceWallet, - action = { - Button(onClick = { onNavigateToRoute(GroupWalletRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, relayHint = null)) }) { - Text(stringResource(Res.string.group_wallet)) - } - } - ) - - is GroupLightningWalletUIState.NeedsKey -> EmptyState( - modifier = Modifier.padding(padding).readableContent(), - message = when { - state.ceremony != null -> stringResource(Res.string.the_group_is_making_its_lightning_wallet_key) - !state.canMakeKey -> stringResource(Res.string.a_lightning_wallet_needs_four_signers) - else -> stringResource(Res.string.this_group_has_no_lightning_wallet_key_yet) - }, - icon = Icons.Default.Key, - action = if (state.ceremony != null || state.canMakeKey) { - { - Button(onClick = { toCeremony(state.ceremony?.id) }) { - Text(stringResource(if (state.ceremony != null) Res.string.see_the_key_ceremony else Res.string.make_a_key)) - } - } - } else null - ) - - is GroupLightningWalletUIState.NotOpened -> EmptyState( - modifier = Modifier.padding(padding).readableContent(), - message = stringResource(Res.string.opening_a_lightning_wallet_asks, GroupLightningRollout.channelCapFor(GroupLightningRollout.NETWORK)?.grouped() ?: ""), - icon = Icons.Default.Bolt, - action = if (state.canPropose) { - { - Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)) { - Text(stringResource(Res.string.your_share_of_this_key_is_stored_unencrypted), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) - Button(onClick = { viewModel.openWallet(onSession = toSession, onFailure = { notify(couldNotPropose) }) }, enabled = !viewModel.isActionPending.value) { - Icon(Icons.Default.Bolt, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.open_a_lightning_wallet)) - } - } - } - } else null - ) - - is GroupLightningWalletUIState.Opened -> OpenedWallet( - modifier = Modifier.padding(padding), - state = state, - onReceive = { onNavigateToRoute(GroupLightningReceiveRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId)) }, - onSend = { onNavigateToRoute(GroupLightningSendRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId)) }, - onAddLiquidity = { onNavigateToRoute(GroupLightningLiquidityRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId)) }, - onClose = { channelId, force -> viewModel.close(channelId, force, onSession = toSession, onFailure = { notify(couldNotPropose) }) }, - onSweep = { viewModel.sweep(onSession = toSession, onFailure = { notify(couldNotPropose) }) }, - onRekey = { - if (state.canOpenNew) viewModel.openWallet(onSession = toSession, onFailure = { notify(couldNotPropose) }) else toCeremony(null) - }, - onCloseEarlier = { viewModel.closeEarlier(it, onSession = toSession, onFailure = { notify(couldNotPropose) }) }, - onSweepEarlier = { viewModel.sweepEarlier(it, onSession = toSession, onFailure = { notify(couldNotPropose) }) }, - onRunEarlier = { viewModel.nominateSelf(onSession = toSession, onFailure = { notify(couldNotPropose) }, wallet = it.wallet.statement.wallet) }, - isPending = viewModel.isActionPending.value, - onNominate = { viewModel.nominateSelf(onSession = toSession, onFailure = { notify(couldNotPropose) }) }, - onStepDown = { viewModel.stepDown(onSession = toSession, onFailure = { notify(couldNotPropose) }) }, - ) - } - } - } -} - -@Composable -private fun OpenedWallet(modifier: Modifier, state: GroupLightningWalletUIState.Opened, onReceive: () -> Unit, onSend: () -> Unit, onAddLiquidity: () -> Unit, onClose: (channelId: String, force: Boolean) -> Unit, onSweep: () -> Unit, - onRekey: () -> Unit, - onCloseEarlier: (GroupLightningWalletUIState.Earlier) -> Unit, - onSweepEarlier: (GroupLightningWalletUIState.Earlier) -> Unit, - onRunEarlier: (GroupLightningWalletUIState.Earlier) -> Unit, - isPending: Boolean, onNominate: () -> Unit, onStepDown: () -> Unit) { - val statement = state.wallet.statement - val operatorName = state.operator?.publicKey?.let { key -> - if (state.isOperator) stringResource(Res.string.you) - else state.localChatRoom.localParticipants.firstOrNull { it.participant.participantPublicKey == key }?.profile?.humanReadableNameOrPubkey() ?: key.take(16) - } - LazyColumn( - modifier = modifier.readableContent().fillMaxSize().padding(MaterialTheme.spacing.screenMargin), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - ) { - // A member left: until a new wallet replaces this one, they can still grief it with the seed. - if (state.departed.isNotEmpty()) { - item { - Card(modifier = Modifier.fillMaxWidth()) { - Column(modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { - Text(stringResource(Res.string.s_people_who_left_still_hold_a_share, state.departed.size.toString()), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.error) - Button(onClick = onRekey, enabled = !isPending) { - Text(stringResource(if (state.canOpenNew) Res.string.open_a_new_lightning_wallet else Res.string.make_a_key)) - } - } - } - } - } - val liquidity = LiquidityPrice.availability(state.report?.snapshot, state.operator?.publicKey != null, GroupLightningRollout.channelCapFor(statement.chain)?.sat) - .takeIf { GroupLightningRollout.LIQUIDITY_ENABLED && state.isParticipant } - item { - Balance( - state.report, - onReceive = onReceive.takeIf { state.operator?.publicKey != null }, - onSend = onSend.takeIf { state.operator?.publicKey != null }, - onAddLiquidity = onAddLiquidity.takeIf { liquidity is LiquidityPrice.Availability.Available && !isPending }, - liquidityNote = liquidity?.takeIf { it !is LiquidityPrice.Availability.Available && it != LiquidityPrice.Availability.NoOperator }?.let { unavailableBecause(it) }, - ) - } - if (state.unswept.isNotEmpty()) { - item { - Card(modifier = Modifier.fillMaxWidth()) { - Column(modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { - Text(stringResource(Res.string.s_sats_wait_in_closed_channels, Satoshi(state.unswept.sumOf { it.amountSat }).grouped()), style = MaterialTheme.typography.titleMedium) - Text(stringResource(Res.string.a_closed_channel_s_outputs_go_to_the_onchain_wallet), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) - Button(onClick = onSweep, enabled = !isPending) { Text(stringResource(Res.string.sweep_into_the_onchain_wallet)) } - } - } - } - } - state.report?.takeIf { it.checks.isNotEmpty() }?.let { report -> - item { Text(stringResource(Res.string.channels), style = MaterialTheme.typography.titleSmall) } - items(report.checks, key = { it.channel.channelId }) { check -> - val purchase = report.snapshot.purchases.lastOrNull { it.channelId == check.channel.channelId && it.state != WalletWire.LOCKED } - ChannelRow(check, purchase, onClose = { force: Boolean -> onClose(check.channel.channelId, force) }.takeIf { !isPending }) - } - } - item { Text(stringResource(Res.string.payments), style = MaterialTheme.typography.titleSmall) } - if (state.payments.isEmpty()) { - item { Text(stringResource(Res.string.no_payments_yet), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) } - } - items(state.payments, key = { it.id }) { PaymentRow(it) } - item { - Card(modifier = Modifier.fillMaxWidth()) { - Column(modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { - Text( - text = if (operatorName == null) stringResource(Res.string.nobody_runs_this_wallet) else stringResource(Res.string.run_by_s_term_s, operatorName, state.operator!!.term.toString()), - style = MaterialTheme.typography.titleMedium, - ) - Text(stringResource(Res.string.the_operator_s_device_runs_the_node), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) - if (state.isParticipant && !state.isOperator) { - Button(onClick = onNominate, enabled = !isPending) { Text(stringResource(Res.string.run_this_wallet_on_my_device)) } - } - if (state.isOperator) { - OutlinedButton(onClick = onStepDown, enabled = !isPending) { Text(stringResource(Res.string.step_down)) } - } - } - } - } - items(state.earlier, key = { "earlier:${it.wallet.statement.wallet}" }) { earlier -> - EarlierWallet( - earlier = earlier, - canRun = earlier.operator?.publicKey == null && state.localChatRoom.chatRoom.userPublicKey.lowercase() in earlier.wallet.statement.participants, - isPending = isPending, - onClose = { onCloseEarlier(earlier) }, - onSweep = { onSweepEarlier(earlier) }, - onRun = { onRunEarlier(earlier) }, - ) - } - item { - ListItem( - leadingContent = { Icon(Icons.Default.Key, contentDescription = Decorative) }, - headlineContent = { Text(stringResource(Res.string.signers_needed_s_of_s, statement.threshold.toString(), statement.participants.size.toString())) }, - supportingContent = { Text(stringResource(Res.string.at_most_s_sats_in_flight, Satoshi(statement.policy.inFlightCapSat).grouped())) }, - ) - } - item { - ListItem( - leadingContent = { Icon(Icons.Default.Router, contentDescription = Decorative) }, - headlineContent = { SelectionContainer { Text(stringResource(Res.string.node_s, statement.nodeId)) } }, - supportingContent = { SelectionContainer { Text(stringResource(Res.string.lsp_s, statement.lspNodeId)) } }, - ) - } - } -} - -/** - * The operator's figure for what the group can spend and receive, or a word that there is none yet. Below - * the two actions, *Add liquidity* when the group can be asked for it, or [liquidityNote], why not. - */ -@Composable -private fun Balance(report: GroupLightningReports.Report?, onReceive: (() -> Unit)?, onSend: (() -> Unit)?, onAddLiquidity: (() -> Unit)? = null, liquidityNote: String? = null) { - Card(modifier = Modifier.fillMaxWidth()) { - Column(modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { - Text(stringResource(Res.string.balance), style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.onSurfaceVariant) - if (report == null) { - Text(stringResource(Res.string.the_operator_hasn_t_reported_the_wallet_yet), style = MaterialTheme.typography.bodyLarge) - } else { - Text(stringResource(Res.string.s_sats, Satoshi(report.snapshot.spendableMsat / 1000).grouped()), style = MaterialTheme.typography.headlineMedium) - Text(stringResource(Res.string.s_sats_can_be_received, Satoshi(report.snapshot.inboundMsat / 1000).grouped()), style = MaterialTheme.typography.bodyMedium) - Text(stringResource(Res.string.reported_by_the_operator_in_term_s, report.snapshot.term.toString()), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - } - // Whoever runs the node makes the invoice and pays what the group signs for, so there is - // nothing to ask while nobody does. - if (onReceive != null || onSend != null) { - Row(horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)) { - onReceive?.let { - OutlinedButton(onClick = it) { - Icon(Icons.AutoMirrored.Filled.CallReceived, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.receive)) - } - } - onSend?.let { - OutlinedButton(onClick = it) { - Icon(Icons.AutoMirrored.Filled.CallMade, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.send)) - } - } - } - } - onAddLiquidity?.let { - TextButton(onClick = it) { - Icon(Icons.Default.AddLink, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.add_liquidity)) - } - } - liquidityNote?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } - } - } -} - -/** One channel, and whether the operator's figure for it is the one this device co-signed. */ -@Composable -private fun ChannelRow(check: GroupLightningReports.ChannelCheck, purchase: WalletWire.LiquidityPurchase?, onClose: ((force: Boolean) -> Unit)?) { - val channel = check.channel - ListItem( - leadingContent = { - Icon( - imageVector = if (check.agrees == false) Icons.Default.Warning else Icons.Default.Bolt, - contentDescription = if (check.agrees == false) stringResource(Res.string.your_device_signed_for_s_sats, Satoshi(check.signedOursMsat!! / 1000).grouped()) else Decorative, - tint = if (check.agrees == false) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, - ) - }, - headlineContent = { Text(stringResource(Res.string.s_of_s_sats_are_the_group_s, Satoshi(channel.oursMsat / 1000).grouped(), Satoshi(channel.capacitySat).grouped())) }, - supportingContent = { - Column { - Text( - when (check.agrees) { - true -> stringResource(Res.string.matches_what_your_device_signed) - false -> stringResource(Res.string.your_device_signed_for_s_sats, Satoshi(check.signedOursMsat!! / 1000).grouped()) - null -> stringResource(Res.string.your_device_hasn_t_signed_for_this_channel) - }, - color = if (check.agrees == false) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, - ) - // A purchase the operator's node is making for this channel, or could not make. - purchase?.let { p -> - val amount = Satoshi(p.amountSat).grouped() - Text( - when (p.state) { - WalletWire.WAITING -> stringResource(Res.string.waiting_for_the_last_splice_before_adding_s_sats, amount) - WalletWire.FAILED -> stringResource(Res.string.couldn_t_add_liquidity_s, p.reason.orEmpty()) - else -> stringResource(Res.string.adding_s_sats_of_inbound_liquidity, amount) - }, - color = if (p.state == WalletWire.FAILED) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - }, - // Closing is a proposal like any other: the menu only opens the signing session. - trailingContent = onClose?.let { close -> - { - var expanded by remember { mutableStateOf(false) } - Box { - IconButton(onClick = { expanded = true }) { - Icon(Icons.Default.MoreVert, contentDescription = stringResource(Res.string.channel_actions)) - } - DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) { - DropdownMenuItem(text = { Text(stringResource(Res.string.close_to_the_onchain_wallet)) }, onClick = { expanded = false; close(false) }) - DropdownMenuItem(text = { Text(stringResource(Res.string.force_close)) }, onClick = { expanded = false; close(true) }) - } - } - } - }, - ) -} - -/** - * One payment the operator's node reported. A channel's close comes in this list too -- lightning-kmp - * files it as an outgoing payment -- and is said as a close, since the money went to the group's own - * onchain wallet rather than to anybody. A payment sent is said as what reached the recipient, with the - * fee beside it, not the two added together. - */ -@Composable -internal fun PaymentRow(payment: GroupLightningPaymentRow) { - val isClose = GroupLightningReports.isChannelClose(payment.incoming, payment.paymentHash) - val liquidity = payment.liquiditySat - val amount = Satoshi( - if (payment.incoming || isClose) payment.amountMsat / 1000 - else GroupLightningReports.recipientMsat(payment.amountMsat, payment.feesMsat) / 1000 - ).grouped() - ListItem( - leadingContent = { - Icon( - when { - liquidity != null -> Icons.Default.AddLink - isClose -> Icons.Default.LinkOff - payment.incoming -> Icons.AutoMirrored.Filled.CallReceived - else -> Icons.AutoMirrored.Filled.CallMade - }, - contentDescription = Decorative, - ) - }, - headlineContent = { - Text( - when { - // Bought liquidity is room to be paid, never money sent: its amount is what it cost. - liquidity != null -> stringResource(Res.string.inbound_liquidity_added_s_sats_for_s_sats, Satoshi(liquidity).grouped(), Satoshi(payment.amountMsat / 1000).grouped()) - payment.incoming -> stringResource(Res.string.received_s_sats, amount) - isClose && payment.succeeded -> stringResource(Res.string.a_channel_closed_s_sats_to_the_onchain_wallet, amount) - isClose -> stringResource(Res.string.a_channel_is_closing_s_sats_to_the_onchain_wallet, amount) - payment.succeeded -> stringResource(Res.string.sent_s_sats_with_a_fee_of_s_sats, amount, Satoshi(payment.feesMsat / 1000).grouped()) - else -> stringResource(Res.string.couldn_t_send_s_sats, amount) - } - ) - }, - supportingContent = payment.description?.let { { Text(it, maxLines = 2, overflow = TextOverflow.Ellipsis) } }, - ) -} - -/** A wallet a re-key left behind: what is still in it, and the two ways it reaches the onchain wallet. */ -@Composable -private fun EarlierWallet(earlier: GroupLightningWalletUIState.Earlier, canRun: Boolean, isPending: Boolean, onClose: () -> Unit, onSweep: () -> Unit, onRun: () -> Unit) { - Card(modifier = Modifier.fillMaxWidth()) { - Column(modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { - Text(stringResource(Res.string.earlier_wallet_s, earlier.wallet.statement.wallet.toString()), style = MaterialTheme.typography.titleSmall) - earlier.report?.let { report -> - Text(stringResource(Res.string.s_sats_in_s_channels, Satoshi(report.snapshot.spendableMsat / 1000).grouped(), report.checks.size.toString()), style = MaterialTheme.typography.bodyMedium) - } - if (earlier.operator?.publicKey == null && earlier.openChannels.isNotEmpty()) { - Text(stringResource(Res.string.nobody_runs_this_wallet_s_node), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - } - Row(horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)) { - if (earlier.openChannels.isNotEmpty()) OutlinedButton(onClick = onClose, enabled = !isPending) { Text(stringResource(Res.string.close_its_channels)) } - if (earlier.unswept.isNotEmpty()) { - OutlinedButton(onClick = onSweep, enabled = !isPending) { Text(stringResource(Res.string.sweep_s_sats, Satoshi(earlier.unswept.sumOf { it.amountSat }).grouped())) } - } - } - if (canRun) OutlinedButton(onClick = onRun, enabled = !isPending) { Text(stringResource(Res.string.run_this_wallet_on_my_device)) } - } - } -} - diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupWalletScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupWalletScreen.kt index 4929a5a9..601b908a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupWalletScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupWalletScreen.kt @@ -680,7 +680,7 @@ private fun SpendRowCard( ListItem( headlineContent = { Text( - text = (row.spend?.let { ProposedSpend.summarize(it, chain) } ?: row.sweep?.let(ProposedSpend::summarize) ?: ProposedSpend.UNREADABLE).detail, + text = (row.spend?.let { ProposedSpend.summarize(it, chain) } ?: ProposedSpend.UNREADABLE).detail, maxLines = 2, overflow = TextOverflow.Ellipsis, ) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/HomeScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/HomeScreen.kt index a58a36aa..1ce948f6 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/HomeScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/HomeScreen.kt @@ -1,6 +1,5 @@ package mobi.giza.compose.ui.composable -import mobi.giza.compose.repository.GroupLightningRepository import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -102,7 +101,6 @@ fun HomeScreen( // loses its detail pane on a desktop is a worse failure than a compile error. frostSigningRepository: FrostSigningRepository, dkgRepository: DkgRepository, - lightningRepository: GroupLightningRepository, ) { val sheetState = rememberModalBottomSheetState() val scope = rememberCoroutineScope() @@ -348,7 +346,6 @@ fun HomeScreen( chatRepository = chatRepository, frostSigningRepository = frostSigningRepository, dkgRepository = dkgRepository, - lightningRepository = lightningRepository, // "Replace what is on screen" is a route push // on a phone and a change of selection here. // It fires when a conversation that did not @@ -448,7 +445,6 @@ It has survived not only five centuries, but also the leap into electronic types chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, dkgRepository = DkgRepository.NO_OP_DKG_REPOSITORY, - lightningRepository = GroupLightningRepository.NO_OP_GROUP_LIGHTNING_REPOSITORY, ) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/IcebergCeremonyScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/IcebergCeremonyScreen.kt deleted file mode 100644 index 09c58e78..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/IcebergCeremonyScreen.kt +++ /dev/null @@ -1,349 +0,0 @@ -package mobi.giza.compose.ui.composable - -import androidx.compose.material.icons.filled.ErrorOutline -import androidx.compose.material3.CardDefaults -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Bolt -import androidx.compose.material.icons.filled.Key -import androidx.compose.material3.AlertDialog -import androidx.compose.material3.Button -import androidx.compose.material3.ButtonDefaults -import androidx.compose.material3.Card -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.FilterChip -import androidx.compose.material3.Icon -import androidx.compose.material3.ListItem -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextOverflow -import androidx.lifecycle.viewmodel.compose.viewModel -import mobi.giza.compose.resources.Res -import mobi.giza.compose.resources.a_lightning_wallet_needs_four_signers -import mobi.giza.compose.resources.abandon -import mobi.giza.compose.resources.abandon_ceremony -import mobi.giza.compose.resources.abandon_this_key_ceremony_question -import mobi.giza.compose.resources.cancel -import mobi.giza.compose.resources.couldn_t_abandon_the_ceremony -import mobi.giza.compose.resources.if_it_hasn_t_finished_s_hours_after -import mobi.giza.compose.resources.it_ends_for_everyone_in_it_no_key_is_created -import mobi.giza.compose.resources.the_ceremony_was_abandoned -import mobi.giza.compose.resources.nothing_was_created_and_no_key_exists_it_is -import mobi.giza.compose.resources.confirm_what_you_saw -import mobi.giza.compose.resources.confirming_publishes_your_public_share -import mobi.giza.compose.resources.couldn_t_approve_this_step -import mobi.giza.compose.resources.couldn_t_start_the_key_ceremony -import mobi.giza.compose.resources.hasn_t_answered_the_proposal_yet -import mobi.giza.compose.resources.join_the_ceremony -import mobi.giza.compose.resources.joining_publishes_commitments -import mobi.giza.compose.resources.lightning_wallet_key -import mobi.giza.compose.resources.open_the_group_s_onchain_wallet_first -import mobi.giza.compose.resources.s_of_3_steps -import mobi.giza.compose.resources.send_your_contributions -import mobi.giza.compose.resources.sending_contributions_encrypts_each -import mobi.giza.compose.resources.signers_needed_s_of_s -import mobi.giza.compose.resources.start_a_key_ceremony -import mobi.giza.compose.resources.the_group_has_a_lightning_wallet_key -import mobi.giza.compose.resources.the_lightning_wallet_key_is_made_by_everyone -import mobi.giza.compose.resources.this_group_has_no_lightning_wallet_key_yet -import mobi.giza.compose.resources.waiting_for_contributions -import mobi.giza.compose.resources.waiting_for_everyone_to_confirm -import mobi.giza.compose.resources.waiting_for_everyone_to_join -import mobi.giza.compose.resources.your_share_of_this_key_is_stored_unencrypted -import mobi.giza.compose.database.model.types.IcebergApprovalStep -import mobi.giza.compose.database.model.types.IcebergRitualStage -import mobi.giza.compose.identity.Identity -import mobi.giza.compose.managers.IcebergRitualManager -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import mobi.giza.compose.repository.ChatRepository -import mobi.giza.compose.repository.GroupLightningRepository -import mobi.giza.compose.ui.composable.widgets.Decorative -import mobi.giza.compose.ui.composable.widgets.EmptyState -import mobi.giza.compose.ui.composable.widgets.ErrorState -import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator -import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState -import mobi.giza.compose.ui.composable.widgets.NavigateBackButton -import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition -import mobi.giza.compose.ui.composable.widgets.rememberNotifier -import mobi.giza.compose.ui.theme.readableContent -import mobi.giza.compose.ui.theme.spacing -import mobi.giza.compose.ui.view.model.IcebergCeremonyViewModel -import mobi.giza.compose.ui.view.state.IcebergCeremonyUIState -import mobi.giza.compose.wallet.GroupLightningRollout -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.flow.StateFlow -import org.jetbrains.compose.resources.stringResource - -/** - * A group's Lightning wallet key ceremony: who has done which of its three rounds, whether this device - * has been asked to join, the way to abandon it, and -- for a group without one -- the way to start it. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun IcebergCeremonyScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - sessionId: String?, - activeIdentityStateFlow: StateFlow, - chatRepository: ChatRepository, - lightningRepository: GroupLightningRepository, - onNavigateBack: () -> Unit, -) { - val viewModel: IcebergCeremonyViewModel = viewModel( - factory = IcebergCeremonyViewModel.factory( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId, - chain = GroupLightningRollout.NETWORK, - activeIdentityStateFlow = activeIdentityStateFlow, - chatRepository = chatRepository, - lightningRepository = lightningRepository, - ) - ) - LaunchedEffect(true) { viewModel.initiate() } - - val notify = rememberNotifier(rememberCoroutineScope()) - val couldNotStart = stringResource(Res.string.couldn_t_start_the_key_ceremony) - val couldNotApprove = stringResource(Res.string.couldn_t_approve_this_step) - val couldNotAbandon = stringResource(Res.string.couldn_t_abandon_the_ceremony) - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { Text(stringResource(Res.string.lightning_wallet_key), maxLines = 1, overflow = TextOverflow.Ellipsis) }, - navigationIcon = { NavigateBackButton(onNavigateBack) } - ) - } - ) { padding -> - ScreenStateTransition(viewModel.uiState) { uiState -> - when (val state = uiState) { - is IcebergCeremonyUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = state.message, onRetry = null) - - IcebergCeremonyUIState.Loading -> LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding)) - - is IcebergCeremonyUIState.Loaded -> if (state.session == null) { - EmptyState( - modifier = Modifier.padding(padding).readableContent(), - message = when { - !state.hasOnchainWallet -> stringResource(Res.string.open_the_group_s_onchain_wallet_first) - state.thresholds.isEmpty() -> stringResource(Res.string.a_lightning_wallet_needs_four_signers) - else -> stringResource(Res.string.this_group_has_no_lightning_wallet_key_yet) - }, - icon = Icons.Default.Bolt, - action = if (viewModel.canPropose()) { - { - StartCeremony( - thresholds = state.thresholds, - participants = state.holderCount, - chosen = viewModel.threshold.value, - onChoose = { viewModel.threshold.value = it }, - isPending = viewModel.isActionPending.value, - onStart = { viewModel.propose(onFailure = { notify(couldNotStart) }) }, - ) - } - } else null - ) - } else { - Ceremony( - modifier = Modifier.padding(padding), - state = state, - isPending = viewModel.isActionPending.value, - onApprove = { viewModel.approve(onFailure = { notify(couldNotApprove) }) }, - canAbandon = viewModel.canAbandon(), - onAbandon = { viewModel.abandon(onFailure = { notify(couldNotAbandon) }) }, - ) - } - } - } - } -} - -@Composable -private fun StartCeremony(thresholds: List, participants: Int, chosen: Int?, onChoose: (Int) -> Unit, isPending: Boolean, onStart: () -> Unit) { - Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)) { - Text(stringResource(Res.string.the_lightning_wallet_key_is_made_by_everyone, (2 * (chosen ?: 2) - 1).toString()), style = MaterialTheme.typography.bodyMedium) - Row(horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { - thresholds.forEach { t -> - FilterChip( - selected = t == chosen, - onClick = { onChoose(t) }, - label = { Text(stringResource(Res.string.signers_needed_s_of_s, t.toString(), participants.toString())) }, - ) - } - } - Text(stringResource(Res.string.your_share_of_this_key_is_stored_unencrypted), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) - Button(onClick = onStart, enabled = !isPending && chosen != null) { - Icon(Icons.Default.Key, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.start_a_key_ceremony)) - } - } -} - -@Composable -private fun Ceremony( - modifier: Modifier, - state: IcebergCeremonyUIState.Loaded, - isPending: Boolean, - onApprove: () -> Unit, - canAbandon: Boolean, - onAbandon: () -> Unit, -) { - val session = state.session ?: return - val members = state.localChatRoom.localParticipants.associate { it.participant.participantPublicKey.lowercase() to it } - var isConfirmingAbandon by remember { mutableStateOf(false) } - LazyColumn( - modifier = modifier.readableContent().fillMaxSize().padding(MaterialTheme.spacing.screenMargin), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - ) { - item { - Text( - text = when (session.stage) { - IcebergRitualStage.COLLECTING_COMMITMENTS -> stringResource(Res.string.waiting_for_everyone_to_join) - IcebergRitualStage.COLLECTING_REVEALS -> stringResource(Res.string.waiting_for_contributions) - IcebergRitualStage.COLLECTING_CONFIRMATIONS -> stringResource(Res.string.waiting_for_everyone_to_confirm) - IcebergRitualStage.COMPLETE -> stringResource(Res.string.the_group_has_a_lightning_wallet_key) - IcebergRitualStage.FAILED -> stringResource(Res.string.the_ceremony_was_abandoned) - }, - style = MaterialTheme.typography.titleMedium, - ) - Text( - text = stringResource(Res.string.signers_needed_s_of_s, session.threshold.toString(), session.participantCount.toString()), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - // Said while it runs, so a member who has not joined knows the room is not held forever. - if (canAbandon) { - Text( - text = stringResource(Res.string.if_it_hasn_t_finished_s_hours_after, IcebergRitualManager.DEADLINE.inWholeHours.toString()), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - // As the shared key's ceremony says it: why, in the sentence the device that - // stopped it wrote, and that nothing was made. - if (session.stage == IcebergRitualStage.FAILED) { - item { - Card( - modifier = Modifier.fillMaxWidth(), - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.errorContainer, - contentColor = MaterialTheme.colorScheme.onErrorContainer, - ), - ) { - Row( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.containerPadding), - horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - verticalAlignment = Alignment.CenterVertically, - ) { - Icon(Icons.Default.ErrorOutline, contentDescription = Decorative) - Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { - session.failureReason?.let { Text(it, style = MaterialTheme.typography.bodyMedium) } - Text(stringResource(Res.string.nothing_was_created_and_no_key_exists_it_is), style = MaterialTheme.typography.labelMedium) - } - } - } - } - } - state.pending?.let { step -> - item { - Card(modifier = Modifier.fillMaxWidth()) { - Column(modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { - Text( - text = when (step) { - IcebergApprovalStep.JOIN -> stringResource(Res.string.joining_publishes_commitments) - IcebergApprovalStep.REVEAL -> stringResource(Res.string.sending_contributions_encrypts_each) - IcebergApprovalStep.CONFIRM -> stringResource(Res.string.confirming_publishes_your_public_share) - }, - style = MaterialTheme.typography.bodyMedium, - ) - Button(onClick = onApprove, enabled = !isPending) { - Text( - when (step) { - IcebergApprovalStep.JOIN -> stringResource(Res.string.join_the_ceremony) - IcebergApprovalStep.REVEAL -> stringResource(Res.string.send_your_contributions) - IcebergApprovalStep.CONFIRM -> stringResource(Res.string.confirm_what_you_saw) - } - ) - } - } - } - } - } - items(session.participants()) { participant -> - ListItem( - headlineContent = { Text(members[participant]?.profile?.humanReadableNameOrPubkey() ?: participant.take(16)) }, - supportingContent = { - // Phase 15: a member whose build does not know these kinds never answers, and the - // group would be smaller for it, so the screen says who has not. - val steps = state.progress[participant] ?: 0 - val failed = session.stage == IcebergRitualStage.FAILED - Text( - text = if (steps == 0 && !failed) stringResource(Res.string.hasn_t_answered_the_proposal_yet) else stringResource(Res.string.s_of_3_steps, steps.toString()), - color = if (steps == 0 && !failed) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, - ) - }, - ) - } - // Below the members rather than beside the join button: the consequence is the whole - // ceremony's, and reads against who is in it. - if (canAbandon) { - item { - TextButton( - onClick = { isConfirmingAbandon = true }, - enabled = !isPending, - colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.error), - ) { - Text(stringResource(Res.string.abandon_ceremony)) - } - } - } - } - - if (isConfirmingAbandon) { - AlertDialog( - onDismissRequest = { isConfirmingAbandon = false }, - title = { Text(stringResource(Res.string.abandon_this_key_ceremony_question)) }, - text = { Text(stringResource(Res.string.it_ends_for_everyone_in_it_no_key_is_created)) }, - confirmButton = { - TextButton( - onClick = { - isConfirmingAbandon = false - onAbandon() - } - ) { - Text(stringResource(Res.string.abandon)) - } - }, - dismissButton = { - TextButton(onClick = { isConfirmingAbandon = false }) { - Text(stringResource(Res.string.cancel)) - } - }, - ) - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt index 46271440..829a47e6 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt @@ -1,16 +1,5 @@ package mobi.giza.compose.ui.composable.navigation -import mobi.giza.compose.ui.composable.navigation.routes.GroupLightningWalletRoute -import mobi.giza.compose.ui.composable.GroupLightningWalletScreen -import mobi.giza.compose.ui.composable.GroupLightningReceiveScreen -import mobi.giza.compose.ui.composable.GroupLightningSendScreen -import mobi.giza.compose.ui.composable.GroupLightningLiquidityScreen -import mobi.giza.compose.ui.composable.navigation.routes.GroupLightningLiquidityRoute -import mobi.giza.compose.ui.composable.navigation.routes.GroupLightningSendRoute -import mobi.giza.compose.ui.composable.navigation.routes.GroupLightningReceiveRoute -import mobi.giza.compose.ui.composable.navigation.routes.IcebergCeremonyRoute -import mobi.giza.compose.ui.composable.IcebergCeremonyScreen -import mobi.giza.compose.database.repository.DatabaseGroupLightningRepository import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent import mobi.giza.compose.ui.composable.MemberWalletPolicyScreen import mobi.giza.compose.ui.composable.navigation.routes.MemberWalletPolicyRoute @@ -221,11 +210,6 @@ fun GizaNavHost( applicationIOScope ) } - - val databaseGroupLightningRepository = remember { - DatabaseGroupLightningRepository(database = auxDatabaseManager.auxDatabase) - } - val databaseFrostSigningRepository = remember { DatabaseFrostSigningRepository( database = auxDatabaseManager.auxDatabase, @@ -623,83 +607,6 @@ fun GizaNavHost( } ) } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - GroupLightningWalletScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - activeIdentityStateFlow = sovereignWalletViewModel.activeIdentity, - chatRepository = databaseChatRepository, - lightningRepository = databaseGroupLightningRepository, - onNavigateToRoute = { actionRoute -> - navController.navigate(route = actionRoute) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - GroupLightningReceiveScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - chatRepository = databaseChatRepository, - lightningRepository = databaseGroupLightningRepository, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - GroupLightningLiquidityScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - chatRepository = databaseChatRepository, - lightningRepository = databaseGroupLightningRepository, - onNavigateToRoute = { actionRoute -> - navController.navigate(route = actionRoute) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - GroupLightningSendScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - chatRepository = databaseChatRepository, - lightningRepository = databaseGroupLightningRepository, - onNavigateToRoute = { actionRoute -> - navController.navigate(route = actionRoute) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - IcebergCeremonyScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - sessionId = route.sessionId, - activeIdentityStateFlow = sovereignWalletViewModel.activeIdentity, - chatRepository = databaseChatRepository, - lightningRepository = databaseGroupLightningRepository, - onNavigateBack = { - navController.popBackStack() - } - ) - } composable { backStackEntry -> val route = backStackEntry.toRoute() @@ -969,7 +876,6 @@ fun GizaNavHost( chatRepository = databaseChatRepository, frostSigningRepository = databaseFrostSigningRepository, dkgRepository = databaseDkgRepository, - lightningRepository = databaseGroupLightningRepository, ) } composable { @@ -1126,7 +1032,6 @@ fun GizaNavHost( chatRepository = databaseChatRepository, frostSigningRepository = databaseFrostSigningRepository, dkgRepository = databaseDkgRepository, - lightningRepository = databaseGroupLightningRepository, onNavigateToRouteAndPopUpInclusive = { chatRoomDetailRoute -> navController.navigate( route = chatRoomDetailRoute diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupLightningLiquidityRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupLightningLiquidityRoute.kt deleted file mode 100644 index f898e5d2..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupLightningLiquidityRoute.kt +++ /dev/null @@ -1,10 +0,0 @@ -package mobi.giza.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** Asking the group to buy inbound liquidity for its Lightning wallet, from the Lightning wallet screen. */ -@Serializable -data class GroupLightningLiquidityRoute( - val activeUserPublicKey: String, - val chatRoomId: String, -) : Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupLightningReceiveRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupLightningReceiveRoute.kt deleted file mode 100644 index 0852c249..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupLightningReceiveRoute.kt +++ /dev/null @@ -1,10 +0,0 @@ -package mobi.giza.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** Asking the group's Lightning node for an invoice, from the Lightning wallet screen. */ -@Serializable -data class GroupLightningReceiveRoute( - val activeUserPublicKey: String, - val chatRoomId: String, -) : Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupLightningSendRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupLightningSendRoute.kt deleted file mode 100644 index 1854e799..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupLightningSendRoute.kt +++ /dev/null @@ -1,10 +0,0 @@ -package mobi.giza.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** Proposing a payment from the group's Lightning wallet, from the Lightning wallet screen. */ -@Serializable -data class GroupLightningSendRoute( - val activeUserPublicKey: String, - val chatRoomId: String, -) : Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupLightningWalletRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupLightningWalletRoute.kt deleted file mode 100644 index acdd8e0a..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupLightningWalletRoute.kt +++ /dev/null @@ -1,10 +0,0 @@ -package mobi.giza.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** The group's Lightning wallet, from its row on the group's screen. */ -@Serializable -data class GroupLightningWalletRoute( - val activeUserPublicKey: String, - val chatRoomId: String, -) : Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/IcebergCeremonyRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/IcebergCeremonyRoute.kt deleted file mode 100644 index f0337963..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/IcebergCeremonyRoute.kt +++ /dev/null @@ -1,15 +0,0 @@ -package mobi.giza.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** - * The Iceberg key ceremony a group's Lightning wallet signs with: watch it, approve this device's - * steps, or start one. Pushed from a transcript line, which names its ceremony, or from the Lightning - * wallet screen, which passes null and gets the room's newest. - */ -@Serializable -data class IcebergCeremonyRoute( - val activeUserPublicKey: String, - val chatRoomId: String, - val sessionId: String? = null, -) : Route() 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 46765a3c..4ce96f60 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 @@ -32,18 +32,9 @@ import mobi.giza.compose.resources.the_subgroups_key_ceremony_needs_you import mobi.giza.compose.resources.the_key_ceremony_needs_you import mobi.giza.compose.resources.ceremonies_need_you import mobi.giza.compose.database.model.types.DkgApprovalStep -import mobi.giza.compose.database.model.types.IcebergApprovalStep import androidx.compose.material.icons.filled.Bolt -import mobi.giza.compose.resources.the_lightning_wallet_s_key_ceremony_needs_you -import mobi.giza.compose.resources.the_lightning_wallet_s_key_is_ready -import mobi.giza.compose.resources.join_the_ceremony -import mobi.giza.compose.resources.send_your_contributions -import mobi.giza.compose.resources.confirm_what_you_saw -import mobi.giza.compose.resources.open_a_lightning_wallet import mobi.giza.compose.resources.open_the_shared_key_ceremony -import mobi.giza.compose.resources.open_the_lightning_wallet_s_key_ceremony import mobi.giza.compose.resources.open_the_proposal -import mobi.giza.compose.resources.open_the_lightning_wallet import androidx.compose.material.icons.filled.Badge import androidx.compose.material.icons.filled.Payments import androidx.compose.material.icons.filled.RequestQuote @@ -135,10 +126,6 @@ import mobi.giza.compose.ui.composable.widgets.ErrorState fun ChatTranscript( viewModel: ChatMessageListViewModel, onOpenSharedKey: (dkgSessionId: String) -> Unit, - /** Opens the Lightning wallet key ceremony an [ChatMessage.ICEBERG_TYPES] line is about. */ - onOpenIcebergCeremony: (sessionId: String?) -> Unit = {}, - /** Opens the room's Lightning wallet, where a finished key is opened as a wallet. */ - onOpenLightningWallet: () -> Unit, /** * Opens the signing this line is about, by session id -- or the room's * whole list of proposals when the line predates [ChatMessage.frostSigningSessionId] @@ -229,20 +216,7 @@ fun ChatTranscript( item { CeremoniesAwaitingYouNotice( ceremonies = ceremoniesAwaitingYou, - // Each ceremony has its own screen, and a - // finished Lightning key is opened from the - // wallet's. - onClick = { ceremony -> - when (ceremony.ask) { - is ChatMessageListViewModel.Ask.SharedKeyStep, - is ChatMessageListViewModel.Ask.RoomCreation -> - onOpenSharedKey(ceremony.sessionId) - is ChatMessageListViewModel.Ask.LightningKeyStep -> - onOpenIcebergCeremony(ceremony.sessionId) - ChatMessageListViewModel.Ask.LightningWalletOpening -> - onOpenLightningWallet() - } - } + onClick = { ceremony -> onOpenSharedKey(ceremony.sessionId) } ) } } @@ -317,15 +291,19 @@ fun ChatTranscript( return@items } - // The Lightning wallet's key ceremony, the same kind of - // notice as the onchain key's, opening its own screen. - if (localChatMessage.chatMessage.messageType in ChatMessage.ICEBERG_TYPES) { + // What a Lightning wallet's key ceremony and its devices + // wrote, before Giza took no part in one: kept as quiet, + // settled lines that lead nowhere, until the migration + // that deletes them (docs/giza-wallet-removal.md, Phase 5). + if (localChatMessage.chatMessage.messageType in ChatMessage.ICEBERG_TYPES || + localChatMessage.chatMessage.messageType in ChatMessage.LIGHTNING_TYPES + ) { RitualNotice( localChatMessage = localChatMessage, - isAnswered = localChatMessage.chatMessage.id in answeredRequests, - isSettled = localChatMessage.chatMessage.id in settledRequests, - onClick = { onOpenIcebergCeremony(localChatMessage.chatMessage.dkgSessionId) }, - opens = stringResource(Res.string.open_the_lightning_wallet_s_key_ceremony), + isAnswered = true, + isSettled = true, + onClick = null, + opens = null, ) return@items } @@ -402,35 +380,18 @@ fun ChatTranscript( return@items } - // What the Lightning wallet's devices told each other. - // Reports, not asks -- an invoice request is the - // operator's node's to answer -- so they stay quiet, - // and each leads to the wallet it is about. - if (localChatMessage.chatMessage.messageType in ChatMessage.LIGHTNING_TYPES) { - RitualNotice( - localChatMessage = localChatMessage, - isAnswered = true, - isSettled = true, - onClick = onOpenLightningWallet, - opens = stringResource(Res.string.open_the_lightning_wallet), - ) - return@items - } - // Something the group signed. Same treatment and for // the same reason: nobody said it. Answered and // settled because it reports rather than asks -- a // quorum has already signed by the time this line - // exists. It leads nowhere, except the Lightning - // wallet's, which lead to the wallet. + // exists. It leads nowhere. if (localChatMessage.chatMessage.messageType in ChatMessage.GROUP_IDENTITY_TYPES) { - val isLightning = localChatMessage.chatMessage.messageType in ChatMessage.GROUP_LIGHTNING_SIGNED_TYPES RitualNotice( localChatMessage = localChatMessage, isAnswered = true, isSettled = true, - onClick = if (isLightning) onOpenLightningWallet else null, - opens = if (isLightning) stringResource(Res.string.open_the_lightning_wallet) else null, + onClick = null, + opens = null, ) return@items } @@ -676,14 +637,9 @@ private fun CeremoniesAwaitingYouNotice( onClick: (ChatMessageListViewModel.AwaitingCeremony) -> Unit, ) { val single = ceremonies.singleOrNull() - val isLightning = single?.ask is ChatMessageListViewModel.Ask.LightningKeyStep || - single?.ask == ChatMessageListViewModel.Ask.LightningWalletOpening val headline = when { single == null -> stringResource(Res.string.ceremonies_need_you, ceremonies.size) - single.ask == ChatMessageListViewModel.Ask.LightningWalletOpening -> - stringResource(Res.string.the_lightning_wallet_s_key_is_ready) - isLightning -> stringResource(Res.string.the_lightning_wallet_s_key_ceremony_needs_you) single.isSubgroup -> stringResource(Res.string.the_subgroups_key_ceremony_needs_you) else -> stringResource(Res.string.the_key_ceremony_needs_you) } @@ -701,12 +657,6 @@ private fun CeremoniesAwaitingYouNotice( DkgApprovalStep.ROUND_2 -> stringResource(Res.string.check_the_combined_result) } is ChatMessageListViewModel.Ask.RoomCreation -> stringResource(Res.string.the_group_has_its_key_finish_setting_it_up) - is ChatMessageListViewModel.Ask.LightningKeyStep -> when (ask.step) { - IcebergApprovalStep.JOIN -> stringResource(Res.string.join_the_ceremony) - IcebergApprovalStep.REVEAL -> stringResource(Res.string.send_your_contributions) - IcebergApprovalStep.CONFIRM -> stringResource(Res.string.confirm_what_you_saw) - } - ChatMessageListViewModel.Ask.LightningWalletOpening -> stringResource(Res.string.open_a_lightning_wallet) } } @@ -723,7 +673,7 @@ private fun CeremoniesAwaitingYouNotice( horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125), verticalAlignment = Alignment.CenterVertically ) { - Icon(if (isLightning) Icons.Default.Bolt else Icons.Default.Key, contentDescription = Decorative) + Icon(Icons.Default.Key, contentDescription = Decorative) Column( modifier = Modifier.weight(1f), diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatMessageListViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatMessageListViewModel.kt index a6e49bc0..38f3da2a 100755 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatMessageListViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatMessageListViewModel.kt @@ -28,8 +28,6 @@ import mobi.giza.compose.repository.ChatRepository import mobi.giza.compose.database.model.types.DkgRitualStage import mobi.giza.compose.database.model.types.DkgApprovalStep import mobi.giza.compose.repository.DkgRepository -import mobi.giza.compose.repository.GroupLightningRepository -import mobi.giza.compose.database.model.types.IcebergApprovalStep import mobi.giza.compose.repository.FrostSigningRepository import mobi.giza.compose.repository.NostrRepository import mobi.giza.compose.text.ProposedEvent @@ -50,7 +48,6 @@ class ChatMessageListViewModel( val chatRepository: ChatRepository, val frostSigningRepository: FrostSigningRepository, val dkgRepository: DkgRepository, - val lightningRepository: GroupLightningRepository, ): ViewModel() { val logger = Logger.withTag(TAG) var chatMessageListUIState: ChatMessageListUIState by mutableStateOf(initialChatMessageListUIState) @@ -112,9 +109,7 @@ class ChatMessageListViewModel( * transcript to its request line -- which for a subgroup means scrolling past * whatever else the room has been used for. * - * Either of the room's two ceremonies: the shared key's, and the Lightning - * wallet's. They open different screens, so [ask] says which this is as well - * as what it wants. docs/group-lightning-transcript.md, Phase 2. + * [ask] says what it wants. */ data class AwaitingCeremony( val sessionId: String, @@ -140,17 +135,6 @@ class ChatMessageListViewModel( * would ever tell them so. */ data class RoomCreation(val chatRoomId: String) : Ask - - /** One of the Lightning wallet's key ceremony's approval gates. */ - data class LightningKeyStep(val step: IcebergApprovalStep) : Ask - - /** - * The Lightning wallet's key, finished, that no wallet uses yet -- the - * Lightning counterpart to [RoomCreation], and asked of the same person: - * whoever opened the ceremony. A key is not a wallet until the group signs - * a statement for it, and until then nothing can be paid into it. - */ - data object LightningWalletOpening : Ask } /** @@ -258,7 +242,7 @@ class ChatMessageListViewModel( // signing screen is where the spend is checked. ProposedSpend.UNREADABLE.copy(detail = "") } else if (local.session.subject == FrostSigningSubject.SWEEP) { - ProposedSpend.UNREADABLE_SWEEP.copy(detail = "") + ProposedSpend.SWEEP.copy(detail = "") } else { local.items.firstNotNullOfOrNull { item -> Event.fromJsonOrNull(item.unsignedEventJson) @@ -484,7 +468,6 @@ class ChatMessageListViewModel( chatRepository: ChatRepository, frostSigningRepository: FrostSigningRepository, dkgRepository: DkgRepository, - lightningRepository: GroupLightningRepository, ): ViewModelProvider.Factory = viewModelFactory { initializer { ChatMessageListViewModel( @@ -494,7 +477,6 @@ class ChatMessageListViewModel( chatRepository = chatRepository, frostSigningRepository = frostSigningRepository, dkgRepository = dkgRepository, - lightningRepository = lightningRepository, ) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/FrostSigningViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/FrostSigningViewModel.kt index aaf21f7f..d2f9484e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/FrostSigningViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/FrostSigningViewModel.kt @@ -1,7 +1,6 @@ package mobi.giza.compose.ui.view.model import mobi.giza.compose.wallet.GroupSpend -import mobi.giza.compose.wallet.lightning.GroupSweep import mobi.giza.compose.database.model.types.FrostSigningSubject import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue @@ -91,9 +90,6 @@ class FrostSigningViewModel( if (session?.subject == FrostSigningSubject.TRANSACTION && checkedSpend == null) { checkedSpend = frostSigningRepository.checkedSpend(session.id) } - if (session?.subject == FrostSigningSubject.SWEEP && checkedSweep == null) { - checkedSweep = frostSigningRepository.checkedSweep(session.id) - } frostSigningUIState = FrostSigningUIState.Loaded( localChatRoom = localChatRoom, @@ -114,14 +110,12 @@ class FrostSigningViewModel( .toSet(), silent = owed, spend = checkedSpend, - sweep = checkedSweep, ) } } } private var checkedSpend: GroupSpend.Checked? = null - private var checkedSweep: GroupSweep.Checked? = null /** One emission of everything the screen is drawn from -- the fourth flow outgrew `Triple`. */ private data class Observed( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupLightningLiquidityViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupLightningLiquidityViewModel.kt deleted file mode 100644 index 94a39e6a..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupLightningLiquidityViewModel.kt +++ /dev/null @@ -1,123 +0,0 @@ -package mobi.giza.compose.ui.view.model - -import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableIntStateOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import co.touchlab.kermit.Logger -import mobi.giza.compose.managers.GroupLightningAuthorisations -import mobi.giza.compose.repository.ChatRepository -import mobi.giza.compose.repository.GroupLightningRepository -import mobi.giza.compose.text.SatsInput -import mobi.giza.compose.text.parseSats -import mobi.giza.compose.ui.view.state.GroupLightningLiquidityUIState -import mobi.giza.compose.wallet.GroupLightningRollout -import mobi.giza.compose.wallet.lightning.LiquidityPrice -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.Chain -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext - -/** - * A liquidity purchase, as a proposal (`docs/group-lightning-liquidity.md`, Phase 7): one of Phoenix's - * amounts that the LSP sells and the channel has room for, priced on this device from what the - * operator reported, and a fee cap with room above the estimate. The group signs it like any decision, - * and the operator's node buys once it has. - */ -class GroupLightningLiquidityViewModel( - val activeUserPublicKey: HexKey, - val chatRoomId: String, - val chain: Chain, - initialUIState: GroupLightningLiquidityUIState, - private val chatRepository: ChatRepository, - private val lightningRepository: GroupLightningRepository, -) : ViewModel() { - private val logger = Logger.withTag(TAG) - - var uiState: GroupLightningLiquidityUIState by mutableStateOf(initialUIState) - private set - - /** Which of the offered amounts is chosen. */ - var choice by mutableIntStateOf(0) - - val maxFeeField = TextFieldState() - /** The review sheet is open, and whether its acknowledgement is ticked. */ - var reviewing by mutableStateOf(false) - var acknowledged by mutableStateOf(false) - val isActionPending: MutableState = mutableStateOf(false) - - fun initiate() { - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - ?: return@launch run { uiState = GroupLightningLiquidityUIState.Error("Couldn't find the group") } - val wallet = lightningRepository.lightningWallet(chatRoomId, chain) - ?: return@launch run { uiState = GroupLightningLiquidityUIState.Unavailable(LiquidityPrice.Availability.NoOperator) } - val hasOperator = lightningRepository.operator(chatRoomId, chain, wallet.statement.wallet)?.publicKey != null - lightningRepository.observeReport(chatRoomId, chain, wallet.statement.wallet).collect { report -> - uiState = when (val availability = LiquidityPrice.availability(report?.snapshot, hasOperator, GroupLightningRollout.channelCapFor(chain)?.sat)) { - is LiquidityPrice.Availability.Available -> { - choice = choice.coerceIn(0, availability.offered.lastIndex) - GroupLightningLiquidityUIState.Form(localChatRoom, wallet, report!!.snapshot, availability) - } - else -> GroupLightningLiquidityUIState.Unavailable(availability) - } - } - } - } - - /** The amount chosen, in sats. */ - fun amountSat(form: GroupLightningLiquidityUIState.Form): Long = form.available.offered[choice.coerceIn(0, form.available.offered.lastIndex)] - - fun price(form: GroupLightningLiquidityUIState.Form): LiquidityPrice.Price? = - LiquidityPrice.price(form.available.rates, amountSat(form), form.available.feeratePerByte) - - fun maxFee(): SatsInput = parseSats(maxFeeField.text) - - /** The cap the proposal will carry: the field's, or the estimate with room above it when the field is empty. */ - fun maxFeeSat(form: GroupLightningLiquidityUIState.Form): Long? = when (val fee = maxFee()) { - SatsInput.Empty -> price(form)?.let(LiquidityPrice::defaultCap) - is SatsInput.Sats -> fee.amount.sat - else -> null - } - - fun propose(onSession: (sessionId: String) -> Unit, onFailure: () -> Unit) { - val form = uiState as? GroupLightningLiquidityUIState.Form ?: return - val cap = maxFeeSat(form) ?: return onFailure() - val buy = GroupLightningAuthorisations.prepareBuyLiquidity(form.wallet, form.available.channel.channelId, form.available.channel.capacitySat, amountSat(form), cap).getOrNull() ?: return onFailure() - if (isActionPending.value) return - isActionPending.value = true - viewModelScope.launch(Dispatchers.IO) { - val session = runCatching { lightningRepository.proposeLiquidity(form.localChatRoom, activeUserPublicKey, buy) } - .onFailure { logger.e("Liquidity proposal in $chatRoomId failed", it) }.getOrNull() - isActionPending.value = false - withContext(Dispatchers.Main) { - reviewing = false - if (session != null) onSession(session.id) else onFailure() - } - } - } - - companion object { - private const val TAG = "GroupLightningLiquidityViewModel" - - fun factory( - activeUserPublicKey: HexKey, - chatRoomId: String, - chain: Chain, - chatRepository: ChatRepository, - lightningRepository: GroupLightningRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - GroupLightningLiquidityViewModel(activeUserPublicKey, chatRoomId, chain, GroupLightningLiquidityUIState.Loading, chatRepository, lightningRepository) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupLightningReceiveViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupLightningReceiveViewModel.kt deleted file mode 100644 index 395e4a1a..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupLightningReceiveViewModel.kt +++ /dev/null @@ -1,97 +0,0 @@ -package mobi.giza.compose.ui.view.model - -import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import co.touchlab.kermit.Logger -import mobi.giza.compose.repository.ChatRepository -import mobi.giza.compose.repository.GroupLightningRepository -import mobi.giza.compose.text.SatsInput -import mobi.giza.compose.text.parseSats -import mobi.giza.compose.ui.view.state.GroupLightningReceiveUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.Chain -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.flow.filterNotNull -import kotlinx.coroutines.flow.first -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext - -/** - * Asks the operator's node for an invoice and waits for it. Any member may ask; the invoice arrives - * only once the inbound path has checked that it pays the node the group signed for. - */ -class GroupLightningReceiveViewModel( - val activeUserPublicKey: HexKey, - val chatRoomId: String, - val chain: Chain, - initialUIState: GroupLightningReceiveUIState, - private val chatRepository: ChatRepository, - private val lightningRepository: GroupLightningRepository, -) : ViewModel() { - private val logger = Logger.withTag(TAG) - - var uiState: GroupLightningReceiveUIState by mutableStateOf(initialUIState) - private set - - val amountField = TextFieldState() - val descriptionField = TextFieldState() - val isActionPending: MutableState = mutableStateOf(false) - - fun initiate() { - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - ?: return@launch run { uiState = GroupLightningReceiveUIState.Error("Couldn't find the group") } - val wallet = lightningRepository.lightningWallet(chatRoomId, chain) - uiState = if (wallet == null || lightningRepository.operator(chatRoomId, chain, wallet.statement.wallet)?.publicKey == null) GroupLightningReceiveUIState.Unavailable - else GroupLightningReceiveUIState.Form(localChatRoom, wallet, lightningRepository.observeReport(chatRoomId, chain, wallet.statement.wallet).first()?.snapshot?.offer) - } - } - - /** The amount typed, in sats; null for none, and [SatsInput] problems as they are. */ - fun amount(): SatsInput = parseSats(amountField.text) - - fun request(onFailure: () -> Unit) { - val form = uiState as? GroupLightningReceiveUIState.Form ?: return - val amountMsat = when (val amount = amount()) { - SatsInput.Empty -> null - is SatsInput.Sats -> amount.amount.sat * 1000 - else -> return onFailure() - } - if (isActionPending.value) return - isActionPending.value = true - viewModelScope.launch(Dispatchers.IO) { - val requestId = runCatching { - lightningRepository.requestInvoice(form.localChatRoom, activeUserPublicKey, form.wallet, amountMsat, descriptionField.text.toString().trim()) - }.onFailure { logger.e("Invoice request in $chatRoomId failed", it) }.getOrNull() - isActionPending.value = false - if (requestId == null) return@launch withContext(Dispatchers.Main) { onFailure() } - uiState = GroupLightningReceiveUIState.Waiting(requestId) - val invoice = lightningRepository.observeInvoice(chatRoomId, chain, form.wallet.statement.wallet, requestId).filterNotNull().first() - uiState = GroupLightningReceiveUIState.Invoice(invoice.bolt11) - } - } - - companion object { - private const val TAG = "GroupLightningReceiveViewModel" - - fun factory( - activeUserPublicKey: HexKey, - chatRoomId: String, - chain: Chain, - chatRepository: ChatRepository, - lightningRepository: GroupLightningRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - GroupLightningReceiveViewModel(activeUserPublicKey, chatRoomId, chain, GroupLightningReceiveUIState.Loading, chatRepository, lightningRepository) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupLightningSendViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupLightningSendViewModel.kt deleted file mode 100644 index f471442f..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupLightningSendViewModel.kt +++ /dev/null @@ -1,115 +0,0 @@ -package mobi.giza.compose.ui.view.model - -import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import co.touchlab.kermit.Logger -import mobi.giza.compose.managers.GroupLightningAuthorisations -import mobi.giza.compose.nostr.lightning.GroupLightningAuthorisationEvent -import mobi.giza.compose.repository.ChatRepository -import mobi.giza.compose.repository.GroupLightningRepository -import mobi.giza.compose.text.SatsInput -import mobi.giza.compose.text.parseSats -import mobi.giza.compose.ui.view.state.GroupLightningSendUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.Chain -import fr.acinq.lightning.payment.Bolt11Invoice -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext - -/** - * A payment from the group's Lightning wallet, as a proposal: the invoice, the amount when the invoice - * names none, and the most the fee may be. The group signs it like any decision, and the operator's - * node pays it once it has. - */ -class GroupLightningSendViewModel( - val activeUserPublicKey: HexKey, - val chatRoomId: String, - val chain: Chain, - initialUIState: GroupLightningSendUIState, - private val chatRepository: ChatRepository, - private val lightningRepository: GroupLightningRepository, -) : ViewModel() { - private val logger = Logger.withTag(TAG) - - var uiState: GroupLightningSendUIState by mutableStateOf(initialUIState) - private set - - val invoiceField = TextFieldState() - val amountField = TextFieldState() - val maxFeeField = TextFieldState() - val isActionPending: MutableState = mutableStateOf(false) - - fun initiate() { - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - ?: return@launch run { uiState = GroupLightningSendUIState.Error("Couldn't find the group") } - val wallet = lightningRepository.lightningWallet(chatRoomId, chain) - uiState = if (wallet == null || lightningRepository.operator(chatRoomId, chain, wallet.statement.wallet)?.publicKey == null) GroupLightningSendUIState.Unavailable - else GroupLightningSendUIState.Form(localChatRoom, wallet) - } - } - - fun amount(): SatsInput = parseSats(amountField.text) - - /** The amount the invoice in the field names, or null when it names none or is not an invoice. */ - fun invoiceAmountMsat(): Long? = - runCatching { Bolt11Invoice.read(invoiceField.text.toString().trim().removePrefix("lightning:").removePrefix("LIGHTNING:")).get().amount?.msat }.getOrNull() - fun maxFee(): SatsInput = parseSats(maxFeeField.text) - - /** The fee limit when the field is left empty: a percent of [amountSat], and never under ten sats. */ - fun defaultMaxFeeSat(amountSat: Long): Long = maxOf(MIN_FEE_SAT, amountSat / 100) - - /** What the form would propose, or why it cannot; null while the invoice field is empty. */ - fun preview(): Result? { - val form = uiState as? GroupLightningSendUIState.Form ?: return null - if (invoiceField.text.isBlank()) return null - val amountMsat = (amount() as? SatsInput.Sats)?.amount?.sat?.times(1000) - val first = GroupLightningAuthorisations.prepare(form.wallet, invoiceField.text.toString(), amountMsat, maxFeeMsat = 0) - val pay = first.getOrElse { return first } - val maxFeeMsat = when (val fee = maxFee()) { - SatsInput.Empty -> defaultMaxFeeSat(pay.amountMsat / 1000) * 1000 - is SatsInput.Sats -> fee.amount.sat * 1000 - else -> return null - } - return Result.success(pay.copy(maxFeeMsat = maxFeeMsat)) - } - - fun propose(onSession: (sessionId: String) -> Unit, onFailure: () -> Unit) { - val form = uiState as? GroupLightningSendUIState.Form ?: return - val pay = preview()?.getOrNull() ?: return onFailure() - if (isActionPending.value) return - isActionPending.value = true - viewModelScope.launch(Dispatchers.IO) { - val session = runCatching { lightningRepository.proposePayment(form.localChatRoom, activeUserPublicKey, pay) } - .onFailure { logger.e("Payment proposal in $chatRoomId failed", it) }.getOrNull() - isActionPending.value = false - withContext(Dispatchers.Main) { if (session != null) onSession(session.id) else onFailure() } - } - } - - companion object { - private const val TAG = "GroupLightningSendViewModel" - const val MIN_FEE_SAT = 10L - - fun factory( - activeUserPublicKey: HexKey, - chatRoomId: String, - chain: Chain, - chatRepository: ChatRepository, - lightningRepository: GroupLightningRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - GroupLightningSendViewModel(activeUserPublicKey, chatRoomId, chain, GroupLightningSendUIState.Loading, chatRepository, lightningRepository) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupLightningWalletViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupLightningWalletViewModel.kt deleted file mode 100644 index 4255bc42..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupLightningWalletViewModel.kt +++ /dev/null @@ -1,191 +0,0 @@ -package mobi.giza.compose.ui.view.model - -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import co.touchlab.kermit.Logger -import mobi.giza.compose.database.model.FrostSigningSession -import mobi.giza.compose.database.model.types.IcebergRitualStage -import mobi.giza.compose.identity.Identity -import mobi.giza.compose.repository.ChatRepository -import mobi.giza.compose.repository.GroupLightningRepository -import mobi.giza.compose.ui.view.state.GroupLightningWalletUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.Chain -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.Job -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.combine -import kotlinx.coroutines.flow.first -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext - -/** - * The group's Lightning wallet, read for what the room has agreed: whether it can have one yet, the - * statement that opened it, and who runs its node. Every action is a proposal the group signs. - */ -class GroupLightningWalletViewModel( - val activeUserPublicKey: HexKey, - val chatRoomId: String, - val chain: Chain, - initialUIState: GroupLightningWalletUIState, - private val activeIdentityStateFlow: StateFlow, - private val chatRepository: ChatRepository, - private val lightningRepository: GroupLightningRepository, -) : ViewModel() { - private val logger = Logger.withTag(TAG) - - var uiState: GroupLightningWalletUIState by mutableStateOf(initialUIState) - private set - - val isActionPending: MutableState = mutableStateOf(false) - - fun initiate() { - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - if (localChatRoom == null) { - uiState = GroupLightningWalletUIState.Error("Couldn't find the group") - return@launch - } - uiState = when { - !lightningRepository.hasOnchainWallet(chatRoomId, chain) -> GroupLightningWalletUIState.NeedsOnchainWallet(localChatRoom) - else -> { - val wallet = lightningRepository.lightningWallet(chatRoomId, chain) - val key = lightningRepository.completedCeremony(chatRoomId) - when { - wallet != null -> { - val operator = lightningRepository.operator(chatRoomId, chain, wallet.statement.wallet) - GroupLightningWalletUIState.Opened( - localChatRoom = localChatRoom, - wallet = wallet, - operator = operator, - isParticipant = activeUserPublicKey.lowercase() in wallet.statement.participants && wallet.ceremony?.share != null, - isOperator = operator?.publicKey == activeUserPublicKey, - departed = lightningRepository.departed(wallet), - canOpenNew = lightningRepository.hasUnusedKey(chatRoomId, chain) && canPropose(), - earlier = lightningRepository.earlierWallets(chatRoomId, chain).map { earlier -> - val report = lightningRepository.observeReport(chatRoomId, chain, earlier.statement.wallet).first() - GroupLightningWalletUIState.Earlier( - wallet = earlier, - operator = lightningRepository.operator(chatRoomId, chain, earlier.statement.wallet), - report = report, - unswept = lightningRepository.unswept(chatRoomId, report), - ) - }, - ) - } - key != null -> GroupLightningWalletUIState.NotOpened( - localChatRoom = localChatRoom, - key = key, - canPropose = canPropose(), - ) - else -> { - val running = lightningRepository.observeCeremonies(chatRoomId).first().firstOrNull { it.stage != IcebergRitualStage.FAILED } - GroupLightningWalletUIState.NeedsKey(localChatRoom, running, canMakeKey = lightningRepository.ceremonyThresholds(chatRoomId).isNotEmpty()) - } - } - } - } - if (uiState is GroupLightningWalletUIState.Opened) watchReports() - } - } - - /** Whether this device can propose a wallet statement: an LSP to name, and a key to send the seed with. */ - private fun canPropose(): Boolean = lightningRepository.lspNodeId(chain) != null && activeIdentityStateFlow.value?.nostrPrivateKey != null - - private var watching: Job? = null - - /** Keeps an opened wallet's snapshot and payments current as the operator's reports arrive. */ - private fun watchReports() { - watching?.cancel() - watching = viewModelScope.launch(Dispatchers.IO) { - val wallet = (uiState as? GroupLightningWalletUIState.Opened)?.wallet?.statement?.wallet ?: return@launch - combine(lightningRepository.observeReport(chatRoomId, chain, wallet), lightningRepository.observePayments(chatRoomId, chain, wallet)) { report, payments -> report to payments } - .collect { (report, payments) -> - val unswept = lightningRepository.unswept(chatRoomId, report) - (uiState as? GroupLightningWalletUIState.Opened)?.let { uiState = it.copy(report = report, payments = payments, unswept = unswept) } - } - } - } - - /** Proposes the wallet's statement; the wallet exists once a quorum signs, on the session it returns. */ - fun openWallet(onSession: (sessionId: String) -> Unit, onFailure: () -> Unit) { - // The first wallet, or the one a re-key opens beside the current one under a new key. - val localChatRoom = (uiState as? GroupLightningWalletUIState.NotOpened)?.localChatRoom - ?: (uiState as? GroupLightningWalletUIState.Opened)?.takeIf { it.canOpenNew }?.localChatRoom - ?: return - val privateKey = activeIdentityStateFlow.value?.nostrPrivateKey?.value?.toByteArray() ?: return onFailure() - act(onSession, onFailure) { lightningRepository.proposeWallet(localChatRoom, activeUserPublicKey, privateKey, chain) } - } - - /** Nominates this device to run [wallet]'s node: the current wallet's when null. */ - fun nominateSelf(onSession: (sessionId: String) -> Unit, onFailure: () -> Unit, wallet: Long? = null) { - val state = uiState as? GroupLightningWalletUIState.Opened ?: return - act(onSession, onFailure) { lightningRepository.nominateSelf(state.localChatRoom, activeUserPublicKey, chain, wallet ?: state.wallet.statement.wallet) } - } - - fun stepDown(onSession: (sessionId: String) -> Unit, onFailure: () -> Unit) { - val state = uiState as? GroupLightningWalletUIState.Opened ?: return - act(onSession, onFailure) { lightningRepository.stepDown(state.localChatRoom, activeUserPublicKey, chain, state.wallet.statement.wallet) } - } - - /** Proposes closing every channel an earlier wallet still has, so its money reaches the onchain wallet. */ - fun closeEarlier(earlier: GroupLightningWalletUIState.Earlier, onSession: (sessionId: String) -> Unit, onFailure: () -> Unit) { - val state = uiState as? GroupLightningWalletUIState.Opened ?: return - if (earlier.openChannels.isEmpty()) return - act(onSession, onFailure) { lightningRepository.proposeCloseAll(state.localChatRoom, activeUserPublicKey, earlier.wallet, earlier.openChannels) } - } - - /** Proposes sweeping what an earlier wallet's closed channels left the group. */ - fun sweepEarlier(earlier: GroupLightningWalletUIState.Earlier, onSession: (sessionId: String) -> Unit, onFailure: () -> Unit) { - val state = uiState as? GroupLightningWalletUIState.Opened ?: return - if (earlier.unswept.isEmpty()) return - act(onSession, onFailure) { lightningRepository.proposeSweep(state.localChatRoom, activeUserPublicKey, earlier.wallet, earlier.unswept) } - } - - /** Proposes closing [channelId] to the onchain wallet, or by force when the LSP is gone. */ - fun close(channelId: String, force: Boolean, onSession: (sessionId: String) -> Unit, onFailure: () -> Unit) { - val state = uiState as? GroupLightningWalletUIState.Opened ?: return - act(onSession, onFailure) { lightningRepository.proposeClose(state.localChatRoom, activeUserPublicKey, state.wallet, channelId, force) } - } - - /** Proposes sweeping everything closed channels left the group into the onchain wallet. */ - fun sweep(onSession: (sessionId: String) -> Unit, onFailure: () -> Unit) { - val state = uiState as? GroupLightningWalletUIState.Opened ?: return - if (state.unswept.isEmpty()) return - act(onSession, onFailure) { lightningRepository.proposeSweep(state.localChatRoom, activeUserPublicKey, state.wallet, state.unswept) } - } - - private fun act(onSession: (String) -> Unit, onFailure: () -> Unit, propose: suspend () -> FrostSigningSession) { - if (isActionPending.value) return - isActionPending.value = true - viewModelScope.launch(Dispatchers.IO) { - val session = runCatching { propose() }.onFailure { logger.e("Lightning wallet proposal in $chatRoomId failed", it) }.getOrNull() - isActionPending.value = false - withContext(Dispatchers.Main) { if (session != null) onSession(session.id) else onFailure() } - } - } - - companion object { - private const val TAG = "GroupLightningWalletViewModel" - - fun factory( - activeUserPublicKey: HexKey, - chatRoomId: String, - chain: Chain, - activeIdentityStateFlow: StateFlow, - chatRepository: ChatRepository, - lightningRepository: GroupLightningRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - GroupLightningWalletViewModel(activeUserPublicKey, chatRoomId, chain, GroupLightningWalletUIState.Loading, activeIdentityStateFlow, chatRepository, lightningRepository) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupWalletViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupWalletViewModel.kt index 55553847..56ecfaf9 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupWalletViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupWalletViewModel.kt @@ -7,7 +7,6 @@ import mobi.giza.compose.database.model.GroupTransaction import mobi.giza.compose.ui.view.state.SpendRow import mobi.giza.compose.ui.view.state.SpendStatus import mobi.giza.compose.wallet.GroupSpend -import mobi.giza.compose.wallet.lightning.GroupSweep import mobi.giza.compose.wallet.GroupSpendBuilder import mobi.giza.compose.wallet.GroupTransactionWatcher import mobi.giza.compose.wallet.GroupWalletRollout @@ -211,14 +210,12 @@ class GroupWalletViewModel( /** Checked once per session: the PSBT is write-once, so what it says cannot change. */ private val checkedSpends = mutableMapOf() - private val checkedSweeps = mutableMapOf() private suspend fun rowOf(transaction: GroupTransaction): SpendRow { val sessionId = transaction.frostSigningSessionId val spend = checkedSpends.getOrPut(sessionId) { frostSigningRepository.checkedSpend(sessionId) } - val sweep = if (spend == null) checkedSweeps.getOrPut(sessionId) { frostSigningRepository.checkedSweep(sessionId) } else null val stage = frostSigningRepository.getSessionById(sessionId)?.stage - return SpendRow(transaction = transaction, status = SpendStatus.of(stage, transaction), spend = spend, sweep = sweep) + return SpendRow(transaction = transaction, status = SpendStatus.of(stage, transaction), spend = spend) } /** Sends a signed spend again now. Only worth anything while Electrum has not reported it back. */ diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/IcebergCeremonyViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/IcebergCeremonyViewModel.kt deleted file mode 100644 index cf5f4336..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/IcebergCeremonyViewModel.kt +++ /dev/null @@ -1,195 +0,0 @@ -package mobi.giza.compose.ui.view.model - -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import co.touchlab.kermit.Logger -import mobi.giza.compose.database.model.IcebergKeySession -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.database.model.types.IcebergRitualStage -import mobi.giza.compose.identity.Identity -import mobi.giza.compose.repository.ChatRepository -import mobi.giza.compose.repository.GroupLightningRepository -import mobi.giza.compose.ui.view.state.IcebergCeremonyUIState -import mobi.giza.compose.wallet.GroupLightningRollout -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.Chain -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.Job -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.map -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext - -/** - * Watches a group's Lightning wallet key ceremony, opens one, joins it, and abandons it. - * - * Nothing here drives the protocol: [mobi.giza.compose.managers.IcebergRitualManager] - * advances as messages arrive, and this only reads the session and asks its owner whether to join. - */ -class IcebergCeremonyViewModel( - val activeUserPublicKey: HexKey, - val chatRoomId: String, - /** The ceremony to show, when the caller knew which; null shows the room's newest. */ - val sessionId: String?, - val chain: Chain, - initialUIState: IcebergCeremonyUIState, - private val activeIdentityStateFlow: StateFlow, - private val chatRepository: ChatRepository, - private val lightningRepository: GroupLightningRepository, -) : ViewModel() { - private val logger = Logger.withTag(TAG) - - var uiState: IcebergCeremonyUIState by mutableStateOf(initialUIState) - private set - - val isActionPending: MutableState = mutableStateOf(false) - - /** The threshold a new ceremony would be opened at; starts at the smallest the group allows. */ - val threshold: MutableState = mutableStateOf(null) - - private var watching: Job? = null - - /** The ceremonies this screen has nudged once, so a re-read does not nudge them again. */ - private val resumed = mutableSetOf() - - fun initiate() { - watching?.cancel() - watching = viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - if (localChatRoom == null) { - uiState = IcebergCeremonyUIState.Error("Couldn't find the group") - return@launch - } - val thresholds = lightningRepository.ceremonyThresholds(chatRoomId) - if (threshold.value == null) threshold.value = thresholds.firstOrNull() - val hasOnchainWallet = lightningRepository.hasOnchainWallet(chatRoomId, chain) - val holderCount = lightningRepository.keyHolderCount(chatRoomId) - - val sessions = if (sessionId != null) { - lightningRepository.observeCeremony(sessionId) - } else { - lightningRepository.observeCeremonies(chatRoomId).map { it.firstOrNull() } - } - sessions.collect { session -> - if (session != null) resume(localChatRoom, session) - val messages = session?.let { lightningRepository.ceremonyMessages(it.id) }.orEmpty() - uiState = IcebergCeremonyUIState.Loaded( - localChatRoom = localChatRoom, - session = session, - progress = session?.participants().orEmpty().associateWith { p -> messages.count { it.participantPublicKey == p } }, - pending = session?.let { lightningRepository.pendingApproval(it) }, - thresholds = thresholds, - holderCount = holderCount, - hasOnchainWallet = hasOnchainWallet, - ) - } - } - } - - /** - * A joined ceremony this device has not moved since an earlier build stopped it at a gate that no - * longer exists: the others are waiting on it, so nothing will arrive to move it. Once per ceremony. - */ - private suspend fun resume(localChatRoom: LocalChatRoom, session: IcebergKeySession) { - val running = session.stage != IcebergRitualStage.FAILED && session.stage != IcebergRitualStage.COMPLETE - if (!running || session.joinApprovedAt == null || !resumed.add(session.id)) return - val privateKey = activeIdentityStateFlow.value?.nostrPrivateKey?.value?.toByteArray() ?: return - runCatching { lightningRepository.resumeCeremony(localChatRoom, session.id, privateKey) } - .onFailure { logger.e("Could not resume ${session.id}", it) } - } - - /** Whether this device can open a ceremony: none running, a deployable size, an onchain wallet, a key to sign with. */ - fun canPropose(): Boolean { - val loaded = uiState as? IcebergCeremonyUIState.Loaded ?: return false - val running = loaded.session?.stage?.let { it != IcebergRitualStage.FAILED && it != IcebergRitualStage.COMPLETE } == true - return !running && loaded.thresholds.isNotEmpty() && loaded.hasOnchainWallet && GroupLightningRollout.allows(chain) && - activeIdentityStateFlow.value?.nostrPrivateKey != null - } - - fun propose(onFailure: () -> Unit) { - val loaded = uiState as? IcebergCeremonyUIState.Loaded ?: return - val t = threshold.value ?: return - val privateKey = activeIdentityStateFlow.value?.nostrPrivateKey?.value?.toByteArray() ?: return onFailure() - if (isActionPending.value) return - isActionPending.value = true - viewModelScope.launch(Dispatchers.IO) { - val proposed = runCatching { lightningRepository.proposeCeremony(loaded.localChatRoom, activeUserPublicKey, privateKey, t, chain) } - .onFailure { logger.e("Could not open a Lightning wallet key ceremony in $chatRoomId", it) } - .getOrNull() - isActionPending.value = false - if (proposed == null) withContext(Dispatchers.Main) { onFailure() } - } - } - - fun approve(onFailure: () -> Unit) { - val loaded = uiState as? IcebergCeremonyUIState.Loaded ?: return - val session = loaded.session ?: return - val step = loaded.pending ?: return - val privateKey = activeIdentityStateFlow.value?.nostrPrivateKey?.value?.toByteArray() ?: return onFailure() - if (isActionPending.value) return - isActionPending.value = true - viewModelScope.launch(Dispatchers.IO) { - val done = runCatching { lightningRepository.approveCeremony(loaded.localChatRoom, session.id, step, privateKey) } - .onFailure { logger.e("Could not approve $step of ${session.id}", it) } - .isSuccess - isActionPending.value = false - if (!done) withContext(Dispatchers.Main) { onFailure() } - // The ceremony may have moved without a new row being written; read it again. - initiate() - } - } - - /** Whether the shown ceremony is still running, which is when a participant may end it. */ - fun canAbandon(): Boolean { - val loaded = uiState as? IcebergCeremonyUIState.Loaded ?: return false - return loaded.session?.stage?.let { it != IcebergRitualStage.FAILED && it != IcebergRitualStage.COMPLETE } == true - } - - fun abandon(onFailure: () -> Unit) { - val loaded = uiState as? IcebergCeremonyUIState.Loaded ?: return - val session = loaded.session ?: return - if (isActionPending.value) return - isActionPending.value = true - viewModelScope.launch(Dispatchers.IO) { - val abandoned = runCatching { lightningRepository.abandonCeremony(loaded.localChatRoom, session.id) } - .onFailure { logger.e("Could not abandon ${session.id}", it) } - .getOrDefault(false) - isActionPending.value = false - if (!abandoned) withContext(Dispatchers.Main) { onFailure() } - } - } - - companion object { - private const val TAG = "IcebergCeremonyViewModel" - - fun factory( - activeUserPublicKey: HexKey, - chatRoomId: String, - sessionId: String?, - chain: Chain, - activeIdentityStateFlow: StateFlow, - chatRepository: ChatRepository, - lightningRepository: GroupLightningRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - IcebergCeremonyViewModel( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId, - chain = chain, - initialUIState = IcebergCeremonyUIState.Loading, - activeIdentityStateFlow = activeIdentityStateFlow, - chatRepository = chatRepository, - lightningRepository = lightningRepository, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ProposalListViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ProposalListViewModel.kt index 9b2dc716..91f5d56b 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ProposalListViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ProposalListViewModel.kt @@ -170,7 +170,7 @@ class ProposalListViewModel( ?: ProposedSpend.UNREADABLE ) } else if (local.session.subject == FrostSigningSubject.SWEEP) { - listOf(frostSigningRepository.checkedSweep(local.session.id)?.let(ProposedSpend::summarize) ?: ProposedSpend.UNREADABLE_SWEEP) + listOf(ProposedSpend.SWEEP) } else { events.map { ProposedEvent.summarize(it) } }, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/FrostSigningUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/FrostSigningUIState.kt index 036e9a1b..d7b61d6e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/FrostSigningUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/FrostSigningUIState.kt @@ -1,7 +1,6 @@ package mobi.giza.compose.ui.view.state import mobi.giza.compose.wallet.GroupSpend -import mobi.giza.compose.wallet.lightning.GroupSweep import com.vitorpamplona.quartz.nip01Core.core.HexKey import kotlin.time.Clock import kotlin.time.Instant @@ -66,8 +65,6 @@ sealed interface FrostSigningUIState { * the screen refuses to let anybody sign. */ val spend: GroupSpend.Checked? = null, - /** The sweep a sweep session signs, as this device checked it; null for anything else. */ - val sweep: GroupSweep.Checked? = null, ): FrostSigningUIState { /** * The members the session can be answered by, as rows to draw. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupLightningLiquidityUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupLightningLiquidityUIState.kt deleted file mode 100644 index c8c7205d..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupLightningLiquidityUIState.kt +++ /dev/null @@ -1,26 +0,0 @@ -package mobi.giza.compose.ui.view.state - -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.managers.GroupLightningWalletManager -import mobi.giza.compose.wallet.lightning.LiquidityPrice -import mobi.giza.compose.wallet.lightning.WalletWire - -/** Asking the group to buy inbound liquidity (`docs/group-lightning-liquidity.md`, Phase 7). */ -sealed class GroupLightningLiquidityUIState { - data object Loading : GroupLightningLiquidityUIState() - - data class Error(val message: String) : GroupLightningLiquidityUIState() - - /** Nothing can be asked for now, and [why]. */ - data class Unavailable(val why: LiquidityPrice.Availability) : GroupLightningLiquidityUIState() - - /** What can be bought, priced from the operator's [snapshot] of the term [term]. */ - data class Form( - val localChatRoom: LocalChatRoom, - val wallet: GroupLightningWalletManager.Wallet, - val snapshot: WalletWire.Snapshot, - val available: LiquidityPrice.Availability.Available, - ) : GroupLightningLiquidityUIState() { - val term: Long get() = snapshot.term - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupLightningReceiveUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupLightningReceiveUIState.kt deleted file mode 100644 index 6ca974af..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupLightningReceiveUIState.kt +++ /dev/null @@ -1,22 +0,0 @@ -package mobi.giza.compose.ui.view.state - -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.managers.GroupLightningWalletManager - -/** Asking the operator's node for an invoice: the form, the wait for the operator's device, the invoice. */ -sealed class GroupLightningReceiveUIState { - data object Loading : GroupLightningReceiveUIState() - - data class Error(val message: String) : GroupLightningReceiveUIState() - - /** No wallet, or no operator to run its node. */ - data object Unavailable : GroupLightningReceiveUIState() - - /** [offer] is the group node's reusable Bolt12 offer, once a snapshot carried one this device checked. */ - data class Form(val localChatRoom: LocalChatRoom, val wallet: GroupLightningWalletManager.Wallet, val offer: String? = null) : GroupLightningReceiveUIState() - - data class Waiting(val requestId: String) : GroupLightningReceiveUIState() - - /** An invoice the operator made, already checked to pay the group's node. */ - data class Invoice(val bolt11: String) : GroupLightningReceiveUIState() -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupLightningSendUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupLightningSendUIState.kt deleted file mode 100644 index 83b86410..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupLightningSendUIState.kt +++ /dev/null @@ -1,16 +0,0 @@ -package mobi.giza.compose.ui.view.state - -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.managers.GroupLightningWalletManager - -/** Proposing a payment from the group's Lightning wallet. */ -sealed class GroupLightningSendUIState { - data object Loading : GroupLightningSendUIState() - - data class Error(val message: String) : GroupLightningSendUIState() - - /** No wallet, or no operator whose node would pay. */ - data object Unavailable : GroupLightningSendUIState() - - data class Form(val localChatRoom: LocalChatRoom, val wallet: GroupLightningWalletManager.Wallet) : GroupLightningSendUIState() -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupLightningWalletUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupLightningWalletUIState.kt deleted file mode 100644 index efac75e4..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupLightningWalletUIState.kt +++ /dev/null @@ -1,59 +0,0 @@ -package mobi.giza.compose.ui.view.state - -import mobi.giza.compose.database.model.IcebergKeySession -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.database.model.GroupLightningPaymentRow -import mobi.giza.compose.managers.GroupLightningOperatorManager -import mobi.giza.compose.managers.GroupLightningReports -import mobi.giza.compose.managers.GroupLightningWalletManager -import mobi.giza.compose.wallet.lightning.GroupSweep - -/** - * The group's Lightning wallet screen, through every state a group passes on its way to one: no onchain - * wallet to close to, no key, a key but no statement, and a wallet with or without an operator. - */ -sealed class GroupLightningWalletUIState { - data object Loading : GroupLightningWalletUIState() - - data class Error(val message: String) : GroupLightningWalletUIState() - - /** The onchain wallet on the Lightning wallet's network is not open yet (decision D2). */ - data class NeedsOnchainWallet(val localChatRoom: LocalChatRoom) : GroupLightningWalletUIState() - - /** No completed Iceberg key; [ceremony] is one in progress, if any. [canMakeKey] is false for a group too small. */ - data class NeedsKey(val localChatRoom: LocalChatRoom, val ceremony: IcebergKeySession?, val canMakeKey: Boolean) : GroupLightningWalletUIState() - - /** A key, and no statement the group signed. [canPropose] is whether this device holds a share and knows the LSP. */ - data class NotOpened(val localChatRoom: LocalChatRoom, val key: IcebergKeySession, val canPropose: Boolean) : GroupLightningWalletUIState() - - data class Opened( - val localChatRoom: LocalChatRoom, - val wallet: GroupLightningWalletManager.Wallet, - val operator: GroupLightningOperatorManager.Operator?, - /** Whether this device holds a share of the key, and so can be elected and can co-sign. */ - val isParticipant: Boolean, - val isOperator: Boolean, - /** The operator's newest snapshot, or null before the first arrives. */ - val report: GroupLightningReports.Report? = null, - val payments: List = emptyList(), - /** What closed channels left the group that no sweep spends yet. */ - val unswept: List = emptyList(), - /** Participants who have left the room, and still hold a share of the key and the node's seed. */ - val departed: List = emptyList(), - /** Whether a new wallet can be opened now: a key no wallet uses, and this device can propose. */ - val canOpenNew: Boolean = false, - /** The wallets a re-key left behind, whose channels are still to be closed and swept. */ - val earlier: List = emptyList(), - ) : GroupLightningWalletUIState() - - /** A wallet a re-key left behind, with what its operator last said of it. */ - data class Earlier( - val wallet: GroupLightningWalletManager.Wallet, - val operator: GroupLightningOperatorManager.Operator?, - val report: GroupLightningReports.Report?, - val unswept: List, - ) { - val openChannels: List get() = report?.checks?.map { it.channel.channelId }.orEmpty() - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupWalletUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupWalletUIState.kt index 1985a6d3..16a43755 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupWalletUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupWalletUIState.kt @@ -10,7 +10,6 @@ import fr.acinq.lightning.utils.sum import mobi.giza.compose.nostr.wallet.GroupWallet import mobi.giza.compose.wallet.GroupWalletState import mobi.giza.compose.wallet.GroupSpend -import mobi.giza.compose.wallet.lightning.GroupSweep import mobi.giza.compose.database.model.GroupTransaction import mobi.giza.compose.database.model.types.FrostSigningStage import com.vitorpamplona.quartz.nip01Core.core.HexKey @@ -175,10 +174,8 @@ enum class SpendStatus { data class SpendRow( val transaction: GroupTransaction, val status: SpendStatus, - /** The spend, checked again; null where this device cannot check it, or for a sweep. */ + /** The spend, checked again; null where this device cannot check it. */ val spend: GroupSpend.Checked?, - /** A sweep from the Lightning wallet into this one, checked again; null for a spend. */ - val sweep: GroupSweep.Checked? = null, ) { /** Signed, never reported back: the one moment sending it again is worth anything. */ val canSendAgain: Boolean get() = status == SpendStatus.SIGNED diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/IcebergCeremonyUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/IcebergCeremonyUIState.kt deleted file mode 100644 index 67088199..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/IcebergCeremonyUIState.kt +++ /dev/null @@ -1,27 +0,0 @@ -package mobi.giza.compose.ui.view.state - -import mobi.giza.compose.database.model.IcebergKeySession -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.database.model.types.IcebergApprovalStep -import com.vitorpamplona.quartz.nip01Core.core.HexKey - -sealed class IcebergCeremonyUIState { - data object Loading : IcebergCeremonyUIState() - - data class Error(val message: String) : IcebergCeremonyUIState() - - /** - * @param session null when the room has no ceremony yet, which is the screen's empty state. - * @param progress for each participant, how many of the three rounds this device has from them. - * @param thresholds what a new ceremony could be opened at; empty when the room cannot have one. - */ - data class Loaded( - val localChatRoom: LocalChatRoom, - val session: IcebergKeySession?, - val progress: Map, - val pending: IcebergApprovalStep?, - val thresholds: List, - val holderCount: Int, - val hasOnchainWallet: Boolean, - ) : IcebergCeremonyUIState() -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/GroupLightningRollout.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/GroupLightningRollout.kt deleted file mode 100644 index c2f8332a..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/GroupLightningRollout.kt +++ /dev/null @@ -1,60 +0,0 @@ -package mobi.giza.compose.wallet - -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.Satoshi -import fr.acinq.phoenix.managers.NodeParamsManager - -/** - * The gates the group Lightning wallet ships behind -- `docs/group-lightning-wallet.md`, Phase 15 -- - * in one place, each with the condition that lifts it. - * - * As with [GroupWalletRollout], these decide what this device offers, never what it accepts: a device - * with a gate closed still verifies and co-signs for a wallet another member opened -- except the - * channel cap, which every co-signer holds to, since it is the one gate that bounds what can be lost. - */ -object GroupLightningRollout { - /** - * Whether the group's screen offers a Lightning wallet, and whether this device runs the group nodes - * it is elected to. On: the phases are in, the JVM suite passes and the regtest end-to-end run passes. - */ - const val ENABLED: Boolean = true - - /** - * The network a Lightning wallet is opened on: the node's own, mainnet, where the group's onchain - * wallet already is. Lifted to mainnet by decision, ahead of what the plan named for it -- a review - * of the Iceberg scheme and the DKG outside the project, and a month of a testnet3 group with no - * refused label and no lost channel. The Iceberg library itself says not to put money behind it. - * What bounds the loss meanwhile is [MAINNET_CHANNEL_CAP], the statement's in-flight cap, and - * every co-signer's checks. - */ - val NETWORK: Chain = NodeParamsManager.chain - - /** - * The most one channel may hold on mainnet. Every co-signer refuses to sign the first commitment of a - * bigger channel, so it never opens, and the shared input of a splice to a bigger one, so it never grows - * past it: the one splice they sign is the liquidity purchase the group authorised. Lifts - * on the same condition as [GroupWalletRollout.MAINNET_CAP]: a release that has run real channels, - * payments and closes with no refused label and no lost channel. - */ - val MAINNET_CHANNEL_CAP: Satoshi = Satoshi(1_000_000) - - /** - * Whether a member may ask the group to buy inbound liquidity, and the operator's node buys it - * (`docs/group-lightning-liquidity.md`). Co-signers check a purchase whether or not it is on. - * - * On, on mainnet, by decision, ahead of the plan's Phase 0 mainnet check: ACINQ's LSP has not yet - * been seen to accept a splice whose funding key from us does not change. If it refuses, the splice - * aborts before anything is signed into it, and the purchase is reported as failed. What bounds a - * purchase meanwhile is [MAINNET_CHANNEL_CAP], the fee cap the group signs, and every co-signer's checks. - */ - const val LIQUIDITY_ENABLED: Boolean = true - - /** The most a channel on [chain] may hold, or null where there is no cap. */ - fun channelCapFor(chain: Chain): Satoshi? = MAINNET_CHANNEL_CAP.takeIf { chain.isMainnet() } - - /** - * Whether a Lightning wallet may be opened on [chain] at all: [NETWORK], and regtest for tests and - * development. - */ - fun allows(chain: Chain): Boolean = chain == NETWORK || chain == Chain.Regtest -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/lightning/CoSignerPolicy.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/lightning/CoSignerPolicy.kt deleted file mode 100644 index c9a9ead4..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/lightning/CoSignerPolicy.kt +++ /dev/null @@ -1,157 +0,0 @@ -package mobi.giza.compose.wallet.lightning - -import fr.acinq.lightning.transactions.CommitmentSpec -import fr.acinq.lightning.transactions.IncomingHtlc -import fr.acinq.lightning.transactions.OutgoingHtlc - -/** - * What a co-signer lets a counterparty's commitment do to the group's money (`docs/group-lightning-wallet.md`, - * Phase 9, check 5). Pure: the ledger it reads and returns is the caller's to store. - * - * In the counterparty's commitment `toRemote` is ours, and an HTLC *they* receive is one *we* offered. - * What the group can claim from a commitment is [value]: our balance plus what we have offered and not yet - * lost, because an offered HTLC comes back if it fails. Everything else is the counterparty's. - * - * The rules, in order: - * - * 1. **The commitment number moves forward by one**, or repeats with the same transaction (a - * retransmission after a reconnect). - * 2. **A new HTLC we offer is a payment the group authorised**: its hash has an authorisation with budget - * left for it. Refusing here is the only refusal that works -- once the counterparty has the preimage, - * a commitment we do not sign does not stop it claiming on chain. - * 3. **The value never falls below the floor.** The floor starts at the value of the channel's first - * commitment less the fee allowance, rises by what the group receives, and falls by what an authorised - * payment spends. A fall in value is explained by an authorised HTLC we offered disappearing without - * coming back, which consumes its budget; any other fall eats the fee allowance, and when that is gone - * the co-signer stops signing. - * - * A splice moves the channel to a new funding output, and each output keeps a ledger of its own: until - * the splice confirms, both carry one commitment per update, at the same number. The new output's first - * commitment is [openSplice]'s, from the parent's ledger (`docs/group-lightning-liquidity.md`, Phase 5). - */ -object CoSignerPolicy { - data class OfferedHtlc(val paymentHash: String, val amountMsat: Long) - - /** What a co-signer remembers about a channel between signatures. */ - data class Ledger( - val commitIndex: Long, - val commitTxId: String, - val oursMsat: Long, - /** HTLCs we offered, by id. */ - val offered: Map, - /** HTLCs offered to us, by id, with their amounts. */ - val incoming: Map, - val floorMsat: Long, - ) { - val valueMsat: Long get() = oursMsat + offered.values.sumOf { it.amountMsat } - } - - sealed class Verdict { - /** Sign. [consumed] is how much of each authorisation's budget this commitment used, by payment hash. */ - data class Sign(val ledger: Ledger, val consumed: Map) : Verdict() - data class Refuse(val reason: String) : Verdict() - } - - private fun offeredBy(spec: CommitmentSpec): Map = - spec.htlcs.filterIsInstance().associate { it.add.id to OfferedHtlc(it.add.paymentHash.toHex(), it.add.amountMsat.toLong()) } - - private fun incomingTo(spec: CommitmentSpec): Map = - spec.htlcs.filterIsInstance().associate { it.add.id to it.add.amountMsat.toLong() } - - /** The ledger for a channel's first commitment: whatever it holds is where the floor starts. */ - fun open(commitIndex: Long, commitTxId: String, remoteSpec: CommitmentSpec, feeAllowanceMsat: Long): Ledger { - val offered = offeredBy(remoteSpec) - val ours = remoteSpec.toRemote.toLong() - return Ledger(commitIndex, commitTxId, ours, offered, incomingTo(remoteSpec), floorMsat = ours + offered.values.sumOf { it.amountMsat } - feeAllowanceMsat) - } - - /** - * The ledger for the first commitment on a splice's new funding output, from [parent], the ledger of - * the output it spends. lightning-kmp signs it at the parent's commitment number, with the same HTLCs; - * all that may change is our balance, which a liquidity purchase lowers by its fees. That fall is - * allowed up to [maxFallMsat] -- the authorisation's fee cap -- and it lowers the floor with the value, - * once, so the fee is not later read as money that went missing. - */ - fun openSplice(parent: Ledger, commitIndex: Long, commitTxId: String, remoteSpec: CommitmentSpec, maxFallMsat: Long): Verdict { - if (commitIndex != parent.commitIndex) return Verdict.Refuse("the splice's first commitment is number $commitIndex, not ${parent.commitIndex} as the channel's") - val offered = offeredBy(remoteSpec) - val incoming = incomingTo(remoteSpec) - if (offered != parent.offered || incoming != parent.incoming) return Verdict.Refuse("the splice's first commitment carries other HTLCs than the channel's") - val ours = remoteSpec.toRemote.toLong() - val fall = parent.oursMsat - ours - if (fall < 0) return Verdict.Refuse("the splice's first commitment gives the group more than the channel did") - if (fall > maxFallMsat) return Verdict.Refuse("the splice takes $fall msat from the group, over the $maxFallMsat the group agreed to pay") - return Verdict.Sign(Ledger(commitIndex, commitTxId, ours, offered, incoming, parent.floorMsat - fall), emptyMap()) - } - - /** - * @param budgets what each authorisation has left to spend, by payment hash, in millisatoshi. - * @param closed the payment hashes whose authorisations have expired: an HTLC already in flight for - * one still settles against its budget, and no new one is offered. - * @param inFlightCapMsat the most the HTLCs the group offers may add up to at once: the statement's cap. - */ - fun checkRemoteCommitment( - previous: Ledger, - commitIndex: Long, - commitTxId: String, - remoteSpec: CommitmentSpec, - budgets: Map, - closed: Set = emptySet(), - inFlightCapMsat: Long = Long.MAX_VALUE, - ): Verdict { - if (commitIndex == previous.commitIndex) { - return if (commitTxId == previous.commitTxId) Verdict.Sign(previous, emptyMap()) - else Verdict.Refuse("commitment $commitIndex was already signed as a different transaction") - } - if (commitIndex != previous.commitIndex + 1) return Verdict.Refuse("commitment $commitIndex does not follow ${previous.commitIndex}") - - val offered = offeredBy(remoteSpec) - val incoming = incomingTo(remoteSpec) - val ours = remoteSpec.toRemote.toLong() - - // Rule 2: every newly offered HTLC is an authorised payment with budget left -- left after the - // HTLCs for the same payment that are still in flight from earlier commitments. - val remaining = budgets.toMutableMap() - offered.filterKeys { it in previous.offered }.values.forEach { htlc -> - remaining[htlc.paymentHash]?.let { remaining[htlc.paymentHash] = it - htlc.amountMsat } - } - val added = offered.filterKeys { it !in previous.offered } - for ((id, htlc) in added.entries.sortedBy { it.key }) { - val left = remaining[htlc.paymentHash] ?: return Verdict.Refuse("HTLC $id pays ${htlc.paymentHash.take(16)}, which the group has not authorised") - if (htlc.paymentHash in closed) return Verdict.Refuse("HTLC $id pays ${htlc.paymentHash.take(16)}, whose authorisation has expired") - if (htlc.amountMsat > left) return Verdict.Refuse("HTLC $id sends ${htlc.amountMsat} msat against an authorisation with $left msat left") - remaining[htlc.paymentHash] = left - htlc.amountMsat - } - - // The cap holds only for what the group sends: an HTLC offered to it is the counterparty's to - // add, and refusing to sign over one would stall the channel rather than protect anything. - val outgoing = offered.values.sumOf { it.amountMsat } - if (added.isNotEmpty() && outgoing > inFlightCapMsat) return Verdict.Refuse("$outgoing msat would be in flight, over the cap of $inFlightCapMsat") - - // Rule 3: the value against the floor. - val value = ours + offered.values.sumOf { it.amountMsat } - val decrease = (previous.valueMsat - value).coerceAtLeast(0) - val removedOffered = previous.offered.filterKeys { it !in offered } - // A fall in value is first explained by authorised HTLCs that left without coming back. - val consumed = mutableMapOf() - var toExplain = decrease - for ((_, htlc) in removedOffered.entries.sortedBy { it.key }) { - if (toExplain <= 0) break - val left = budgets[htlc.paymentHash] ?: continue - val take = minOf(toExplain, htlc.amountMsat, left) - if (take > 0) { - consumed[htlc.paymentHash] = (consumed[htlc.paymentHash] ?: 0) + take - toExplain -= take - } - } - val spent = consumed.values.sum() - // A rise in our balance as an HTLC offered to us disappears is the group being paid. - val removedIncoming = previous.incoming.filterKeys { it !in incoming }.values.sum() - val returned = removedOffered.values.sumOf { it.amountMsat } - spent - val received = minOf(removedIncoming, (ours - previous.oursMsat - returned).coerceAtLeast(0)) - val floor = previous.floorMsat - spent + received - if (value < floor) return Verdict.Refuse("the group could claim $value msat, under the floor of $floor msat") - - return Verdict.Sign(Ledger(commitIndex, commitTxId, ours, offered, incoming, floor), consumed) - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/lightning/CoSigningWire.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/lightning/CoSigningWire.kt deleted file mode 100644 index ad1c72f1..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/lightning/CoSigningWire.kt +++ /dev/null @@ -1,288 +0,0 @@ -package mobi.giza.compose.wallet.lightning - -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.KeyPath -import fr.acinq.bitcoin.OutPoint -import fr.acinq.bitcoin.PublicKey -import fr.acinq.bitcoin.Satoshi -import fr.acinq.bitcoin.Transaction -import fr.acinq.bitcoin.TxId -import fr.acinq.bitcoin.TxOut -import fr.acinq.lightning.CltvExpiry -import fr.acinq.lightning.CltvExpiryDelta -import fr.acinq.lightning.Features -import fr.acinq.lightning.FeatureSupport -import fr.acinq.lightning.blockchain.fee.FeeratePerKw -import fr.acinq.lightning.channel.ChannelConfig -import fr.acinq.lightning.channel.ChannelFeatures -import fr.acinq.lightning.channel.ChannelFlags -import fr.acinq.lightning.channel.ChannelParams -import fr.acinq.lightning.channel.CommitParams -import fr.acinq.lightning.channel.LocalChannelParams -import fr.acinq.lightning.channel.RemoteChannelParams -import fr.acinq.lightning.crypto.FundingSigner -import fr.acinq.lightning.transactions.CommitmentSpec -import fr.acinq.lightning.transactions.DirectedHtlc -import fr.acinq.lightning.transactions.IncomingHtlc -import fr.acinq.lightning.transactions.OutgoingHtlc -import fr.acinq.lightning.transactions.Transactions -import fr.acinq.lightning.utils.msat -import fr.acinq.lightning.wire.LiquidityAds -import fr.acinq.lightning.wire.OnionRoutingPacket -import fr.acinq.lightning.wire.UpdateAddHtlc -import fr.acinq.secp256k1.Hex -import kotlinx.serialization.Serializable - -/** - * The messages the operator's node and the members' co-signers exchange (`docs/group-lightning-wallet.md`, - * Phase 9), as JSON inside Marmot inner events. - * - * A signing request carries the transaction and what it is -- the [FundingSigner.SigningContext] - * lightning-kmp built it from -- but never the hash to sign. A co-signer recomputes the hash from the - * transaction, and rebuilds the transaction from the context with lightning-kmp's own builders, so an - * operator that describes one transaction and asks for a signature on another is refused. - * - * HTLCs travel as their id, amount, hash, expiry and direction: everything a commitment is built from, - * and not the 1,366-byte onion that only the next hop reads. - */ -object CoSigningWire { - @Serializable - data class Htlc(val incoming: Boolean, val id: Long, val amountMsat: Long, val paymentHash: String, val cltvExpiry: Long) - - @Serializable - data class Spec(val feeratePerKw: Long, val toLocalMsat: Long, val toRemoteMsat: Long, val htlcs: List) - - @Serializable - data class Commit(val dustLimitSat: Long, val maxHtlcValueInFlightMsat: Long, val htlcMinimumMsat: Long, val toSelfDelay: Int, val maxAcceptedHtlcs: Int) - - @Serializable - data class Params( - val channelId: String, - val channelConfig: String, - val channelFeatures: String, - val localNodeId: String, - val fundingKeyPath: String, - val isChannelOpener: Boolean, - val paysCommitTxFees: Boolean, - val defaultFinalScriptPubKey: String, - val localFeatures: String, - val remoteNodeId: String, - val revocationBasepoint: String, - val paymentBasepoint: String, - val delayedPaymentBasepoint: String, - val htlcBasepoint: String, - val remoteFeatures: String, - val announceChannel: Boolean, - val nonInitiatorPaysCommitFees: Boolean, - ) - - /** - * Liquidity bought with a splice, as lightning-kmp's `LiquidityAds.Purchase` says it: [amountSat] of - * inbound, for [miningFeeSat] (the LSP's inputs) and [serviceFeeSat], paid as [paymentType] names, a - * BOLT name such as `from_channel_balance`. [feeCreditUsedMsat] is set only when fee credit paid part of it. - */ - @Serializable - data class Purchase( - val amountSat: Long, - val miningFeeSat: Long, - val serviceFeeSat: Long, - val paymentType: String, - val feeCreditUsedMsat: Long? = null, - ) - - /** - * One of the four things lightning-kmp says it is signing. [type] is `remote`, `local`, `closing` or - * `splice`. A commitment names the funding output it is on by [fundingTxIndex]: while a splice is - * unconfirmed there is one per output, at the same commitment number. - * - * A splice is its shared input: the parent funding output [parentFunding], of [parentFundingTxIndex], - * spent by a transaction whose output [fundingOutputIndex] is the new funding output, of - * [fundingTxIndex], shared with the counterparty's [newRemoteFundingPubKey]; what each side added - * ([localContributionSat], [remoteContributionSat]), the [purchase] if it bought liquidity, and the - * feerate it was built at. A splice has no [spec]: the money in the new output is the first commitment - * on it, signed before this. - */ - @Serializable - data class Context( - val type: String, - val params: Params, - val commit: Commit? = null, - val commitIndex: Long? = null, - val remotePerCommitmentPoint: String? = null, - val spec: Spec? = null, - val localScript: String? = null, - val remoteScript: String? = null, - val fundingTxIndex: Long = 0, - val parentFundingTxIndex: Long? = null, - val parentFunding: Input? = null, - val fundingOutputIndex: Int? = null, - val newRemoteFundingPubKey: String? = null, - val localContributionSat: Long? = null, - val remoteContributionSat: Long? = null, - val purchase: Purchase? = null, - val feeratePerKw: Long? = null, - ) - - @Serializable - data class Input(val txid: String, val index: Long, val amountSat: Long, val script: String) - - /** Kind 30358, from the operator. [kind] is a [fr.acinq.lightning.crypto.IcebergRoundTwoRequest.Kind] name. */ - @Serializable - data class SigningRequest( - val wallet: String, - val term: Long, - val requestId: String, - val kind: String, - val label: String, - val counter: Long, - val tx: String, - val input: Input, - val fundingTxId: String, - val remoteFundingPubKey: String, - val commitIndex: Long? = null, - val contributions: List, - val cosignerAggregatedNonce: String, - val context: Context? = null, - /** - * What every other input of [tx] spends. A commitment or a close has one input, [input], and this - * is empty; a splice's shared input is one of several, and its signature commits to all of them. - */ - val extraUtxos: List = emptyList(), - ) - - /** Kind 30359: a co-signer saw [messageHash] under [label], and will sign nothing else under it. */ - @Serializable - data class Echo(val wallet: String, val requestId: String, val label: String, val messageHash: String) - - /** Kind 30360: round-one contributions for consecutive pool counters from [from]. */ - @Serializable - data class NonceBatch(val wallet: String, val from: Long, val contributions: List) - - /** Kind 30361: one co-signer's round-two answer. */ - @Serializable - data class SignatureShareMessage(val wallet: String, val requestId: String, val label: String, val share: String) - - private fun hex(bytes: ByteArray) = Hex.encode(bytes) - private fun hex(v: ByteVector) = v.toHex() - - fun spec(spec: CommitmentSpec): Spec = Spec( - feeratePerKw = spec.feerate.feerate.sat, - toLocalMsat = spec.toLocal.toLong(), - toRemoteMsat = spec.toRemote.toLong(), - htlcs = spec.htlcs.map { h -> Htlc(h is IncomingHtlc, h.add.id, h.add.amountMsat.toLong(), h.add.paymentHash.toHex(), h.add.cltvExpiry.toLong()) }.sortedWith(compareBy({ it.incoming }, { it.id })), - ) - - /** A placeholder onion: a commitment is built from an HTLC's amount, hash and expiry, never from its onion. */ - private val noOnion = OnionRoutingPacket(0, ByteVector(ByteArray(33) { if (it == 0) 2 else 0 }), ByteVector.empty, ByteVector32.Zeroes) - - fun spec(wire: Spec, channelId: ByteVector32): CommitmentSpec = CommitmentSpec( - htlcs = wire.htlcs.map { h -> - val add = UpdateAddHtlc(channelId, h.id, h.amountMsat.msat, ByteVector32(h.paymentHash), CltvExpiry(h.cltvExpiry), noOnion) - if (h.incoming) IncomingHtlc(add) else OutgoingHtlc(add) - }.toSet(), - feerate = FeeratePerKw(Satoshi(wire.feeratePerKw)), - toLocal = wire.toLocalMsat.msat, - toRemote = wire.toRemoteMsat.msat, - ) - - fun commit(c: CommitParams): Commit = Commit(c.dustLimit.sat, c.maxHtlcValueInFlightMsat, c.htlcMinimum.toLong(), c.toSelfDelay.toInt(), c.maxAcceptedHtlcs) - - fun commit(w: Commit): CommitParams = CommitParams(Satoshi(w.dustLimitSat), w.maxHtlcValueInFlightMsat, w.htlcMinimumMsat.msat, CltvExpiryDelta(w.toSelfDelay), w.maxAcceptedHtlcs) - - fun params(p: ChannelParams): Params = Params( - channelId = p.channelId.toHex(), - channelConfig = hex(p.channelConfig.toByteArray()), - channelFeatures = hex(Features(p.channelFeatures.features.associateWith { FeatureSupport.Optional }).toByteArray()), - localNodeId = p.localParams.nodeId.toString(), - fundingKeyPath = p.localParams.fundingKeyPath.toString(), - isChannelOpener = p.localParams.isChannelOpener, - paysCommitTxFees = p.localParams.paysCommitTxFees, - defaultFinalScriptPubKey = hex(p.localParams.defaultFinalScriptPubKey), - localFeatures = hex(p.localParams.features.toByteArray()), - remoteNodeId = p.remoteParams.nodeId.toString(), - revocationBasepoint = p.remoteParams.revocationBasepoint.toString(), - paymentBasepoint = p.remoteParams.paymentBasepoint.toString(), - delayedPaymentBasepoint = p.remoteParams.delayedPaymentBasepoint.toString(), - htlcBasepoint = p.remoteParams.htlcBasepoint.toString(), - remoteFeatures = hex(p.remoteParams.features.toByteArray()), - announceChannel = p.channelFlags.announceChannel, - nonInitiatorPaysCommitFees = p.channelFlags.nonInitiatorPaysCommitFees, - ) - - fun params(w: Params): ChannelParams = ChannelParams( - channelId = ByteVector32(w.channelId), - channelConfig = ChannelConfig(Hex.decode(w.channelConfig)), - channelFeatures = ChannelFeatures(Features(Hex.decode(w.channelFeatures)).activated.keys), - localParams = LocalChannelParams( - nodeId = PublicKey.fromHex(w.localNodeId), - fundingKeyPath = KeyPath(w.fundingKeyPath), - isChannelOpener = w.isChannelOpener, - paysCommitTxFees = w.paysCommitTxFees, - defaultFinalScriptPubKey = ByteVector(w.defaultFinalScriptPubKey), - features = Features(Hex.decode(w.localFeatures)), - ), - remoteParams = RemoteChannelParams( - nodeId = PublicKey.fromHex(w.remoteNodeId), - revocationBasepoint = PublicKey.fromHex(w.revocationBasepoint), - paymentBasepoint = PublicKey.fromHex(w.paymentBasepoint), - delayedPaymentBasepoint = PublicKey.fromHex(w.delayedPaymentBasepoint), - htlcBasepoint = PublicKey.fromHex(w.htlcBasepoint), - features = Features(Hex.decode(w.remoteFeatures)), - ), - channelFlags = ChannelFlags(w.announceChannel, w.nonInitiatorPaysCommitFees), - ) - - fun context(c: FundingSigner.SigningContext): Context? = when (c) { - FundingSigner.SigningContext.Unknown -> null - is FundingSigner.SigningContext.RemoteCommitment -> Context("remote", params(c.channelParams), commit(c.commitParams), c.commitIndex, c.remotePerCommitmentPoint.toString(), spec(c.spec), fundingTxIndex = c.fundingTxIndex) - is FundingSigner.SigningContext.LocalCommitment -> Context("local", params(c.channelParams), commit(c.commitParams), c.commitIndex, null, spec(c.spec), fundingTxIndex = c.fundingTxIndex) - is FundingSigner.SigningContext.Closing -> Context("closing", params(c.channelParams), null, null, null, spec(c.spec), hex(c.localScript), hex(c.remoteScript)) - is FundingSigner.SigningContext.Splice -> Context( - type = "splice", - params = params(c.channelParams), - fundingTxIndex = c.fundingTxIndex, - parentFundingTxIndex = c.parentFundingTxIndex, - parentFunding = input(c.parentFunding), - fundingOutputIndex = c.fundingOutputIndex, - newRemoteFundingPubKey = c.remoteFundingPubKey.toString(), - localContributionSat = c.localContribution.sat, - remoteContributionSat = c.remoteContribution.sat, - purchase = c.purchase?.let(::purchase), - feeratePerKw = c.feerate.feerate.sat, - ) - } - - fun purchase(p: LiquidityAds.Purchase): Purchase = Purchase( - amountSat = p.amount.sat, - miningFeeSat = p.fees.miningFee.sat, - serviceFeeSat = p.fees.serviceFee.sat, - paymentType = paymentTypeName(p.paymentDetails.paymentType), - feeCreditUsedMsat = (p as? LiquidityAds.Purchase.WithFeeCredit)?.feeCreditUsed?.toLong(), - ) - - /** The BOLT name of a liquidity-ads payment type, which the wire carries: a co-signer reads only `from_channel_balance` as one it signs. */ - fun paymentTypeName(t: LiquidityAds.PaymentType): String = when (t) { - LiquidityAds.PaymentType.FromChannelBalance -> FROM_CHANNEL_BALANCE - LiquidityAds.PaymentType.FromFutureHtlc -> "from_future_htlc" - LiquidityAds.PaymentType.FromFutureHtlcWithPreimage -> "from_future_htlc_with_preimage" - LiquidityAds.PaymentType.FromChannelBalanceForFutureHtlc -> "from_channel_balance_for_future_htlc" - is LiquidityAds.PaymentType.Unknown -> "unknown_${t.bitIndex}" - } - - const val FROM_CHANNEL_BALANCE = "from_channel_balance" - - /** What every input of [tx] spends, [input] among them, in input order; null when one is not known. */ - fun spentOutputs(tx: Transaction, input: Transactions.InputInfo, extra: List): List? { - val known = extra.map(::inputInfo).associate { it.outPoint to it.txOut } + (input.outPoint to input.txOut) - return tx.txIn.map { known[it.outPoint] ?: return null } - } - - fun input(info: Transactions.InputInfo): Input = Input(info.outPoint.txid.toString(), info.outPoint.index, info.txOut.amount.sat, hex(info.txOut.publicKeyScript)) - - fun inputInfo(w: Input): Transactions.InputInfo = Transactions.InputInfo(OutPoint(TxId(w.txid), w.index), TxOut(Satoshi(w.amountSat), ByteVector(w.script))) - - fun tx(tx: Transaction): String = hex(Transaction.write(tx)) - - fun tx(hex: String): Transaction = Transaction.read(hex) -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/lightning/GroupLightningNodes.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/lightning/GroupLightningNodes.kt deleted file mode 100644 index 4aaafce8..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/lightning/GroupLightningNodes.kt +++ /dev/null @@ -1,104 +0,0 @@ -package mobi.giza.compose.wallet.lightning - -import co.touchlab.kermit.Logger -import mobi.giza.compose.database.GizaDatabase -import mobi.giza.compose.managers.GroupLightningNode -import mobi.giza.compose.managers.GroupLightningOperatorManager -import mobi.giza.compose.managers.GroupLightningWalletManager -import mobi.giza.compose.managers.IcebergRitualManager -import mobi.giza.compose.wallet.GroupLightningRollout -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.Chain -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Job -import kotlinx.coroutines.delay -import kotlinx.coroutines.isActive -import kotlinx.coroutines.launch -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock -import kotlin.time.Duration -import kotlin.time.Duration.Companion.minutes - -/** - * The group Lightning nodes one identity runs: one for every wallet this device is the elected operator - * of, started when it may run and stopped when it may not (`docs/group-lightning-wallet.md`, Phase 8). - * - * Made where the identity's node is and stopped with it, like the onchain wallets. Every [CHECK] it looks - * again at every Lightning wallet this device holds a share of: a node starts once this device is elected - * and has heard from the room recently, and each running node stops itself when a later term begins. - * - * The same check abandons any of this identity's Lightning key ceremonies that has passed its deadline - * ([IcebergRitualManager.abandonOverdue]): it is the one loop an identity runs for its Lightning wallets, - * and a ceremony nobody is looking at is exactly the one that needs it. - * - * On Android the node runs while the app does. A foreground service that keeps it running with the app - * in the background is the next piece of work, and the nomination screen says so meanwhile. - */ -class GroupLightningNodes( - private val database: GizaDatabase, - private val userPublicKey: HexKey, - private val scope: CoroutineScope, - private val peerFactory: suspend (GroupLightningNode.NodeConfiguration) -> GroupLightningNode.PeerHandle, - private val chain: Chain = GroupLightningRollout.NETWORK, - private val minimumPool: Int = GroupLightningNode.MINIMUM_POOL, -) { - private val logger = Logger.withTag("GroupLightningNodes") - private val mutex = Mutex() - private val nodes = mutableMapOf() - private var job: Job? = null - - /** The node of [chatRoomId]'s wallet [wallet] -- its current one when null -- if this device runs it. */ - fun nodeFor(chatRoomId: String, wallet: Long? = null): GroupLightningNode? = - if (wallet != null) nodes[key(chatRoomId, wallet)] - else nodes.filterKeys { it.startsWith("$chatRoomId:") }.maxByOrNull { it.value.wallet.statement.wallet }?.value - - private fun key(chatRoomId: String, wallet: Long) = "$chatRoomId:$wallet" - - /** - * Starts every node this device may run, and forgets the ones that stopped. After a re-key a room has - * two wallets, each with its own operator: the old one runs until its channels are closed (Phase 14). - */ - suspend fun refresh() = mutex.withLock { - if (!GroupLightningRollout.ENABLED && chain != Chain.Regtest) return@withLock - val rooms = database.icebergKeySessionDao().getCompletedSessions().filter { it.userPublicKey == userPublicKey }.map { it.chatRoomId }.toSet() - for (roomId in rooms) { - val localChatRoom = database.chatRoomDao().findChatRoomById(roomId) ?: continue - for (wallet in GroupLightningWalletManager.wallets(database, roomId, chain)) { - val key = key(roomId, wallet.statement.wallet) - val operator = GroupLightningOperatorManager.current(database, roomId, chain, wallet.statement.wallet) - val existing = nodes[key] - if (existing?.state?.value is GroupLightningNode.State.Running) continue - if (operator?.publicKey != userPublicKey) { - nodes.remove(key) - continue - } - val node = existing ?: GroupLightningNode(database, localChatRoom, userPublicKey, wallet, scope, peerFactory, minimumPool = minimumPool).also { nodes[key] = it } - val state = runCatching { node.start() }.onFailure { logger.e("Could not start the node for $key", it) }.getOrNull() - if (state is GroupLightningNode.State.Refused) logger.i("Not running the node for $key: ${state.reason}") - } - } - } - - fun start() { - job?.cancel() - job = scope.launch { - while (isActive) { - runCatching { IcebergRitualManager.abandonOverdue(database, userPublicKey) }.onFailure { logger.e("Could not abandon overdue key ceremonies", it) } - runCatching { refresh() }.onFailure { logger.e("Could not refresh the group nodes", it) } - delay(CHECK) - } - } - } - - suspend fun stop() { - job?.cancel() - mutex.withLock { - nodes.values.forEach { runCatching { it.stop() } } - nodes.clear() - } - } - - companion object { - val CHECK: Duration = 1.minutes - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/lightning/GroupNodeKeyManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/lightning/GroupNodeKeyManager.kt deleted file mode 100644 index 6e116f5c..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/lightning/GroupNodeKeyManager.kt +++ /dev/null @@ -1,26 +0,0 @@ -package mobi.giza.compose.wallet.lightning - -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.KeyPath -import fr.acinq.lightning.crypto.ChannelKeys -import fr.acinq.lightning.crypto.FundingSigner -import fr.acinq.lightning.crypto.GroupBasepoints -import fr.acinq.lightning.crypto.KeyManager - -/** - * The key manager a group Lightning wallet's node runs on (`docs/group-lightning-wallet.md`, Phase 8): - * the node seed's own keys for everything but three things. Every channel's funding key is the group's - * Iceberg key, held by [fundingSigner]; its payment and delayed-payment basepoints are the group's FROST - * keys ([basepoints]); and it closes to [finalScriptPubKey], the group's onchain wallet. - */ -class GroupNodeKeyManager( - private val delegate: KeyManager, - private val fundingSigner: FundingSigner, - private val basepoints: GroupBasepoints, - private val finalScriptPubKey: ByteVector, -) : KeyManager by delegate { - override fun channelKeys(fundingKeyPath: KeyPath): ChannelKeys = - delegate.channelKeys(fundingKeyPath).withFundingSigner(fundingSigner).withGroupBasepoints(basepoints) - - override val defaultFinalScriptPubKey: ByteVector get() = finalScriptPubKey -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/lightning/GroupSweep.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/lightning/GroupSweep.kt deleted file mode 100644 index fdf021c0..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/lightning/GroupSweep.kt +++ /dev/null @@ -1,194 +0,0 @@ -package mobi.giza.compose.wallet.lightning - -import mobi.giza.compose.managers.FrostSigningManager -import mobi.giza.compose.managers.GroupLightningDerivation -import mobi.giza.compose.managers.GroupWalletDerivation -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.ByteVector64 -import fr.acinq.bitcoin.OP_CHECKSEQUENCEVERIFY -import fr.acinq.bitcoin.OP_CHECKSIGVERIFY -import fr.acinq.bitcoin.OP_PUSHDATA -import fr.acinq.bitcoin.OutPoint -import fr.acinq.bitcoin.Satoshi -import fr.acinq.bitcoin.Script -import fr.acinq.bitcoin.ScriptTree -import fr.acinq.bitcoin.ScriptWitness -import fr.acinq.bitcoin.SigHash -import fr.acinq.bitcoin.Transaction -import fr.acinq.bitcoin.TxId -import fr.acinq.bitcoin.TxIn -import fr.acinq.bitcoin.TxOut -import fr.acinq.bitcoin.XonlyPublicKey -import fr.acinq.bitcoin.crypto.frost.TweakCache -import fr.acinq.lightning.channel.GroupHeldOutputs -import fr.acinq.lightning.transactions.Scripts -import fr.acinq.secp256k1.Hex -import kotlinx.serialization.Serializable - -/** - * Moving what a closed channel left the group into its onchain wallet (`docs/group-lightning-wallet.md`, - * Phase 13): a FROST spend whose inputs are taproot *script* paths, one leaf of an output a commitment - * or HTLC transaction pays to the group's basepoints. - * - * Every member checks a sweep the way [mobi.giza.compose.wallet.GroupSpend] checks a spend, - * trusting nothing the proposer computed: - * - * - **The key is the group's.** Each input names a basepoint and a tweak; the member derives the leaf key - * from its own basepoints ([GroupLightningDerivation.leafCache]) and rebuilds the one leaf it signs -- - * ` OP_CHECKSIGVERIFY OP_CHECKSEQUENCEVERIFY`, the only shape lightning-kmp gives a - * group-held output. A tweak the proposer made up gives a key the group can sign for and nobody else - * can, so it costs nothing. - * - **Everything goes to the onchain wallet.** Every output is a receive address of the wallet the - * statement closes to, at an index the member derives. - * - **What is spent is what the sighash says.** BIP341's script-path sighash commits to every spent - * amount and script and to the leaf, so a lie about any of them is a transaction nobody can mine, - * not one that pays someone else. - * - * The internal key and the control block are the proposer's to get right, for the same reason. - */ -object GroupSweep { - /** The highest feerate a sweep may pay, in sats per virtual byte: the onchain wallet's own limit. */ - const val MAX_FEERATE_SAT_PER_VBYTE: Long = mobi.giza.compose.wallet.GroupSpend.MAX_FEERATE_SAT_PER_VBYTE - - const val PAYMENT = "payment" - const val DELAYED = "delayed" - - /** One output to sweep, as a proposal carries it. [tweak] is null for an output under the payment basepoint itself. */ - @Serializable - data class Input( - val txid: String, - val index: Long, - val amountSat: Long, - val script: String, - val basepoint: String, - val tweak: String? = null, - val leafScript: String, - val controlBlock: String, - val csvDelay: Long, - ) - - /** A sweep proposal: the unsigned transaction, what each input spends, and which receive address each output is. */ - @Serializable - data class Sweep(val wallet: Long, val tx: String, val inputs: List, val receiveIndices: List) - - data class CheckedInput( - val index: Int, - val outPoint: OutPoint, - val txOut: TxOut, - val leafKey: XonlyPublicKey, - val cache: TweakCache, - val leafScript: ByteVector, - val controlBlock: ByteVector, - val sighash: ByteVector32, - ) - - data class Checked(val sweep: Sweep, val tx: Transaction, val inputs: List, val fee: Satoshi, val weight: Int) { - val amount: Satoshi get() = Satoshi(tx.txOut.sumOf { it.amount.sat }) - val spentOutputs: List get() = inputs.map { it.txOut } - val feeratePerVbyte: Long get() = fee.sat / ((weight.toLong() + 3) / 4) - } - - sealed interface Result { - data class Ok(val checked: Checked) : Result - data class Refused(val reason: String) : Result - } - - /** The one leaf a group-held output is spent by, for [leafKey] after [csvDelay] blocks. */ - fun leafScript(leafKey: XonlyPublicKey, csvDelay: Long): ByteVector = - ByteVector(Script.write(listOf(OP_PUSHDATA(leafKey), OP_CHECKSIGVERIFY, Scripts.encodeNumber(csvDelay), OP_CHECKSEQUENCEVERIFY))) - - /** Checks [sweep] against the group's [basepoints] and the onchain [account] it must pay. */ - fun check(sweep: Sweep, basepoints: GroupLightningDerivation.Basepoints, account: GroupWalletDerivation.Account): Result { - val tx = runCatching { Transaction.read(sweep.tx) }.getOrElse { return Result.Refused("is not a transaction") } - if (tx.txIn.isEmpty()) return Result.Refused("spends nothing") - if (tx.txIn.size != sweep.inputs.size) return Result.Refused("describes ${sweep.inputs.size} inputs of ${tx.txIn.size}") - if (tx.txIn.size > FrostSigningManager.MAX_BATCH_SIZE) return Result.Refused("spends more than ${FrostSigningManager.MAX_BATCH_SIZE} outputs") - if (tx.version != 2L) return Result.Refused("is version ${tx.version}, not 2") - if (tx.lockTime != 0L) return Result.Refused("has a lock time") - if (tx.txOut.isEmpty() || tx.txOut.size != sweep.receiveIndices.size) return Result.Refused("does not say where every output goes") - tx.txOut.zip(sweep.receiveIndices).forEach { (out, index) -> - if (index !in 0..mobi.giza.compose.wallet.GroupSpend.MAX_ADDRESS_INDEX) return Result.Refused("names receive address $index") - if (out.publicKeyScript != GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, index).pubkeyScript) { - return Result.Refused("pays somewhere that is not the group's onchain wallet") - } - } - - val spent = sweep.inputs.map { TxOut(Satoshi(it.amountSat), ByteVector(it.script)) } - val inputs = sweep.inputs.mapIndexed { i, input -> - val txIn = tx.txIn[i] - if (txIn.outPoint != OutPoint(TxId(input.txid), input.index)) return Result.Refused("input $i is not the output it describes") - if (input.csvDelay !in 1..0xFFFF) return Result.Refused("input $i has a delay of ${input.csvDelay}") - if (txIn.sequence != input.csvDelay) return Result.Refused("input $i does not wait the ${input.csvDelay} blocks its leaf asks") - val basepoint = when (input.basepoint) { - PAYMENT -> basepoints.payment - DELAYED -> basepoints.delayedPayment - else -> return Result.Refused("input $i names no basepoint of the group's") - } - val tweak = input.tweak?.let { runCatching { ByteVector32(it) }.getOrElse { return Result.Refused("input $i has an unreadable tweak") } } - if (input.basepoint == DELAYED && tweak == null) return Result.Refused("input $i is a delayed output with no per-commitment tweak") - val cache = GroupLightningDerivation.leafCache(basepoint, tweak) - val leaf = leafScript(cache.tweakedPublicKey, input.csvDelay) - if (ByteVector(input.leafScript) != leaf) return Result.Refused("input $i is not spent by the group's own leaf") - val sighash = tx.hashForSigningTaprootScriptPath(i, spent, SigHash.SIGHASH_DEFAULT, ScriptTree.Leaf(leaf.toByteArray().let(Script::parse)).hash()) - CheckedInput(i, txIn.outPoint, spent[i], cache.tweakedPublicKey, cache, leaf, ByteVector(input.controlBlock), sighash) - } - - val fee = spent.sumOf { it.amount.sat } - tx.txOut.sumOf { it.amount.sat } - if (fee < 0) return Result.Refused("pays out more than it spends") - val weight = witnessed(tx, inputs, inputs.map { ByteVector64.Zeroes }).weight() - val checked = Checked(sweep, tx, inputs, Satoshi(fee), weight) - if (checked.feeratePerVbyte > MAX_FEERATE_SAT_PER_VBYTE) return Result.Refused("pays ${checked.feeratePerVbyte} sats per vbyte in fees") - return Result.Ok(checked) - } - - /** [tx] with each input's witness: the group's signature, the leaf, and the control block. */ - fun witnessed(tx: Transaction, inputs: List, signatures: List): Transaction = - inputs.zip(signatures).fold(tx) { acc, (input, signature) -> - acc.updateWitness(input.index, ScriptWitness(listOf(signature, input.leafScript, input.controlBlock))) - } - - /** What a proposal carries for [output], as lightning-kmp found it in a published transaction. */ - fun inputOf(output: GroupHeldOutputs.Output): Input { - val witness = output.witness(ByteVector64.Zeroes) - return Input( - txid = output.outPoint.txid.toString(), - index = output.outPoint.index, - amountSat = output.txOut.amount.sat, - script = Hex.encode(output.txOut.publicKeyScript.toByteArray()), - basepoint = if (output.kind == GroupHeldOutputs.Kind.TO_REMOTE) PAYMENT else DELAYED, - tweak = output.tweak?.toHex(), - leafScript = Hex.encode(witness.stack[1].toByteArray()), - controlBlock = Hex.encode(witness.stack[2].toByteArray()), - csvDelay = output.csvDelay, - ) - } - - /** - * A sweep of [inputs] to the onchain wallet's receive address [receiveIndex], paying [feeratePerVbyte], - * or null when there is nothing left after the fee. - */ - fun build(wallet: Long, inputs: List, account: GroupWalletDerivation.Account, receiveIndex: Long, feeratePerVbyte: Long): Sweep? { - if (inputs.isEmpty()) return null - val to = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, receiveIndex).pubkeyScript - val total = inputs.sumOf { it.amountSat } - fun txPaying(amount: Long) = Transaction( - version = 2, - txIn = inputs.map { TxIn(OutPoint(TxId(it.txid), it.index), ByteVector.empty, it.csvDelay) }, - txOut = listOf(TxOut(Satoshi(amount), to)), - lockTime = 0, - ) - // Weighed with stand-in signatures: a script-path witness is the same size whatever it signs. - val draft = txPaying(total).let { tx -> - inputs.foldIndexed(tx) { i, acc, input -> - acc.updateWitness(i, ScriptWitness(listOf(ByteVector64.Zeroes, ByteVector(input.leafScript), ByteVector(input.controlBlock)))) - } - } - val fee = feeratePerVbyte * ((draft.weight().toLong() + 3) / 4) - if (total - fee < DUST_SAT) return null - return Sweep(wallet, Hex.encode(Transaction.write(txPaying(total - fee))), inputs, listOf(receiveIndex)) - } - - /** The smallest output a sweep leaves: anything under is not worth the fee to sweep. */ - private const val DUST_SAT = 330L -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/lightning/LiquidityPrice.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/lightning/LiquidityPrice.kt deleted file mode 100644 index 34c137f8..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/lightning/LiquidityPrice.kt +++ /dev/null @@ -1,109 +0,0 @@ -package mobi.giza.compose.wallet.lightning - -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.OutPoint -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.Satoshi -import fr.acinq.bitcoin.TxId -import fr.acinq.bitcoin.TxOut -import fr.acinq.lightning.blockchain.fee.FeeratePerByte -import fr.acinq.lightning.blockchain.fee.FeeratePerKw -import fr.acinq.lightning.channel.FundingContributions -import fr.acinq.lightning.channel.SharedFundingInput -import fr.acinq.lightning.transactions.Transactions -import fr.acinq.lightning.wire.LiquidityAds - -/** - * What buying inbound liquidity costs, worked out on a member's own device from what the operator - * reported (`docs/group-lightning-liquidity.md`, decision L5 and Phase 7): the LSP's rates and the - * node's feerate. The service fee follows from the rate alone; the mining fee from the feerate, which - * is the operator's claim, so the authorisation's cap leaves room above it. - * - * The arithmetic is lightning-kmp's own, as Phoenix's estimate is: the rate's [LiquidityAds.FundingRate.fees] - * for the service fee and the LSP's inputs, and [FundingContributions.computeWeightPaid] for our share of - * the splice, which depends only on the sizes of a taproot funding input and output. - */ -object LiquidityPrice { - /** Phoenix's amounts (`LiquidityLimits.liquidityOptions`), in sats. */ - val OPTIONS: List = listOf(100_000, 250_000, 500_000, 1_000_000, 2_000_000, 10_000_000) - - /** How much above the estimate the cap the group signs sits, in percent: room for the feerate to rise before the purchase. */ - const val CAP_HEADROOM_PERCENT = 50 - - /** Phoenix warns when the fee reaches this share of the amount, in percent. */ - const val EXPENSIVE_PERCENT = 25 - - /** What one purchase costs: our share of the mining fee, the LSP's inputs' share, and the service fee. */ - data class Price(val ourMiningSat: Long, val lspMiningSat: Long, val serviceSat: Long) { - val miningSat: Long get() = ourMiningSat + lspMiningSat - val totalSat: Long get() = miningSat + serviceSat - } - - private fun rateOf(rate: WalletWire.FundingRate) = LiquidityAds.FundingRate( - Satoshi(rate.minAmountSat), Satoshi(rate.maxAmountSat), rate.fundingWeight, rate.feeProportional, Satoshi(rate.feeBaseSat), Satoshi(rate.channelCreationFeeSat), - ) - - /** The rate that sells [amountSat], as lightning-kmp's `findRate` picks it: the first that covers it. */ - fun rateFor(rates: WalletWire.FundingRates, amountSat: Long): WalletWire.FundingRate? = - rates.rates.firstOrNull { amountSat in it.minAmountSat..it.maxAmountSat } - - /** Our weight in a splice that only buys liquidity: the shared input and output and the common fields. */ - private val ourWeight: Int by lazy { - val script = Transactions.makeFundingInputInfo(TxId(ByteArray(32)), 0, Satoshi(0), PrivateKey(ByteArray(32) { 1 }).publicKey(), PrivateKey(ByteArray(32) { 2 }).publicKey(), Transactions.CommitmentFormat.SimpleTaprootChannels).txOut.publicKeyScript - val shared = SharedFundingInput(Transactions.InputInfo(OutPoint(TxId(ByteArray(32)), 0), TxOut(Satoshi(0), script)), 0, PrivateKey(ByteArray(32) { 2 }).publicKey(), Transactions.CommitmentFormat.SimpleTaprootChannels) - FundingContributions.computeWeightPaid(isInitiator = true, sharedInput = shared, sharedOutputScript = ByteVector(script.toByteArray()), walletInputs = emptyList(), localOutputs = emptyList()) - } - - /** What buying [amountSat] would cost at [feeratePerByte], or null when no rate sells that amount. */ - fun price(rates: WalletWire.FundingRates, amountSat: Long, feeratePerByte: Long): Price? { - val rate = rateFor(rates, amountSat)?.let(::rateOf) ?: return null - val feerate = FeeratePerKw(FeeratePerByte(Satoshi(feeratePerByte))) - val fees = rate.fees(feerate, Satoshi(amountSat), Satoshi(amountSat), isChannelCreation = false) - return Price(Transactions.weight2fee(feerate, ourWeight).sat, fees.miningFee.sat, fees.serviceFee.sat) - } - - /** The fee cap a proposal carries by default: the estimate and [CAP_HEADROOM_PERCENT] more. */ - fun defaultCap(price: Price): Long = price.totalSat + price.totalSat * CAP_HEADROOM_PERCENT / 100 - - /** Whether the fee is [EXPENSIVE_PERCENT] of the amount or more, as Phoenix warns. */ - fun expensive(price: Price, amountSat: Long): Boolean = price.totalSat * 100 >= amountSat * EXPENSIVE_PERCENT - - /** - * The amounts that can be offered for a channel of [capacitySat]: Phoenix's, less those no rate sells - * and those that would take the channel over [capSat], the most a channel may hold on this network. - */ - fun offered(rates: WalletWire.FundingRates, capacitySat: Long, capSat: Long?): List = - OPTIONS.filter { rateFor(rates, it) != null && (capSat == null || capacitySat + it <= capSat) } - - /** Whether the group can be asked to buy liquidity now, and if not, why not. */ - sealed class Availability { - data object NoOperator : Availability() - /** The operator has not reported the wallet, or not what the LSP sells. */ - data object NoPrices : Availability() - /** No channel to splice: the first payment opens one. */ - data object NoChannel : Availability() - /** The channel is at the most a channel may hold on this network. */ - data object AtTheCap : Availability() - /** The LSP sells none of [OPTIONS]. */ - data object NothingSold : Availability() - data class Available(val channel: WalletWire.ChannelView, val offered: List, val rates: WalletWire.FundingRates, val feeratePerByte: Long) : Availability() - } - - /** What [snapshot] lets a member ask for, on a network whose channels hold at most [capSat]. */ - fun availability(snapshot: WalletWire.Snapshot?, hasOperator: Boolean, capSat: Long?): Availability { - if (!hasOperator) return Availability.NoOperator - if (snapshot == null) return Availability.NoPrices - val channel = snapshot.channels.firstOrNull { it.state == NORMAL } ?: return Availability.NoChannel - val rates = snapshot.fundingRates ?: return Availability.NoPrices - val feerate = snapshot.feeratePerByte ?: return Availability.NoPrices - val offered = offered(rates, channel.capacitySat, capSat) - return when { - offered.isNotEmpty() -> Availability.Available(channel, offered, rates, feerate) - offered(rates, channel.capacitySat, null).isNotEmpty() -> Availability.AtTheCap - else -> Availability.NothingSold - } - } - - /** lightning-kmp's name for the state a channel can be spliced in. */ - private const val NORMAL = "Normal" -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/lightning/WalletWire.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/lightning/WalletWire.kt deleted file mode 100644 index a91b025f..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/lightning/WalletWire.kt +++ /dev/null @@ -1,110 +0,0 @@ -package mobi.giza.compose.wallet.lightning - -import kotlinx.serialization.Serializable - -/** - * What the operator tells the group about its Lightning wallet, and how a member asks to be paid - * (`docs/group-lightning-wallet.md`, Phases 10 and 11), as JSON inside Marmot inner events. - */ -object WalletWire { - /** One channel as the operator's node holds it. */ - @Serializable - data class ChannelView( - val channelId: String, - val state: String, - val capacitySat: Long, - val oursMsat: Long, - val theirsMsat: Long, - val fundingTxId: String, - val fundingIndex: Long, - val commitIndex: Long, - /** - * How many funding outputs carry commitments: 1, or 2 while a splice has not locked, when the LSP - * refuses another (`docs/group-lightning-liquidity.md`, Phase 6). - */ - val liveFundingOutputs: Int = 1, - ) - - /** One payment the node made or received. [id] is lightning-kmp's own. */ - @Serializable - data class PaymentView( - val id: String, - val incoming: Boolean, - val amountMsat: Long, - val feesMsat: Long, - val paymentHash: String? = null, - val description: String? = null, - val completedAt: Long? = null, - val succeeded: Boolean, - /** [PAYMENT], or [LIQUIDITY] for inbound bought: then [amountMsat] is its fee, as in Phoenix, and [liquiditySat] what it bought. */ - val kind: String = PAYMENT, - val liquiditySat: Long? = null, - ) - - const val PAYMENT = "payment" - const val LIQUIDITY = "liquidity" - - /** One of the LSP's liquidity-ads rates, as lightning-kmp's `LiquidityAds.FundingRate` has it. */ - @Serializable - data class FundingRate(val minAmountSat: Long, val maxAmountSat: Long, val fundingWeight: Int, val feeProportional: Int, val feeBaseSat: Long, val channelCreationFeeSat: Long) - - /** What the LSP sells, as its `init` said: [rates], paid by any of [paymentTypes] (BOLT names). */ - @Serializable - data class FundingRates(val rates: List, val paymentTypes: List) - - /** - * What came of one `buy-liquidity` authorisation, [id], on the operator's node: [WAITING] for an - * earlier splice of the channel to lock, [PENDING] with the splice's [fundingTxId] once the LSP signed - * it, [LOCKED] once the channel is on that output alone, or [FAILED] with [reason]. - */ - @Serializable - data class LiquidityPurchase( - val id: String, - val channelId: String, - val amountSat: Long, - val state: String, - val fundingTxId: String? = null, - val feeSat: Long? = null, - val reason: String? = null, - ) - - const val WAITING = "waiting" - const val PENDING = "pending" - const val LOCKED = "locked" - const val FAILED = "failed" - - /** - * Kind 30362: the operator's claim about the wallet, sent when something changes and every few - * minutes while the node runs. [assignments] is the round-one pool's assignments, so an operator - * elected after this one can sign under the verification nonces this one published. - */ - @Serializable - data class Snapshot( - val wallet: String, - val term: Long, - val nodeId: String, - val sentAt: Long, - val channels: List, - val payments: List, - val offer: String? = null, - val assignments: Map = emptyMap(), - /** What closed channels left the group, for any member to sweep into the onchain wallet. */ - val heldOutputs: List = emptyList(), - /** What the LSP sells, for a member to price a purchase from, and the feerate the node would buy at, in sat/vbyte: the operator's claim. */ - val fundingRates: FundingRates? = null, - val feeratePerByte: Long? = null, - /** What came of each liquidity purchase the group authorised. */ - val purchases: List = emptyList(), - ) { - val spendableMsat: Long get() = channels.sumOf { it.oursMsat } - val inboundMsat: Long get() = channels.sumOf { it.theirsMsat } - } - - /** Kind 30364: a member asks the operator for an invoice. */ - @Serializable - data class InvoiceRequest(val wallet: String, val requestId: String, val amountMsat: Long? = null, val description: String) - - /** Kind 30365: the operator's answer, addressed to the whole room by [requestId]. */ - @Serializable - data class InvoiceReply(val wallet: String, val requestId: String, val bolt11: String) -} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ForkCompatibilityTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ForkCompatibilityTest.kt index ae587200..c89fcf50 100644 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ForkCompatibilityTest.kt +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ForkCompatibilityTest.kt @@ -3,7 +3,6 @@ package mobi.giza.compose.managers import fr.acinq.bitcoin.ByteVector32 import fr.acinq.bitcoin.Chain import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.byteVector32 import fr.acinq.secp256k1.Hex import mobi.giza.compose.identity.StoredIdentity import fr.acinq.lightning.crypto.LocalKeyManager @@ -37,7 +36,6 @@ class ForkCompatibilityTest { private val threshold = key(0x91fa).publicKey().toString() private val room = "00".repeat(31) + "2a" - private val ceremony = ByteVector32("11".repeat(32)) // mantra/chilldkg/host-key/v1 @Test @@ -54,44 +52,6 @@ class ForkCompatibilityTest { assertEquals(PINNED_SHARED_KEY, SharedKeyDerivation.derive(threshold).hex) } - // bennu/group-lightning/basepoints/v1 - @Test - fun `group lightning basepoints`() { - val basepoints = GroupLightningDerivation.basepoints(threshold, Chain.Mainnet, 0L) - assertEquals(PINNED_PAYMENT_BASEPOINT, basepoints.payment.publicKey.toString()) - assertEquals(PINNED_DELAYED_BASEPOINT, basepoints.delayedPayment.publicKey.toString()) - } - - // bennu/iceberg/pool/v1 - @Test - fun `iceberg pool label`() { - assertEquals(PINNED_POOL_LABEL, GroupLightningCoSigner.poolLabel(threshold, 7L).toHex()) - } - - // bennu/iceberg-dkg/session/v1, …/contribution/v1, …/commit/v1 and …/seed/v1 - @Test - fun `iceberg dkg session, contribution, commitment and seed`() { - val params = IcebergDkg.Params.of(2, listOf(key(1).publicKey(), key(2).publicKey(), key(3).publicKey(), key(4).publicKey()), ceremony) - assertEquals(PINNED_ICEBERG_SESSION, params.sessionId.toHex()) - val root = ByteVector32("22".repeat(32)) - // The first seed participant 1 holds, and the contributions of everyone who holds it. - val rank = params.heldRanks(1).first() - val contribution = IcebergDkg.contribution(params, 1, root, rank) - assertEquals(PINNED_ICEBERG_CONTRIBUTION, contribution.toHex()) - assertEquals(PINNED_ICEBERG_COMMITMENT, IcebergDkg.commitment(params, 1, rank, contribution).toHex()) - val contributions = params.holders(params.subsets[rank]).map { IcebergDkg.contribution(params, it, root, rank) } - assertEquals(PINNED_ICEBERG_SEED, IcebergDkg.seed(params, rank, contributions).toHex()) - } - - // bennu/iceberg-dkg/transcript/v1 - @Test - fun `iceberg dkg transcript`() { - val params = IcebergDkg.Params.of(2, listOf(key(1).publicKey(), key(2).publicKey(), key(3).publicKey(), key(4).publicKey()), ceremony) - val root = ByteVector32("22".repeat(32)) - val commitments = (1..4).associateWith { IcebergDkg.round1(params, it, root) } - assertEquals(PINNED_ICEBERG_TRANSCRIPT, IcebergDkg.transcriptHash(params, commitments).toHex()) - } - // bennu/member-wallet/id/v1 and bennu/member-wallet/possession/v1 @Test fun `member wallet id and possession message`() { @@ -142,14 +102,6 @@ class ForkCompatibilityTest { const val PINNED_PHRASE_HOST_KEY = "03b93ca2ea2bac313457180953bbede99450d59ce01916e98d42df09fdabbbe83f" const val PINNED_HOST_KEY = "028871ab105eac8812fa7aab4b9110ad20b5dcfba9f65271431dcb417258da08af" const val PINNED_SHARED_KEY = "5eb33e9c2a5a90ae4d273b687eb1265f8b79c2bcee28f9ae9dc44dba6e788444" - const val PINNED_PAYMENT_BASEPOINT = "02973930314ffd75c72fc909bc0b3586b7f2f1196d6423281a24eec32671f3b510" - const val PINNED_DELAYED_BASEPOINT = "02531089bc88fe949dc54394b8bbb7db2439cb2865495bd239b4ecf0264904a270" - const val PINNED_POOL_LABEL = "9490bb167e551d6e247329d60392e0e9b127c978e9b3a89bd4ddbcb2c2f17b99" - const val PINNED_ICEBERG_SESSION = "fba343265271b4c2ee52d54cf4ea99963ae7205333e36b92af81d9d43aaaceed" - const val PINNED_ICEBERG_CONTRIBUTION = "bd11ce00c8d1a1a825395cd32116e606cba857644e7ef2823b03fedbba362360" - const val PINNED_ICEBERG_COMMITMENT = "ee2b1e4e0a92d2d2722a9149bb8f0487e2dc75d4cd9d76a9510a3e60153c960e" - const val PINNED_ICEBERG_SEED = "d68eeef4eafd2581b55e74e59eb7f6872b0aafd2afe12d3baf6d837fa916d755" - const val PINNED_ICEBERG_TRANSCRIPT = "a0e23009ad3462804bfef145de94ad23901bf188f6ea9a259a30e3db00509316" const val PINNED_MEMBER_WALLET_ID = "2282987a87614b622a25500102158d65ed01165919f98bc372aa3d39c828d5db" const val PINNED_POSSESSION_MESSAGE = "43a8cc800f2205edb6384d2758e53b40692859524255449521036f11cdca3396" const val PINNED_GROUP_ADDRESS = "bc1paul0w26tuf9sm75htghayux7xf6vep4zsqrrm0sysawghqjkdm9smddcqp" diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/GroupLightningDerivationTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/GroupLightningDerivationTest.kt deleted file mode 100644 index 5367add3..00000000 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/GroupLightningDerivationTest.kt +++ /dev/null @@ -1,147 +0,0 @@ -package mobi.giza.compose.managers - -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.ByteVector64 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.Crypto -import fr.acinq.bitcoin.OutPoint -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.PublicKey -import fr.acinq.bitcoin.Satoshi -import fr.acinq.bitcoin.Script -import fr.acinq.bitcoin.ScriptFlags -import fr.acinq.bitcoin.ScriptTree -import fr.acinq.bitcoin.ScriptWitness -import fr.acinq.bitcoin.SigHash -import fr.acinq.bitcoin.Transaction -import fr.acinq.bitcoin.TxId -import fr.acinq.bitcoin.TxIn -import fr.acinq.bitcoin.TxOut -import fr.acinq.bitcoin.XonlyPublicKey -import fr.acinq.bitcoin.byteVector32 -import fr.acinq.bitcoin.crypto.dkg.chill.ChillDKG -import fr.acinq.bitcoin.crypto.dkg.chill.ParticipantFinalizeResult -import fr.acinq.bitcoin.crypto.frost.IndividualNonce -import fr.acinq.bitcoin.crypto.frost.SecretNonce -import fr.acinq.bitcoin.crypto.frost.Session -import fr.acinq.bitcoin.crypto.frost.TweakCache -import fr.acinq.lightning.CltvExpiryDelta -import fr.acinq.lightning.crypto.ChannelKeys -import fr.acinq.lightning.crypto.CommitmentPublicKeys -import fr.acinq.lightning.transactions.Scripts -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFails -import kotlin.test.assertNotEquals -import kotlin.test.assertTrue - -/** - * The Lightning wallet's basepoints, pinned, and spent by FROST the way a closing channel's outputs - * would be. - * - * The spends are built with lightning-kmp's own `Scripts.Taproot`, so a leaf this test signs is the leaf - * a real commitment carries; the judge is the script interpreter. Several per-commitment points are - * used because a parity mistake in a plain tweak passes half the time. - */ -class GroupLightningDerivationTest { - private val participants = 3 - private val threshold = 2 - - private val dkg: List = run { - val hostSecretKeys = (1..participants).map { PrivateKey(ByteVector32(ByteArray(32) { i -> (it * 5 + i).toByte() })) } - val hostPublicKeys = hostSecretKeys.map { ChillDKG.hostPublicKey(it) } - val step1 = hostSecretKeys.mapIndexed { i, key -> ChillDKG.participantStep1(key, hostPublicKeys, threshold, ByteVector32(ByteArray(32) { (i + 3).toByte() })) } - val coordinator1 = ChillDKG.coordinatorStep1(step1.map { it.message }, hostPublicKeys, threshold) - val step2 = hostSecretKeys.mapIndexed { i, key -> ChillDKG.participantStep2(key, step1[i].state, coordinator1.message, ByteVector32(ByteArray(32) { (i + 17).toByte() })) } - val certificate = ChillDKG.coordinatorFinalize(coordinator1.state, step2.map { it.certEqSignature }, threshold).certificate - (0 until participants).map { i -> ChillDKG.participantFinalize(step2[i].state, certificate, participants, threshold) } - .onEach { assertTrue(it.fault.isOk) } - } - private val k: PublicKey = dkg[0].thresholdPublicKey!! - private val basepoints = GroupLightningDerivation.basepoints(k.toString(), Chain.Regtest, wallet = 0) - - private fun key(seed: Int) = PrivateKey(ByteVector32(ByteArray(32) { (seed + it).toByte() })) - - /** A FROST signature by members 0 and 2, under [cache], over [message]. */ - private fun frost(message: ByteVector32, cache: TweakCache, seed: Int): ByteVector64 { - val signers = listOf(0, 2) - val nonces = signers.map { id -> - SecretNonce.generate(ByteVector32(ByteArray(32) { (seed * 16 + id).toByte() }), dkg[id].secretShare!!, dkg[0].publicShares[id], cache.tweakedPublicKey, message, null) - } - val session = Session.create(IndividualNonce.aggregate(nonces.map { it.second }).right!!, signers.map { it.toUInt() }, signers.map { dkg[0].publicShares[it] }, participants, threshold, cache, message) - val partials = signers.mapIndexed { i, id -> session.sign(nonces[i].first, dkg[id].secretShare!!, id.toUInt()).right!! } - return session.aggregateSigs(partials).right!! - } - - /** Spend a leaf of a NUMS-keyed output the way the group sweeps one. */ - private fun spendsUnderFrost(script: List, leaf: ScriptTree.Leaf, tree: ScriptTree, csv: Long, cache: TweakCache, seed: Int): Boolean { - val output = TxOut(Satoshi(50_000), script) - val funding = Transaction(2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 7 })), 0), 0xffffffffL)), listOf(output), 0) - val unsigned = Transaction(2, listOf(TxIn(OutPoint(funding, 0), csv)), listOf(TxOut(Satoshi(49_000), Script.pay2wpkh(key(90).publicKey()))), 0) - val sighash = unsigned.hashForSigningTaprootScriptPath(0, listOf(output), SigHash.SIGHASH_DEFAULT, leaf.hash()) - val sig = frost(sighash, cache, seed) - val signed = unsigned.updateWitness(0, Script.witnessScriptPathPay2tr(Scripts.Taproot.NUMS_POINT.xOnly(), leaf, ScriptWitness(listOf(sig)), tree)) - return runCatching { Transaction.correctlySpends(signed, mapOf(OutPoint(funding, 0) to output), ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) }.isSuccess - } - - private fun commitmentKeys(remotePayment: PublicKey = key(1).publicKey(), localDelayed: PublicKey = key(2).publicKey()) = - CommitmentPublicKeys(localDelayed, remotePayment, key(3).publicKey(), key(4).publicKey(), key(5).publicKey()) - - @Test - fun `a quorum spends to_remote under the payment basepoint`() { - val keys = commitmentKeys(remotePayment = basepoints.payment.publicKey) - val leaf = Scripts.Taproot.toRemoteScriptTree(keys) - assertTrue(spendsUnderFrost(Scripts.Taproot.toRemote(keys), leaf, leaf, 1, GroupLightningDerivation.leafCache(basepoints.payment, null), seed = 1)) - } - - @Test - fun `a quorum spends to_local under the delayed basepoint plus each commitment's tweak`() { - val delay = CltvExpiryDelta(144) - for (n in 0 until 8) { - val pcp = key(40 + n).publicKey() - val leafKey = ChannelKeys.remotePerCommitmentPublicKey(basepoints.delayedPayment.publicKey, pcp) - val tweak = Crypto.sha256(pcp.value + basepoints.delayedPayment.publicKey.value).byteVector32() - val keys = commitmentKeys(localDelayed = leafKey) - val tree = Scripts.Taproot.toLocalScriptTree(keys, delay) - val cache = GroupLightningDerivation.leafCache(basepoints.delayedPayment, tweak) - assertEquals(leafKey.xOnly(), cache.tweakedPublicKey, "commitment $n") - assertTrue(spendsUnderFrost(Scripts.Taproot.toLocal(keys, delay), tree.localDelayed, tree.scriptTree, delay.toLong(), cache, seed = 10 + n), "commitment $n") - // The untweaked basepoint is not the leaf key. - assertTrue(!spendsUnderFrost(Scripts.Taproot.toLocal(keys, delay), tree.localDelayed, tree.scriptTree, delay.toLong(), basepoints.delayedPayment.cache, seed = 30 + n)) - } - } - - @Test - fun `the derivation is pinned`() { - // A fixed K, so the tag, the byte order of the chain hash and the order of the HMAC's inputs are - // frozen here. Changing any of them moves every group's basepoints: a protocol fork. - val fixed = PrivateKey(ByteVector32(ByteArray(32) { 0x2a })).publicKey().toString() - val regtest = GroupLightningDerivation.basepoints(fixed, Chain.Regtest, 0) - val mainnet = GroupLightningDerivation.basepoints(fixed, Chain.Mainnet, 0) - val next = GroupLightningDerivation.basepoints(fixed, Chain.Regtest, 1) - assertEquals("020c73decf91066ea570ede057f2ef4521914a4902ceb12c124a54132f8c0cc319", regtest.payment.publicKey.toString()) - assertEquals("02c7d1b23df4878458422d042342d16b157f7628381e9977efc85d1be6d470eb14", regtest.delayedPayment.publicKey.toString()) - assertEquals("03fc539a36e31dc5940a34e06be922aeb65dd8b6a72bc414d34c8d0f88c44ca5e4", mainnet.payment.publicKey.toString()) - assertEquals("03c5901c78139d459aef3ed252431090c3d12a4e14b0f094c89284a8d4d58931d4", mainnet.delayedPayment.publicKey.toString()) - assertEquals("0309dac3e80cd059749ff10add118a4d85cb90688021f54be3be55de782c4391c6", next.payment.publicKey.toString()) - assertEquals("02b8fe5fe20854fb244ae7f95b0827a9d9c2a3b974cef24c8e0d92a72cd3f66dfe", next.delayedPayment.publicKey.toString()) - } - - @Test - fun `the basepoints are unrelated to every other key the group holds`() { - val wallet = GroupWalletDerivation.account(k.toString(), Chain.Regtest) - val others = setOf( - k.xOnly(), - SharedKeyDerivation.derive(k.toString()).publicKey, - wallet.extendedPublicKey.publicKey.xOnly(), - GroupWalletDerivation.derive(wallet, GroupWalletDerivation.RECEIVE, 0).internalKey, - GroupWalletDerivation.derive(wallet, GroupWalletDerivation.CHANGE, 0).internalKey, - ) - assertTrue(basepoints.payment.publicKey.xOnly() !in others) - assertTrue(basepoints.delayedPayment.publicKey.xOnly() !in others) - assertNotEquals(basepoints.payment.publicKey, basepoints.delayedPayment.publicKey) - assertNotEquals(basepoints.payment.publicKey, GroupLightningDerivation.basepoints(k.toString(), Chain.Mainnet, 0).payment.publicKey) - assertNotEquals(basepoints.payment.publicKey, GroupLightningDerivation.basepoints(k.toString(), Chain.Regtest, 1).payment.publicKey) - assertFails { GroupLightningDerivation.basepoints(k.toString(), Chain.Regtest, 0x80000000L) } - } -} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/IcebergDkgTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/IcebergDkgTest.kt deleted file mode 100644 index 6195f9fb..00000000 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/IcebergDkgTest.kt +++ /dev/null @@ -1,210 +0,0 @@ -package mobi.giza.compose.managers - -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Crypto -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.PublicKey -import fr.acinq.bitcoin.byteVector32 -import fr.acinq.bitcoin.crypto.Pack -import fr.acinq.bitcoin.crypto.iceberg.Iceberg -import fr.acinq.bitcoin.crypto.iceberg.PublicShare -import fr.acinq.bitcoin.crypto.iceberg.Share -import fr.acinq.bitcoin.crypto.musig2.IndividualNonce -import fr.acinq.bitcoin.crypto.musig2.KeyAggCache -import fr.acinq.bitcoin.crypto.musig2.SecretNonce -import fr.acinq.bitcoin.crypto.musig2.Session -import fr.acinq.bitcoin.utils.Either -import kotlin.random.Random -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertFalse -import kotlin.test.assertIs -import kotlin.test.assertNotEquals -import kotlin.test.assertTrue - -/** - * The Iceberg DKG, run between simulated participants against the real library. - * - * The layout test is the one to read first: it proves, against the library's - * own dealer, that a share this DKG assembles is laid out the way - * `secp256k1_iceberg_share_parse` reads it. Everything after it would pass for a - * DKG whose seeds were in the wrong order -- the shares would still parse and - * still aggregate -- right up to the signature that did not verify. - */ -class IcebergDkgTest { - private val random = Random(0x1ceb) - - private fun bytes32() = random.nextBytes(32).byteVector32() - - private fun hostKeys(n: Int): List = (1..n).map { PrivateKey(bytes32()).publicKey() } - - private class Run(val params: IcebergDkg.Params, val shares: List, val publicShares: List, val groupKey: PublicKey) - - /** Every participant runs every round, honestly. */ - private fun run(n: Int, t: Int): Run { - val params = IcebergDkg.Params.of(t, hostKeys(n), bytes32()) - val roots = (1..n).associateWith { bytes32() } - val commitments = (1..n).associateWith { IcebergDkg.round1(params, it, roots.getValue(it)) } - val shares = (1..n).map { k -> - val reveals = (1..n).filter { it != k }.associateWith { j -> IcebergDkg.round2(params, j, roots.getValue(j), k) } - val share = IcebergDkg.assemble(params, k, roots.getValue(k), commitments, reveals) - assertIs>(share).value - } - val publicShares = shares.map { Iceberg.publicShare(it, null) } - val key = assertIs>(IcebergDkg.groupPublicKey(params, publicShares)).value - return Run(params, shares, publicShares, key) - } - - /** One signature by [signers] (1-based) beside a stock MuSig2 cosigner, judged by BIP340. */ - private fun signs(run: Run, signers: List): Boolean { - val n = run.params.n - val t = run.params.t - val cosigner = PrivateKey(bytes32()) - val msg = bytes32() - val sid = bytes32() - val keys = listOf(run.groupKey, cosigner.publicKey()) - val (aggregateKey, cache) = KeyAggCache.create(keys) - val contributions = signers.map { Iceberg.generateNonce(run.shares[it - 1], null, sid) } - val groupNonce = Iceberg.aggregateNonces(contributions, n, t, run.groupKey).right ?: return false - val (cosignerSecret, cosignerPublic) = SecretNonce.generate(bytes32(), Either.Left(cosigner), msg, cache, null) - val aggregated = IndividualNonce.aggregate(listOf(groupNonce, cosignerPublic)).right ?: return false - val cosignerAggregated = IndividualNonce.aggregate(listOf(cosignerPublic)).right ?: return false - val session = Session.create(aggregated, msg, cache) - val signatureShares = signers.map { - Iceberg.partialSign(run.shares[it - 1], null, sid, contributions, run.groupKey, cache, msg, cosignerAggregated).right ?: return false - } - val groupPartial = Iceberg.aggregatePartialSignatures(signatureShares, n, t).right ?: return false - val cosignerPartial = session.sign(cosignerSecret, cosigner).right ?: return false - val sig = session.aggregateSigs(listOf(groupPartial, cosignerPartial)).right ?: return false - return Crypto.verifySignatureSchnorr(msg, sig, aggregateKey) - } - - private fun quorums(n: Int, t: Int): List> = - IcebergDkg.subsetsInRankOrder(n, 2 * t - 1).map { mask -> (1..n).filter { mask and (1 shl it) != 0 } } - - @Test - fun `an assembled share is laid out as the library's dealer lays one out`() { - for ((n, t) in listOf(4 to 2, 7 to 3, 10 to 4, 5 to 3)) { - val root = bytes32() - val dealt = Iceberg.dealShares(n, t, root) - val ranks = IcebergDkg.subsetsInRankOrder(n, t - 1) - for (k in 1..n) { - // keygen_impl.h: seed(rank) = H_"Iceberg/dealer"(root || n || t || rank), appended for every subset k is outside of. - val seeds = ranks.indices.filter { ranks[it] and (1 shl k) == 0 }.map { - Crypto.taggedHash(root.toByteArray() + byteArrayOf(n.toByte(), t.toByte()) + Pack.writeInt32BE(it), "Iceberg/dealer") - } - assertEquals(dealt[k - 1], IcebergDkg.share(n, t, k, seeds), "participant $k of $t-of-$n") - } - } - } - - @Test - fun `the rank order is rss_h's`() { - // The example rss.h writes out because the reference's docstring was off by one. - val expected = listOf(setOf(1, 2), setOf(1, 3), setOf(1, 4), setOf(1, 5), setOf(2, 3), setOf(2, 4), setOf(2, 5), setOf(3, 4), setOf(3, 5), setOf(4, 5)) - assertEquals(expected, IcebergDkg.subsetsInRankOrder(5, 2).map { mask -> (1..5).filter { mask and (1 shl it) != 0 }.toSet() }) - } - - @Test - fun `2-of-4 and 3-of-7 sign from every quorum, and every quorum agrees on the key`() { - for ((n, t) in listOf(4 to 2, 7 to 3)) { - val run = run(n, t) - for (q in quorums(n, t)) { - assertTrue(signs(run, q), "quorum $q of $t-of-$n") - val key = Iceberg.groupPublicKey(q.map { run.publicShares[it - 1] }, n, t).right - assertEquals(run.groupKey, key, "key over $q") - } - } - } - - @Test - fun `4-of-10 signs`() { - val run = run(10, 4) - assertTrue(signs(run, listOf(1, 2, 3, 4, 5, 6, 7))) - assertTrue(signs(run, listOf(4, 5, 6, 7, 8, 9, 10))) - assertTrue(signs(run, listOf(1, 3, 5, 7, 8, 9, 10))) - } - - @Test - fun `a reveal that was not committed to names its sender`() { - val params = IcebergDkg.Params.of(2, hostKeys(4), bytes32()) - val roots = (1..4).associateWith { bytes32() } - val commitments = (1..4).associateWith { IcebergDkg.round1(params, it, roots.getValue(it)) } - val reveals = (2..4).associateWith { j -> IcebergDkg.round2(params, j, roots.getValue(j), 1) }.toMutableMap() - reveals[3] = reveals.getValue(3).mapValues { bytes32() } - val result = IcebergDkg.assemble(params, 1, roots.getValue(1), commitments, reveals) - val fault = assertIs(assertIs>(result).value) - assertEquals(3, fault.participant) - } - - @Test - fun `a silent participant is named`() { - val params = IcebergDkg.Params.of(2, hostKeys(4), bytes32()) - val roots = (1..4).associateWith { bytes32() } - val commitments = (1..4).associateWith { IcebergDkg.round1(params, it, roots.getValue(it)) } - val reveals = (2..3).associateWith { j -> IcebergDkg.round2(params, j, roots.getValue(j), 1) } - assertEquals(4, (IcebergDkg.assemble(params, 1, roots.getValue(1), commitments, reveals) as Either.Left).value.participant) - assertEquals(2, (IcebergDkg.assemble(params, 1, roots.getValue(1), commitments - 2, reveals) as Either.Left).value.participant) - } - - @Test - fun `a share off the polynomial fails the group key`() { - val run = run(4, 2) - val bytes = run.shares[2].toByteArray().also { it[10] = (it[10] + 1).toByte() } - val tampered = run.publicShares.toMutableList().apply { this[2] = Iceberg.publicShare(Share(bytes), null) } - assertIs>(IcebergDkg.groupPublicKey(run.params, tampered)) - } - - @Test - fun `the session binds the participants, the threshold and the ceremony, but not the order they were listed in`() { - val keys = hostKeys(5) - val ceremony = bytes32() - val base = IcebergDkg.Params.of(2, keys, ceremony) - assertEquals(base.sessionId, IcebergDkg.Params.of(2, keys.reversed(), ceremony).sessionId) - assertEquals(base.hostKeys, IcebergDkg.Params.of(2, keys.shuffled(random), ceremony).hostKeys) - assertNotEquals(base.sessionId, IcebergDkg.Params.of(2, keys, bytes32()).sessionId) - assertNotEquals(base.sessionId, IcebergDkg.Params.of(2, keys.dropLast(1), ceremony).sessionId) - assertFailsWith { IcebergDkg.Params.of(2, keys + keys.first(), ceremony) } - } - - @Test - fun `only deployable groups are offered`() { - assertEquals(emptyList(), IcebergDkg.deployableThresholds(3)) - assertEquals(listOf(2), IcebergDkg.deployableThresholds(4)) - assertEquals(listOf(2), IcebergDkg.deployableThresholds(6)) - assertEquals(listOf(2, 3), IcebergDkg.deployableThresholds(7)) - assertEquals(listOf(2, 3, 4), IcebergDkg.deployableThresholds(10)) - assertEquals(emptyList(), IcebergDkg.deployableThresholds(11)) - assertTrue(IcebergDkg.isExpressible(3, 2)) - assertFalse(IcebergDkg.isDeployable(3, 2)) - assertFalse(IcebergDkg.isExpressible(4, 3)) - assertFailsWith { IcebergDkg.Params.of(3, hostKeys(5), bytes32()) } - } - - @Test - fun `a lost share is repaired from the other holders' seeds`() { - val run = run(7, 3) - val lost = 4 - val received = (1..7).filter { it != lost }.associateWith { IcebergDkg.repairSeeds(run.params, it, run.shares[it - 1], lost) } - val repaired = IcebergDkg.repair(run.params, lost, received, run.publicShares[lost - 1]) - assertEquals(run.shares[lost - 1], assertIs>(repaired).value) - - // One helper lying about one seed is caught, whether or not another helper sent the same seed. - val lying = received.toMutableMap().apply { this[1] = getValue(1).mapValues { bytes32() } } - assertIs>(IcebergDkg.repair(run.params, lost, lying, run.publicShares[lost - 1])) - val onlyTheLiar = mapOf(1 to lying.getValue(1)) + received.filterKeys { it != 1 }.mapValues { (_, seeds) -> seeds - lying.getValue(1).keys } - assertIs>(IcebergDkg.repair(run.params, lost, onlyTheLiar, run.publicShares[lost - 1])) - } - - @Test - fun `members shown different commitments publish different transcripts`() { - val params = IcebergDkg.Params.of(2, hostKeys(4), bytes32()) - val roots = (1..4).associateWith { bytes32() } - val commitments = (1..4).associateWith { IcebergDkg.round1(params, it, roots.getValue(it)) } - val honest = IcebergDkg.transcriptHash(params, commitments) - assertEquals(honest, IcebergDkg.transcriptHash(params, commitments.toList().reversed().toMap())) - val other = commitments + (2 to IcebergDkg.round1(params, 2, bytes32())) - assertNotEquals(honest, IcebergDkg.transcriptHash(params, other)) - } -} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/RetiredKindsTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/RetiredKindsTest.kt index a1619ed6..abd9a62c 100644 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/RetiredKindsTest.kt +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/RetiredKindsTest.kt @@ -35,7 +35,7 @@ class RetiredKindsTest { } @Test - fun `the ranges are the ones Bennu uses`() { + fun `the ranges are the ones the wallets used`() { assertEquals(30331, RetiredKinds.WALLET.first) assertEquals(30337, RetiredKinds.WALLET.last) assertEquals(30350, RetiredKinds.GROUP_LIGHTNING.first) diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/lightning/GroupLightningEventsTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/lightning/GroupLightningEventsTest.kt deleted file mode 100644 index 1eba2372..00000000 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/lightning/GroupLightningEventsTest.kt +++ /dev/null @@ -1,71 +0,0 @@ -package mobi.giza.compose.nostr.lightning - -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.FrostSigningEvents -import mobi.giza.compose.nostr.frost.GroupKeyStateEvent -import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent -import mobi.giza.compose.nostr.wallet.GroupKeyNoticeEvent -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import mobi.giza.compose.nostr.wallet.GuardedWalletNoticeEvent -import mobi.giza.compose.nostr.wallet.MemberWalletCertificateEvent -import mobi.giza.compose.nostr.wallet.MemberWalletPolicyEvent -import mobi.giza.compose.nostr.wallet.MemberWalletRequestEvent -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertTrue - -/** - * The Lightning wallet's kinds stand apart from every family the inbound path - * already dispatches on. The FROST family's note says its own separation from - * the DKG's was "an accident of routing rather than a decision"; this test is - * the decision, written down where a new kind would break it. - */ -class GroupLightningEventsTest { - private val taken = DkgRitualEvents.ALL + FrostSigningEvents.ALL + setOf( - GroupKeyStateEvent.KIND, - ChronicleEvent.KIND, - ChronicleRequestEvent.KIND, - SubgroupBirthCertificateEvent.KIND, - MarmotDirectMessage.ENVELOPE_KIND, - GroupWalletStatementEvent.KIND, - // The guarded-wallet family, which took 30333-30337 while this one was being built under - // those numbers: the reason it moved. - GuardedWalletNoticeEvent.KIND, - MemberWalletCertificateEvent.KIND, - MemberWalletRequestEvent.KIND, - GroupKeyNoticeEvent.KIND, - MemberWalletPolicyEvent.KIND, - ) + (30300..30312).toSet() // the nip30303 document kinds, gone but not to be reused - - @Test - fun `no lightning kind is a kind the app already routes`() { - assertEquals(emptySet(), GroupLightningEvents.ALL intersect taken) - } - - @Test - fun `the family starts past every kind the app uses, so the next family can follow it`() { - assertTrue(GroupLightningEvents.ALL.min() > taken.max(), "a Lightning kind sits inside another family's range") - } - - @Test - fun `the family is one unbroken run from 30350 to 30366`() { - assertEquals((30350..30366).toSet(), GroupLightningEvents.ALL) - } - - @Test - fun `the groups partition the family`() { - val groups = listOf( - GroupLightningEvents.CEREMONY, - GroupLightningEvents.CO_SIGNING, - GroupLightningEvents.WALLET_TRAFFIC, - GroupLightningEvents.GROUP_SIGNED, - ) - assertEquals(GroupLightningEvents.ALL.size, groups.sumOf { it.size }) - for (i in groups.indices) for (j in i + 1 until groups.size) { - assertTrue((groups[i] intersect groups[j]).isEmpty(), "groups $i and $j overlap") - } - } -} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/wallet/lightning/CoSignerPolicyTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/wallet/lightning/CoSignerPolicyTest.kt deleted file mode 100644 index 17309787..00000000 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/wallet/lightning/CoSignerPolicyTest.kt +++ /dev/null @@ -1,128 +0,0 @@ -package mobi.giza.compose.wallet.lightning - -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Satoshi -import fr.acinq.lightning.CltvExpiry -import fr.acinq.lightning.blockchain.fee.FeeratePerKw -import fr.acinq.lightning.transactions.CommitmentSpec -import fr.acinq.lightning.transactions.DirectedHtlc -import fr.acinq.lightning.transactions.IncomingHtlc -import fr.acinq.lightning.transactions.OutgoingHtlc -import fr.acinq.lightning.utils.msat -import fr.acinq.lightning.wire.OnionRoutingPacket -import fr.acinq.lightning.wire.UpdateAddHtlc -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertIs -import kotlin.test.assertTrue - -/** - * What a co-signer lets the counterparty's commitment do to the group's money. Every spec here is the - * counterparty's view: `toRemote` is ours, an HTLC they receive is one we offered. - */ -class CoSignerPolicyTest { - private val channel = ByteVector32.Zeroes - private val onion = OnionRoutingPacket(0, ByteVector(ByteArray(33) { if (it == 0) 2 else 0 }), ByteVector.empty, ByteVector32.Zeroes) - private val allowance = 5_000_000L - private fun hash(n: Int) = ByteVector32(ByteArray(32) { n.toByte() }) - - private fun add(id: Long, amount: Long, hash: ByteVector32) = UpdateAddHtlc(channel, id, amount.msat, hash, CltvExpiry(800_000), onion) - - /** We offered these (they receive them). */ - private fun offered(id: Long, amount: Long, h: Int): DirectedHtlc = IncomingHtlc(add(id, amount, hash(h))) - - /** They offered these to us. */ - private fun toUs(id: Long, amount: Long, h: Int): DirectedHtlc = OutgoingHtlc(add(id, amount, hash(h))) - - private fun spec(ours: Long, theirs: Long, vararg htlcs: DirectedHtlc) = CommitmentSpec(htlcs.toSet(), FeeratePerKw(Satoshi(2_500)), toLocal = theirs.msat, toRemote = ours.msat) - - /** The commitment after [previous]'s, as the counterparty would send it. */ - private fun next(previous: CoSignerPolicy.Ledger, spec: CommitmentSpec, budgets: Map = emptyMap(), closed: Set = emptySet()): CoSignerPolicy.Verdict = - CoSignerPolicy.checkRemoteCommitment(previous, previous.commitIndex + 1, "tx${previous.commitIndex + 1}:$spec".hashCode().toString(), spec, budgets, closed) - - private fun signed(verdict: CoSignerPolicy.Verdict) = assertIs(verdict) - private fun refused(verdict: CoSignerPolicy.Verdict) = assertIs(verdict) - - private val start = CoSignerPolicy.open(0, "tx0", spec(ours = 100_000_000, theirs = 900_000_000), allowance) - - @Test - fun `receiving raises the floor, so what was received cannot be drained`() { - val incoming = signed(next(start, spec(100_000_000, 850_000_000, toUs(0, 50_000_000, 1)))).ledger - val received = signed(next(incoming, spec(150_000_000, 850_000_000))).ledger - assertEquals(start.floorMsat + 50_000_000, received.floorMsat) - // A fall bigger than the fee allowance, with nothing authorised to explain it, is refused. - refused(next(received, spec(140_000_000, 860_000_000))) - // Within the allowance it is a fee. - signed(next(received, spec(147_000_000, 853_000_000))) - } - - @Test - fun `an outgoing payment needs an authorisation, and spends its budget when it settles`() { - val budgets = mapOf(hash(7).toHex() to 30_000_000L) - refused(next(start, spec(70_000_000, 900_000_000, offered(0, 30_000_000, 7)))) - val inFlight = signed(next(start, spec(70_000_000, 900_000_000, offered(0, 30_000_000, 7)), budgets)).ledger - assertEquals(start.valueMsat, inFlight.valueMsat, "an HTLC in flight is still the group's to claim back") - val settled = signed(next(inFlight, spec(70_000_000, 930_000_000), budgets)) - assertEquals(mapOf(hash(7).toHex() to 30_000_000L), settled.consumed) - assertEquals(start.floorMsat - 30_000_000, settled.ledger.floorMsat) - } - - @Test - fun `a failed payment comes back and spends nothing`() { - val budgets = mapOf(hash(7).toHex() to 30_000_000L) - val inFlight = signed(next(start, spec(70_000_000, 900_000_000, offered(0, 30_000_000, 7)), budgets)).ledger - val failed = signed(next(inFlight, spec(100_000_000, 900_000_000), budgets)) - assertTrue(failed.consumed.isEmpty()) - assertEquals(start.floorMsat, failed.ledger.floorMsat) - // So the payment can be tried again. - signed(next(failed.ledger, spec(70_000_000, 900_000_000, offered(1, 30_000_000, 7)), budgets)) - } - - @Test - fun `one authorisation cannot be offered twice over`() { - val budgets = mapOf(hash(7).toHex() to 30_000_000L) - val first = signed(next(start, spec(80_000_000, 900_000_000, offered(0, 20_000_000, 7)), budgets)).ledger - // A second part of the same payment fits only in what is left of its budget. - refused(next(first, spec(60_000_000, 900_000_000, offered(0, 20_000_000, 7), offered(1, 20_000_000, 7)), budgets)) - signed(next(first, spec(70_000_000, 900_000_000, offered(0, 20_000_000, 7), offered(1, 10_000_000, 7)), budgets)) - } - - @Test - fun `a spent budget is gone, whatever arrives afterwards`() { - val budgets = mapOf(hash(7).toHex() to 30_000_000L) - val inFlight = signed(next(start, spec(70_000_000, 900_000_000, offered(0, 30_000_000, 7)), budgets)).ledger - val spent = signed(next(inFlight, spec(70_000_000, 930_000_000), budgets)).ledger - val paid = signed(next(signed(next(spent, spec(70_000_000, 900_000_000, toUs(1, 30_000_000, 2)))).ledger, spec(100_000_000, 900_000_000))).ledger - // The receipt does not refill the budget: what came in is the group's, and the floor says so. - refused(next(paid, spec(70_000_000, 930_000_000))) - } - - @Test - fun `the commitment number moves forward one at a time, and a repeat is the same transaction`() { - assertIs(CoSignerPolicy.checkRemoteCommitment(start, 0, "tx0", spec(100_000_000, 900_000_000), emptyMap())) - refused(CoSignerPolicy.checkRemoteCommitment(start, 0, "other", spec(100_000_000, 900_000_000), emptyMap())) - refused(CoSignerPolicy.checkRemoteCommitment(start, 2, "tx2", spec(100_000_000, 900_000_000), emptyMap())) - } - - @Test - fun `an expired authorisation settles what is in flight, and offers nothing new`() { - val budgets = mapOf(hash(7).toHex() to 30_000_000L) - val closed = setOf(hash(7).toHex()) - refused(next(start, spec(80_000_000, 900_000_000, offered(0, 20_000_000, 7)), budgets, closed)) - val inFlight = signed(next(start, spec(80_000_000, 900_000_000, offered(0, 20_000_000, 7)), budgets)).ledger - refused(next(inFlight, spec(70_000_000, 900_000_000, offered(0, 20_000_000, 7), offered(1, 10_000_000, 7)), budgets, closed)) - val settled = signed(next(inFlight, spec(80_000_000, 920_000_000), budgets, closed)) - assertEquals(mapOf(hash(7).toHex() to 20_000_000L), settled.consumed) - } - - @Test - fun `what the group offers at once stays under the cap, and what it is offered is not counted`() { - val budgets = mapOf(hash(7).toHex() to 50_000_000L, hash(8).toHex() to 50_000_000L) - fun capped(previous: CoSignerPolicy.Ledger, spec: CommitmentSpec) = - CoSignerPolicy.checkRemoteCommitment(previous, previous.commitIndex + 1, "tx${previous.commitIndex + 1}:$spec".hashCode().toString(), spec, budgets, inFlightCapMsat = 40_000_000) - val one = signed(capped(start, spec(70_000_000, 900_000_000, offered(0, 30_000_000, 7)))).ledger - refused(capped(one, spec(50_000_000, 900_000_000, offered(0, 30_000_000, 7), offered(1, 20_000_000, 8)))) - signed(capped(one, spec(70_000_000, 850_000_000, offered(0, 30_000_000, 7), toUs(1, 50_000_000, 2)))) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/LightningProtocolLinesMigrationJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/LightningProtocolLinesMigrationJvmTest.kt deleted file mode 100644 index 7ada042d..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/migrations/LightningProtocolLinesMigrationJvmTest.kt +++ /dev/null @@ -1,89 +0,0 @@ -package mobi.giza.compose.database.migrations - -import androidx.sqlite.SQLiteConnection -import androidx.sqlite.driver.bundled.BundledSQLiteDriver -import androidx.sqlite.execSQL -import kotlinx.coroutines.runBlocking -import kotlinx.serialization.json.Json -import kotlinx.serialization.json.JsonObject -import kotlinx.serialization.json.jsonArray -import kotlinx.serialization.json.jsonObject -import kotlinx.serialization.json.jsonPrimitive -import java.io.File -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals - -/** - * The v32 -> v33 migration, against a database holding the raw-JSON bubbles the Lightning - * wallet's messages left and the lines that have to survive beside them. Built from the - * exported v32 schema, the way [RemoveDocumentsMigrationJvmTest] builds v26. - */ -class LightningProtocolLinesMigrationJvmTest { - - private val connection: SQLiteConnection = BundledSQLiteDriver().open(":memory:") - - @AfterTest - fun close() = connection.close() - - private val schemas: File = - (File("schemas").takeIf { it.isDirectory } ?: File("composeApp/schemas")) - .resolve("mobi.giza.compose.database.GizaDatabase") - - private fun createV32() { - Json.parseToJsonElement(schemas.resolve("32.json").readText()) - .jsonObject["database"]!!.jsonObject["entities"]!!.jsonArray - .map { it.jsonObject } - .forEach { entity: JsonObject -> - val table = entity["tableName"]!!.jsonPrimitive.content - connection.execSQL(entity["createSql"]!!.jsonPrimitive.content.replace("\${TABLE_NAME}", table)) - } - } - - private fun lines(): List> = connection.prepare( - "SELECT id, messageType FROM ChatMessage ORDER BY id" - ).use { statement -> - buildList { while (statement.step()) add(statement.getLong(0) to statement.getText(1)) } - } - - private fun innerEvent(id: String, kind: Int) = connection.execSQL( - "INSERT INTO MarmotInnerEvent (id, publicKey, chatRoomId, kind, tags, content, createdAt, updatedAt, savedAt) " + - "VALUES ('$id', 'author', 'room', $kind, '[]', '{}', 1, 1, 1)" - ) - - private fun line(id: Long, type: String, innerEventId: String? = null) = connection.execSQL( - "INSERT INTO ChatMessage (id, senderPublicKey, isUserMessage, marmotInnerEventId, chatRoomId, " + - "content, messageType, createdAt, updatedAt, savedAt) VALUES " + - "($id, 'author', 0, ${innerEventId?.let { "'$it'" } ?: "NULL"}, 'room', 'x', '$type', 1, 1, 1)" - ) - - @Test - fun `only the Lightning wallet's raw-JSON bubbles are deleted`(): Unit = runBlocking { - createV32() - - innerEvent("proposal", kind = 30350) // the Iceberg ceremony - innerEvent("nonces", kind = 30360) // co-signing - innerEvent("snapshot", kind = 30362) // the operator's traffic - innerEvent("stopped", kind = 30366) - innerEvent("statement", kind = 30355) // signed by the group - innerEvent("mystery", kind = 4242) // a payload this app does not know - - line(1, "unsupported", innerEventId = "proposal") - line(2, "unsupported", innerEventId = "nonces") - line(3, "unsupported", innerEventId = "snapshot") - line(4, "unsupported", innerEventId = "stopped") - line(5, "groupLightningWalletOpened", innerEventId = "statement") - line(6, "unsupported", innerEventId = "mystery") - line(7, "icebergStarted") - line(8, "message") - - MIGRATION_32_33.migrate(connection) - - assertEquals( - listOf(5L to "groupLightningWalletOpened", 6L to "unsupported", 7L to "icebergStarted", 8L to "message"), - lines(), - "the protocol's bubbles go; the group's statement, an unknown payload's bubble, " + - "the ceremony's own line and a message stay", - ) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/model/ProtocolKindDispatchJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/model/ProtocolKindDispatchJvmTest.kt index e61d5a47..ff0afa5b 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/model/ProtocolKindDispatchJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/model/ProtocolKindDispatchJvmTest.kt @@ -25,7 +25,6 @@ import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.builder.getRoomDatabase import mobi.giza.compose.nostr.dkg.DkgRitualEvents import mobi.giza.compose.nostr.frost.FrostSigningEvents -import mobi.giza.compose.nostr.lightning.GroupLightningEvents /** * A key ceremony's or a signing session's message, arriving in a Marmot room, @@ -181,39 +180,6 @@ class ProtocolKindDispatchJvmTest { ) } - /** - * The Lightning wallet's protocol is the third family, and the one that was missed: - * every kind of it left a raw-JSON bubble, attributed to whoever sent it, beside the - * lines its managers write. docs/group-lightning-transcript.md, Phase 1. - */ - @Test - fun `a Lightning wallet message writes no chat line`(): Unit = runBlocking { - GroupLightningEvents.PROTOCOL.forEach { kind -> - val (_, line) = arrive(kind, content = """{"wallet":"w"}""") - assertNull(line, "kind $kind is the Lightning wallet's protocol") - } - - assertTrue( - database.chatMessageDao().getChatMessagesByChatRoomId(chatRoomId).isEmpty(), - "and the room's transcript is untouched", - ) - assertEquals( - GroupLightningEvents.PROTOCOL, - database.marmotInnerEventDao() - .getByChatRoomAndKinds(chatRoomId, GroupLightningEvents.PROTOCOL.toList()) - .map { it.kind } - .toSet(), - "every one is still stored, for the managers that replay them", - ) - } - - /** The three the group signs are not protocol: their arms check them and describe them. */ - @Test - fun `none of the kinds the group signs is protocol`() { - assertTrue((GroupLightningEvents.PROTOCOL intersect GroupLightningEvents.GROUP_SIGNED).isEmpty()) - assertEquals(GroupLightningEvents.ALL, GroupLightningEvents.PROTOCOL + GroupLightningEvents.GROUP_SIGNED) - } - /** * Bennu's wallets reach a room Giza shares with Bennu members, and Giza takes no part * in them (docs/giza-wallet-removal.md, Phase 1). None of their kinds is ever a diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/FakeGroupNode.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/FakeGroupNode.kt deleted file mode 100644 index d988f71e..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/FakeGroupNode.kt +++ /dev/null @@ -1,81 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.wallet.lightning.GroupSweep -import mobi.giza.compose.wallet.lightning.WalletWire -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.utils.Either -import fr.acinq.lightning.CltvExpiryDelta -import fr.acinq.lightning.Feature -import fr.acinq.lightning.FeatureSupport -import fr.acinq.lightning.Features -import fr.acinq.lightning.Lightning.randomBytes32 -import fr.acinq.lightning.MilliSatoshi -import fr.acinq.lightning.payment.Bolt11Invoice -import fr.acinq.lightning.payment.OfferManager -import kotlinx.coroutines.channels.Channel - -/** - * A stand-in for the group's lightning-kmp node: no LSP to connect to, channels and payments as a test - * sets them, and invoices signed with the node key the configuration carries, so they verify as the - * group's node's. - */ -class FakeGroupNode(private val configuration: GroupLightningNode.NodeConfiguration) : GroupLightningNode.PeerHandle { - var connected = false - var disconnected = false - /** How many times the node has dialled the LSP. */ - var connects = 0 - /** The attempt number each dial carried. */ - val attempts = mutableListOf() - /** A reason sent here ends the current connection, as the LSP hanging up would, with that reason. */ - val drops = Channel(Channel.UNLIMITED) - var channels = listOf() - val payments = mutableListOf() - val invoices = mutableListOf() - /** Every payment asked of the node, as (invoice, amount). */ - val paid = mutableListOf>() - var paymentsSucceed = true - /** Every close asked of the node, as (channel, script), and every force close, by channel. */ - val closed = mutableListOf>() - val forceClosed = mutableListOf() - var heldOutputs = listOf() - var rates: WalletWire.FundingRates? = null - var feerate: Long? = 2 - /** Every purchase asked of the node, as (authorisation id, amount, fee cap). */ - val bought = mutableListOf>() - /** What a purchase costs here, and so whether it is made: one over the cap is never sent. */ - var purchaseFee = 2_521L - - override suspend fun connect(attempt: Int): Boolean { connected = true; connects++; attempts += attempt; return true } - override fun disconnect() { disconnected = true } - override suspend fun awaitDisconnect(): String = drops.receive().also { connected = false } - override fun commitmentNumbers(): Map = mapOf("ab".repeat(32) to 7L) - override fun channels(): List = channels - override fun payments(): List = payments.toList() - override suspend fun createInvoice(amountMsat: Long?, description: String): String = - Bolt11Invoice.create( - configuration.chain, amountMsat?.let(::MilliSatoshi), randomBytes32(), configuration.keyManager.nodeKeys.nodeKey.privateKey, - Either.Left(description), CltvExpiryDelta(144), INVOICE_FEATURES, - ).also { invoices += it }.write() - override suspend fun close(channelId: String, scriptPubKey: ByteVector) { closed += channelId to scriptPubKey } - override suspend fun forceClose(channelId: String) { forceClosed += channelId } - override fun heldOutputs(): List = heldOutputs - override fun offer(): String = - OfferManager.deterministicOffer(configuration.chain.chainHash, configuration.keyManager.nodeKeys.nodeKey.privateKey, configuration.lspNodeId, null, null, null).offer.encode() - override fun fundingRates(): WalletWire.FundingRates? = rates - override fun feeratePerByte(): Long? = feerate - override suspend fun buyLiquidity(id: String, channelId: String, amountSat: Long, maxFeeSat: Long): WalletWire.LiquidityPurchase { - if (purchaseFee > maxFeeSat) return WalletWire.LiquidityPurchase(id, channelId, amountSat, WalletWire.FAILED, reason = "it would cost $purchaseFee sats, over the $maxFeeSat the group agreed to") - bought += Triple(id, amountSat, maxFeeSat) - return WalletWire.LiquidityPurchase(id, channelId, amountSat, WalletWire.PENDING, fundingTxId = "cd".repeat(32), feeSat = purchaseFee) - } - override suspend fun hasPaid(paymentHash: String): Boolean = payments.any { !it.incoming && it.paymentHash == paymentHash } - override suspend fun pay(bolt11: String, amountMsat: Long): WalletWire.PaymentView { - paid += bolt11 to amountMsat - val invoice = Bolt11Invoice.read(bolt11).get() - return WalletWire.PaymentView("out${paid.size}", incoming = false, amountMsat = amountMsat, feesMsat = 1_000, paymentHash = invoice.paymentHash.toHex(), description = invoice.description, completedAt = 1, succeeded = paymentsSucceed) - .also { payments += it } - } -} - -/** What a Bolt11 invoice must advertise to be read back at all. */ -val INVOICE_FEATURES = Features(Feature.VariableLengthOnion to FeatureSupport.Mandatory, Feature.PaymentSecret to FeatureSupport.Mandatory) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningFixture.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningFixture.kt deleted file mode 100644 index 47196231..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningFixture.kt +++ /dev/null @@ -1,173 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.database.model.ChatMessage -import androidx.room3.Room -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.IcebergKeySession -import mobi.giza.compose.database.model.MarmotInnerEvent -import mobi.giza.compose.database.model.NostrEvent -import mobi.giza.compose.database.model.Participant -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.extensions.toHex -import mobi.giza.compose.nostr.dkg.DkgRitualEvents -import mobi.giza.compose.nostr.frost.FrostSigningEvents -import mobi.giza.compose.nostr.lightning.GroupLightningEvents -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.toHexKey -import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.crypto.frost.Frost -import fr.acinq.bitcoin.crypto.frost.KeyMaterial -import kotlin.test.assertNotNull - -/** - * Four devices, each with its own database, holding a 3-of-4 FROST key for one Marmot room -- the - * group a Lightning wallet is made for. Messages move between them as the managers queue them, the - * seam `SubgroupCeremonyInParentRoomTest` uses: MLS itself is not under test. - * - * [pump] delivers every queued message of the given kinds to every other device, and hands each to the - * manager the inbound path would, until nothing new moves. - */ -class GroupLightningFixture(val n: Int = 4, val frostThreshold: Int = 3, val chain: Chain = Chain.Regtest) { - val keyMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey(ByteVector32("1ceb".padEnd(62, '0') + "a1")), - nParticipants = n, - threshold = frostThreshold, - ) - val thresholdPublicKey: String = keyMaterial.thresholdPublicKey.value.toHex() - val onchainCeremonyId: String = "onchain".padEnd(64, '0') - val roomId: String = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) - val account = GroupWalletDerivation.account(thresholdPublicKey, chain) - - val keys: List = (1..n).map { KeyPair() } - val members: List = keys.map { it.pubKey.toHexKey() } - private val hostKeys = (1..n).map { "02" + "2${it}".padEnd(64, '0') } - - val devices = mutableListOf() - - inner class Device(val index: Int, val db: GizaDatabase, val room: LocalChatRoom) { - val publicKey: HexKey = members[index] - val privateKey: ByteArray = keys[index].privKey!! - val received = mutableSetOf() - suspend fun ceremony(id: String): IcebergKeySession? = db.icebergKeySessionDao().getSessionById(id) - } - - fun close() = devices.forEach { it.db.close() } - - /** [member] leaves the room on every device in [on], as an applied removal commit leaves it. */ - suspend fun remove(member: HexKey, on: List) = on.forEach { d -> - d.db.participantDao().delete(d.db.participantDao().findParticipantsByChatRoomId(roomId).filter { it.participantPublicKey == member }) - } - - suspend fun device(index: Int, holders: List = members): Device { - val db = getRoomDatabase(Room.inMemoryDatabaseBuilder()) - members.forEach { member -> - val eventId = "e$member".take(64) - db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = member, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) - db.profileDao().upsert(Profile(publicKey = member, nostrEventId = eventId)) - } - val chatRoom = ChatRoom(id = roomId, userPublicKey = members[index], subject = "Treasury", description = SharedKeyDerivation.describe("Treasury."), mlsGroupState = "00") - db.chatRoomDao().upsert(chatRoom) - db.participantDao().upsert(members.map { Participant(participantPublicKey = it, chatRoomId = roomId, relayHint = null) }) - db.dkgSessionDao().upsert( - DkgSession( - id = onchainCeremonyId, chatRoomId = roomId, coordinatorPublicKey = members.first(), userPublicKey = members[index], - threshold = frostThreshold, participantCount = n, 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() }, - participantPublicKeys = DkgSession.formatParticipants(holders.toSet()), - ) - ) - members.forEachIndexed { i, member -> - db.dkgSessionDao().upsert(DkgParticipantMessage(sessionId = onchainCeremonyId, participantPublicKey = member, kind = DkgRitualEvents.HOST_KEY, payload = hostKeys[i])) - } - val room = db.chatRoomDao().findChatRoomById(roomId) ?: LocalChatRoom(chatRoom = chatRoom) - return Device(index, db, room).also { devices += it } - } - - suspend fun outbox(from: Device, kinds: Set): List = from.db.marmotInnerEventDao() - .getByChatRoomAndKinds(chatRoomId = roomId, kinds = kinds.toList()) - .filter { it.publicKey == from.publicKey } - .sortedWith(compareBy({ it.createdAt }, { it.kind })) - - fun MarmotInnerEvent.asEvent() = Event(id, publicKey, createdAt.epochSeconds, kind, tags, content, "") - - /** What the inbound path does with one message, per kind. Later phases add theirs. */ - var dispatch: suspend (to: Device, event: Event) -> Unit = { to, event -> - when (event.kind) { - in FrostSigningEvents.ALL -> FrostSigningManager.processSigningPayload(to.db, to.room, event, to.publicKey) - in GroupLightningEvents.CEREMONY -> IcebergRitualManager.processCeremonyPayload(to.db, to.room, event, to.publicKey, to.privateKey) - GroupLightningEvents.NODE_SEED -> GroupLightningWalletManager.receiveSeed(to.db, to.room, event, to.publicKey, to.privateKey) - GroupLightningEvents.SNAPSHOT, GroupLightningEvents.INVOICE, GroupLightningEvents.INVOICE_REQUEST -> GroupLightningReports.process(to.db, to.room, event) - GroupLightningEvents.STOPPED -> GroupLightningOperatorManager.receiveStopped(to.db, to.room, event) - } - } - - /** The Lightning wallet's lines of [type] in [device]'s copy of the room. */ - suspend fun lines(device: Device, type: String): List = - device.db.chatMessageDao().getChatMessagesByChatRoomId(roomId).map { it.chatMessage }.filter { it.messageType == type } - - suspend fun pump(between: List, kinds: Set) { - var moved = true - while (moved) { - moved = false - for (from in between) for (to in between) { - if (from === to) continue - outbox(from, kinds).forEach { queued -> - if (to.received.add(queued.id)) { - moved = true - to.db.marmotInnerEventDao().upsert(queued.copy(chatRoomId = roomId)) - dispatch(to, queued.asEvent()) - } - } - } - } - } - - /** Proposes a group-signed event from [proposer] and has every other device approve it. */ - suspend fun sign(all: List, proposer: Device, kind: Int, tags: Array>, content: String) { - val session = FrostSigningManager.proposeSigning(proposer.db, proposer.room, proposer.publicKey, kind, tags, content) - signSession(all, proposer, session.id) - } - - suspend fun signSession(all: List, proposer: Device, sessionId: String) { - pump(all, FrostSigningEvents.ALL + GroupLightningEvents.WALLET_TRAFFIC) - all.filter { it !== proposer }.forEach { FrostSigningManager.approve(it.db, it.room, sessionId) } - pump(all, FrostSigningEvents.ALL + GroupLightningEvents.WALLET_TRAFFIC) - } - - suspend fun openOnchainWallet(all: List) { - val template = GroupWalletStatementEvent.template(account) - sign(all, all[0], template.kind, template.tags, template.content) - all.forEach { assertNotNull(GroupWalletManager.walletFor(it.db, roomId, chain), "device ${it.index} has the onchain wallet") } - } - - /** Four devices with an onchain wallet open. */ - suspend fun group(): List = (0 until n).map { device(it) }.also { openOnchainWallet(it) } - - /** Runs a Lightning wallet key ceremony from [proposer], every other device approving every step. */ - suspend fun runCeremony(all: List, proposer: Device = all[0], threshold: Int = 2): IcebergKeySession { - val proposed = IcebergRitualManager.proposeCeremony(proposer.db, proposer.room, proposer.publicKey, proposer.privateKey, threshold, chain) - repeat(6) { - pump(all, GroupLightningEvents.CEREMONY) - all.forEach { d -> - val session = d.ceremony(proposed.id) ?: return@forEach - IcebergRitualManager.pendingApproval(d.db, session)?.let { step -> IcebergRitualManager.approve(d.db, d.room, session.id, step, d.privateKey) } - } - } - pump(all, GroupLightningEvents.CEREMONY) - return proposed - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningRegtestJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningRegtestJvmTest.kt deleted file mode 100644 index 1e723c75..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningRegtestJvmTest.kt +++ /dev/null @@ -1,369 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.database.model.ChatMessage -import co.touchlab.kermit.Severity -import co.touchlab.kermit.StaticConfig -import co.touchlab.kermit.platformLogWriter -import mobi.giza.compose.database.model.MarmotGroupEvent -import mobi.giza.compose.database.model.NostrEvent -import mobi.giza.compose.nostr.frost.FrostSigningEvents -import mobi.giza.compose.nostr.lightning.GroupLightningEvents -import mobi.giza.compose.wallet.GroupChainClients -import mobi.giza.compose.wallet.GroupTransactionWatcher -import fr.acinq.bitcoin.Bitcoin -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.PublicKey -import fr.acinq.lightning.Lightning.randomBytes32 -import fr.acinq.lightning.NodeUri -import fr.acinq.lightning.blockchain.electrum.ElectrumClient -import fr.acinq.lightning.io.TcpSocket -import fr.acinq.lightning.logging.LoggerFactory -import fr.acinq.lightning.payment.Bolt11Invoice -import fr.acinq.lightning.utils.ServerAddress -import fr.acinq.phoenix.db.createChannelsDbDriver -import fr.acinq.phoenix.db.createPaymentsDbDriver -import fr.acinq.phoenix.db.createSqliteChannelsDb -import fr.acinq.phoenix.db.createSqlitePaymentsDb -import fr.acinq.phoenix.managers.PhoenixDatabases -import fr.acinq.phoenix.utils.PlatformContext -import fr.acinq.phoenixd.conf.LSP -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.cancel -import kotlinx.coroutines.delay -import kotlinx.coroutines.isActive -import kotlinx.coroutines.launch -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock -import kotlinx.coroutines.withTimeout -import kotlinx.serialization.json.Json -import kotlinx.serialization.json.JsonArray -import kotlinx.serialization.json.JsonElement -import kotlinx.serialization.json.JsonObject -import kotlinx.serialization.json.jsonArray -import kotlinx.serialization.json.jsonObject -import kotlinx.serialization.json.jsonPrimitive -import kotlinx.serialization.json.long -import org.junit.Assume.assumeTrue -import java.net.InetSocketAddress -import java.net.Socket -import java.net.URI -import java.net.URLEncoder -import java.net.http.HttpClient -import java.net.http.HttpRequest -import java.net.http.HttpResponse -import java.nio.file.Files -import java.util.Base64 -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertIs -import kotlin.test.assertNotNull -import kotlin.test.assertTrue -import kotlin.time.Clock -import kotlin.time.Duration -import kotlin.time.Duration.Companion.minutes -import kotlin.time.Duration.Companion.seconds - -/** - * The group Lightning wallet end to end, on the regtest network `testing/regtest/regtest.sh up` builds: - * four devices make the key and open the wallet, the operator's device runs a real lightning-kmp node - * against an eclair LSP, and the group receives, pays, closes and sweeps - * (`docs/group-lightning-wallet.md`, "The regtest run"). - * - * Every message between the devices goes through the same managers the inbound path uses, pumped in the - * background; the node's signatures are the group's, made by Iceberg co-signing in the room. - * - * Skipped unless `GIZA_REGTEST=1`, because it needs the docker network. - */ -class GroupLightningRegtestJvmTest { - private val enabled = System.getenv("GIZA_REGTEST") == "1" - private val fixture = GroupLightningFixture(chain = Chain.Regtest) - private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) - private val loggerFactory = LoggerFactory(StaticConfig(Severity.Info, listOf(platformLogWriter()))) - private val http = HttpClient.newHttpClient() - private val json = Json { ignoreUnknownKeys = true } - - @AfterTest - fun close() { - scope.cancel() - fixture.close() - } - - // --- the network ------------------------------------------------------------------------------ - - private fun post(url: String, auth: String, form: Map = emptyMap(), body: String? = null, contentType: String = "application/x-www-form-urlencoded"): JsonElement { - val payload = body ?: form.entries.joinToString("&") { (k, v) -> "$k=${URLEncoder.encode(v, Charsets.UTF_8)}" } - val request = HttpRequest.newBuilder(URI(url)) - .header("Authorization", "Basic " + Base64.getEncoder().encodeToString(auth.toByteArray())) - .header("Content-Type", contentType) - .POST(HttpRequest.BodyPublishers.ofString(payload)) - .build() - val response = http.send(request, HttpResponse.BodyHandlers.ofString()) - check(response.statusCode() in 200..299) { "$url ${form.keys}: ${response.statusCode()} ${response.body()}" } - return json.parseToJsonElement(response.body()) - } - - private fun lsp(method: String, form: Map = emptyMap()) = post("http://127.0.0.1:28080/$method", ":lsp", form) - private fun payer(method: String, form: Map = emptyMap()) = post("http://127.0.0.1:28081/$method", ":payer", form) - - private fun btc(method: String, vararg params: Any, wallet: String? = null): JsonElement { - val args = params.joinToString(",") { if (it is String && !it.startsWith("[")) "\"$it\"" else it.toString() } - val response = post("http://127.0.0.1:28443/" + (wallet?.let { "wallet/$it" } ?: ""), "foo:bar", body = """{"jsonrpc":"1.0","id":1,"method":"$method","params":[$args]}""", contentType = "text/plain").jsonObject - check(response["error"].toString() == "null") { "bitcoind $method: ${response["error"]}" } - return response["result"]!! - } - - private fun mine(blocks: Int = 1) { - btc("generatetoaddress", blocks, btc("getnewaddress", wallet = "miner").jsonPrimitive.content, wallet = "miner") - } - - private fun mempoolSize(): Long = btc("getmempoolinfo").jsonObject["size"]!!.jsonPrimitive.long - - /** What the onchain wallet's first receive address holds, confirmed, in sats. */ - private fun receivedAtFirstAddress(): Long { - val address = Bitcoin.addressFromPublicKeyScript(Chain.Regtest.chainHash, GroupWalletDerivation.derive(fixture.account, GroupWalletDerivation.RECEIVE, 0).pubkeyScript.toByteArray()).right!! - val result = btc("scantxoutset", "start", "[\"addr($address)\"]").jsonObject - return (result["total_amount"]!!.jsonPrimitive.content.toBigDecimal() * 100_000_000.toBigDecimal()).toLong() - } - - /** - * Waits for [condition], mining a block whenever the mempool holds something, so funding and closing - * confirm -- or every pass when [confirming], for what needs more than one confirmation, as a splice does. - */ - private suspend fun mineUntil(what: String, timeout: Duration = 3.minutes, confirming: Boolean = false, condition: suspend () -> T?): T = try { - withTimeout(timeout) { - var result = condition() - while (result == null) { - if (confirming || mempoolSize() > 0) mine(1) - delay(1.seconds) - result = condition() - } - result - } - } catch (e: Throwable) { - diagnose() - throw AssertionError("timed out waiting for $what", e) - } - - /** What the run prints when it gets stuck: set once the group exists. */ - private var diagnose: suspend () -> Unit = {} - - // --- the group ---------------------------------------------------------------------------------- - - private val pumping = Mutex() - - /** Delivers everything between the devices, as the inbound path would, until the test ends. */ - private fun pumpInBackground(all: List) { - val base = fixture.dispatch - fixture.dispatch = { to, event -> - base(to, event) - if (event.kind in GroupLightningEvents.CO_SIGNING) GroupLightningCoSigner.process(to.db, to.room, event, to.publicKey) - } - val kinds = FrostSigningEvents.ALL + GroupLightningEvents.ALL - scope.launch { - while (isActive) { - runCatching { pumping.withLock { fixture.pump(all, kinds) } }.onFailure { println("pump: $it") } - delay(100) - } - } - } - - private suspend fun signed(all: List, proposer: GroupLightningFixture.Device, sessionId: String) = - pumping.withLock { fixture.signSession(all, proposer, sessionId) } - - private suspend fun heardFromRoom(device: GroupLightningFixture.Device) { - val id = randomBytes32().toHex() - device.db.nostrEventDao().upsert(NostrEvent(id = id, pubKey = device.publicKey, kind = 445, tags = emptyArray(), content = "", sig = "0".repeat(128))) - device.db.marmotGroupEventDao().upsert(MarmotGroupEvent(id = id, userPublicKey = device.publicKey, publicKey = device.publicKey, chatRoomId = fixture.roomId, signature = "", encryptedContent = "", expiresAt = null, savedAt = Clock.System.now())) - } - - private val key = GroupLightningCoSigner.walletKey(fixture.roomId, Chain.Regtest, 0) - private suspend fun report(device: GroupLightningFixture.Device) = GroupLightningReports.latest(device.db, key) - - /** - * The payer pays the group [sats], and the channel the LSP opens on the fly for it confirms. It pays the - * offer a member's snapshot carries rather than a Bolt11 invoice: an invoice reaches the group's node - * through a route hint naming it by a peer-id short channel id, which ACINQ's LSP resolves and public - * eclair does not, while an offer's blinded path names the node as a wallet, which eclair funds. - */ - private suspend fun receive(all: List, sats: Long) { - val offer = mineUntil("a member's copy of the group's offer", 1.minutes) { report(all[3])?.snapshot?.offer } - val paid = payer("payoffer", mapOf("offer" to offer, "amountMsat" to (sats * 1000).toString())) - val paymentId = (paid as? JsonObject)?.get("paymentId")?.jsonPrimitive?.content ?: paid.jsonPrimitive.content - mineUntil("the payer's payment of $sats sats") { - val sent = payer("getsentinfo", mapOf("id" to paymentId)).jsonArray - val status = sent.lastOrNull()?.jsonObject?.get("status")?.jsonObject?.get("type")?.jsonPrimitive?.content - check(status != "failed") { "the payment failed: $sent" } - status?.takeIf { it == "sent" } - } - } - - /** - * Fails at once, naming what is missing, when the network `regtest.sh up` builds is not there: every - * service listening, and the payer's channel to the LSP open. Without this a missing network shows up - * as a connection error deep in the first call, or a three-minute timeout. - */ - private fun requireNetwork() { - val up = "Start it with testing/regtest/regtest.sh up; testing/regtest/README.md has the details." - listOf("bitcoind" to 28443, "electrs" to 28001, "the LSP's API" to 28080, "the payer's API" to 28081).forEach { (what, port) -> - val listening = runCatching { Socket().use { it.connect(InetSocketAddress("127.0.0.1", port), 2_000) } }.isSuccess - if (!listening) throw AssertionError("The regtest network is not running: nothing answers for $what on 127.0.0.1:$port. $up") - } - val channels = runCatching { payer("channels").jsonArray }.getOrElse { throw AssertionError("The payer's API on 127.0.0.1:28081 does not answer (${it.message}). Restart the network with testing/regtest/regtest.sh down, then up.", it) } - if (channels.none { it.jsonObject["state"]?.jsonPrimitive?.content == "NORMAL" }) { - throw AssertionError("The regtest network is up but the payer has no open channel to the LSP, so `regtest.sh up` did not finish. Tear it down with testing/regtest/regtest.sh down, then run up again.") - } - } - - @Test - fun `four devices open, receive, pay, close and sweep on regtest`() = runBlocking { - assumeTrue("set GIZA_REGTEST=1 with testing/regtest up", enabled) - requireNetwork() - val lspId = lsp("getinfo").jsonObject["nodeId"]!!.jsonPrimitive.content - - // Open: the onchain wallet, the key, the Lightning wallet, and its operator. - val all = fixture.group() - fixture.runCeremony(all) - fixture.signSession(all, all[0], GroupLightningWalletManager.proposeWallet(all[0].db, all[0].room, all[0].publicKey, all[0].privateKey, Chain.Regtest, lspId).id) - fixture.signSession(all, all[1], GroupLightningOperatorManager.nominateSelf(all[1].db, all[1].room, all[1].publicKey, Chain.Regtest).id) - val operator = all[1] - val wallet = GroupLightningWalletManager.walletFor(operator.db, fixture.roomId, Chain.Regtest)!! - pumpInBackground(all) - diagnose = { - val dao = operator.db.icebergCoSigningDao() - dao.assignments(key).forEach { println("REGTEST assigned ${it.counter} ${it.label.take(16)} ${it.purpose}") } - for (c in 0L..6L) println("REGTEST pool $c: ${dao.noncesFor(key, c).size} rows, label ${GroupLightningCoSigner.poolLabel(wallet.statement.icebergKey, c).toHex().take(16)}") - } - - val electrum = ElectrumClient(scope, loggerFactory) - assertTrue(electrum.connect(ServerAddress("127.0.0.1", 28001, TcpSocket.TLS.DISABLED), TcpSocket.Builder()), "electrs is reachable") - val clients = GroupChainClients.single(electrum) - val ctx = PlatformContext(Files.createTempDirectory("giza-regtest").toFile()) - val walletParams = LSP.from(Chain.Testnet3).walletParams.copy(trampolineNode = NodeUri(PublicKey.fromHex(lspId), "127.0.0.1", 29735)) - val handles = mutableListOf() - val real = GroupLightningNode.lightningKmpPeers( - clients = clients, - databasesFor = { nodeId, chain -> - PhoenixDatabases( - channels = createSqliteChannelsDb(createChannelsDbDriver(ctx, "group-channels-$nodeId-${chain.name}.sqlite")), - payments = createSqlitePaymentsDb(createPaymentsDbDriver(ctx, "group-payments-$nodeId-${chain.name}.sqlite") {}, null, loggerFactory), - cloudKit = null, - ) - }, - walletParamsFor = { _, _ -> walletParams }, - loggerFactory = loggerFactory, - scope = scope, - ) - heardFromRoom(operator) - val node = GroupLightningNode(operator.db, operator.room, operator.publicKey, wallet, scope, { c -> real(c).also { handles += it } }, handoverCheck = 1.seconds, reportEvery = 5.seconds) - assertIs(node.start()) - mineUntil("the LSP to see the group's node", 1.minutes) { - lsp("peers").jsonArray.firstOrNull { it.jsonObject["nodeId"]?.jsonPrimitive?.content == wallet.statement.nodeId && it.jsonObject["state"]?.jsonPrimitive?.content == "CONNECTED" } - } - - // Receive: a member's Bolt11 request comes back as an invoice for the group's node... - val requestId = GroupLightningReports.requestInvoice(all[3].db, all[3].room, all[3].publicKey, wallet, 100_000_000, "first") - val invoice = Bolt11Invoice.read(mineUntil("the operator's invoice", 1.minutes) { all[3].db.groupLightningRecordsDao().invoice(key, requestId)?.bolt11 }).get() - assertEquals(wallet.statement.nodeId, invoice.nodeId.toString()) - // ...and the first payment, to the group's offer, opens the channel on the fly. - receive(all, 100_000) - val received = mineUntil("every member's snapshot of the channel") { - all.map { report(it) }.takeIf { reports -> reports.all { it?.snapshot?.channels?.singleOrNull()?.state == "Normal" && it.snapshot.payments.any { p -> p.incoming && p.succeeded } } } - } - val channel = received.first()!!.snapshot.channels.single() - println("REGTEST received: channel ${channel.channelId.take(16)} capacity ${channel.capacitySat}, ours ${channel.oursMsat} msat") - assertTrue(channel.oursMsat in 90_000_000..100_000_000, "the group holds the payment, less the LSP's fee: ${channel.oursMsat}") - assertTrue(received.count { it!!.checks.single().agrees == true } >= 2, "the members who co-signed agree with the operator") - - // Buy liquidity (docs/group-lightning-liquidity.md, Phase 8): a member prices 200,000 sats of inbound - // from the operator's snapshot, the group authorises it, the operator's node splices, and every - // co-signer checks the first commitment on the new output and the shared input before the group signs. - val priced = mineUntil("the LSP's prices in a member's snapshot", 1.minutes) { report(all[3])?.snapshot?.takeIf { it.fundingRates != null && it.feeratePerByte != null } } - val price = mobi.giza.compose.wallet.lightning.LiquidityPrice.price(priced.fundingRates!!, 200_000, priced.feeratePerByte!!)!! - val buy = GroupLightningAuthorisations.prepareBuyLiquidity(wallet, channel.channelId, channel.capacitySat, 200_000, mobi.giza.compose.wallet.lightning.LiquidityPrice.defaultCap(price)).getOrThrow() - signed(all, all[2], GroupLightningAuthorisations.proposeBuyLiquidity(all[2].db, all[2].room, all[2].publicKey, buy).id) - mineUntil("eclair to see the chain's tip", 1.minutes) { lsp("getinfo").jsonObject["blockHeight"]!!.jsonPrimitive.long.takeIf { it >= btc("getblockcount").jsonPrimitive.long } } - node.buyAuthorised() - val bought = mineUntil("every member to see the purchase locked", 4.minutes, confirming = true) { - all.map { report(it) }.takeIf { reports -> reports.all { r -> r?.snapshot?.purchases?.singleOrNull()?.state == mobi.giza.compose.wallet.lightning.WalletWire.LOCKED } } - } - val spliced = bought.first()!!.snapshot.channels.single() - println("REGTEST bought: ${spliced.capacitySat} sats now, for ${bought.first()!!.snapshot.purchases.single().feeSat} sats; estimated ${price.totalSat}") - assertEquals(channel.channelId, spliced.channelId, "the same channel, grown") - assertTrue(spliced.capacitySat > channel.capacitySat + 190_000, "the channel grew by what was bought: ${spliced.capacitySat}") - assertTrue(bought.first()!!.snapshot.purchases.single().feeSat!! <= buy.maxFeeSat) - all.forEach { d -> assertEquals(0, fixture.lines(d, ChatMessage.TYPE_LIGHTNING_REFUSED).size, "device ${d.index} refused part of an honest purchase") } - // And a payment the channel had no room for before arrives over it, with no on-the-fly splice. - receive(all, 50_000) - val after = mineUntil("the 50,000 sats in a member's snapshot") { report(all[0])?.snapshot?.channels?.singleOrNull()?.takeIf { it.oursMsat > spliced.oursMsat + 45_000_000 } } - assertEquals(spliced.capacitySat, after.capacitySat, "no splice was needed to receive it") - - // Pay: the group authorises paying the payer, and the operator's node pays it. - val owed = payer("createinvoice", mapOf("description" to "back", "amountMsat" to "20000000")).jsonObject - val pay = GroupLightningAuthorisations.prepare(wallet, owed["serialized"]!!.jsonPrimitive.content, null, 2_000_000).getOrThrow() - signed(all, all[2], GroupLightningAuthorisations.propose(all[2].db, all[2].room, all[2].publicKey, pay).id) - mineUntil("the payer to receive 20,000 sats") { - payer("getreceivedinfo", mapOf("paymentHash" to pay.paymentHash)).jsonObject["status"]?.jsonObject?.get("type")?.jsonPrimitive?.content?.takeIf { it == "received" } - } - val paid = mineUntil("the snapshot to show the payment") { report(all[0])?.takeIf { r -> r.snapshot.payments.any { !it.incoming && it.succeeded } } } - println("REGTEST paid: ours now ${paid.snapshot.channels.single().oursMsat} msat") - - // Close: mutually, to the onchain wallet. - val before = receivedAtFirstAddress() - signed(all, all[0], GroupLightningAuthorisations.proposeChannelAction(all[0].db, all[0].room, all[0].publicKey, wallet, channel.channelId, force = false).id) - val closedTo = mineUntil("the close to reach the onchain wallet") { receivedAtFirstAddress().takeIf { it > before } } - println("REGTEST closed: ${closedTo - before} sats at the onchain wallet's first address") - assertTrue(closedTo - before > 70_000, "the group's balance reached its onchain wallet") - - // Sweep: a second channel, force-closed, whose delayed output the group sweeps. - receive(all, 100_000) - val second = mineUntil("the second channel") { - report(all[0])?.snapshot?.channels?.firstOrNull { it.channelId != channel.channelId && it.state == "Normal" } - } - signed(all, all[3], GroupLightningAuthorisations.proposeChannelAction(all[3].db, all[3].room, all[3].publicKey, wallet, second.channelId, force = true).id) - val held = mineUntil("the force close's delayed output") { report(all[3])?.snapshot?.heldOutputs?.takeIf { it.isNotEmpty() } } - println("REGTEST force-closed: ${held.size} output(s) to sweep, after ${held.map { it.csvDelay }} blocks") - mine(held.maxOf { it.csvDelay }.toInt() + 1) - val beforeSweep = receivedAtFirstAddress() - val sweeper = all[3] - signed(all, sweeper, GroupLightningSweeps.propose(sweeper.db, sweeper.room, sweeper.publicKey, wallet, GroupLightningSweeps.unswept(sweeper.db, fixture.roomId, report(sweeper))).id) - val watcher = GroupTransactionWatcher(sweeper.db, clients, scope) - val swept = mineUntil("the sweep to confirm") { - watcher.pass() - receivedAtFirstAddress().takeIf { it > beforeSweep } - } - println("REGTEST swept: ${swept - beforeSweep} sats into the onchain wallet") - assertTrue(swept - beforeSweep > 70_000, "the sweep paid the onchain wallet") - assertNotNull(sweeper.db.groupTransactionDao().getByChatRoomId(fixture.roomId).firstOrNull { it.confirmedAt != null || it.seenAt != null }) - assertEquals(1, held.size) - - // The room's account of all that, on every device (docs/group-lightning-transcript.md, - // Phase 5): one line per fact however many snapshots repeated it, and no raw JSON. Waited - // for, since the last snapshots are still reaching the members. - val channels = setOf(channel.channelId, second.channelId) - mineUntil("every member to be told both channels closed") { - all.all { d -> fixture.lines(d, ChatMessage.TYPE_LIGHTNING_CHANNEL_CLOSED).mapNotNull { it.lightningFactKey }.toSet() == channels }.takeIf { it } - } - all.forEach { d -> - suspend fun count(type: String) = fixture.lines(d, type).size - d.db.chatMessageDao().getChatMessagesByChatRoomId(fixture.roomId).map { it.chatMessage } - .filter { it.messageType in ChatMessage.LIGHTNING_TYPES || it.messageType in ChatMessage.GROUP_LIGHTNING_SIGNED_TYPES } - .forEach { println("REGTEST line, device ${d.index}: ${it.messageType} ${it.content}") } - assertEquals(2, count(ChatMessage.TYPE_LIGHTNING_CHANNEL_OPENED), "device ${d.index}: one opened line per channel") - assertEquals(2, count(ChatMessage.TYPE_LIGHTNING_CHANNEL_CLOSED), "device ${d.index}: one closed line per channel") - assertEquals(3, count(ChatMessage.TYPE_LIGHTNING_PAYMENT_RECEIVED), "device ${d.index}: the three payments in") - assertEquals(1, count(ChatMessage.TYPE_LIGHTNING_LIQUIDITY_ADDED), "device ${d.index}: the liquidity bought") - assertEquals(1, count(ChatMessage.TYPE_LIGHTNING_PAYMENT_SENT), "device ${d.index}: the payment out") - assertEquals(1, count(ChatMessage.TYPE_LIGHTNING_SEED_SHARED), "device ${d.index}") - assertEquals(1, count(ChatMessage.TYPE_LIGHTNING_INVOICE_REQUESTED), "device ${d.index}") - assertEquals(1, count(ChatMessage.TYPE_LIGHTNING_INVOICE_ISSUED), "device ${d.index}") - assertEquals(0, count(ChatMessage.TYPE_LIGHTNING_REFUSED), "device ${d.index}: an honest operator is never refused") - assertEquals(0, count(ChatMessage.TYPE_LIGHTNING_EQUIVOCATION), "device ${d.index}") - assertEquals(0, count("unsupported"), "device ${d.index}: no raw JSON in the room") - } - node.stop() - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/LiquidityPurchaseRegtestJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/LiquidityPurchaseRegtestJvmTest.kt deleted file mode 100644 index dad8374d..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/LiquidityPurchaseRegtestJvmTest.kt +++ /dev/null @@ -1,275 +0,0 @@ -package mobi.giza.compose.managers - -import co.touchlab.kermit.Severity -import co.touchlab.kermit.StaticConfig -import co.touchlab.kermit.platformLogWriter -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.KeyPath -import fr.acinq.bitcoin.OutPoint -import fr.acinq.bitcoin.PublicKey -import fr.acinq.bitcoin.Satoshi -import fr.acinq.bitcoin.TxOut -import fr.acinq.bitcoin.crypto.musig2.IndividualNonce -import fr.acinq.lightning.Lightning.randomBytes32 -import fr.acinq.lightning.NodeParams -import fr.acinq.lightning.NodeUri -import fr.acinq.lightning.blockchain.Feerates -import fr.acinq.lightning.blockchain.electrum.ElectrumClient -import fr.acinq.lightning.blockchain.electrum.ElectrumWatcher -import fr.acinq.lightning.blockchain.fee.FeeratePerByte -import fr.acinq.lightning.blockchain.fee.FeeratePerKw -import fr.acinq.lightning.blockchain.fee.OnChainFeerates -import fr.acinq.lightning.channel.ChannelFundingResponse -import fr.acinq.lightning.channel.states.Normal -import fr.acinq.lightning.crypto.ChannelKeys -import fr.acinq.lightning.crypto.FundingSigner -import fr.acinq.lightning.crypto.KeyManager -import fr.acinq.lightning.io.Peer -import fr.acinq.lightning.io.TcpSocket -import fr.acinq.lightning.logging.LoggerFactory -import fr.acinq.lightning.payment.LiquidityPolicy -import fr.acinq.lightning.transactions.Transactions -import fr.acinq.lightning.utils.ServerAddress -import fr.acinq.lightning.utils.msat -import fr.acinq.phoenix.db.createChannelsDbDriver -import fr.acinq.phoenix.db.createPaymentsDbDriver -import fr.acinq.phoenix.db.createSqliteChannelsDb -import fr.acinq.phoenix.db.createSqlitePaymentsDb -import fr.acinq.phoenix.managers.PhoenixDatabases -import fr.acinq.phoenix.utils.PlatformContext -import fr.acinq.phoenixd.conf.LSP -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.cancel -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.withTimeout -import kotlinx.serialization.json.Json -import kotlinx.serialization.json.JsonElement -import kotlinx.serialization.json.jsonObject -import kotlinx.serialization.json.jsonPrimitive -import kotlinx.serialization.json.long -import org.junit.Assume.assumeTrue -import java.net.URI -import java.net.URLEncoder -import java.net.http.HttpClient -import java.net.http.HttpRequest -import java.net.http.HttpResponse -import java.nio.file.Files -import java.util.Base64 -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertIs -import kotlin.test.assertNotEquals -import kotlin.test.assertNotNull -import kotlin.test.assertTrue -import kotlin.time.Duration -import kotlin.time.Duration.Companion.minutes -import kotlin.time.Duration.Companion.seconds -import kotlin.time.TimeSource - -/** - * Phase 0 of `docs/group-lightning-liquidity.md`, against the eclair LSP `testing/regtest/regtest.sh up` - * builds: a stock lightning-kmp node, not a group, whose channel keys serve the funding key of index 0 at - * every index -- design B, as a group's node will -- buys inbound liquidity by splicing, and the run - * records three things: - * - * 1. whether eclair accepts a splice in which our funding key does not change (step 1); - * 2. how long eclair waits for our signatures inside a splice, by delaying each one (step 3); - * 3. how long two commitments stay live, from the purchase's answer to the splice locking (step 4). - * - * Skipped unless `GIZA_REGTEST=1`. `GIZA_SPLICE_DELAYS` takes the delays to try, in seconds, - * comma-separated; by default 0, 10 and 25. A purchase needs two signatures, the first commitment on the - * new output and the shared input, and eclair allows a splice `channel.quiescence-timeout`, one minute by - * default, from quiescence: at 30 seconds a signature it disconnects as the second arrives (the run of - * 2026-11-01, recorded in the plan's Phase 0). - */ -class LiquidityPurchaseRegtestJvmTest { - private val enabled = System.getenv("GIZA_REGTEST") == "1" - private val delays = (System.getenv("GIZA_SPLICE_DELAYS") ?: "0,10,25").split(",").map { it.trim().toInt().seconds } - private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) - private val loggerFactory = LoggerFactory(StaticConfig(Severity.Warn, listOf(platformLogWriter()))) - private val http = HttpClient.newHttpClient() - private val json = Json { ignoreUnknownKeys = true } - - @AfterTest - fun close() = scope.cancel() - - private fun post(url: String, auth: String, form: Map = emptyMap(), body: String? = null, contentType: String = "application/x-www-form-urlencoded"): JsonElement { - val payload = body ?: form.entries.joinToString("&") { (k, v) -> "$k=${URLEncoder.encode(v, Charsets.UTF_8)}" } - val request = HttpRequest.newBuilder(URI(url)) - .header("Authorization", "Basic " + Base64.getEncoder().encodeToString(auth.toByteArray())) - .header("Content-Type", contentType) - .POST(HttpRequest.BodyPublishers.ofString(payload)) - .build() - val response = http.send(request, HttpResponse.BodyHandlers.ofString()) - check(response.statusCode() in 200..299) { "$url ${form.keys}: ${response.statusCode()} ${response.body()}" } - return json.parseToJsonElement(response.body()) - } - - private fun lsp(method: String, form: Map = emptyMap()) = post("http://127.0.0.1:28080/$method", ":lsp", form) - private fun payer(method: String, form: Map = emptyMap()) = post("http://127.0.0.1:28081/$method", ":payer", form) - - private fun btc(method: String, vararg params: Any, wallet: String? = null): JsonElement { - val args = params.joinToString(",") { if (it is String && !it.startsWith("[")) "\"$it\"" else it.toString() } - val response = post("http://127.0.0.1:28443/" + (wallet?.let { "wallet/$it" } ?: ""), "foo:bar", body = """{"jsonrpc":"1.0","id":1,"method":"$method","params":[$args]}""", contentType = "text/plain").jsonObject - check(response["error"].toString() == "null") { "bitcoind $method: ${response["error"]}" } - return response["result"]!! - } - - private fun mine(blocks: Int = 1) { - btc("generatetoaddress", blocks, btc("getnewaddress", wallet = "miner").jsonPrimitive.content, wallet = "miner") - } - - /** Waits for [condition], mining a block whenever the mempool holds something, or every second when [confirming]. */ - private suspend fun mineUntil(what: String, timeout: Duration = 3.minutes, confirming: Boolean = false, condition: suspend () -> T?): T = try { - withTimeout(timeout) { - var result = condition() - while (result == null) { - if (confirming || btc("getmempoolinfo").jsonObject["size"]!!.jsonPrimitive.long > 0) mine(1) - delay(1.seconds) - result = condition() - } - result - } - } catch (e: Throwable) { - throw AssertionError("timed out waiting for $what", e) - } - - /** - * Waits for eclair to see the chain's tip. Mining a block a second outruns it, and it refuses an - * interactive transaction whose lock time, our node's height, is past its own. - */ - private suspend fun lspCaughtUp() = mineUntil("eclair to see the chain's tip", 1.minutes) { - val tip = btc("getblockcount").jsonPrimitive.long - lsp("getinfo").jsonObject["blockHeight"]!!.jsonPrimitive.long.takeIf { it >= tip } - } - - /** - * The funding signer a stock channel would have at index 0, served at every index, and made to wait - * [delay] before each signature while [delay] is set: a group's node signs the same way, slower. - */ - private class OneKeySlowly(private val underlying: FundingSigner, private val delay: () -> Duration, private val splices: MutableList) : FundingSigner by underlying { - override suspend fun signWithFreshNonce(tx: Transactions.ChannelSpendTransaction, remoteFundingPubKey: PublicKey, extraUtxos: Map, fundingTxId: fr.acinq.bitcoin.TxId, remoteNonce: IndividualNonce, context: FundingSigner.SigningContext) = - delay(delay()).let { underlying.signWithFreshNonce(tx, remoteFundingPubKey, extraUtxos, fundingTxId, remoteNonce, context) } - override suspend fun signWithPublishedNonce(tx: Transactions.ChannelSpendTransaction, remoteFundingPubKey: PublicKey, extraUtxos: Map, session: FundingSigner.PublishedNonceSession, remoteNonce: IndividualNonce, context: FundingSigner.SigningContext) = - delay(delay()).let { - if (context is FundingSigner.SigningContext.Splice) splices += context - underlying.signWithPublishedNonce(tx, remoteFundingPubKey, extraUtxos, session, remoteNonce, context) - } - override suspend fun signWithVerificationNonce(tx: Transactions.ChannelSpendTransaction, remoteFundingPubKey: PublicKey, extraUtxos: Map, id: FundingSigner.VerificationNonceId, remoteNonce: IndividualNonce, context: FundingSigner.SigningContext) = - delay(delay()).let { underlying.signWithVerificationNonce(tx, remoteFundingPubKey, extraUtxos, id, remoteNonce, context) } - } - - private class OneKeyManager(private val delegate: KeyManager, private val delay: () -> Duration) : KeyManager by delegate { - /** What each splice's shared input was said to be: Phase 2's context, as a real purchase fills it. */ - val splices = mutableListOf() - override fun channelKeys(fundingKeyPath: KeyPath): ChannelKeys { - val keys = delegate.channelKeys(fundingKeyPath) - return keys.withFundingSigner(OneKeySlowly(FundingSigner.PrivateKeyFundingSigner(keys.fundingKey(0)), delay, splices)) - } - } - - private fun Peer.normal(): Normal? = channelsFlow.value.values.singleOrNull() as? Normal - - @Test - fun `a node that keeps its funding key buys liquidity from eclair, and how long eclair waits`() = runBlocking { - assumeTrue("set GIZA_REGTEST=1 with testing/regtest up", enabled) - val lspId = PublicKey.fromHex(lsp("getinfo").jsonObject["nodeId"]!!.jsonPrimitive.content) - - var signingDelay = Duration.ZERO - val keyManager = OneKeyManager(GroupLightningCoSigner.keyManagerOf(ByteVector(randomBytes32().toByteArray()), Chain.Regtest)) { signingDelay } - val nodeParams = NodeParams(Chain.Regtest, loggerFactory, keyManager).copy( - zeroConfPeers = setOf(lspId), - liquidityPolicy = MutableStateFlow(LiquidityPolicy.Auto(inboundLiquidityTarget = null, maxAbsoluteFee = Satoshi(20_000), maxRelativeFeeBasisPoints = 50_00, skipAbsoluteFeeCheck = false, maxAllowedFeeCredit = 0.msat)), - ) - val electrum = ElectrumClient(scope, loggerFactory) - check(electrum.connect(ServerAddress("127.0.0.1", 28001, TcpSocket.TLS.DISABLED), TcpSocket.Builder())) { "electrs is not reachable: testing/regtest/regtest.sh up" } - val ctx = PlatformContext(Files.createTempDirectory("giza-liquidity").toFile()) - val databases = PhoenixDatabases( - channels = createSqliteChannelsDb(createChannelsDbDriver(ctx, "channels.sqlite")), - payments = createSqlitePaymentsDb(createPaymentsDbDriver(ctx, "payments.sqlite") {}, null, loggerFactory), - cloudKit = null, - ) - val walletParams = LSP.from(Chain.Testnet3).walletParams.copy(trampolineNode = NodeUri(lspId, "127.0.0.1", 29735)) - val peer = Peer(nodeParams, walletParams, electrum, ElectrumWatcher(electrum, scope, loggerFactory), databases, TcpSocket.Builder(), scope) - peer.currentTipFlow.value = electrum.startHeaderSubscription().blockHeight - val feerate = FeeratePerByte(Satoshi(2)) - peer.onChainFeeratesFlow.value = OnChainFeerates(Feerates(feerate, feerate, feerate, feerate, feerate)) - check(peer.connect(connectTimeout = 5.seconds, handshakeTimeout = 10.seconds)) { "could not connect to the LSP" } - - // A channel, by on-the-fly funding of a payment to the node's offer; confirmed, since eclair splices - // only a channel whose funding transaction has locked. - val offer = nodeParams.defaultOffer(lspId).offer.encode() - payer("payoffer", mapOf("offer" to offer, "amountMsat" to "100000000")) - mineUntil("the on-the-fly channel") { peer.normal() } - mineUntil("the on-the-fly channel to confirm", confirming = true) { peer.normal()?.takeIf { it.commitments.latest.localFundingStatus is fr.acinq.lightning.channel.LocalFundingStatus.ConfirmedFundingTx } } - val inboundAtOpen = peer.normal()!!.commitments.latest.localCommit.spec.toRemote - val rates = mineUntil("the LSP's funding rates") { peer.remoteFundingRates.value } - println("PHASE0 the LSP sells: ${rates.fundingRates.joinToString { "${it.minAmount}..${it.maxAmount} base ${it.feeBase} ${it.feeProportional}bp weight ${it.fundingWeight} creation ${it.channelCreationFee}" }}, paid by ${rates.paymentTypes}") - - val results = mutableListOf() - for (wait in delays) { - lspCaughtUp() - val before = peer.normal()!!.commitments.latest - val amount = Satoshi(200_000) - val rate = assertNotNull(rates.findRate(amount)) - val (actualFeerate, fees) = assertNotNull(peer.estimateFeeForInboundLiquidity(amount, FeeratePerKw(feerate), rate)) - signingDelay = wait - val started = TimeSource.Monotonic.markNow() - val response = withTimeout(10.minutes) { peer.requestInboundLiquidity(amount, actualFeerate, rate) } - val answeredAfter = started.elapsedNow() - signingDelay = Duration.ZERO - if (response !is ChannelFundingResponse.Success) { - results += "delay $wait: refused after $answeredAfter, $response" - println("PHASE0 ${results.last()}") - // Whatever eclair did, get the channel back to Normal and quiescent-free before the next try. - mineUntil("the channel to settle after the refused splice", 2.minutes) { peer.normal()?.takeIf { it.spliceStatus is fr.acinq.lightning.channel.SpliceStatus.None } } - continue - } - // The answer comes as the splice is signed; the channel's state shows it once both sides sent tx_signatures. - val after = mineUntil("the splice in the channel's state", 1.minutes) { peer.normal()?.commitments?.latest?.takeIf { it.fundingTxIndex == response.fundingTxIndex } } - // Step 1: our half of the new funding output is the key of index 0 again, and eclair's half changed. - val ourKey = keyManager.channelKeys(peer.normal()!!.commitments.channelParams.localParams.fundingKeyPath).fundingPublicKey(0) - assertEquals(before.fundingTxIndex + 1, after.fundingTxIndex) - assertNotEquals(before.remoteFundingPubkey, after.remoteFundingPubkey, "eclair did not rotate its key") - assertEquals(Transactions.makeFundingScript(ourKey, after.remoteFundingPubkey, Transactions.CommitmentFormat.SimpleTaprootChannels).pubkeyScript, after.localFundingStatus.txOut.publicKeyScript) - // Phase 2: the shared input was told it was this purchase. - val told = keyManager.splices.last() - assertEquals(after.fundingTxIndex, told.fundingTxIndex) - assertEquals(amount, told.purchase?.amount) - assertEquals(amount, told.remoteContribution) - // What the group pays comes out two ways. Our share of the splice's mining fee leaves the funding - // output (a negative contribution); the purchase's fees -- service, and the mining fee for the - // LSP's inputs -- move from our balance to the LSP's in the first commitment on the new output. - // Together they are the estimate. - val purchase = assertNotNull(told.purchase) - assertEquals(before.fundingAmount + amount + told.localContribution, response.capacity, "the capacity grew by what was bought, less our own share of the mining fee") - assertEquals(fees.total, purchase.fees.total - told.localContribution, "the estimate is our mining share plus the purchase's fees") - assertEquals(fees.serviceFee, purchase.fees.serviceFee) - // Step 4: how long two commitments stay live. - val live = TimeSource.Monotonic.markNow() - mineUntil("the splice to lock", confirming = true) { peer.normal()?.takeIf { it.commitments.active.size == 1 && it.commitments.latest.fundingTxIndex == after.fundingTxIndex } } - results += "delay $wait: bought ${response.liquidityPurchase?.amount} for ${fees.total} (mining ${fees.miningFee}, service ${fees.serviceFee}), answered after $answeredAfter, two commitments live for ${live.elapsedNow()}" - println("PHASE0 ${results.last()}") - } - println("PHASE0 summary:\n" + results.joinToString("\n")) - // The one claim the rest of the plan rests on: with no delay, eclair takes the splice. - assertIs(results.first { it.startsWith("delay 0s") }.takeIf { it.contains("bought") }, "eclair refused a splice with an unchanged funding key: ${results.first()}") - - // And the spliced channel carries a payment it had no room for before the purchases: the on-the-fly - // channel left a few thousand sats of inbound. Not more than 100,000: the channel's in-flight maximum - // was fixed at its opening, at the 100,000 sats it then held, and a splice does not raise it -- eclair - // refuses a bigger HTLC with "in-flight htlcs hold too much value". - val received = peer.normal()!!.commitments.latest.localCommit.spec.toLocal - payer("payoffer", mapOf("offer" to offer, "amountMsat" to "90000000")) - mineUntil("a 90,000-sat payment over the spliced channel", 2.minutes) { peer.normal()?.takeIf { it.commitments.latest.localCommit.spec.toLocal > received + 85_000_000.msat } } - println("PHASE0 a 90,000-sat payment arrived; before the purchases the channel could receive ${inboundAtOpen.truncateToSatoshi()}") - assertTrue(inboundAtOpen < 90_000_000.msat, "the payment needed the liquidity bought") - peer.disconnect() - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatPaneLayoutJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatPaneLayoutJvmTest.kt index b9785237..db672101 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatPaneLayoutJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatPaneLayoutJvmTest.kt @@ -1,6 +1,5 @@ package mobi.giza.compose.ui.composable -import mobi.giza.compose.repository.GroupLightningRepository import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertWidthIsEqualTo @@ -99,7 +98,6 @@ class ChatPaneLayoutJvmTest { chatRepository = NoRooms, frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, dkgRepository = DkgRepository.NO_OP_DKG_REPOSITORY, - lightningRepository = GroupLightningRepository.NO_OP_GROUP_LIGHTNING_REPOSITORY, ) } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatPaneSelectionJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatPaneSelectionJvmTest.kt index 68b2235c..c2f58618 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatPaneSelectionJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatPaneSelectionJvmTest.kt @@ -1,6 +1,5 @@ package mobi.giza.compose.ui.composable -import mobi.giza.compose.repository.GroupLightningRepository import androidx.compose.runtime.Composable import androidx.compose.ui.test.ComposeUiTest import androidx.compose.ui.test.ExperimentalTestApi @@ -133,7 +132,6 @@ class ChatPaneSelectionJvmTest { chatRepository = TwoRooms, frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, dkgRepository = DkgRepository.NO_OP_DKG_REPOSITORY, - lightningRepository = GroupLightningRepository.NO_OP_GROUP_LIGHTNING_REPOSITORY, ) } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/LightningPaymentRowJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/LightningPaymentRowJvmTest.kt deleted file mode 100644 index a1ec9f0e..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/LightningPaymentRowJvmTest.kt +++ /dev/null @@ -1,67 +0,0 @@ -package mobi.giza.compose.ui.composable - -import androidx.compose.foundation.layout.Column -import androidx.compose.ui.test.ExperimentalTestApi -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.runDesktopComposeUiTest -import mobi.giza.compose.database.model.GroupLightningPaymentRow -import mobi.giza.compose.ui.theme.GizaTheme -import kotlin.test.Test - -/** - * The Lightning wallet's payment list says what the node's payments were, as lightning-kmp reports - * them: a sent amount with its fee already in it, and a channel's close filed as an outgoing payment - * with no payment hash. Found by the regtest run, which listed a close as "sent" and 20,000 sats with - * an 84-sat fee as 20,084 sent. docs/group-lightning-transcript.md. - */ -@OptIn(ExperimentalTestApi::class) -class LightningPaymentRowJvmTest { - - private fun row(id: String, incoming: Boolean, amountMsat: Long, feesMsat: Long, paymentHash: String?, succeeded: Boolean) = - GroupLightningPaymentRow("w", id, incoming, amountMsat, feesMsat, paymentHash, description = null, completedAt = null, succeeded = succeeded) - - @Test - fun `a payment sent is what reached the recipient, and a close is said as a close`() = runDesktopComposeUiTest { - setContent { - GizaTheme { - Column { - PaymentRow(row("in", incoming = true, amountMsat = 96_900_000, feesMsat = 0, paymentHash = "aa".repeat(32), succeeded = true)) - PaymentRow(row("out", incoming = false, amountMsat = 20_084_000, feesMsat = 84_000, paymentHash = "bb".repeat(32), succeeded = true)) - PaymentRow(row("closed", incoming = false, amountMsat = 76_816_000, feesMsat = 0, paymentHash = null, succeeded = true)) - PaymentRow(row("closing", incoming = false, amountMsat = 50_000_000, feesMsat = 0, paymentHash = null, succeeded = false)) - } - } - } - onNodeWithText("Received 96,900 sats").assertIsDisplayed() - onNodeWithText("Sent 20,000 sats, with a fee of 84 sats").assertIsDisplayed() - onNodeWithText("A channel closed: 76,816 sats to the onchain wallet").assertIsDisplayed() - onNodeWithText("A channel is closing: 50,000 sats to the onchain wallet").assertIsDisplayed() - } - - @Test - fun `bought liquidity is room to be paid, with what it cost, never money sent`() = runDesktopComposeUiTest { - setContent { - GizaTheme { - PaymentRow(GroupLightningPaymentRow("w", "liquidity:t", incoming = false, amountMsat = 2_521_000, feesMsat = 2_521_000, paymentHash = null, description = null, completedAt = null, succeeded = true, liquiditySat = 200_000)) - } - } - onNodeWithText("Inbound liquidity added: 200,000 sats, for 2,521 sats in fees").assertIsDisplayed() - } - - @Test - fun `why liquidity cannot be asked for is said in words`() = runDesktopComposeUiTest { - setContent { - GizaTheme { - Column { - androidx.compose.material3.Text(unavailableBecause(mobi.giza.compose.wallet.lightning.LiquidityPrice.Availability.NoChannel)) - androidx.compose.material3.Text(unavailableBecause(mobi.giza.compose.wallet.lightning.LiquidityPrice.Availability.AtTheCap)) - androidx.compose.material3.Text(unavailableBecause(mobi.giza.compose.wallet.lightning.LiquidityPrice.Availability.NoPrices)) - } - } - } - onNodeWithText("Receive a payment first: it opens the channel.").assertIsDisplayed() - onNodeWithText("The channel holds the most a channel may on this network for now.").assertIsDisplayed() - onNodeWithText("The operator hasn't reported what the LSP sells yet.").assertIsDisplayed() - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/NavigateBackButtonJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/NavigateBackButtonJvmTest.kt index 7fa7d080..4b236311 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/NavigateBackButtonJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/NavigateBackButtonJvmTest.kt @@ -1,6 +1,5 @@ package mobi.giza.compose.ui.composable -import mobi.giza.compose.repository.GroupLightningRepository import androidx.compose.runtime.Composable import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.assertIsDisplayed @@ -93,7 +92,6 @@ class NavigateBackButtonJvmTest { chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, dkgRepository = DkgRepository.NO_OP_DKG_REPOSITORY, - lightningRepository = GroupLightningRepository.NO_OP_GROUP_LIGHTNING_REPOSITORY, onNavigateToRouteAndPopUpInclusive = {}, onNavigateToRoute = {}, onNavigateBack = onNavigateBack, diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ReadOnlyEntrancesJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ReadOnlyEntrancesJvmTest.kt index e6538876..89acb57f 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ReadOnlyEntrancesJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ReadOnlyEntrancesJvmTest.kt @@ -1,6 +1,5 @@ package mobi.giza.compose.ui.composable -import mobi.giza.compose.repository.GroupLightningRepository import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.test.ExperimentalTestApi @@ -283,7 +282,6 @@ class ReadOnlyEntrancesJvmTest { chatRepository = NoRooms, frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, dkgRepository = DkgRepository.NO_OP_DKG_REPOSITORY, - lightningRepository = GroupLightningRepository.NO_OP_GROUP_LIGHTNING_REPOSITORY, ) } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/GroupLightningWalletViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/GroupLightningWalletViewModelJvmTest.kt deleted file mode 100644 index 6cb2b560..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/GroupLightningWalletViewModelJvmTest.kt +++ /dev/null @@ -1,266 +0,0 @@ -package mobi.giza.compose.ui.view.model - -import mobi.giza.compose.database.model.ChatRoom -import mobi.giza.compose.database.model.FrostSigningSession -import mobi.giza.compose.database.model.GroupLightningInvoiceRow -import mobi.giza.compose.database.model.GroupLightningPaymentRow -import mobi.giza.compose.database.model.GroupSignedEvent -import mobi.giza.compose.database.model.IcebergKeySession -import mobi.giza.compose.database.model.IcebergParticipantMessage -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.database.model.types.IcebergApprovalStep -import mobi.giza.compose.database.model.types.IcebergRitualStage -import mobi.giza.compose.managers.GroupLightningAuthorisations -import mobi.giza.compose.managers.GroupLightningDerivation -import mobi.giza.compose.managers.GroupLightningOperatorManager -import mobi.giza.compose.managers.GroupLightningReports -import mobi.giza.compose.managers.GroupLightningWalletManager -import mobi.giza.compose.nostr.lightning.GroupLightningAuthorisationEvent -import mobi.giza.compose.nostr.lightning.GroupLightningOperatorStatementEvent -import mobi.giza.compose.nostr.lightning.GroupLightningWalletStatementEvent -import mobi.giza.compose.repository.ChatRepository -import mobi.giza.compose.repository.GroupLightningRepository -import mobi.giza.compose.ui.view.state.GroupLightningReceiveUIState -import mobi.giza.compose.ui.view.state.GroupLightningSendUIState -import mobi.giza.compose.ui.view.state.GroupLightningWalletUIState -import mobi.giza.compose.wallet.lightning.GroupSweep -import mobi.giza.compose.wallet.lightning.WalletWire -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.utils.Either -import fr.acinq.lightning.CltvExpiryDelta -import fr.acinq.lightning.Feature -import fr.acinq.lightning.FeatureSupport -import fr.acinq.lightning.Features -import fr.acinq.lightning.payment.Bolt11Invoice -import fr.acinq.lightning.utils.msat -import fr.acinq.secp256k1.Hex -import kotlin.test.AfterTest -import kotlin.test.BeforeTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertIs -import kotlin.test.assertTrue -import kotlin.time.Instant -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.flowOf -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.test.UnconfinedTestDispatcher -import kotlinx.coroutines.test.resetMain -import kotlinx.coroutines.test.setMain -import kotlinx.coroutines.withTimeout - -/** Which of its states the Lightning wallet screen puts a room in, on the way from nothing to an elected operator. */ -@OptIn(ExperimentalCoroutinesApi::class) -class GroupLightningWalletViewModelJvmTest { - @BeforeTest - fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher()) - - @AfterTest - fun tearDown() = Dispatchers.resetMain() - - private val chatRoomId = "d4c3b2a1".repeat(8) - private val me = "a".repeat(64) - private val localChatRoom = LocalChatRoom(chatRoom = ChatRoom(id = chatRoomId, userPublicKey = me, subject = "Treasury", description = null, mlsGroupState = "state")) - private val roomKey = PrivateKey(ByteVector32(Hex.decode("1c0ffee".padStart(64, '0')))).publicKey().toString() - - private val key = IcebergKeySession( - id = "ab".repeat(32), chatRoomId = chatRoomId, coordinatorPublicKey = me, userPublicKey = me, threshold = 2, participantCount = 4, - participantPublicKeys = IcebergKeySession.formatParticipants(listOf(me, "b".repeat(64), "c".repeat(64), "d".repeat(64))), - onchainDkgSessionId = "x", stage = IcebergRitualStage.COMPLETE, share = "00", groupPublicKey = "02" + "11".repeat(32), - ) - - private val wallet = GroupLightningWalletManager.Wallet( - statement = GroupLightningWalletStatementEvent.Statement(Chain.Testnet3, 0, 0, key.groupPublicKey!!, key.id, 2, key.participants(), "02" + "33".repeat(32), "02" + "44".repeat(32), GroupLightningWalletStatementEvent.Policy.DEFAULT), - signedEvent = GroupSignedEvent(id = "e".repeat(64), chatRoomId = chatRoomId, publicKey = chatRoomId, kind = GroupLightningWalletStatementEvent.KIND, tags = emptyArray(), content = "", signature = "f".repeat(128), createdAt = Instant.fromEpochSeconds(1)), - basepoints = GroupLightningDerivation.basepoints(roomKey, Chain.Testnet3, 0), - ceremony = key, - seed = null, - ) - - private fun operator(publicKey: HexKey?) = GroupLightningOperatorManager.Operator( - GroupLightningOperatorStatementEvent.Statement(Chain.Testnet3, 0, publicKey, 4, null), - wallet.signedEvent, - ) - - private class Lightning( - val onchain: Boolean = true, - val completed: IcebergKeySession? = null, - val running: IcebergKeySession? = null, - val wallet: GroupLightningWalletManager.Wallet? = null, - val operator: GroupLightningOperatorManager.Operator? = null, - val thresholds: List = listOf(2), - val report: GroupLightningReports.Report? = null, - val payments: List = emptyList(), - val invoice: GroupLightningInvoiceRow? = null, - val departedMembers: List = emptyList(), - val earlier: List = emptyList(), - val unusedKey: Boolean = false, - ) : GroupLightningRepository { - val requests = mutableListOf>() - override fun observeCeremony(sessionId: String): Flow = flowOf(running) - override fun observeCeremonies(chatRoomId: String): Flow> = flowOf(listOfNotNull(running)) - override suspend fun ceremonyMessages(sessionId: String): List = emptyList() - override suspend fun pendingApproval(session: IcebergKeySession): IcebergApprovalStep? = null - override suspend fun ceremonyThresholds(chatRoomId: String): List = thresholds - override suspend fun keyHolderCount(chatRoomId: String): Int = 4 - override suspend fun hasOnchainWallet(chatRoomId: String, chain: Chain): Boolean = onchain - override suspend fun proposeCeremony(localChatRoom: LocalChatRoom, userPublicKey: HexKey, nostrPrivateKey: ByteArray, threshold: Int, chain: Chain): IcebergKeySession = error("unused") - override suspend fun approveCeremony(localChatRoom: LocalChatRoom, sessionId: String, step: IcebergApprovalStep, nostrPrivateKey: ByteArray) = Unit - override suspend fun resumeCeremony(localChatRoom: LocalChatRoom, sessionId: String, nostrPrivateKey: ByteArray) = Unit - override suspend fun abandonCeremony(localChatRoom: LocalChatRoom, sessionId: String): Boolean = false - override suspend fun completedCeremony(chatRoomId: String): IcebergKeySession? = completed - override suspend fun lightningWallet(chatRoomId: String, chain: Chain): GroupLightningWalletManager.Wallet? = wallet - override suspend fun operator(chatRoomId: String, chain: Chain, wallet: Long): GroupLightningOperatorManager.Operator? = operator - override fun lspNodeId(chain: Chain): HexKey? = "02" + "44".repeat(32) - override suspend fun proposeWallet(localChatRoom: LocalChatRoom, userPublicKey: HexKey, nostrPrivateKey: ByteArray, chain: Chain): FrostSigningSession = error("unused") - override suspend fun nominateSelf(localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain, wallet: Long): FrostSigningSession = error("unused") - override suspend fun stepDown(localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain, wallet: Long): FrostSigningSession = error("unused") - override fun observeReport(chatRoomId: String, chain: Chain, wallet: Long): Flow = flowOf(report) - override fun observePayments(chatRoomId: String, chain: Chain, wallet: Long): Flow> = flowOf(payments) - override suspend fun requestInvoice(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, amountMsat: Long?, description: String): String = - "r1".also { requests += amountMsat to description } - override fun observeInvoice(chatRoomId: String, chain: Chain, wallet: Long, requestId: String): Flow = flowOf(invoice?.takeIf { it.requestId == requestId }) - override suspend fun proposePayment(localChatRoom: LocalChatRoom, userPublicKey: HexKey, pay: GroupLightningAuthorisationEvent.Pay): FrostSigningSession = error("unused") - override suspend fun proposeLiquidity(localChatRoom: LocalChatRoom, userPublicKey: HexKey, buy: GroupLightningAuthorisationEvent.BuyLiquidity): FrostSigningSession = error("unused") - override suspend fun proposeClose(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelId: String, force: Boolean): FrostSigningSession = error("unused") - override suspend fun earlierWallets(chatRoomId: String, chain: Chain): List = earlier - override suspend fun departed(wallet: GroupLightningWalletManager.Wallet): List = departedMembers - override suspend fun hasUnusedKey(chatRoomId: String, chain: Chain): Boolean = unusedKey - override suspend fun unusedKey(chatRoomId: String, chain: Chain): IcebergKeySession? = completed?.takeIf { unusedKey } - override suspend fun proposeCloseAll(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelIds: List): FrostSigningSession = error("unused") - override suspend fun unswept(chatRoomId: String, report: GroupLightningReports.Report?): List = report?.snapshot?.heldOutputs.orEmpty() - override suspend fun proposeSweep(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, inputs: List): FrostSigningSession = error("unused") - } - - private val chat = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { - override suspend fun getChatRoomByIdentifier(identifier: String): LocalChatRoom? = localChatRoom - } - - private fun settled(lightning: GroupLightningRepository): GroupLightningWalletUIState { - val viewModel = GroupLightningWalletViewModel(me, chatRoomId, Chain.Testnet3, GroupLightningWalletUIState.Loading, MutableStateFlow(null), chat, lightning) - viewModel.initiate() - return runBlocking { - withTimeout(5_000) { - while (viewModel.uiState == GroupLightningWalletUIState.Loading) delay(10) - viewModel.uiState - } - } - } - - @Test - fun `without an onchain wallet there is nothing to open`() { - assertIs(settled(Lightning(onchain = false, completed = key, wallet = wallet))) - } - - @Test - fun `with no key the group is asked to make one, or told it is too small`() { - assertTrue(assertIs(settled(Lightning())).canMakeKey) - assertTrue(!assertIs(settled(Lightning(thresholds = emptyList()))).canMakeKey) - val running = key.copy(stage = IcebergRitualStage.COLLECTING_REVEALS, share = null) - assertEquals(running, assertIs(settled(Lightning(running = running))).ceremony) - } - - @Test - fun `with a key and no statement the wallet can be opened, given the key to sign it`() { - val state = assertIs(settled(Lightning(completed = key))) - assertEquals(key, state.key) - assertTrue(!state.canPropose, "a profile with no private key to send the seed with cannot propose") - } - - @Test - fun `an open wallet says who runs it, and whether that is this device`() { - val nobody = assertIs(settled(Lightning(completed = key, wallet = wallet))) - assertTrue(nobody.isParticipant && !nobody.isOperator && nobody.operator == null) - val mine = assertIs(settled(Lightning(completed = key, wallet = wallet, operator = operator(me)))) - assertTrue(mine.isOperator) - val theirs = assertIs(settled(Lightning(completed = key, wallet = wallet, operator = operator("b".repeat(64))))) - assertTrue(!theirs.isOperator) - } - - @Test - fun `an open wallet shows the operator's report and the payments it has heard of`() { - val channel = WalletWire.ChannelView("cc".repeat(32), "Normal", 1_000_000, 400_000_000, 600_000_000, "dd".repeat(32), 0, 3) - val snapshot = WalletWire.Snapshot("w", 4, wallet.statement.nodeId, 100, listOf(channel), emptyList()) - val report = GroupLightningReports.Report(snapshot, listOf(GroupLightningReports.ChannelCheck(channel, 400_000_000))) - val payment = GroupLightningPaymentRow("w", "p", incoming = true, amountMsat = 21_000, feesMsat = 0, paymentHash = null, description = "lunch", completedAt = null, succeeded = true) - val viewModel = GroupLightningWalletViewModel(me, chatRoomId, Chain.Testnet3, GroupLightningWalletUIState.Loading, MutableStateFlow(null), chat, Lightning(completed = key, wallet = wallet, report = report, payments = listOf(payment))) - viewModel.initiate() - val state = runBlocking { - withTimeout(5_000) { - while ((viewModel.uiState as? GroupLightningWalletUIState.Opened)?.report == null) delay(10) - viewModel.uiState as GroupLightningWalletUIState.Opened - } - } - assertEquals(400_000_000, state.report!!.snapshot.spendableMsat) - assertEquals(true, state.report!!.checks.single().agrees) - assertEquals(listOf(payment), state.payments) - } - - @Test - fun `receiving asks the operator for an invoice and shows it once it arrives`() { - assertIs(receiving(Lightning(completed = key, wallet = wallet)).uiState, "nobody runs the node") - - val lightning = Lightning(completed = key, wallet = wallet, operator = operator("b".repeat(64)), invoice = GroupLightningInvoiceRow("w", "r1", "lnbcrt1")) - val viewModel = receiving(lightning) - assertIs(viewModel.uiState) - viewModel.amountField.edit { append("2,100") } - viewModel.descriptionField.edit { append(" lunch ") } - viewModel.request(onFailure = { error("the request failed") }) - val shown = runBlocking { withTimeout(5_000) { while (viewModel.uiState !is GroupLightningReceiveUIState.Invoice) delay(10); viewModel.uiState } } - assertEquals("lnbcrt1", assertIs(shown).bolt11) - assertEquals(listOf>(2_100_000L to "lunch"), lightning.requests.toList()) - } - - private fun receiving(lightning: GroupLightningRepository): GroupLightningReceiveViewModel { - val viewModel = GroupLightningReceiveViewModel(me, chatRoomId, Chain.Testnet3, GroupLightningReceiveUIState.Loading, chat, lightning) - viewModel.initiate() - runBlocking { withTimeout(5_000) { while (viewModel.uiState == GroupLightningReceiveUIState.Loading) delay(10) } } - return viewModel - } - - @Test - fun `sending previews the authorisation, with a fee limit when none is given`() { - val lightning = Lightning(completed = key, wallet = wallet, operator = operator("b".repeat(64))) - val viewModel = GroupLightningSendViewModel(me, chatRoomId, Chain.Testnet3, GroupLightningSendUIState.Loading, chat, lightning) - viewModel.initiate() - runBlocking { withTimeout(5_000) { while (viewModel.uiState == GroupLightningSendUIState.Loading) delay(10) } } - assertIs(viewModel.uiState) - assertEquals(null, viewModel.preview(), "nothing typed, nothing to say") - - fun invoice(chain: Chain, amount: Long?) = Bolt11Invoice.create( - chain, amount?.msat, ByteVector32(Hex.decode("07".repeat(32))), PrivateKey(ByteVector32(Hex.decode("05".repeat(32)))), Either.Left("tea"), CltvExpiryDelta(144), - Features(Feature.VariableLengthOnion to FeatureSupport.Mandatory, Feature.PaymentSecret to FeatureSupport.Mandatory), - ).write() - viewModel.invoiceField.edit { append(invoice(Chain.Testnet3, 50_000_000)) } - val pay = viewModel.preview()!!.getOrThrow() - assertEquals(50_000_000, pay.amountMsat) - assertEquals(500_000, pay.maxFeeMsat, "a percent of fifty thousand sats") - assertEquals(50_000_000, viewModel.invoiceAmountMsat()) - - viewModel.maxFeeField.edit { append("20") } - assertEquals(20_000, viewModel.preview()!!.getOrThrow().maxFeeMsat) - - viewModel.invoiceField.edit { replace(0, length, invoice(Chain.Mainnet, 1_000)) } - val problem = (viewModel.preview()!!.exceptionOrNull() as GroupLightningAuthorisations.ProblemException).problem - assertEquals(GroupLightningAuthorisations.Problem.OtherNetwork, problem) - } - - @Test - fun `after a member leaves, the wallet says so, and lists the wallet a re-key left behind`() { - val earlier = wallet.copy(statement = wallet.statement.copy(wallet = 0)) - val current = wallet.copy(statement = wallet.statement.copy(wallet = 1)) - val state = assertIs( - settled(Lightning(completed = key, wallet = current, departedMembers = listOf("d".repeat(64)), earlier = listOf(earlier), unusedKey = true)) - ) - assertEquals(listOf("d".repeat(64)), state.departed) - assertEquals(listOf(0L), state.earlier.map { it.wallet.statement.wallet }) - assertTrue(!state.canOpenNew, "a profile with no private key to send the seed with cannot open the new wallet") - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/lightning/CoSigningWireJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/lightning/CoSigningWireJvmTest.kt deleted file mode 100644 index 3a8f9565..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/lightning/CoSigningWireJvmTest.kt +++ /dev/null @@ -1,155 +0,0 @@ -package mobi.giza.compose.wallet.lightning - -import mobi.giza.compose.managers.GroupLightningCoSigner -import mobi.giza.compose.network.serialization.CommonJson -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.OutPoint -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.Satoshi -import fr.acinq.bitcoin.Script -import fr.acinq.bitcoin.Transaction -import fr.acinq.bitcoin.TxId -import fr.acinq.bitcoin.TxIn -import fr.acinq.bitcoin.TxOut -import fr.acinq.bitcoin.byteVector32 -import fr.acinq.lightning.CltvExpiryDelta -import fr.acinq.lightning.Features -import fr.acinq.lightning.blockchain.fee.FeeratePerKw -import fr.acinq.lightning.channel.ChannelConfig -import fr.acinq.lightning.channel.ChannelFeatures -import fr.acinq.lightning.channel.ChannelFlags -import fr.acinq.lightning.channel.ChannelParams -import fr.acinq.lightning.channel.CommitParams -import fr.acinq.lightning.channel.LocalChannelParams -import fr.acinq.lightning.channel.RemoteChannelParams -import fr.acinq.lightning.crypto.FundingSigner -import fr.acinq.lightning.transactions.CommitmentSpec -import fr.acinq.lightning.transactions.Transactions -import fr.acinq.lightning.utils.msat -import fr.acinq.lightning.wire.LiquidityAds -import kotlin.random.Random -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertNotNull -import kotlin.test.assertNull - -/** - * The co-signing wire with a splice on it (`docs/group-lightning-liquidity.md`, Phase 3): every context - * survives the trip, a request from a build before it still reads, and the hash a co-signer recomputes - * for a splice's shared input is the one lightning-kmp signs. - */ -class CoSigningWireJvmTest { - private fun key() = PrivateKey(Random.nextBytes(32).byteVector32()) - private fun p2tr() = ByteVector(Script.write(Script.pay2tr(key().publicKey().xOnly(), fr.acinq.bitcoin.Crypto.TaprootTweak.KeyPathTweak))) - - private val params = ChannelParams( - channelId = Random.nextBytes(32).byteVector32(), - channelConfig = ChannelConfig.standard, - channelFeatures = ChannelFeatures(setOf()), - localParams = LocalChannelParams(key().publicKey(), fr.acinq.bitcoin.KeyPath("m/1/2"), isChannelOpener = false, paysCommitTxFees = false, defaultFinalScriptPubKey = ByteVector("0014" + "11".repeat(20)), features = Features.empty), - remoteParams = RemoteChannelParams(key().publicKey(), key().publicKey(), key().publicKey(), key().publicKey(), key().publicKey(), Features.empty), - channelFlags = ChannelFlags(announceChannel = false, nonInitiatorPaysCommitFees = false), - ) - private val commitParams = CommitParams(Satoshi(546), 1_000_000_000L, 1.msat, CltvExpiryDelta(144), 30) - private val spec = CommitmentSpec(setOf(), FeeratePerKw(Satoshi(2_500)), toLocal = 600_000_000.msat, toRemote = 400_000_000.msat) - - private val groupKey = key().publicKey() - private val oldLspKey = key().publicKey() - private val newLspKey = key().publicKey() - private val parent = Transactions.makeFundingInputInfo(TxId(Random.nextBytes(32).byteVector32()), 1, Satoshi(1_000_000), groupKey, oldLspKey, Transactions.CommitmentFormat.SimpleTaprootChannels) - private val lspInput = Transactions.InputInfo(OutPoint(TxId(Random.nextBytes(32).byteVector32()), 0), TxOut(Satoshi(300_000), p2tr())) - private val lspInput2 = Transactions.InputInfo(OutPoint(TxId(Random.nextBytes(32).byteVector32()), 3), TxOut(Satoshi(50_000), p2tr())) - - /** A liquidity purchase as the LSP would put it together: its two inputs around ours, its change, the new funding output. */ - private val newFunding = Transactions.makeFundingInputInfo(TxId(ByteArray(32)), 0, Satoshi(1_199_700), groupKey, newLspKey, Transactions.CommitmentFormat.SimpleTaprootChannels).txOut - private val spliceTx = Transaction( - version = 2, - txIn = listOf(TxIn(lspInput.outPoint, 0xfffffffdL), TxIn(parent.outPoint, 0xfffffffdL), TxIn(lspInput2.outPoint, 0xfffffffdL)), - txOut = listOf(TxOut(Satoshi(149_000), p2tr()), newFunding), - lockTime = 0, - ) - private val purchase = LiquidityAds.Purchase.Standard(Satoshi(200_000), LiquidityAds.Fees(Satoshi(200), Satoshi(2_100)), LiquidityAds.PaymentDetails.FromChannelBalance) - private val splice = FundingSigner.SigningContext.Splice( - channelParams = params, - parentFundingTxIndex = 0, - parentFunding = parent, - fundingTxIndex = 1, - fundingOutputIndex = 1, - remoteFundingPubKey = newLspKey, - localContribution = Satoshi(-300), - remoteContribution = Satoshi(200_000), - purchase = purchase, - feerate = FeeratePerKw(Satoshi(500)), - spentOutputs = mapOf(parent.outPoint to parent.txOut, lspInput.outPoint to lspInput.txOut, lspInput2.outPoint to lspInput2.txOut), - ) - - private fun request(context: FundingSigner.SigningContext, input: Transactions.InputInfo, tx: Transaction, extra: Map = emptyMap()) = CoSigningWire.SigningRequest( - wallet = "room:mainnet:0", term = 1, requestId = "r", kind = "PUBLISHED", label = "00".repeat(32), counter = 0, - tx = CoSigningWire.tx(tx), input = CoSigningWire.input(input), fundingTxId = input.outPoint.txid.toString(), remoteFundingPubKey = oldLspKey.toString(), - contributions = emptyList(), cosignerAggregatedNonce = "", context = CoSigningWire.context(context), - extraUtxos = extra.map { (o, t) -> CoSigningWire.input(Transactions.InputInfo(o, t)) }, - ) - - private fun roundTrip(r: CoSigningWire.SigningRequest) = - CommonJson.decodeFromString(CoSigningWire.SigningRequest.serializer(), CommonJson.encodeToString(CoSigningWire.SigningRequest.serializer(), r)) - - @Test - fun `every context survives the trip, and a commitment names its funding output`() { - val point = key().publicKey() - val remote = assertNotNull(roundTrip(request(FundingSigner.SigningContext.RemoteCommitment(params, commitParams, 7, point, spec, fundingTxIndex = 1), parent, spliceTx)).context) - assertEquals("remote", remote.type) - assertEquals(1, remote.fundingTxIndex) - assertEquals(7, remote.commitIndex) - assertEquals(spec, CoSigningWire.spec(assertNotNull(remote.spec), params.channelId)) - assertEquals(params, CoSigningWire.params(remote.params)) - - val local = assertNotNull(roundTrip(request(FundingSigner.SigningContext.LocalCommitment(params, commitParams, 7, spec, fundingTxIndex = 2), parent, spliceTx)).context) - assertEquals("local", local.type) - assertEquals(2, local.fundingTxIndex) - - val closing = assertNotNull(roundTrip(request(FundingSigner.SigningContext.Closing(params, ByteVector("51"), ByteVector("52"), spec), parent, spliceTx)).context) - assertEquals("closing", closing.type) - assertEquals("51", closing.localScript) - - val read = assertNotNull(roundTrip(request(splice, parent, spliceTx, splice.spentOutputs - parent.outPoint)).context) - assertEquals(GroupLightningCoSigner.SPLICE, read.type) - assertNull(read.spec, "a splice carries no commitment") - assertEquals(0, read.parentFundingTxIndex) - assertEquals(1, read.fundingTxIndex) - assertEquals(parent, CoSigningWire.inputInfo(assertNotNull(read.parentFunding))) - assertEquals(1, read.fundingOutputIndex) - assertEquals(newLspKey.toString(), read.newRemoteFundingPubKey) - assertEquals(-300, read.localContributionSat) - assertEquals(200_000, read.remoteContributionSat) - assertEquals(500, read.feeratePerKw) - assertEquals(CoSigningWire.Purchase(200_000, 200, 2_100, CoSigningWire.FROM_CHANNEL_BALANCE), read.purchase) - } - - @Test - fun `fee credit and other payment types are named, so a co-signer can refuse them`() { - val withCredit = LiquidityAds.Purchase.WithFeeCredit(Satoshi(200_000), LiquidityAds.Fees(Satoshi(200), Satoshi(2_100)), 1_500_000.msat, LiquidityAds.PaymentDetails.FromFutureHtlc(listOf(Random.nextBytes(32).byteVector32()))) - assertEquals(CoSigningWire.Purchase(200_000, 200, 2_100, "from_future_htlc", feeCreditUsedMsat = 1_500_000), CoSigningWire.purchase(withCredit)) - } - - @Test - fun `a request from a build before splices still reads, as a commitment on the first funding output`() { - val old = request(FundingSigner.SigningContext.RemoteCommitment(params, commitParams, 3, key().publicKey(), spec), parent, spliceTx) - val json = CommonJson.encodeToString(CoSigningWire.SigningRequest.serializer(), old) - .replace(",\"fundingTxIndex\":0", "").replace(",\"extraUtxos\":[]", "") - val read = CommonJson.decodeFromString(CoSigningWire.SigningRequest.serializer(), json) - assertEquals(0, read.context!!.fundingTxIndex) - assertEquals(emptyList(), read.extraUtxos) - } - - @Test - fun `the hash a co-signer recomputes for a splice's shared input is the one lightning-kmp signs`() { - val extra = splice.spentOutputs - parent.outPoint - val expected = Transactions.SpliceTx(parent, spliceTx).taprootSighash(extra) - assertEquals(expected, GroupLightningCoSigner.messageOf(request(splice, parent, spliceTx, extra)), "the shared input is input 1 of 3, over all three spent outputs") - // Without what the other inputs spend there is no hash, and so nothing to sign. - assertNull(GroupLightningCoSigner.messageOf(request(splice, parent, spliceTx, extra - lspInput2.outPoint))) - // A commitment is unchanged: one input, no extras. - val commitTx = Transaction(2, listOf(TxIn(parent.outPoint, 0)), listOf(TxOut(Satoshi(999_000), p2tr())), 0) - assertEquals(commitTx.hashForSigningTaprootKeyPath(0, listOf(parent.txOut), fr.acinq.bitcoin.SigHash.SIGHASH_DEFAULT), GroupLightningCoSigner.messageOf(request(splice, parent, commitTx))) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/lightning/LiquidityPriceJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/lightning/LiquidityPriceJvmTest.kt deleted file mode 100644 index 372a8264..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/lightning/LiquidityPriceJvmTest.kt +++ /dev/null @@ -1,59 +0,0 @@ -package mobi.giza.compose.wallet.lightning - -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertNull -import kotlin.test.assertTrue - -/** - * What a member's device works out a purchase costs (`docs/group-lightning-liquidity.md`, Phase 7), - * held to what eclair charged in Phase 0's regtest run: 200,000 sats at 2 sat/vbyte for 2,521, our - * share of the mining fee 221, the LSP's inputs' 200 and the service fee 2,100. - */ -class LiquidityPriceJvmTest { - private val regtestRates = WalletWire.FundingRates(listOf(WalletWire.FundingRate(10_000, 10_000_000, 400, 100, 100, 1_000)), listOf("from_channel_balance")) - - @Test - fun `the price is what eclair charged`() { - val price = LiquidityPrice.price(regtestRates, 200_000, 2)!! - assertEquals(LiquidityPrice.Price(ourMiningSat = 221, lspMiningSat = 200, serviceSat = 2_100), price) - assertEquals(2_521, price.totalSat) - assertEquals(3_781, LiquidityPrice.defaultCap(price)) - } - - @Test - fun `no rate, no price, and the amounts offered are those the LSP sells under the cap`() { - assertNull(LiquidityPrice.price(regtestRates, 5_000, 2)) - assertEquals(LiquidityPrice.OPTIONS, LiquidityPrice.offered(regtestRates, 25_000, null)) - assertEquals(listOf(100_000L, 250_000L, 500_000L), LiquidityPrice.offered(regtestRates, 25_000, 1_000_000), "a 25,000-sat channel under the mainnet cap") - assertEquals(emptyList(), LiquidityPrice.offered(regtestRates, 950_000, 1_000_000), "a channel at the cap buys nothing") - val narrow = WalletWire.FundingRates(listOf(WalletWire.FundingRate(200_000, 600_000, 400, 100, 100, 1_000)), listOf("from_channel_balance")) - assertEquals(listOf(250_000L, 500_000L), LiquidityPrice.offered(narrow, 25_000, null)) - } - - @Test - fun `a fee of a quarter of the amount or more is expensive, as Phoenix warns`() { - assertFalse(LiquidityPrice.expensive(LiquidityPrice.price(regtestRates, 200_000, 2)!!, 200_000)) - assertTrue(LiquidityPrice.expensive(LiquidityPrice.Price(0, 0, 25_000), 100_000)) - } - - private fun channel(state: String = "Normal", capacitySat: Long = 25_000) = WalletWire.ChannelView("c", state, capacitySat, 21_900_000, 3_100_000, "f", 0, 1) - private fun snapshot(channels: List, rates: WalletWire.FundingRates? = regtestRates, feerate: Long? = 2) = - WalletWire.Snapshot("w", 1, "n", 0, channels, emptyList(), fundingRates = rates, feeratePerByte = feerate) - - @Test - fun `when the group can be asked, and why not`() { - assertEquals(LiquidityPrice.Availability.NoOperator, LiquidityPrice.availability(snapshot(listOf(channel())), hasOperator = false, capSat = null)) - assertEquals(LiquidityPrice.Availability.NoPrices, LiquidityPrice.availability(null, true, null)) - assertEquals(LiquidityPrice.Availability.NoChannel, LiquidityPrice.availability(snapshot(emptyList()), true, null)) - assertEquals(LiquidityPrice.Availability.NoChannel, LiquidityPrice.availability(snapshot(listOf(channel(state = "Closing"))), true, null)) - assertEquals(LiquidityPrice.Availability.NoPrices, LiquidityPrice.availability(snapshot(listOf(channel()), rates = null), true, null)) - assertEquals(LiquidityPrice.Availability.NoPrices, LiquidityPrice.availability(snapshot(listOf(channel()), feerate = null), true, null)) - assertEquals(LiquidityPrice.Availability.AtTheCap, LiquidityPrice.availability(snapshot(listOf(channel(capacitySat = 950_000))), true, 1_000_000)) - val none = WalletWire.FundingRates(listOf(WalletWire.FundingRate(20_000_000, 30_000_000, 400, 100, 100, 1_000)), listOf("from_channel_balance")) - assertEquals(LiquidityPrice.Availability.NothingSold, LiquidityPrice.availability(snapshot(listOf(channel()), rates = none), true, null)) - val available = LiquidityPrice.availability(snapshot(listOf(channel())), true, 1_000_000) - assertTrue(available is LiquidityPrice.Availability.Available && available.offered == listOf(100_000L, 250_000L, 500_000L)) - } -} diff --git a/docs/README.md b/docs/README.md index 3b06c5bd..02385751 100644 --- a/docs/README.md +++ b/docs/README.md @@ -45,7 +45,6 @@ on purpose ([giza-rebrand.md](./giza-rebrand.md)). | [group-lightning-transcript.md](./group-lightning-transcript.md) | the group Lightning wallet in a room's chat, phased — why every Lightning kind but the three the group signs became a raw-JSON bubble, the standing notice the Iceberg ceremony never got, and which of the operator's messages earn a line and which never should | | [group-lightning-liquidity.md](./group-lightning-liquidity.md) | buying inbound liquidity for the group's Lightning wallet as Phoenix does, phased — why a purchase is a splice every co-signer refuses today, why the group decides it with an authorisation rather than the operator with a tap, the same group key at every funding index, and the rule that lets a device that missed a splice follow the channel to its new output | | [lightning/README.md](./lightning/README.md) | the remediation plans for the review of the group Lightning wallet — seven findings, one phased plan each, and the order to build them in | -| [../testing/regtest/README.md](../testing/regtest/README.md) | running the group Lightning wallet end to end on a regtest network of bitcoind, electrs and two eclair nodes — the prerequisites and ports, where the run's output and eclair's log end up, and what each failure means. Not part of `check` or CI | | [marmot-v2.md](./marmot-v2.md) | bringing the group layer onto the Marmot current profile after the quartz 1.15.2 bump — the nine rules that reach this app, why the room's id and the routing id have to become two values, nine phases from reading both profiles to publishing before applying, and the one fork the library cannot yet settle | | [giza-wallet-removal.md](./giza-wallet-removal.md) | taking every wallet out of Giza, phased and not yet built. Covers why a Giza member declines a Bennu peer's wallet proposal instead of ignoring or signing it, why the wallet's kinds are retired rather than freed, why a recovery phrase stays as a key backup that has to derive the same npub and id byte for byte, and why the threshold crypto keeps the build tied to the wallet library until the last phase | | [giza-rebrand.md](./giza-rebrand.md) | forking Bennu as Giza under `mobi.giza` — what carries the name, what must not be renamed and why, why the desktop data directory changes first, and how the fork keeps merging from Bennu | diff --git a/docs/giza-wallet-removal.md b/docs/giza-wallet-removal.md index 3a52cde7..9964e7ce 100644 --- a/docs/giza-wallet-removal.md +++ b/docs/giza-wallet-removal.md @@ -20,7 +20,8 @@ written against `caf1fb18`. | phase | state | |---|---| | 0 | the baseline: `jvmTest` 1,651 run, 0 failed, 2 skipped (the regtest pair); `m3-audit` clean, with **adaptive APIs at 12 against a floor of 12**, none of them in wallet code; `brand-audit` clean. `ForkCompatibilityTest` pins a recovery phrase's secret, npub, profile id and host key, on NIP-06's own test vector. 0.4: a refused proposal is **silent** today (`acceptProposal` logs and returns null), so Phase 1 adds the decline | -| 1 | built. `RetiredKinds`; `WalletRefusal` declines a wallet's proposal on arrival, through a filed session so `advance` publishes the `DECLINE` (with the reason `Giza doesn't sign for wallets`) and repeats it after a crash; `approve` declines a wallet's session instead. Retired kinds fall to one line or none, never `unsupported`. The detail screen, both profile screens and the subgroup picker lose their wallet parts; a guarded room says why it offers no subgroup (W5). `jvmTest` 1,495 run, 0 failed, 2 skipped; `m3-audit` floors unchanged | Paths below are under +| 1 | built. `RetiredKinds`; `WalletRefusal` declines a wallet's proposal on arrival, through a filed session so `advance` publishes the `DECLINE` (with the reason `Giza doesn't sign for wallets`) and repeats it after a crash; `approve` declines a wallet's session instead. Retired kinds fall to one line or none, never `unsupported`. The detail screen, both profile screens and the subgroup picker lose their wallet parts; a guarded room says why it offers no subgroup (W5). `jvmTest` 1,495 run, 0 failed, 2 skipped; `m3-audit` floors unchanged | +| 2 | built. 63 files deleted: the Lightning events, managers, Iceberg, `wallet/lightning/`, the repository, five screens with their view models, states and routes, and the regtest network with its build wiring and its section in `CLAUDE.md`. Its four DAOs go; the entities stay for Phase 5. The 147 strings Phases 1 and 2 left unread go. `jvmTest` 1,440 run, 0 failed, 0 skipped; `m3-audit` floors unchanged | Paths below are under `composeApp/src/commonMain/kotlin/mobi/giza/compose/` unless they say otherwise. Line numbers were right at that commit; confirm them with a grep before using them. @@ -43,6 +44,9 @@ Where the build chose differently from the phases as written: | Phase 1 turns off entry points and declines proposals | also everything Giza did on its own about a wallet, none of which a screen offered: `NostrDao` dispatching a Bennu operator's Lightning traffic to the managers (so an Iceberg ceremony is never filed or joined), `ChatMessage` forwarding a guarded wallet upward on arrival and answering member-wallet key requests, and the chat list's catch-up forward and Lightning asks | | the subgroup picker's wallet choice goes in Phase 3 | in Phase 1, with its view model state and twelve of the picker test's fifteen cases: a picker that still offered *guarded* would be offering a wallet. `SubgroupManager.proposeBirthCertificate` writes no wallet tags from Phase 1, and refuses under a parent whose certificate says `wallet=guarded` | | wallet tests are deleted with their code, in Phases 2-4 | the ones Phase 1's behaviour breaks went in Phase 1: fourteen group Lightning, spend, guardian and Iceberg test files, `LightningCeremonyAwaitingYouJvmTest`, and the guardian and policy cases of `SubgroupManagerJvmTest`. They tested Giza taking part, which it no longer does. `GroupSignedWorkRowsJvmTest` became `ChatRoomDetailWithoutWalletsJvmTest` | +| FROST's sweep path goes in Phase 4, with the spend | in Phase 2, because it is built on `wallet/lightning/GroupSweep`. A sweep that arrives is filed declined by `declineWalletProposal`, which reads nothing of what it spends -- the path Phase 4 sends every transaction proposal down | +| a Lightning kind's line is the retired arm's | and its protocol kinds are no longer *protocol* in `fromGroupEventResult` either: nothing acts on them, so they reach `applyInnerEvent` and its retired arm, which is how a 30355 gets its one line | +| existing Lightning and Iceberg lines keep their types as names only | their constants and sets stay in `ChatMessage`, and the transcript draws them as settled lines that open nothing, until Phase 5 deletes the rows | | a retired kind's arm becomes one line or none | the arms the wallet kinds already have keep writing their own lines until their phases delete them; the fallback catches each kind as its arm goes. `ProtocolKindDispatchJvmTest` asserts no retired kind is ever `unsupported`, at every phase | ## What the wallets are, measured diff --git a/testing/regtest/README.md b/testing/regtest/README.md deleted file mode 100644 index 664dd8f3..00000000 --- a/testing/regtest/README.md +++ /dev/null @@ -1,101 +0,0 @@ -# Regtest network for the group Lightning wallet - -A Bitcoin regtest network on one machine, for `GroupLightningRegtestJvmTest`: four devices open a -group Lightning wallet, receive, pay, close and sweep against a real lightning-kmp node and an eclair -LSP. What the run checks, what it found, and why each LSP setting is there is in -[docs/group-lightning-wallet.md](../../docs/group-lightning-wallet.md), "The regtest run". - -`LiquidityPurchaseRegtestJvmTest` uses the same network for the liquidity plan's Phase 0 -([docs/group-lightning-liquidity.md](../../docs/group-lightning-liquidity.md)): a stock node that keeps one -funding key buys inbound liquidity from the LSP, with its signatures delayed, to see what eclair accepts -and how long it waits. The group run buys liquidity too, between receiving and paying. - -The run is **not** part of `./gradlew check` or CI. Without `GIZA_REGTEST=1` the test is reported as -skipped, so a green `jvmTest` says nothing about it. - -## Prerequisites - -- Docker with the Compose v2 plugin (`docker compose`, not `docker-compose`) -- `curl` and `python3`, which `regtest.sh` uses to call the nodes and read their answers -- About 800 MB for the images, which the first `up` downloads: `bitcoin/bitcoin:31.1`, - `getumbrel/electrs:v0.11.1` and `acinq/eclair:v0.14.4`. eclair 0.14.4 refuses a Bitcoin Core - older than 31. -- These localhost ports free: - -| port | what | -|---|---| -| 28443 | bitcoind RPC (`foo` / `bar`) | -| 28001 | electrs, Electrum protocol, no TLS | -| 29735 | the LSP's Lightning port, which the group's node connects to | -| 28080 | the LSP's API (password `lsp`) | -| 28081 | the payer's API (password `payer`) | - -Nothing listens on any other interface, and the compose project is named `giza-regtest`, so it sits -beside other stacks without touching them, Bennu's `bennu-regtest` among them. The ports are the -same as Bennu's, though, so the two stacks cannot be up at once. - -## Running it - -From this directory: - -```bash -./regtest.sh up -``` - -`up` starts bitcoind, makes three wallets (a miner, the LSP's, the payer's) and funds two of them, -starts electrs and both eclair nodes, and opens a 5,000,000-sat channel from the payer to the LSP. It -finishes by printing the LSP's node id. Allow a minute the first time, after the downloads. - -From the repository root: - -```bash -GIZA_REGTEST=1 ./gradlew :composeApp:jvmTest --tests '*GroupLightningRegtestJvmTest' -``` - -It takes about thirty seconds. It can be run again on the same network as often as you like. Each -run makes a new Lightning wallet with a new node. The group's onchain key is fixed in the test fixture, -though, so its first address collects coins across runs; the checks compare balances before and after. - -When you are done: - -```bash -./regtest.sh down -``` - -`down` removes the containers, bitcoind's volume and the network. The images stay cached. - -To reach each piece by hand: `./regtest.sh mine 6`, `./regtest.sh btc [args]`, -`./regtest.sh lsp -d key=value` and `./regtest.sh payer -d key=value`. The last two -call eclair's API, for example `./regtest.sh lsp channels` or `./regtest.sh payer usablebalances`. - -## Where the output goes - -- **The run's own lines and the node's log.** With Gradle's `-q`, or whenever the test passes, nothing - reaches the console. Everything the test printed is in - `composeApp/build/test-results/jvmTest/TEST-mobi.giza.compose.managers.GroupLightningRegtestJvmTest.xml`, - under ``: the `REGTEST …` progress lines, lightning-kmp's log (`fr.acinq.lightning.*`), - and the app's managers (`GroupLightningNode`, `GroupLightningCoSigner`, `FrostSigningManager`). The - HTML report beside it, `composeApp/build/reports/tests/jvmTest/index.html`, shows the same. -- **eclair's log.** `docker compose logs` shows almost nothing for eclair, which writes to a file in its - data directory: - - ```bash - docker compose exec lsp tail -n 200 /data/eclair.log - ``` - - Use `payer` in place of `lsp` for the payer's. -- **bitcoind and electrs** log to the console: `docker compose logs bitcoind` or `docker compose logs electrs`. - -## Troubleshooting - -| what you see | what it means | -|---|---| -| the test is reported as skipped | `GIZA_REGTEST=1` was not set in the environment Gradle runs the test in | -| `The regtest network is not running: nothing answers for … on 127.0.0.1:…` | that service is down. Run `./regtest.sh up`, or check it with `docker compose ps -a` and its logs | -| `the payer has no open channel to the LSP` | `up` stopped part way through. Run `./regtest.sh down`, then `up` again | -| `up` prints `timed out waiting for: …` | a container exited: `docker compose ps -a` shows which, and its log says why | -| `timed out waiting for …` from the test | it lists the round-one label assignments and pool counts first (`REGTEST assigned …` and `REGTEST pool …` in the report). A pool counter with fewer than three rows is a co-signer that never answered. Otherwise look for `Error(` and `Warn:` lines in the node's log and for `WARN` in the LSP's | -| `Error(… data=…)` in the node's log | an error message from the LSP or to it. Its `data` is text in hex: `python3 -c "print(bytes.fromhex('').decode())"` reads it | -| `the payment failed: … route not found` | the LSP has no usable route to the payer. Check `./regtest.sh lsp usablebalances` and `./regtest.sh lsp allupdates`: an update with `htlcMaximumMsat` of 1 means eclair's balance thresholds were on when the channel opened (`lsp.conf` turns them off; `./regtest.sh lsp updaterelayfee -d nodeIds= -d feeBaseMsat=1000 -d feeProportionalMillionths=100` refreshes one) | -| a port is already in use | another stack has it. Change the host side of that port in `compose.yml`, and the matching port in `GroupLightningRegtestJvmTest` | -| the LSP refuses to start: `requires Bitcoin Core 31 or higher` | `compose.yml` was changed to an older bitcoind image | diff --git a/testing/regtest/compose.yml b/testing/regtest/compose.yml deleted file mode 100644 index 77c66875..00000000 --- a/testing/regtest/compose.yml +++ /dev/null @@ -1,66 +0,0 @@ -# A regtest network for the group Lightning wallet's end-to-end run (docs/group-lightning-wallet.md, -# "The regtest run"): bitcoind, electrs for the group's Electrum client, an eclair LSP speaking -# Phoenix's taproot channels and on-the-fly funding, and a second eclair that pays the group and is -# paid by it. Every port is bound to localhost, in a range nothing else on a development machine uses. -name: giza-regtest - -services: - bitcoind: - image: bitcoin/bitcoin:31.1 - command: - - -printtoconsole - - -regtest=1 - - -server=1 - - -txindex=1 - # foo:bar for eclair and the scripts; the cookie, readable by all, for electrs. - - -rpcauth=foo:abd66bf47451e26a7809d47370140dc9$$101b2636d908b296314aaad45c40bb42e0bbf631ea37b3f7767319e638e1662e - - -rpccookieperms=all - - -rpcallowip=0.0.0.0/0 - - -rpcbind=0.0.0.0 - - -fallbackfee=0.0002 - - -listen=1 - - -bind=0.0.0.0 - - -zmqpubhashblock=tcp://0.0.0.0:29000 - - -zmqpubrawtx=tcp://0.0.0.0:29001 - volumes: - - bitcoind:/home/bitcoin/.bitcoin - ports: - - "127.0.0.1:28443:18443" - - electrs: - image: getumbrel/electrs:v0.11.1 - # bitcoind's data directory is its own; root is what reads the cookie in it. - user: root - command: - - --network=regtest - - --daemon-rpc-addr=bitcoind:18443 - - --daemon-p2p-addr=bitcoind:18444 - - --electrum-rpc-addr=0.0.0.0:50001 - - --cookie-file=/bitcoin/regtest/.cookie - - --db-dir=/tmp/electrs - depends_on: [bitcoind] - volumes: - - bitcoind:/bitcoin:ro - ports: - - "127.0.0.1:28001:50001" - - lsp: - image: acinq/eclair:v0.14.4 - depends_on: [bitcoind] - volumes: - - ./lsp.conf:/data/eclair.conf:ro - ports: - - "127.0.0.1:29735:9735" - - "127.0.0.1:28080:8080" - - payer: - image: acinq/eclair:v0.14.4 - depends_on: [bitcoind] - volumes: - - ./payer.conf:/data/eclair.conf:ro - ports: - - "127.0.0.1:29736:9735" - - "127.0.0.1:28081:8080" - -volumes: - bitcoind: diff --git a/testing/regtest/lsp.conf b/testing/regtest/lsp.conf deleted file mode 100644 index 3a24b22d..00000000 --- a/testing/regtest/lsp.conf +++ /dev/null @@ -1,67 +0,0 @@ -// The LSP: what Phoenix's ACINQ node offers a wallet, as far as eclair's public features go. Not -// zero-conf: eclair takes that only per peer, and the group's node id is not known until its wallet is -// made, so the run mines the funding transaction instead. -eclair { - chain = "regtest" - node-alias = "giza-lsp" - server.binding-ip = "0.0.0.0" - api { - enabled = true - binding-ip = "0.0.0.0" - port = 8080 - password = "lsp" - } - bitcoind { - host = "bitcoind" - rpcport = 18443 - rpcuser = "foo" - rpcpassword = "bar" - wallet = "lsp" - zmqblock = "tcp://bitcoind:29000" - zmqtx = "tcp://bitcoind:29001" - } - trampoline-payments-enable = true - // Messages and payments to a wallet node go through eclair's wake-up path, even when it is connected. - peer-wake-up.enabled = true - features { - option_dual_fund = optional - option_splice = optional - option_quiesce = optional - option_simple_close = optional - // ACINQ's mainnet LSP does not list this one, or phoenix_zero_reserve, in the init it sends a new - // wallet, yet Phoenix wallets get taproot channels from it. They are on here, so this LSP's init offers - // more than ACINQ's: a node that requires a feature ACINQ leaves out passes here and is dropped there. - option_simple_taproot_phoenix = optional - // part of the Phoenix taproot channel type - phoenix_zero_reserve = optional - option_provide_storage = optional - on_the_fly_funding = optional - funding_fee_credit = optional - trampoline_payment_prototype = optional - } - channel { - // Advertise the whole channel: eclair otherwise caps an update by the balance it had when it was made, - // which for a channel the other side funded is nothing, and refreshes it only now and then. - channel-update.balance-thresholds = [] - // A wallet opening on the fly contributes nothing: the LSP funds the channel and is paid from the payment. - min-private-funding-satoshis = 0 - // How long the group waits for its own output after a force close: short, so the run's sweep comes soon. - to-remote-delay-blocks = 144 - // A channel opened on the fly is the size of the payment that opened it, so all of it is in flight at once. - max-htlc-value-in-flight-percent = 100 - } - // On-the-fly funding sells the wallet the inbound liquidity a payment needs, paid from the payment. - liquidity-ads { - funding-rates = [ - { - min-funding-amount-satoshis = 10000 - max-funding-amount-satoshis = 10000000 - funding-weight = 400 - fee-base-satoshis = 100 - fee-basis-points = 100 - channel-creation-fee-satoshis = 1000 - } - ] - payment-types = ["from_channel_balance", "from_future_htlc", "from_future_htlc_with_preimage", "from_channel_balance_for_future_htlc"] - } -} diff --git a/testing/regtest/payer.conf b/testing/regtest/payer.conf deleted file mode 100644 index 19db61d1..00000000 --- a/testing/regtest/payer.conf +++ /dev/null @@ -1,29 +0,0 @@ -// Somebody else on the network: pays the group through the LSP, and is paid by it. -eclair { - chain = "regtest" - node-alias = "giza-payer" - server.binding-ip = "0.0.0.0" - api { - enabled = true - binding-ip = "0.0.0.0" - port = 8080 - password = "payer" - } - bitcoind { - host = "bitcoind" - rpcport = 18443 - rpcuser = "foo" - rpcpassword = "bar" - wallet = "payer" - zmqblock = "tcp://bitcoind:29000" - zmqtx = "tcp://bitcoind:29001" - } - // Advertise the whole channel: eclair otherwise caps an update by the balance it had when it was made. - channel.channel-update.balance-thresholds = [] - features { - option_dual_fund = optional - option_splice = optional - option_quiesce = optional - option_simple_close = optional - } -} diff --git a/testing/regtest/regtest.sh b/testing/regtest/regtest.sh deleted file mode 100755 index e0e7d2a4..00000000 --- a/testing/regtest/regtest.sh +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env bash -# The group Lightning wallet's regtest network. `up` builds it from nothing: bitcoind with three -# wallets (a miner, the LSP's, the payer's), electrs, both eclair nodes, and a channel from the payer to -# the LSP. `down` removes all of it. -set -euo pipefail -cd "$(dirname "$0")" - -btc() { docker compose exec -T bitcoind bitcoin-cli -regtest -rpcuser=foo -rpcpassword=bar "$@"; } -lsp() { local m=$1; shift; curl -sf -u :lsp -X POST "http://127.0.0.1:28080/$m" "$@"; } -payer() { local m=$1; shift; curl -sf -u :payer -X POST "http://127.0.0.1:28081/$m" "$@"; } -mine() { btc -rpcwallet=miner generatetoaddress "${1:-1}" "$(btc -rpcwallet=miner getnewaddress)" >/dev/null; } -wait_for() { for _ in $(seq 1 90); do if eval "$1" >/dev/null 2>&1; then return 0; fi; sleep 1; done; echo "timed out waiting for: $1" >&2; return 1; } - -case "${1:-}" in - up) - docker compose up -d bitcoind - wait_for "btc getblockchaininfo" - for w in miner lsp payer; do btc -named createwallet wallet_name=$w load_on_startup=true >/dev/null 2>&1 || btc loadwallet $w >/dev/null 2>&1 || true; done - mine 150 - btc -rpcwallet=miner sendtoaddress "$(btc -rpcwallet=lsp getnewaddress)" 10 >/dev/null - btc -rpcwallet=miner sendtoaddress "$(btc -rpcwallet=payer getnewaddress)" 10 >/dev/null - mine 6 - docker compose up -d electrs lsp payer - wait_for "lsp getinfo" - wait_for "payer getinfo" - lspId=$(lsp getinfo | python3 -c 'import sys,json; print(json.load(sys.stdin)["nodeId"])') - payer connect -d uri="$lspId@lsp:9735" >/dev/null - payer open -d nodeId="$lspId" -d fundingSatoshis=5000000 >/dev/null - # The funding transaction reaches the mempool a moment after the open is answered. - wait_for "[ \$(btc getmempoolinfo | python3 -c 'import sys,json; print(json.load(sys.stdin)[\"size\"])') -gt 0 ]" - wait_for "mine 1; payer channels | grep -q NORMAL" - echo "LSP $lspId on 127.0.0.1:29735, electrs on 127.0.0.1:28001" - ;; - down) docker compose down -v ;; - mine) mine "${2:-1}" ;; - btc) shift; btc "$@" ;; - lsp) shift; lsp "$@"; echo ;; - payer) shift; payer "$@"; echo ;; - *) echo "usage: $0 up | down | mine [n] | btc | lsp [-d k=v] | payer [-d k=v]"; exit 1 ;; -esac