From 8e0f1bd38ab1daef2378fe87f241a38fbf2c27c4 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Wed, 18 Nov 2026 15:14:53 +0200 Subject: [PATCH] feat: Giza neither offers nor signs a wallet (wallet removal, Phase 1) A Bennu member can put a wallet to a group Giza is in. Giza can no longer check one, so it declines on arrival, out loud: the proposal is filed as a declined session and advance() publishes the DECLINE, which the group counts. Refusing used to be silent, which looks like a phone in a pocket. - RetiredKinds: 30331-30337 and 30350-30366 stay Bennu's, never reused. - WalletRefusal: what is a wallet's to sign, read by tag name so it outlives the wallet's parsers. approve() declines one instead. - A retired kind is one line or none in the transcript, never a raw bubble. - No Lightning dispatch, no guarded-wallet forwarding, no key answers. - The detail and profile screens and the subgroup picker lose their wallets; a guarded room says why it offers no subgroup (W5), and certificates carry no wallet tags. - The wallet tests this behaviour breaks are deleted with it. jvmTest: 1,495 run, 0 failed, 2 skipped. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 1 + .../giza/compose/database/dao/NostrDao.kt | 59 +- .../compose/database/model/ChatMessage.kt | 85 +- .../compose/managers/FrostSigningManager.kt | 86 +- .../giza/compose/managers/SubgroupManager.kt | 50 +- .../giza/compose/managers/WalletRefusal.kt | 56 ++ .../mobi/giza/compose/nostr/RetiredKinds.kt | 52 ++ .../ui/composable/ActiveProfileScreen.kt | 33 - .../ui/composable/ChatRoomDetailScreen.kt | 337 +------- .../ui/composable/ProfilePreviewScreen.kt | 95 -- .../composable/SelectSubgroupAdminsScreen.kt | 134 --- .../ui/composable/navigation/GizaNavHost.kt | 111 +-- .../composable/widgets/chat/ChatTranscript.kt | 2 + .../ui/view/model/ChatMessageListViewModel.kt | 68 +- .../ui/view/model/ChatRoomDetailViewModel.kt | 59 +- .../model/SelectSubgroupAdminsViewModel.kt | 103 --- .../ui/view/state/ChatRoomDetailUIState.kt | 47 +- .../view/state/SelectSubgroupAdminsUIState.kt | 24 - .../giza/compose/nostr/RetiredKindsTest.kt | 54 ++ .../model/ProtocolKindDispatchJvmTest.kt | 16 + .../GroupLightningCoSigningJvmTest.kt | 340 -------- .../GroupLightningCoSigningMainnetJvmTest.kt | 9 - .../GroupLightningLiquidityJvmTest.kt | 234 ----- .../managers/GroupLightningNodeJvmTest.kt | 260 ------ .../managers/GroupLightningPaymentsJvmTest.kt | 206 ----- .../managers/GroupLightningRekeyJvmTest.kt | 115 --- .../managers/GroupLightningReportsJvmTest.kt | 276 ------ .../GroupLightningSpliceCoSigningJvmTest.kt | 392 --------- .../managers/GroupLightningSweepJvmTest.kt | 133 --- .../managers/GroupLightningWalletJvmTest.kt | 194 ----- .../managers/GroupSpendSigningJvmTest.kt | 529 ------------ .../managers/GuardedWalletForwardJvmTest.kt | 328 ------- .../managers/GuardianSigningJvmTest.kt | 814 ------------------ .../managers/IcebergCeremonyJvmTest.kt | 420 --------- .../managers/SubgroupManagerJvmTest.kt | 285 +----- .../compose/managers/WalletDeclineJvmTest.kt | 243 ++++++ .../ChatRoomDetailWithoutWalletsJvmTest.kt | 111 +++ .../composable/GroupSignedWorkRowsJvmTest.kt | 188 ---- .../composable/ProfilePreviewScreenJvmTest.kt | 32 - .../LightningCeremonyAwaitingYouJvmTest.kt | 171 ---- .../SelectSubgroupAdminsViewModelJvmTest.kt | 181 +--- docs/giza-wallet-removal.md | 12 +- 42 files changed, 721 insertions(+), 6224 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/WalletRefusal.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/RetiredKinds.kt create mode 100644 composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/RetiredKindsTest.kt delete mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningCoSigningJvmTest.kt delete mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningCoSigningMainnetJvmTest.kt delete mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningLiquidityJvmTest.kt delete mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningNodeJvmTest.kt delete mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningPaymentsJvmTest.kt delete mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningRekeyJvmTest.kt delete mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningReportsJvmTest.kt delete mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningSpliceCoSigningJvmTest.kt delete mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningSweepJvmTest.kt delete mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningWalletJvmTest.kt delete mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupSpendSigningJvmTest.kt delete mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GuardedWalletForwardJvmTest.kt delete mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GuardianSigningJvmTest.kt delete mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/IcebergCeremonyJvmTest.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/WalletDeclineJvmTest.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailWithoutWalletsJvmTest.kt delete mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt delete mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/LightningCeremonyAwaitingYouJvmTest.kt diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 7cb3f65b..cb03a75a 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -346,6 +346,7 @@ Key package rotated Subgroups Add subgroup + This group's subgroups must keep guarded wallets. Giza doesn't take part in wallets, so it can't add a subgroup here. No subgroups have been made by this group. Certified, not created yet Created, you aren't a member diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt index 5f983ce4..5e3178dc 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt @@ -1,11 +1,5 @@ package mobi.giza.compose.database.dao -import mobi.giza.compose.managers.GroupLightningOperatorManager -import mobi.giza.compose.managers.GroupLightningCoSigner -import mobi.giza.compose.managers.GroupLightningReports -import mobi.giza.compose.managers.GroupLightningWalletManager -import mobi.giza.compose.nostr.lightning.GroupLightningEvents -import mobi.giza.compose.managers.IcebergRitualManager import androidx.room3.Dao import androidx.room3.Transaction import mobi.giza.compose.database.GENESIS_AT @@ -1604,56 +1598,9 @@ abstract class NostrDao( nostrPrivateKey = activeKeyPair.privKey!! ) - // The Lightning wallet's co-signing: round one ahead of time, - // the operator's requests, every member's echo, the shares. - innerEvent.kind in GroupLightningEvents.CO_SIGNING -> - GroupLightningCoSigner.process( - database = database, - localChatRoom = localChatRoom, - innerEvent = innerEvent, - userPublicKey = activeKeyPair.pubKey.toHex() - ) - - // A member handing out the Lightning wallet's node seed, - // encrypted to each participant inside the room. - innerEvent.kind == GroupLightningEvents.NODE_SEED -> - GroupLightningWalletManager.receiveSeed( - database = database, - localChatRoom = localChatRoom, - innerEvent = innerEvent, - userPublicKey = activeKeyPair.pubKey.toHex(), - nostrPrivateKey = activeKeyPair.privKey!! - ) - - // What the operator says about the Lightning wallet, and the - // invoices it makes for members who ask. - innerEvent.kind == GroupLightningEvents.SNAPSHOT || - innerEvent.kind == GroupLightningEvents.INVOICE || - innerEvent.kind == GroupLightningEvents.INVOICE_REQUEST -> - GroupLightningReports.process( - database = database, - localChatRoom = localChatRoom, - innerEvent = innerEvent, - ) - - // An operator's node stopping: a line, from whoever ran that term. - innerEvent.kind == GroupLightningEvents.STOPPED -> - GroupLightningOperatorManager.receiveStopped( - database = database, - localChatRoom = localChatRoom, - innerEvent = innerEvent, - ) - - // The group Lightning wallet's key ceremony. Marmot only: - // it runs where the onchain wallet it closes to already is. - innerEvent.kind in GroupLightningEvents.CEREMONY -> - IcebergRitualManager.processCeremonyPayload( - database = database, - localChatRoom = localChatRoom, - innerEvent = innerEvent, - userPublicKey = activeKeyPair.pubKey.toHex(), - nostrPrivateKey = activeKeyPair.privKey!! - ) + // Nothing for the group Lightning wallet's kinds: Giza takes no + // part in it, so a Bennu member's ceremony, co-signing and node + // traffic are filed and ignored. docs/giza-wallet-removal.md. } } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt index 48f7016e..c8a1dd4e 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 @@ -1,5 +1,7 @@ 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 @@ -22,8 +24,6 @@ import mobi.giza.compose.database.model.traits.TimestampedEntity import mobi.giza.compose.database.model.traits.UserViewableEntity import mobi.giza.compose.exceptions.MarmotUnprocessableInnerEventException import mobi.giza.compose.managers.ChronicleManager -import mobi.giza.compose.managers.MemberWalletManager -import mobi.giza.compose.nostr.wallet.GroupKeyNoticeEvent import mobi.giza.compose.nostr.wallet.MemberWalletCertificateEvent import mobi.giza.compose.nostr.wallet.MemberWalletRequestEvent import mobi.giza.compose.managers.GroupKeyStateManager @@ -482,6 +482,15 @@ data class ChatMessage( */ const val TYPE_SUBGROUP_CERTIFIED = "subgroupCertified" + /** + * A Bennu member's group having signed something that announces a wallet -- a + * group wallet, a member's guarded wallet, a Lightning wallet -- in a room this + * device is in. Giza has no wallet and signs for none (docs/giza-wallet-removal.md), + * so this is the one line it writes about one, and it says that. The rest of a + * wallet's traffic is no line at all. + */ + const val TYPE_WALLET_NOT_TAKEN_PART_IN = "walletNotTakenPartIn" + /** * Lines the curated-lists feature wrote: the group signing a list's schema, * and an entry into one. The feature is gone and nothing writes either any @@ -574,6 +583,7 @@ data class ChatMessage( TYPE_MEMBER_WALLET_REQUESTED, TYPE_MEMBER_WALLET_GUARDED, TYPE_MEMBER_WALLET_POLICY, + TYPE_WALLET_NOT_TAKEN_PART_IN, ) /** The lines in [GROUP_IDENTITY_TYPES] about the Lightning wallet, which open its screen. */ @@ -1125,33 +1135,6 @@ data class ChatMessage( return null } - // A descendant's guarded wallet, carried up by a member who is in - // both rooms. The row above is the whole record of it -- there is - // no table -- so all that is left is the line, and only for a - // notice this room can actually believe. - if (event.kind == GuardedWalletNoticeEvent.KIND) { - // And on, a generation further: the statement inside, to - // the groups above this one that this device is in. Any - // device that believes it can, whether or not it holds this - // room's key. docs/guarded-wallet-forwarding.md. - GuardedWalletNoticeEvent.statementOf(event)?.let { - GuardianManager.forwardOnArrival(database, it, groupEventResult.groupId) - } - val content = GuardianManager.describeNotice(database, groupEventResult.groupId, event) - ?: return null - return ChatMessage( - giftWrapPayloadId = null, - messageType = TYPE_GUARDED_WALLET_SHARED, - marmotGroupEventId = groupEvent.id, - marmotInnerEventId = event.id, - senderPublicKey = senderIdentity ?: event.pubKey, - isUserMessage = senderIdentity == activeKeyPair.pubKey.toHex(), - chatRoomId = groupEventResult.groupId, - createdAt = Instant.fromEpochSeconds(event.createdAt), - content = content, - ) - } - // Somebody in the room holds none of its signed work and is // asking. Any member may answer and none is elected to: a // duplicate answer costs bandwidth and nothing else, since @@ -1172,23 +1155,6 @@ data class ChatMessage( return null } - // A member asking what the group signs with, so their device - // can work out a guarded wallet's leaves, or a member - // answering. Plumbing, so no line either way: the row above - // is the record, and an answer is checked each time it is - // read. Answered like the chronicle's request -- by any - // member holding the key state, none elected. - // docs/member-guarded-wallets.md, Phase 2. - if (event.kind == GroupKeyNoticeEvent.KIND) { - MemberWalletManager.answerKeyRequest( - database = database, - chatRoomId = groupEventResult.groupId, - request = event, - userPublicKey = activeKeyPair.pubKey.toHex(), - ) - - return null - } applyInnerEvent( database = database, @@ -1483,9 +1449,6 @@ data class ChatMessage( // checks it there again. MemberWalletCertificateEvent.KIND -> { val verified = MemberWalletCertificateEvent.verify(event, groupId) ?: return null - // The groups above this one guard the wallet too, and learn - // of it only by being told. docs/guarded-wallet-forwarding.md. - GuardianManager.forwardOnArrival(database, event, groupId) ChatMessage( giftWrapPayloadId = null, @@ -1536,9 +1499,6 @@ data class ChatMessage( val thresholdPublicKey = GroupWalletManager.thresholdKeyFor(database, groupId) ?: return null val wallet = GroupWallet.of(signed, thresholdPublicKey) ?: return null - // A guarded wallet is one the groups above can find only by - // being told of it. docs/guarded-wallet-forwarding.md. - if (wallet.account.isGuarded) GuardianManager.forwardOnArrival(database, event, groupId) ChatMessage( giftWrapPayloadId = null, @@ -1641,6 +1601,27 @@ data class ChatMessage( // which is the only trace an unrecognised payload leaves. MarmotAppEvent.KIND_SYSTEM, MarmotAppEvent.KIND_EDIT -> null + // Bennu's wallets, which a Bennu member can bring into a room this + // device shares. What announces one is a line saying Giza takes no part; + // everything else -- the wallet's protocol and its traffic -- is none, + // rather than the raw-JSON bubble an unknown kind gets. Kinds with arms + // of their own above are still read by them until those arms go + // (docs/giza-wallet-removal.md, Phases 1-4). + in RetiredKinds.WALLET, in RetiredKinds.GROUP_LIGHTNING -> + if (event.kind in RetiredKinds.ANNOUNCEMENTS) { + ChatMessage( + giftWrapPayloadId = null, + messageType = TYPE_WALLET_NOT_TAKEN_PART_IN, + marmotGroupEventId = marmotGroupEventId, + marmotInnerEventId = marmotInnerEventId, + senderPublicKey = senderPublicKey, + isUserMessage = isUserMessage, + chatRoomId = groupId, + createdAt = createdAt, + content = "The group signed a wallet into being. Giza doesn't take part in wallets" + ) + } else null + else -> unsupported() } } 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 376122b4..b8d8bbef 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt @@ -442,6 +442,13 @@ object FrostSigningManager { return } + // A transaction or a sweep is a wallet's to sign, and Giza declines every one + // (docs/giza-wallet-removal.md, Phase 1). Filed first, by the code that has + // always filed them, so the decline goes out through [advance] like any other. + if (FrostSigningEvents.isProposal(innerEvent.kind) && declinesAsWallet(database, session)) { + update(database, session) { it.copy(signDeclinedAt = Clock.System.now()) } + } + if (session.stage == FrostSigningStage.FAILED) { logger.i("Session $sessionId already failed; ignoring kind ${innerEvent.kind}") return @@ -468,6 +475,29 @@ object FrostSigningManager { advance(database, localChatRoom, session.id) } + private fun newSession( + sessionId: String, + localChatRoom: LocalChatRoom, + innerEvent: Event, + userPublicKey: HexKey, + key: DkgSession, + signerId: Int, + path: List? + ) = FrostSigningSession( + id = sessionId, + chatRoomId = localChatRoom.chatRoom.id, + // Whoever proposes coordinates. Aggregating nonces and partial + // signatures gives no power over the outcome -- a wrong aggregate + // produces a signature that does not verify, not a forged one. + coordinatorPublicKey = innerEvent.pubKey, + userPublicKey = userPublicKey, + dkgSessionId = key.id, + threshold = key.threshold, + participantCount = key.participantCount, + signerId = signerId, + derivationPath = path?.let(SharedKeyDerivation::formatPath) + ) + /** * Records a proposal. Returns the session, whether it was just created or * already known. @@ -569,6 +599,22 @@ object FrostSigningManager { } } + // A wallet's to sign: declined on arrival, and said out loud so the group + // counts it. Giza can no longer check a spend, a member wallet or a guarded + // subgroup, and a device that signs what it cannot check is a rubber stamp. + // Filed as a session so that [advance] publishes the decline the way it + // publishes any other -- and again after a crash, until a copy is on file. + // docs/giza-wallet-removal.md, Phase 1. + WalletRefusal.of(unsignedEvents)?.let { why -> + logger.w("Signing proposal $sessionId $why; declining") + val declined = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path) + .copy(signDeclinedAt = Clock.System.now()) + database.frostSigningSessionDao().upsert(declined) + database.frostSigningSessionDao().upsertItems(itemsOver(sessionId, unsignedEvents)) + announceStarted(database, declined) + return declined + } + // A birth certificate's guardian keys are a promise by the group signing // it, so they have to be the keys it grants: recomputed here from the key // this session signs with and the group's own certificate, never taken @@ -636,20 +682,7 @@ object FrostSigningManager { } } - val session = FrostSigningSession( - id = sessionId, - chatRoomId = localChatRoom.chatRoom.id, - // Whoever proposes coordinates. Aggregating nonces and partial - // signatures gives no power over the outcome -- a wrong aggregate - // produces a signature that does not verify, not a forged one. - coordinatorPublicKey = innerEvent.pubKey, - userPublicKey = userPublicKey, - dkgSessionId = key.id, - threshold = key.threshold, - participantCount = key.participantCount, - signerId = signerId, - derivationPath = path?.let(SharedKeyDerivation::formatPath) - ) + val session = newSession(sessionId, localChatRoom, innerEvent, userPublicKey, key, signerId, path) database.frostSigningSessionDao().upsert(session) database.frostSigningSessionDao().upsertItems(itemsOver(sessionId, unsignedEvents)) announceStarted(database, session) @@ -1795,6 +1828,19 @@ object FrostSigningManager { return true } + /** Whether [session] is waiting on this device and is a wallet's to sign. */ + private suspend fun declinesAsWallet(database: GizaDatabase, session: FrostSigningSession): Boolean = + session.signApprovedAt == null && session.signDeclinedAt == null && + isWalletSession(session, database.frostSigningSessionDao().getItems(session.id)) + + /** + * A transaction, a sweep, or events [WalletRefusal] says are a wallet's: what this + * device declines rather than signs. docs/giza-wallet-removal.md, Phase 1. + */ + private fun isWalletSession(session: FrostSigningSession, items: List): Boolean = + session.subject != FrostSigningSubject.EVENTS || + items.any { item -> Event.fromJsonOrNull(item.unsignedEventJson)?.let(WalletRefusal::of) != null } + private fun isFromCoordinator( session: FrostSigningSession, innerEvent: Event @@ -2839,6 +2885,15 @@ object FrostSigningManager { return } + // Nothing should be asking, since [processSigningPayload] declines these on arrival. This is + // the backstop, for a session filed before it did. + if (isWalletSession(session, items)) { + logger.w("Session $sessionId is a wallet's to sign, and this device declines those; declining") + update(database, session) { it.copy(signDeclinedAt = Clock.System.now()) } + advance(database, localChatRoom, sessionId) + return + } + update(database, session) { it.copy(signApprovedAt = Clock.System.now()) } logger.i("Session $sessionId: signing approved") @@ -3329,7 +3384,8 @@ object FrostSigningManager { localChatRoom: LocalChatRoom, session: FrostSigningSession ) { - val reason = "Declined to sign" + val items = database.frostSigningSessionDao().getItems(session.id) + val reason = if (isWalletSession(session, items)) WalletRefusal.REASON else "Declined to sign" broadcast( database = database, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/SubgroupManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/SubgroupManager.kt index fd11aba8..067993eb 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/SubgroupManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/SubgroupManager.kt @@ -249,43 +249,15 @@ object SubgroupManager { "$parentChatRoomId has already certified $subgroupChatRoomId" } - // What the child's wallet is to be. A guarded parent can only make guarded - // subgroups, and every one of its signers refuses anything else -- so an - // unguarded ceremony under one is stranded, and proposing it would only - // spend a quorum's attention. It is not quietly certified as guarded - // instead: its admins joined on the understanding it would not be, and - // every child signer refuses a certificate that says otherwise. An older - // build's ceremony carried no policy and showed its admins none, so under - // a guarded parent the certificate says the only thing its signers accept. - val parentGuarded = walletPolicyOf(database, parentChatRoomId).isDecided(SubgroupWalletPolicy.GUARDED) - val walletPolicy = when (key.subgroupWalletPolicy) { - SubgroupWalletPolicy.UNGUARDED -> { - check(!parentGuarded) { - "This group is guarded, so its subgroups are too. Start the subgroup again: " + - "its admins joined it as unguarded." - } - SubgroupWalletPolicy.UNGUARDED - } - SubgroupWalletPolicy.GUARDED -> SubgroupWalletPolicy.GUARDED - null -> SubgroupWalletPolicy.GUARDED.takeIf { parentGuarded } - } - - // The parent's guardian keys for the child: its own, and the ones its - // ancestors granted it -- or none, for an unguarded child, whose - // certificate then grants nothing to it or to anything beneath it. Every - // signer recomputes this list and refuses a certificate carrying any - // other -- see [refuseCertificate]. - val guardians = if (walletPolicy == SubgroupWalletPolicy.UNGUARDED) { - emptyList() - } else { - val parentKey = FrostSigningManager.completedKey(database, parentChatRoomId)?.thresholdPublicKey - ?: throw IllegalStateException("$parentChatRoomId has no key to grant a guardian key under") - // The parent's own leaf's delay as its coordinator chose it, or the - // default an older build's ceremony would have written. Every - // inherited key keeps the delay its own ancestor chose. - // docs/guardian-delay.md. - grantFor(database, parentChatRoomId, parentKey, subgroupChatRoomId, key.guardianDelay ?: GuardianDerivation.DEFAULT_DELAY) - ?: throw IllegalStateException("$parentChatRoomId's own certificate carries guardian keys this build cannot read") + // A plain subgroup: no wallet policy and no guardian keys, which is what a + // certificate from before policies carried and what every client accepts + // under a parent that decided nothing about wallets. Under one that decided + // `guarded` every Bennu signer refuses it, so it is not proposed at all. + // docs/giza-wallet-removal.md, W5. + val parentCertificate = database.groupKeyStateDao().getByChatRoomId(parentChatRoomId) + ?.birthCertificateJson?.let { Event.fromJsonOrNull(it) } + check(parentCertificate == null || !WalletRefusal.isGuarded(parentCertificate)) { + "This group's subgroups must keep guarded wallets, and Giza doesn't take part in wallets." } logger.i("Asking $parentChatRoomId to certify $subgroupChatRoomId as its subgroup") @@ -302,8 +274,8 @@ object SubgroupManager { adminPublicKeys = adminPublicKeys, name = subgroupName, path = path, - guardians = guardians, - walletPolicy = walletPolicy + guardians = emptyList(), + walletPolicy = null ), content = subgroupChatRoomId ) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/WalletRefusal.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/WalletRefusal.kt new file mode 100644 index 00000000..29fad5cd --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/WalletRefusal.kt @@ -0,0 +1,56 @@ +package mobi.giza.compose.managers + +import com.vitorpamplona.quartz.nip01Core.core.Event +import mobi.giza.compose.nostr.RetiredKinds +import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent + +/** + * What Giza declines to sign, now that it has no wallet (docs/giza-wallet-removal.md, + * Phase 1). + * + * A Bennu member can share a group with a Giza member and put a wallet to it: a spend, a + * guarded member wallet, a guarded subgroup. Giza used to check each of these before it + * signed. With that code gone it can check none of them, and a device that signs what it + * cannot check is a rubber stamp -- in a 2-of-3 group, one Giza approval and one dishonest + * Bennu member are a quorum. So it fails closed: it declines, out loud, so the group counts + * the refusal rather than waiting on a member who will never answer. + * + * Read from the tags as they are on the wire, by name, rather than through the wallet's + * own parsers -- this has to keep working after those are deleted. + */ +object WalletRefusal { + /** What a decline says, on the wire and in this device's transcript. */ + const val REASON = "Giza doesn't sign for wallets" + + private const val GUARDIAN_TAG = "guardian" + private const val WALLET_TAG = "wallet" + private const val UNGUARDED = "unguarded" + private const val GUARDED = "guarded" + + /** + * Why [events] are a wallet's to sign, or null when they are not. A birth certificate + * is one when it grants guardian keys or decides anything but `unguarded`: a plain + * certificate is the group making a subgroup, which Giza still does. + */ + fun of(events: List): String? = events.firstNotNullOfOrNull(::of) + + /** + * Whether a birth certificate decided its subgroup is guarded: a `wallet` tag saying + * `guarded`. A Bennu signer refuses an unguarded child of such a group + * (`refuseCertificate` in Bennu's SubgroupManager), so Giza does not offer to make one + * (W5). Guardian keys alone, on a certificate from before policies, decide nothing, + * and Bennu lets such a group make a plain child. + */ + fun isGuarded(certificate: Event): Boolean = + certificate.tags.any { it.firstOrNull() == WALLET_TAG && it.getOrNull(1) == GUARDED } + + fun of(event: Event): String? = when { + RetiredKinds.isRetired(event.kind) -> "is a wallet's (kind ${event.kind})" + event.kind == SubgroupBirthCertificateEvent.KIND && event.tags.any { it.firstOrNull() == GUARDIAN_TAG } -> + "grants guardian keys over a subgroup's wallet" + event.kind == SubgroupBirthCertificateEvent.KIND && + event.tags.any { it.firstOrNull() == WALLET_TAG && it.getOrNull(1) != UNGUARDED } -> + "decides a subgroup's wallet" + else -> null + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/RetiredKinds.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/RetiredKinds.kt new file mode 100644 index 00000000..e983c558 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/RetiredKinds.kt @@ -0,0 +1,52 @@ +package mobi.giza.compose.nostr + +import com.vitorpamplona.quartz.nip01Core.core.Kind + +/** + * The kinds Bennu's wallets put on the wire, which Giza no longer reads, writes or signs + * -- and which it never gives to anything else (docs/giza-wallet-removal.md). + * + * Retired, not freed. Bennu goes on using every one of them, and a Bennu member can share + * a group with a Giza member. A Giza kind put on one of these numbers would be read by + * every Bennu peer as a wallet message, which is how the nip30303 documents and the key + * ceremony came to collide (docs/ceremony-creation.md, F13). `RetiredKindsTest` fails if a + * live kind set ever overlaps them. + * + * Written out rather than read from the wallet's own classes, for the reason a migration + * writes out its constants: this has to keep meaning what it means after those classes + * are deleted. + */ +object RetiredKinds { + /** + * The group's on-chain wallet, its member wallets and the guardian notices: + * + * - 30331 a group wallet statement, which the group signs; + * - 30332 a signing proposal over a transaction or a sweep (the `chain`, `account`, + * `sweep` and `guarded` tags ride it); + * - 30333 a guarded wallet notice; + * - 30334 a member wallet certificate, which the group signs; + * - 30335 a member wallet request; + * - 30336 a member wallet key notice; + * - 30337 a member wallet policy, which the group signs. + */ + val WALLET: IntRange = 30331..30337 + + /** + * The group Lightning wallet: its Iceberg ceremony (30350-30354), its statements and + * authorisations (30355, 30356, 30363, which the group signs), the node seed (30357), + * co-signing (30358-30361) and the operator's traffic (30362, 30364-30366). + */ + val GROUP_LIGHTNING: IntRange = 30350..30366 + + /** A signing proposal over a transaction or a sweep, rather than over events. */ + const val TRANSACTION_PROPOSAL: Kind = 30332 + + /** + * The kinds that announce a wallet, rather than run one: what the group signed to open + * a wallet, guard a member's, or open a Lightning wallet. One of these arriving in a + * room is the only one worth a line; the rest of the traffic is silent. + */ + val ANNOUNCEMENTS: Set = setOf(30331, 30334, 30355) + + fun isRetired(kind: Kind): Boolean = kind in WALLET || kind in GROUP_LIGHTNING +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ActiveProfileScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ActiveProfileScreen.kt index 61319c98..affa6a83 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ActiveProfileScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ActiveProfileScreen.kt @@ -1,10 +1,5 @@ package mobi.giza.compose.ui.composable -import mobi.giza.compose.repository.MemberWalletRepository -import mobi.giza.compose.wallet.GroupOnchainWallets -import mobi.giza.compose.ui.view.model.MemberWalletsViewModel -import mobi.giza.compose.ui.composable.navigation.routes.MemberWalletRoute -import mobi.giza.compose.ui.composable.navigation.routes.NewMemberWalletRoute import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row @@ -37,7 +32,6 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import mobi.giza.compose.database.model.NostrEvent import mobi.giza.compose.database.model.intermdiate.LocalNostrEvent @@ -78,7 +72,6 @@ import mobi.giza.compose.ui.view.model.SignOutViewModel import kotlinx.coroutines.flow.StateFlow import androidx.compose.runtime.collectAsState import androidx.compose.runtime.rememberCoroutineScope -import mobi.giza.compose.resources.something_went_wrong import mobi.giza.compose.resources.we_couldn_t_find_the_local_profile_please import mobi.giza.compose.ui.composable.widgets.ErrorState import androidx.compose.material3.SnackbarHost @@ -104,11 +97,6 @@ fun ActiveProfileScreen( // an identity to sign out of (previews, tests), in which case the button keeps its // pending route for every kind. signOut: SignOutDependencies? = null, - // The member's guarded wallets (docs/member-guarded-wallets.md). The no-op - // repository lists none, and null wallets watch nothing: both for previews - // and tests, which compose the screen without an identity. - memberWalletRepository: MemberWalletRepository = MemberWalletRepository.NO_OP, - wallets: GroupOnchainWallets? = null, ) { // Whether this identity can sign, which decides which rows below exist. @@ -140,16 +128,6 @@ fun ActiveProfileScreen( if (signOutState is SignOutViewModel.State.Failed) notify(couldNotSignOut) } - val memberWalletsViewModel: MemberWalletsViewModel = viewModel( - factory = MemberWalletsViewModel.factory( - ownerPublicKey = activeUserPublicKey, - memberWalletRepository = memberWalletRepository, - wallets = wallets, - ), - ) - // Each time the profile is shown: a certificate can arrive while it is not. - LaunchedEffect(true) { memberWalletsViewModel.refresh() } - val activeProfileViewModel: ActiveProfileViewModel = viewModel( factory = ActiveProfileViewModel.factory( nostrEventId = nostrEventId, @@ -292,17 +270,6 @@ fun ActiveProfileScreen( } } - memberWalletItems( - rows = memberWalletsViewModel.rows, - onOpen = { walletId -> - onNavigateToRoute.invoke(MemberWalletRoute(activeUserPublicKey = activeUserPublicKey, walletId = walletId)) - }, - // A read-only identity cannot sign a request, so it is not offered one. - onNew = if (canSign) { - { onNavigateToRoute.invoke(NewMemberWalletRoute(activeUserPublicKey = activeUserPublicKey)) } - } else null, - ) - // Key packages are signed, and there is nothing to recover for // an identity the device holds no secret for: neither row for a // read-only identity. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt index 7405b389..472db605 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt @@ -1,47 +1,7 @@ package mobi.giza.compose.ui.composable -import androidx.compose.material.icons.filled.Bolt -import mobi.giza.compose.resources.lightning_wallet -import mobi.giza.compose.resources.lightning_needs_an_onchain_wallet -import mobi.giza.compose.resources.member_removal_requested_lightning -import mobi.giza.compose.ui.composable.navigation.routes.GroupLightningWalletRoute -import mobi.giza.compose.wallet.GroupLightningRollout -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Box -import mobi.giza.compose.resources.change -import mobi.giza.compose.resources.guard_members_wallets -import mobi.giza.compose.nostr.wallet.MemberWalletPolicyEvent -import mobi.giza.compose.ui.composable.navigation.routes.MemberWalletPolicyRoute -import mobi.giza.compose.resources.guarded_wallet_after -import mobi.giza.compose.ui.composable.widgets.delayText -import mobi.giza.compose.managers.MemberWalletManager -import mobi.giza.compose.repository.MemberWalletRepository -import mobi.giza.compose.ui.composable.navigation.routes.NewMemberWalletRoute -import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute -import mobi.giza.compose.resources.members_guarded_wallets -import mobi.giza.compose.resources.ask_this_group_to_guard_a_wallet_for_you -import mobi.giza.compose.resources.asked_by_s_not_yet_signed -import mobi.giza.compose.resources.put_to_the_group -import mobi.giza.compose.resources.couldn_t_put_it_to_the_group -import mobi.giza.compose.resources.at_s -import mobi.giza.compose.resources.s_dot_s -import androidx.compose.material.icons.filled.AccountBalanceWallet import androidx.compose.material3.ListItem -import androidx.compose.material3.ListItemDefaults -import androidx.compose.material3.minimumInteractiveComponentSize -import androidx.compose.foundation.clickable import androidx.compose.ui.text.style.TextOverflow -import mobi.giza.compose.resources.unguarded_wallet -import mobi.giza.compose.resources.guarded_wallet -import mobi.giza.compose.nostr.subgroup.WalletPolicyReading -import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy -import mobi.giza.compose.wallet.GroupWalletRollout -import mobi.giza.compose.ui.composable.navigation.routes.GroupWalletRoute -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import mobi.giza.compose.resources.open_on_s -import mobi.giza.compose.resources.not_opened_yet -import mobi.giza.compose.resources.group_wallet -import mobi.giza.compose.resources.s_onchain_wallet import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer @@ -65,7 +25,6 @@ import androidx.compose.material.icons.filled.PersonRemove import androidx.compose.material.icons.filled.Draw import androidx.compose.material.icons.filled.PersonAdd import androidx.compose.material.icons.filled.Unsubscribe -import androidx.compose.material.icons.filled.WaterfallChart import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Card import androidx.compose.material3.CircularProgressIndicator @@ -90,7 +49,6 @@ import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalClipboardManager import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.font.FontFamily @@ -131,6 +89,7 @@ import mobi.giza.compose.resources.certified_not_yet_created import mobi.giza.compose.resources.no_subgroups_have_been_made_by_this_group import mobi.giza.compose.resources.add_subgroup import mobi.giza.compose.resources.subgroups +import mobi.giza.compose.resources.subgroups_of_this_group_need_a_wallet import mobi.giza.compose.ui.composable.navigation.routes.SelectSubgroupAdminsRoute import mobi.giza.compose.ui.composable.navigation.routes.NostrEventDetailRoute import mobi.giza.compose.ui.composable.navigation.routes.ChatRoomDetailRoute @@ -182,7 +141,6 @@ fun ChatRoomDetailScreen( initialChatRoomDetailUIState: ChatRoomDetailUIState = ChatRoomDetailUIState.Loading, nostrRepository: NostrRepository, chatRepository: ChatRepository, - memberWalletRepository: MemberWalletRepository = MemberWalletRepository.NO_OP, onNavigateToRoute: (Route) -> Unit, onPopBackToRoute: (Route) -> Unit, onNavigateBack: () -> Unit, @@ -195,16 +153,13 @@ fun ChatRoomDetailScreen( nostrRepository = nostrRepository, chatRepository = chatRepository, activeUserPublicKey = activeUserPublicKey, - memberWalletRepository = memberWalletRepository, ) ) - val couldNotPutToGroup = stringResource(Res.string.couldn_t_put_it_to_the_group) // Read outside the click handlers: stringResource and rememberNotifier are both // composable, and a lambda passed to onClick is not. val notify = rememberNotifier(rememberCoroutineScope()) val removalRequested = stringResource(Res.string.member_removal_requested) - val removalLeavesLightningShare = stringResource(Res.string.member_removal_requested_lightning) ScreenStateTransition(chatRoomDetailViewModel.chatRoomDetailUIState) { uiState -> when (val chatRoomDetailUIState = uiState) { @@ -339,11 +294,6 @@ fun ChatRoomDetailScreen( maxLines = 1, overflow = TextOverflow.MiddleEllipsis ) - // What the parent decided about - // this room's wallet at its birth. - // Nothing for one that decided - // nothing, as before policies. - walletPolicyLabel(chatRoomDetailUIState.walletPolicy, chatRoomDetailUIState.guardianDelay)?.let { Text(it) } } } ) @@ -365,76 +315,6 @@ fun ChatRoomDetailScreen( HorizontalDivider() } - // The group's coins, signed by the room's key and read - // by nobody outside the room: the statement opening it - // never leaves the group. Shown to every member, open - // or not -- the screen behind it is where a member who - // can sign asks the group to open one. - // - // Marmot rooms only, and absent rather than empty in a - // NIP-17 one. A NIP-17 room's id is not a key it can - // sign as, so it has no wallet to open. - if ( - GroupWalletRollout.ENABLED && - chatRoomDetailUIState.localChatRoom.chatRoom.mlsGroupState != null - ) { - item { - SignedWorkRow( - icon = Icons.Default.AccountBalanceWallet, - headline = chatRoomDetailUIState.localChatRoom.chatRoom.subject - ?.let { stringResource(Res.string.s_onchain_wallet, it) } - ?: stringResource(Res.string.group_wallet), - supporting = chatRoomDetailUIState.groupWallet?.let { wallet -> - stringResource( - Res.string.open_on_s, - GroupWalletStatementEvent.chainName(wallet.chain) - ) - } ?: stringResource(Res.string.not_opened_yet), - onOpen = { - onNavigateToRoute.invoke( - GroupWalletRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - ) - } - - // The group's Lightning wallet, which closes to the onchain - // wallet -- the row above this one, on the same network. - // Its key is made by the onchain wallet's signers and its - // channels close to that wallet, so until the group has - // opened one there is nothing behind this row: it stays, - // disabled, and says what it is waiting for. - if (GroupLightningRollout.ENABLED) item { - val hasOnchainWallet = chatRoomDetailUIState.groupWallet != null - SignedWorkRow( - icon = Icons.Default.Bolt, - headline = stringResource(Res.string.lightning_wallet), - supporting = if (hasOnchainWallet) { - GroupWalletStatementEvent.chainName(GroupLightningRollout.NETWORK) - } else { - stringResource(Res.string.lightning_needs_an_onchain_wallet) - }, - enabled = hasOnchainWallet, - onOpen = { - onNavigateToRoute.invoke( - GroupLightningWalletRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId - ) - ) - } - ) - } - - item { - HorizontalDivider() - } - } - item { Text( text = stringResource(Res.string.subgroups), @@ -480,7 +360,20 @@ fun ChatRoomDetailScreen( // certificate session, and the room is a Marmot one, so // there is a group with admins to be a parent. Hidden // rather than disabled, the way the shared key entry is. - if (chatRoomDetailUIState.canAddSubgroup) { + // A guarded group's subgroups have to be guarded, which Giza + // cannot do: a Bennu signer refuses an unguarded child of a + // guarded parent, so the ceremony could never finish. Said + // rather than hidden, since the reason is not obvious. + // docs/giza-wallet-removal.md, W5. + if (chatRoomDetailUIState.subgroupsNeedAWallet) { + item { + Text( + text = stringResource(Res.string.subgroups_of_this_group_need_a_wallet), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } else if (chatRoomDetailUIState.canAddSubgroup) { item { TextButton( onClick = { @@ -507,79 +400,6 @@ fun ChatRoomDetailScreen( } } - // A member's wallet is a person, not a room, so it is its - // own section and its row opens the person -- there is no - // chat to open. docs/member-guarded-wallets.md, Phase 11. - if (chatRoomDetailUIState.memberWallets.isNotEmpty() || chatRoomDetailUIState.canAskForMemberWallet || chatRoomDetailUIState.showsMemberWalletPolicy) { - item { HorizontalDivider() } - item { - Text( - text = stringResource(Res.string.members_guarded_wallets), - style = MaterialTheme.typography.labelMedium - ) - } - // Whether the group guards members' wallets at all, and at - // what delay -- first, because every row under it is a - // wallet it agreed to under one. docs/member-wallet-delay.md. - if (chatRoomDetailUIState.showsMemberWalletPolicy) { - item { - MemberWalletPolicyRow( - policy = chatRoomDetailUIState.memberWalletPolicy, - onChange = if (chatRoomDetailUIState.canSponsor) { - { - onNavigateToRoute.invoke( - MemberWalletPolicyRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId) - ) - } - } else null, - ) - } - } - items( - items = chatRoomDetailUIState.memberWallets, - key = { "member-wallet-" + it.walletId } - ) { wallet -> - MemberWalletRow( - wallet = wallet, - isPending = chatRoomDetailViewModel.isActionPending.value, - onOpen = { - onNavigateToRoute.invoke( - ProfilePreviewRoute(activeUserPublicKey = activeUserPublicKey, profilePublicKey = wallet.ownerPublicKey) - ) - }, - onPutToGroup = if (!wallet.isCertified && chatRoomDetailUIState.canSponsor) { - { - chatRoomDetailViewModel.putToGroup( - request = wallet.request, - onSuccess = { sessionId -> - onNavigateToRoute.invoke( - FrostSigningRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, sessionId = sessionId) - ) - }, - onFailure = { notify(couldNotPutToGroup) }, - ) - } - } else null, - ) - } - if (chatRoomDetailUIState.canAskForMemberWallet) { - item { - TextButton( - onClick = { - onNavigateToRoute.invoke(NewMemberWalletRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId)) - } - ) { - Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125)) - Text(stringResource(Res.string.ask_this_group_to_guard_a_wallet_for_you)) - } - } - } - } - - item { - HorizontalDivider() - } item { Text( @@ -729,10 +549,7 @@ fun ChatRoomDetailScreen( localChatRoom = chatRoomDetailUIState.localChatRoom, memberPublicKey = memberPublicKey, ) { failure -> - // They keep a share of the Lightning wallet's key and its seed: say so, - // since only a new wallet takes it from them (Phase 14). - val holdsShare = memberPublicKey.lowercase() in chatRoomDetailUIState.lightningParticipants - notify(failure ?: if (holdsShare) removalLeavesLightningShare else removalRequested) + notify(failure ?: removalRequested) } } ) { @@ -1131,85 +948,6 @@ internal fun GroupKeyStateSheetContent( } } -/** - * One row for a kind of statement the group has signed: a line summarising it, - * and the way to the screen where it is read in full. - * - * The same shape as the signing key and parent group rows above it -- a card - * with a leading icon and a trailing chevron -- because it is the same kind of - * thing: a fact about the group, opened by tapping. The icons are decorative - * because the headline beside each says what the row is, and the chevron says - * only what every card on this screen already says by being one. - */ -@Composable -private fun SignedWorkRow( - icon: ImageVector, - headline: String, - supporting: String, - enabled: Boolean = true, - onOpen: () -> Unit -) { - Card(modifier = Modifier.fillMaxWidth(), onClick = onOpen, enabled = enabled) { - ListItem( - // A disabled row dims its headline and icon to M3's 38%, but not its - // supporting text, which is where it says why it is disabled. - colors = if (enabled) ListItemDefaults.colors() else ListItemDefaults.colors( - headlineColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f), - leadingIconColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f), - ), - leadingContent = { - Icon(icon, contentDescription = Decorative) - }, - trailingContent = if (enabled) { - { Icon(Icons.Default.ChevronRight, contentDescription = Decorative) } - } else null, - headlineContent = { - Text(text = headline) - }, - supportingContent = { - Text( - text = supporting, - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - } - ) - } -} - -/** - * One member's guarded wallet, as the guarding group's page lists it: the - * person, by the live name of their profile, and the label they gave it. A - * request no signer has put to the group yet says so, and offers the one thing - * a signer can do about it. - */ -@Composable -private fun MemberWalletRow( - wallet: MemberWalletManager.GroupMemberWallet, - isPending: Boolean, - onOpen: () -> Unit, - onPutToGroup: (() -> Unit)?, -) { - val name = stringResource(Res.string.at_s, wallet.ownerName ?: wallet.ownerPublicKey.take(8)) - ListItem( - modifier = Modifier.clickable(onClick = onOpen).minimumInteractiveComponentSize(), - leadingContent = { Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) }, - headlineContent = { - Text( - text = wallet.label?.let { stringResource(Res.string.s_dot_s, name, it) } ?: name, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - }, - supportingContent = if (wallet.isCertified) null else { - { Text(stringResource(Res.string.asked_by_s_not_yet_signed, name)) } - }, - trailingContent = onPutToGroup?.let { put -> - { TextButton(onClick = put, enabled = !isPending) { Text(stringResource(Res.string.put_to_the_group)) } } - }, - ) -} - /** * One subgroup, as the parent's record and this device's rooms together have it. * @@ -1256,55 +994,12 @@ private fun SubgroupCard( else -> stringResource(Res.string.created_you_are_not_a_member) } ) - // What the parent decided about its wallet, from the certificate: - // founding history, like the name the row falls back to. - walletPolicyLabel(subgroup.walletPolicy, subgroup.guardianDelay)?.let { Text(it) } } } ) } } -/** - * The group's own stand on its members' wallets, with *Change* -- or *Guard - * members' wallets* when it has none open -- for a device that can put a change - * to the group. `docs/member-wallet-delay.md`, Phase 6. - */ -@Composable -private fun MemberWalletPolicyRow(policy: MemberWalletPolicyEvent.Policy?, onChange: (() -> Unit)?) { - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - ) { - Box(modifier = Modifier.weight(1f)) { MemberWalletPolicyState(policy) } - onChange?.let { change -> - TextButton(onClick = change) { - Text( - stringResource( - if (policy is MemberWalletPolicyEvent.Policy.Open) Res.string.change else Res.string.guard_members_wallets - ) - ) - } - } - } -} - -/** - * *Guarded wallet, after 144 blocks, about 1 day* or *Unguarded wallet* for a - * policy a parent decided, and null for one it left to the subgroup -- - * `docs/subgroup-wallet-policy.md`. The delay is the parent's own leaf's, - * `docs/guardian-delay.md`. - */ -@Composable -private fun walletPolicyLabel(policy: WalletPolicyReading?, guardianDelay: Long?): String? = when (policy) { - WalletPolicyReading.Decided(SubgroupWalletPolicy.GUARDED) -> guardianDelay - ?.let { stringResource(Res.string.guarded_wallet_after, delayText(it)) } - ?: stringResource(Res.string.guarded_wallet) - WalletPolicyReading.Decided(SubgroupWalletPolicy.UNGUARDED) -> stringResource(Res.string.unguarded_wallet) - else -> null -} - /** One labelled value of a key state, whole and comparable. */ @Composable private fun GroupKeyStateField( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ProfilePreviewScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ProfilePreviewScreen.kt index 9b3d92ad..0a1a7dc0 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ProfilePreviewScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ProfilePreviewScreen.kt @@ -1,23 +1,6 @@ package mobi.giza.compose.ui.composable -import mobi.giza.compose.repository.MemberWalletRepository -import mobi.giza.compose.managers.MemberWalletManager -import mobi.giza.compose.ui.view.model.PersonGuardedWalletsViewModel -import mobi.giza.compose.ui.composable.navigation.routes.GroupSendRoute -import mobi.giza.compose.resources.wallets_your_groups_guard -import mobi.giza.compose.resources.guarded_by_s -import mobi.giza.compose.resources.a_group -import mobi.giza.compose.resources.a_group_below_s -import mobi.giza.compose.resources.another_group -import mobi.giza.compose.resources.guardian_after -import mobi.giza.compose.resources.spend_from_s_as_s -import mobi.giza.compose.resources.the_wallet_guarded_by_s -import mobi.giza.compose.ui.composable.widgets.delayText import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.semantics -import mobi.giza.compose.resources.spend -import androidx.compose.material.icons.filled.AccountBalanceWallet -import androidx.compose.material3.ListItem import androidx.compose.material3.Icon import mobi.giza.compose.ui.composable.widgets.Decorative import androidx.compose.foundation.layout.Arrangement @@ -109,16 +92,8 @@ fun ProfilePreviewScreen( chatRepository: ChatRepository, onStartChat: (Route) -> Unit, onNavigateBack: () -> Unit, - // The person's guarded wallets that this profile's groups guard - // (docs/member-guarded-wallets.md, Phase 11), and where a spend from one goes. - memberWalletRepository: MemberWalletRepository = MemberWalletRepository.NO_OP, onNavigateToRoute: (Route) -> Unit = {}, ) { - val personWalletsViewModel: PersonGuardedWalletsViewModel = viewModel( - factory = PersonGuardedWalletsViewModel.factory(ownerPublicKey = profilePublicKey, memberWalletRepository = memberWalletRepository), - ) - LaunchedEffect(true) { personWalletsViewModel.initiate() } - val profilePreviewViewModel: ProfilePreviewViewModel = viewModel( factory = ProfilePreviewViewModel.factory( activeUserPublicKey = activeUserPublicKey, @@ -214,24 +189,6 @@ fun ProfilePreviewScreen( onRetry = { profilePreviewViewModel.retry() }, ) } - - // One's own wallets are listed on one's own profile, with their - // keys; this is the guardians' view of somebody else's. - if (profilePublicKey != activeUserPublicKey && personWalletsViewModel.rows.isNotEmpty()) { - GuardedByYourGroups( - wallets = personWalletsViewModel.rows, - onSpend = { holder -> - onNavigateToRoute( - GroupSendRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = holder.wallet.ancestorChatRoomId, - relayHint = null, - guardedChatRoomId = holder.wallet.descendantChatRoomId, - ) - ) - }, - ) - } } } @@ -268,58 +225,6 @@ fun ProfilePreviewScreen( } } -/** - * The person's guarded wallets as this profile's groups hold them: one entry per - * wallet, saying which group directly guards it, and under it each group here - * holding a leaf in it, with that leaf's delay and -- where this device holds a - * share of that group's key -- the way to spend through it, which is the - * guardian spend the group's wallet screen already offers. - * `docs/member-wallet-guarding-group.md`, D7. - */ -@Composable -private fun GuardedByYourGroups( - wallets: List, - onSpend: (MemberWalletManager.GuardedHere) -> Unit, -) { - Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { - Text(stringResource(Res.string.wallets_your_groups_guard), style = MaterialTheme.typography.titleMedium) - wallets.forEach { wallet -> - val guardian = wallet.guardianName - ?: wallet.below?.let { stringResource(Res.string.a_group_below_s, it) } - ?: stringResource(Res.string.another_group) - val guardedBy = stringResource(Res.string.guarded_by_s, guardian) - ListItem( - leadingContent = { Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) }, - // Named by its label, or with none by the group that guards it. - headlineContent = { Text(wallet.label ?: guardedBy) }, - supportingContent = wallet.label?.let { { Text(guardedBy) } }, - ) - wallet.holders.forEach { holder -> - val holderName = holder.holderName ?: stringResource(Res.string.a_group) - val spendLabel = stringResource( - Res.string.spend_from_s_as_s, - wallet.label ?: stringResource(Res.string.the_wallet_guarded_by_s, guardian), - holderName, - ) - ListItem( - // Under its wallet, so the holders read as the wallet's. - modifier = Modifier.padding(start = MaterialTheme.spacing.containerPadding), - headlineContent = { - Text(stringResource(Res.string.guardian_after, holderName, delayText(holder.wallet.delay, holder.wallet.chain))) - }, - trailingContent = if (holder.canSpend) { - { - TextButton(onClick = { onSpend(holder) }, modifier = Modifier.semantics { contentDescription = spendLabel }) { - Text(stringResource(Res.string.spend)) - } - } - } else null, - ) - } - } - } -} - /** * Who this is: leading-aligned, because rows with an avatar align to a leading edge * and centring is for a block that is the only thing on the screen, which this is diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/SelectSubgroupAdminsScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/SelectSubgroupAdminsScreen.kt index 03d6a452..a400219f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/SelectSubgroupAdminsScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/SelectSubgroupAdminsScreen.kt @@ -1,25 +1,5 @@ package mobi.giza.compose.ui.composable -import mobi.giza.compose.resources.a_coin_the_subgroup_moves_starts_waiting_again -import mobi.giza.compose.resources.how_long_before_this_group_can_spend_a_coin -import mobi.giza.compose.ui.composable.widgets.GuardianDelayChooser -import mobi.giza.compose.ui.view.state.onlyGuarded -import mobi.giza.compose.ui.view.state.canGuard -import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy -import mobi.giza.compose.resources.this_group_s_guardian_keys_can_t_be_read -import mobi.giza.compose.resources.this_group_is_guarded_so_its_subgroups_are_too -import mobi.giza.compose.resources.only_the_subgroup_can_spend_from_its_wallet -import mobi.giza.compose.resources.this_group_and_the_d_above_it_can_spend -import mobi.giza.compose.resources.this_group_can_spend_its_coins_once -import mobi.giza.compose.resources.unguarded_wallet -import mobi.giza.compose.resources.guarded_wallet -import mobi.giza.compose.resources.the_subgroup_s_wallet -import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.semantics.selected -import androidx.compose.ui.semantics.role -import androidx.compose.ui.semantics.Role -import androidx.compose.material3.RadioButton -import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row @@ -295,34 +275,6 @@ fun SelectSubgroupAdminsScreen( onQuorumChange = viewModel::setThreshold ) } - - item { - WalletPolicyChooser( - policy = viewModel.walletPolicy.value, - parentGuardianCount = state.parentGuardians?.size ?: 0, - onlyGuarded = state.onlyGuarded, - canGuard = state.canGuard, - onPolicyChange = viewModel::setWalletPolicy - ) - } - - // The parent's own leaf's delay, and only for a guarded - // subgroup: docs/guardian-delay.md. - if (viewModel.walletPolicy.value == SubgroupWalletPolicy.GUARDED && state.canGuard) { - item { - GuardianDelayChooser( - title = stringResource(Res.string.how_long_before_this_group_can_spend_a_coin), - consequence = stringResource(Res.string.a_coin_the_subgroup_moves_starts_waiting_again), - input = viewModel.guardianDelayInput.value, - delay = viewModel.guardianDelay(), - isCustom = viewModel.isCustomDelay.value, - problem = viewModel.guardianDelayProblem(), - onPreset = viewModel::setGuardianDelay, - onCustom = viewModel::useCustomDelay, - onInput = viewModel::setGuardianDelayInput, - ) - } - } } } } @@ -380,92 +332,6 @@ private fun QuorumStepper( } } -/** - * Whether the subgroup's wallet is guarded -- `docs/subgroup-wallet-policy.md`. - * - * Settled here for the reason the threshold is: it rides the proposal, every - * admin is shown it before joining, and the parent's quorum signs it into the - * certificate, so there is no later screen where it could be changed. - * - * Under a guarded parent both rows still show, with *unguarded* disabled and its - * reason in place of its description. Hiding it would make the picker look like - * an older build's, where nobody decided anything; showing it says a decision was - * made, and by whom. - */ -@Composable -private fun WalletPolicyChooser( - policy: SubgroupWalletPolicy, - parentGuardianCount: Int, - onlyGuarded: Boolean, - canGuard: Boolean, - onPolicyChange: (SubgroupWalletPolicy) -> Unit, -) { - Column( - modifier = Modifier - .fillMaxWidth() - .padding(top = MaterialTheme.spacing.space50) - .selectableGroup(), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space50) - ) { - Text( - text = stringResource(Res.string.the_subgroup_s_wallet), - style = MaterialTheme.typography.titleSmall - ) - - WalletPolicyRow( - title = stringResource(Res.string.guarded_wallet), - // Names the reach the parent is actually granting: itself, and each - // ancestor whose key its own certificate passes on. - description = if (!canGuard) { - stringResource(Res.string.this_group_s_guardian_keys_can_t_be_read) - } else if (parentGuardianCount == 0) { - stringResource(Res.string.this_group_can_spend_its_coins_once) - } else { - stringResource(Res.string.this_group_and_the_d_above_it_can_spend, parentGuardianCount) - }, - isSelected = policy == SubgroupWalletPolicy.GUARDED, - isEnabled = canGuard, - onSelect = { onPolicyChange(SubgroupWalletPolicy.GUARDED) } - ) - WalletPolicyRow( - title = stringResource(Res.string.unguarded_wallet), - description = if (onlyGuarded) { - stringResource(Res.string.this_group_is_guarded_so_its_subgroups_are_too) - } else { - stringResource(Res.string.only_the_subgroup_can_spend_from_its_wallet) - }, - isSelected = policy == SubgroupWalletPolicy.UNGUARDED, - isEnabled = !onlyGuarded, - onSelect = { onPolicyChange(SubgroupWalletPolicy.UNGUARDED) } - ) - } -} - -@Composable -private fun WalletPolicyRow( - title: String, - description: String, - isSelected: Boolean, - isEnabled: Boolean, - onSelect: () -> Unit, -) { - // The card is the target, as the admin rows above are, and the radio button - // beside the title only says which one is chosen. - Card( - modifier = Modifier.fillMaxWidth().semantics { role = Role.RadioButton; selected = isSelected }, - onClick = onSelect, - enabled = isEnabled - ) { - ListItem( - leadingContent = { - RadioButton(selected = isSelected, onClick = null, enabled = isEnabled) - }, - headlineContent = { Text(title) }, - supportingContent = { Text(description) } - ) - } -} - @ConformancePreviews @Composable private fun SelectSubgroupAdminsScreenPreview() { 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 aa9c6f45..46271440 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,15 +1,5 @@ package mobi.giza.compose.ui.composable.navigation -import fr.acinq.phoenixd.conf.LSP -import fr.acinq.phoenix.db.createPaymentsDbDriver -import fr.acinq.phoenix.db.createSqlitePaymentsDb -import fr.acinq.phoenix.db.createChannelsDbDriver -import fr.acinq.phoenix.db.createSqliteChannelsDb -import fr.acinq.phoenix.managers.PhoenixDatabases -import fr.acinq.phoenix.managers.DatabaseManager -import mobi.giza.compose.wallet.GroupLightningRollout -import mobi.giza.compose.managers.GroupLightningNode -import mobi.giza.compose.wallet.lightning.GroupLightningNodes import mobi.giza.compose.ui.composable.navigation.routes.GroupLightningWalletRoute import mobi.giza.compose.ui.composable.GroupLightningWalletScreen import mobi.giza.compose.ui.composable.GroupLightningReceiveScreen @@ -22,7 +12,6 @@ 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.wallet.GroupChainClients import mobi.giza.compose.ui.composable.MemberWalletPolicyScreen import mobi.giza.compose.ui.composable.navigation.routes.MemberWalletPolicyRoute import mobi.giza.compose.ui.composable.GroupSendScreen @@ -39,7 +28,6 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color import mobi.giza.compose.AppLifecycle import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver @@ -173,7 +161,6 @@ import mobi.giza.compose.ui.composable.MemberWalletScreen import mobi.giza.compose.ui.composable.NewMemberWalletScreen import mobi.giza.compose.database.repository.DatabaseMemberWalletRepository import mobi.giza.compose.wallet.GroupOnchainWallets -import mobi.giza.compose.wallet.IdentityElectrum import mobi.giza.compose.wallet.GroupTransactionWatcher import fr.acinq.phoenix.managers.NodeParamsManager import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute @@ -266,95 +253,11 @@ fun GizaNavHost( ) } - // The Electrum client this identity watches the chain on: its node's, or -- - // for an nsec or npub profile, which has no node -- one of its own. Remade - // with the identity, the last one stopped first, because a switch of profile - // is a restart and a wallet left subscribing on the last one's connection is - // a wallet nobody can see. See docs/standalone-electrum.md. - val activeIdentityForWallets by sovereignWalletViewModel.activeIdentity.collectAsState() - val identityElectrum = remember { - IdentityElectrum(IdentityElectrum.standalone(phoenixGlobal.networkMonitor, phoenixGlobal.loggerFactory)) - } - DisposableEffect(identityElectrum) { - onDispose { identityElectrum.stop() } - } - val electrum = remember(activeIdentityForWallets?.id, activeIdentityForWallets?.business) { - identityElectrum.clientFor(activeIdentityForWallets) - } - - // One Electrum connection per network: the identity's own -- its node's, or the one a - // profile with no node is given -- for the node's network, and one of their own for any - // other a group keeps a wallet on (testnet3, while a Lightning wallet is tried there). - // Shared by the wallets and the watcher below, and remade with the identity's client. - val groupChainClients = remember(electrum) { - val identity = activeIdentityForWallets - if (electrum == null || identity == null) null else GroupChainClients.forNode(NodeParamsManager.chain, electrum) { chain -> - IdentityElectrum.standaloneOn(chain, identity, phoenixGlobal.networkMonitor, phoenixGlobal.loggerFactory) - } - } - DisposableEffect(groupChainClients) { - onDispose { groupChainClients?.let { clients -> applicationIOScope.launch { clients.stop() } } } - } - - // The group wallets this identity is watching. Remade with the client. - val groupOnchainWallets = remember(groupChainClients) { - groupChainClients?.let { GroupOnchainWallets(it, applicationIOScope) } - } - DisposableEffect(groupOnchainWallets) { - onDispose { groupOnchainWallets?.let { wallets -> applicationIOScope.launch { wallets.stop() } } } - } - - // The group Lightning nodes this identity is the elected operator of. Behind the - // rollout gate: nothing is built while it is off. Same lifetime as the wallets. - // A group's node is not the identity's own, and needs only an Electrum client: so a - // profile with no node -- an nsec or an npub, which has one now -- can run it too. - val groupLightningNodes = remember(groupChainClients) { - val clients = groupChainClients - val identity = activeIdentityForWallets - val user = identity?.nostrPublicKey - if (!GroupLightningRollout.ENABLED || clients == null || identity == null || user == null) null else { - val ctx = phoenixGlobal.ctx - GroupLightningNodes( - database = auxDatabaseManager.auxDatabase, - userPublicKey = user, - scope = applicationIOScope, - peerFactory = GroupLightningNode.lightningKmpPeers( - clients = clients, - databasesFor = { nodeId, chain -> - PhoenixDatabases( - channels = createSqliteChannelsDb(createChannelsDbDriver(ctx, "group-" + DatabaseManager.channelsDbName(chain, nodeId))), - payments = createSqlitePaymentsDb(createPaymentsDbDriver(ctx, "group-" + DatabaseManager.paymentsDbName(chain, nodeId)) {}, null, phoenixGlobal.loggerFactory), - cloudKit = null, - ) - }, - // Phoenix's own choice of address: the LSP's onion while Tor is on, on the one network it has one. - walletParamsFor = { chain, tor -> - LSP.from(chain).walletParams.let { params -> - if (tor && chain == NodeParamsManager.chain) params.copy(trampolineNode = NodeParamsManager.trampolineNodeOnionUri) else params - } - }, - loggerFactory = phoenixGlobal.loggerFactory, - scope = applicationIOScope, - torIsEnabled = { identity.userPrefs.getIsTorEnabled.first() }, - ), - ).also { it.start() } - } - } - DisposableEffect(groupLightningNodes) { - onDispose { groupLightningNodes?.let { nodes -> applicationIOScope.launch { nodes.stop() } } } - } - - // Sends the group's signed spends to the network from this device too, and - // follows them to a confirmation -- whether or not anybody opens the wallet. - // Same lifetime as the wallets: the identity's client, and nothing longer. - val groupTransactionWatcher = remember(groupChainClients) { - groupChainClients?.let { - GroupTransactionWatcher(auxDatabaseManager.auxDatabase, it, applicationIOScope).also { watcher -> watcher.start() } - } - } - DisposableEffect(groupTransactionWatcher) { - onDispose { groupTransactionWatcher?.stop() } - } + // Giza keeps no wallet: no Electrum client, no group wallets, no group Lightning + // nodes and no transaction watcher are built (docs/giza-wallet-removal.md, Phase 1). + // The routes below that still take them get nothing, and nothing navigates there. + val groupOnchainWallets: GroupOnchainWallets? = null + val groupTransactionWatcher: GroupTransactionWatcher? = null val navigationViewModel: NavigationViewModel = viewModel ( factory = NavigationViewModel.factory( @@ -1097,8 +1000,6 @@ fun GizaNavHost( ) }, signOut = signOutOfReadOnlyIdentity, - memberWalletRepository = databaseMemberWalletRepository, - wallets = groupOnchainWallets, ) } composable { backStackEntry -> @@ -1256,7 +1157,6 @@ fun GizaNavHost( relayHint = route.relayHint, nostrRepository = databaseNostrRepository, chatRepository = databaseChatRepository, - memberWalletRepository = databaseMemberWalletRepository, onNavigateToRoute = { actionRoute -> navController.navigate( route = actionRoute @@ -1569,7 +1469,6 @@ fun GizaNavHost( profilePublicKey = route.profilePublicKey, nostrRepository = databaseNostrRepository, chatRepository = databaseChatRepository, - memberWalletRepository = databaseMemberWalletRepository, onNavigateToRoute = { actionRoute -> navController.navigate(route = actionRoute) }, // The room replaces the preview, as it replaces the profile detail // above: back from a chat is the list, not the person it was started 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 bea4d5c2..46765a3c 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 @@ -943,6 +943,8 @@ private fun RitualNotice( // path, so they get separate icons -- the whole reason both lines exist is // to be able to see that the first happened and the second did not. ChatMessage.TYPE_SUBGROUP_CERTIFIED -> Icons.Default.AccountTree + // A Bennu member's wallet, which Giza takes no part in: the same icon as a refusal. + ChatMessage.TYPE_WALLET_NOT_TAKEN_PART_IN -> Icons.Default.Block ChatMessage.TYPE_MEMBER_WALLET_REQUESTED, ChatMessage.TYPE_MEMBER_WALLET_GUARDED -> Icons.Default.AccountBalanceWallet ChatMessage.TYPE_MEMBER_INVITED -> Icons.Default.PersonAdd ChatMessage.TYPE_MEMBER_INVITE_SENT -> Icons.Default.Upload 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 981d3eb8..a6e49bc0 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 @@ -30,12 +30,6 @@ 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.database.model.types.IcebergRitualStage -import mobi.giza.compose.database.model.types.FrostSigningStage -import mobi.giza.compose.database.model.intermdiate.LocalFrostSigningSession -import mobi.giza.compose.nostr.lightning.GroupLightningWalletStatementEvent -import mobi.giza.compose.wallet.GroupLightningRollout -import kotlinx.coroutines.flow.combine import mobi.giza.compose.repository.FrostSigningRepository import mobi.giza.compose.repository.NostrRepository import mobi.giza.compose.text.ProposedEvent @@ -233,7 +227,6 @@ class ChatMessageListViewModel( observeProposalsAwaitingYou() observeCeremoniesAwaitingYou() askForGroupHistory() - forwardGuardedWallets() resumeSigningSessions() } @@ -292,23 +285,11 @@ class ChatMessageListViewModel( * A ceremony whose room exists wants nothing from anybody, which is what * `roomAwaitingCreation` is asking. That keeps the notice from becoming * permanent furniture in every room that has ever held a ceremony. - * - * The Lightning wallet's ceremony is read the same way beside it: its gates - * from the same `pendingApproval` its screen reads, and its finished key from - * whether a wallet uses it -- see [lightningWalletAwaitingYou]. */ private fun observeCeremoniesAwaitingYou() { val roomId = localChatRoom.chatRoom.id viewModelScope.launch(Dispatchers.IO) { - combine( - dkgRepository.observeSessionsForChatRoom(roomId), - lightningRepository.observeCeremonies(roomId), - // Only for whether a wallet statement is already being signed: - // once it is, the key has been put to the group and asking its - // opener to open it again would start a second proposal. - frostSigningRepository.observeSessionsForChatRoom(roomId), - ::Triple, - ).collect { (sessions, lightningCeremonies, signings) -> + dkgRepository.observeSessionsForChatRoom(roomId).collect { sessions -> val sharedKey = sessions .filter { it.stage != DkgRitualStage.FAILED } .mapNotNull { session -> @@ -326,40 +307,11 @@ class ChatMessageListViewModel( ) } - val lightningKey = lightningCeremonies - .filter { it.stage != IcebergRitualStage.FAILED } - .mapNotNull { session -> - lightningRepository.pendingApproval(session)?.let { - AwaitingCeremony(session.id, Ask.LightningKeyStep(it), isSubgroup = false) - } - } - - ceremoniesAwaitingYou = sharedKey + lightningKey + listOfNotNull(lightningWalletAwaitingYou(signings)) + ceremoniesAwaitingYou = sharedKey } } } - /** - * The finished Lightning wallet key this member opened the ceremony for, while no - * wallet uses it and no statement for it is being signed; null otherwise, and - * always on a build that does not offer the wallet. - */ - private suspend fun lightningWalletAwaitingYou(signings: List): AwaitingCeremony? { - if (!GroupLightningRollout.ENABLED) return null - val key = lightningRepository.unusedKey(localChatRoom.chatRoom.id, GroupLightningRollout.NETWORK) - ?.takeIf { it.coordinatorPublicKey.equals(it.userPublicKey, ignoreCase = true) } - ?: return null - - val beingSigned = signings - .filter { it.session.stage != FrostSigningStage.FAILED } - .flatMap { it.items } - .mapNotNull { Event.fromJsonOrNull(it.unsignedEventJson) } - .filter { it.kind == GroupLightningWalletStatementEvent.KIND } - .any { GroupLightningWalletStatementEvent.read(it.tags)?.ceremonyId == key.id } - - return if (beingSigned) null else AwaitingCeremony(key.id, Ask.LightningWalletOpening, isSubgroup = false) - } - /** * Ask the group for its signed record, if this device holds none of it. * @@ -384,22 +336,6 @@ class ChatMessageListViewModel( } } - /** - * Tells the groups above this one about every guarded wallet it holds that - * they have not heard of: the catch-up behind the arrival triggers, which - * covers a wallet that arrived while this device was offline, one the - * elected device never sent, and every one filed before forwarding existed. - * `docs/guarded-wallet-forwarding.md`, D5. A Marmot room only -- a guardian - * is a group with a key, and a group with a key has an MLS room. - */ - private fun forwardGuardedWallets() { - if (localChatRoom.chatRoom.mlsGroupState == null) return - viewModelScope.launch(Dispatchers.IO) { - runCatching { chatRepository.forwardGuardedWallets(localChatRoom.chatRoom.id) } - .onFailure { logger.w(throwable = it) { "Could not tell the groups above about this group's guarded wallets" } } - } - } - /** * Lets this room's answered signing sessions take any step they are able to. * diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt index 2bc3165f..4c4798d3 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -1,7 +1,5 @@ package mobi.giza.compose.ui.view.model -import mobi.giza.compose.wallet.GroupLightningRollout -import fr.acinq.phoenix.managers.NodeParamsManager import mobi.giza.compose.nostr.MarmotProfile import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue @@ -25,8 +23,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.launch import mobi.giza.compose.database.model.types.MarmotReindexReport -import mobi.giza.compose.managers.MemberWalletManager -import mobi.giza.compose.repository.MemberWalletRepository +import mobi.giza.compose.managers.WalletRefusal import com.vitorpamplona.quartz.nip01Core.core.Event class ChatRoomDetailViewModel( @@ -36,8 +33,6 @@ class ChatRoomDetailViewModel( initialChatRoomDetailUIState: ChatRoomDetailUIState, val nostrRepository: NostrRepository, val chatRepository: ChatRepository, - /** The member wallets this group guards -- `docs/member-guarded-wallets.md`. The no-op lists none. */ - val memberWalletRepository: MemberWalletRepository = MemberWalletRepository.NO_OP, ): ViewModel() { var chatRoomDetailUIState: ChatRoomDetailUIState by mutableStateOf(initialChatRoomDetailUIState) @@ -92,60 +87,28 @@ class ChatRoomDetailViewModel( val isDisbanded = group?.currentGroupState()?.isDisbanded == true val canGovern = group != null && group.isLocalAdmin() && !isDisbanded && localChatRoom.chatRoom.leftGroupAt == null - // A direct chat is a Marmot room of two with no key, and not a group - // that guards anybody's wallet: no section, no button. - // docs/member-wallet-delay.md. - val couldGuard = memberWalletRepository.couldGuard(chatRoomId) + val groupKeyState = chatRepository.groupKeyState(chatRoomId) + // W5: a guarded group's subgroups have to be guarded, which Giza + // cannot certify -- docs/giza-wallet-removal.md. + val subgroupsNeedAWallet = groupKeyState?.birthCertificateJson + ?.let { Event.fromJsonOrNull(it) } + ?.let(WalletRefusal::isGuarded) == true ChatRoomDetailUIState.Loaded( localChatRoom = localChatRoom, - groupKeyState = chatRepository.groupKeyState(chatRoomId), + groupKeyState = groupKeyState, signedGroupKeyStateEvent = chatRepository.signedGroupKeyStateEvent(chatRoomId), subgroups = chatRepository.subgroupsOf(chatRoomId), parentChatRoomId = chatRepository.parentOf(chatRoomId), - walletPolicy = chatRepository.walletPolicyOf(chatRoomId), - guardianDelay = chatRepository.guardiansOf(chatRoomId)?.firstOrNull()?.delay, - groupWallet = chatRepository.groupWallet(chatRoomId, NodeParamsManager.chain), - lightningParticipants = if (GroupLightningRollout.ENABLED) chatRepository.lightningParticipants(chatRoomId, GroupLightningRollout.NETWORK) else emptySet(), - canAddSubgroup = canSign, + canAddSubgroup = canSign && !subgroupsNeedAWallet, + subgroupsNeedAWallet = canSign && subgroupsNeedAWallet, canGovern = canGovern, isDisbanded = isDisbanded, - memberWallets = memberWalletRepository.memberWalletsOf(chatRoomId), - // Offered wherever the new-wallet screen could get somewhere: - // a group, a profile that signs, a network it is open on. A key - // this device does not know yet is that screen's to ask for. - canAskForMemberWallet = !isDisbanded && couldGuard && memberWalletRepository.refusal(chatRoomId, NodeParamsManager.chain).let { - it == null || it == MemberWalletManager.Refusal.KEY_UNKNOWN - }, - canSponsor = canSign, - memberWalletPolicy = memberWalletRepository.policyOf(chatRoomId), - // Everybody in a Marmot group sees whether it guards members' - // wallets; only a signer is offered to change it. - showsMemberWalletPolicy = !isDisbanded && couldGuard, ) } } } - /** - * Puts a member's request for a guarded wallet to the group, as this device: - * a signing session over the certificate it asks for, which proposing counts - * as approving. [onSuccess] gets the session, for the screen to move onto. - */ - fun putToGroup(request: Event, onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) { - if (isActionPending.value) return - isActionPending.value = true - viewModelScope.launch(Dispatchers.IO) { - val session = runCatching { memberWalletRepository.putToGroup(chatRoomId, request) } - .onFailure { logger.e("Couldn't put a member's wallet to $chatRoomId", it) } - .getOrNull() - viewModelScope.launch(Dispatchers.Main) { - isActionPending.value = false - if (session != null) onSuccess(session.id) else onFailure() - } - } - } - /** * Removes [memberPublicKey] as an admin, and reloads the screen. The commit is * applied when a relay accepts it, so the member's row stays until then; the @@ -258,7 +221,6 @@ class ChatRoomDetailViewModel( initialChatRoomDetailUIState: ChatRoomDetailUIState = ChatRoomDetailUIState.Loading, nostrRepository: NostrRepository, chatRepository: ChatRepository, - memberWalletRepository: MemberWalletRepository = MemberWalletRepository.NO_OP, ): ViewModelProvider.Factory = viewModelFactory { initializer { ChatRoomDetailViewModel( @@ -268,7 +230,6 @@ class ChatRoomDetailViewModel( initialChatRoomDetailUIState = initialChatRoomDetailUIState, nostrRepository = nostrRepository, chatRepository = chatRepository, - memberWalletRepository = memberWalletRepository, ) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SelectSubgroupAdminsViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SelectSubgroupAdminsViewModel.kt index a1630e1f..157b4064 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SelectSubgroupAdminsViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SelectSubgroupAdminsViewModel.kt @@ -1,10 +1,5 @@ package mobi.giza.compose.ui.view.model -import mobi.giza.compose.ui.view.state.canGuard -import mobi.giza.compose.ui.view.state.onlyGuarded -import mobi.giza.compose.database.model.subgroupWalletPolicy -import mobi.giza.compose.nostr.subgroup.isDecided -import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf @@ -89,27 +84,6 @@ class SelectSubgroupAdminsViewModel( val threshold: MutableState = mutableStateOf(ChatRoomType.MINIMUM_QUORUM) - /** - * What the subgroup's wallet is to be -- `docs/subgroup-wallet-policy.md`. - * Guarded unless the coordinator says otherwise, and only ever guarded under a - * parent that is guarded itself: [setWalletPolicy] will not move it, so the - * state never holds a choice the screen shows as disabled. - */ - val walletPolicy: MutableState = mutableStateOf(SubgroupWalletPolicy.GUARDED) - - /** - * How long a coin in a guarded subgroup's wallet waits before this group can - * take it -- `docs/guardian-delay.md`. The parent's own leaf only: each - * ancestor above keeps the delay it chose. - */ - private val delay = GuardianDelayInput() - - /** The delay as typed; see [GuardianDelayInput]. */ - val guardianDelayInput: MutableState get() = delay.input - - /** Whether the delay is being typed rather than picked from a preset. */ - val isCustomDelay: MutableState get() = delay.isCustom - /** Whether [retrying] has been read into the form, which happens once. */ private var prefilled = false @@ -127,24 +101,11 @@ class SelectSubgroupAdminsViewModel( .distinctBy { it.participant.participantPublicKey } .filterNot { it.participant.participantPublicKey == activeUserPublicKey } - // The parent's own wallet policy and guardians, read once: whether it - // may make an unguarded child at all, and whether it can grant a - // guarded one anything. - val parentPolicy = chatRepository.walletPolicyOf(parentChatRoomId) - val parentGuardians = chatRepository.guardiansOf(parentChatRoomId) - uiState = SelectSubgroupAdminsUIState.Loaded( parentRoom = parentRoom, candidates = candidates, - parentPolicy = parentPolicy, - parentGuardians = parentGuardians, ) - // A parent that cannot grant keys can only make an unguarded child, - // and one that is guarded can only make a guarded one. - if (parentGuardians == null) walletPolicy.value = SubgroupWalletPolicy.UNGUARDED - if (parentPolicy.isDecided(SubgroupWalletPolicy.GUARDED)) walletPolicy.value = SubgroupWalletPolicy.GUARDED - // Before the key-package lookup, so anybody who can no longer be // welcomed is unpicked by the same rule as a fresh pick would be. prefillFromRetry(candidates.map { it.participant.participantPublicKey }.toSet()) @@ -180,11 +141,6 @@ class SelectSubgroupAdminsViewModel( threshold.value = failed.threshold.coerceIn(quorumRange()) - // Through the setter, so a policy the parent no longer allows -- the - // failed ceremony can predate the parent's own certificate -- is pulled - // back the way the threshold is pulled into its range. - failed.subgroupWalletPolicy?.let(::setWalletPolicy) - failed.guardianDelay?.let(delay::reset) } /** @@ -236,44 +192,6 @@ class SelectSubgroupAdminsViewModel( name.value = value } - /** - * Chooses the subgroup's wallet policy. *Unguarded* under a guarded parent is - * ignored -- D4 -- and so is *guarded* under a parent that cannot grant keys. - */ - fun setWalletPolicy(value: SubgroupWalletPolicy) { - if (isActionPending.value) return - - val loaded = uiState as? SelectSubgroupAdminsUIState.Loaded ?: return - if (value == SubgroupWalletPolicy.UNGUARDED && loaded.onlyGuarded) return - if (value == SubgroupWalletPolicy.GUARDED && !loaded.canGuard) return - - walletPolicy.value = value - } - - /** Picks a preset delay. */ - fun setGuardianDelay(blocks: Long) { - if (isActionPending.value) return - delay.pick(blocks) - } - - /** Switches to typing a delay, starting from the one already chosen. */ - fun useCustomDelay() { - if (isActionPending.value) return - delay.useCustom() - } - - /** What was typed as the delay, kept as typed. */ - fun setGuardianDelayInput(value: String) { - if (isActionPending.value) return - delay.type(value) - } - - /** The delay typed or picked, or null while the field holds no number. */ - fun guardianDelay(): Long? = delay.delay() - - /** Why the delay cannot be used, or null when it can. */ - fun guardianDelayProblem(): String? = delay.problem() - /** The subgroup's admins: everyone ticked, plus the coordinator. */ fun adminCount(): Int = selectedPublicKeys.size + 1 @@ -297,17 +215,6 @@ class SelectSubgroupAdminsViewModel( if (name.value.isBlank()) return "Give the subgroup a name." - // The policy before the admins and before the key-package lookup, which it - // does not wait on: an answer here sends the coordinator back - // to a choice, not to a person. Checked again on confirm, so a state that - // got past the screen is stopped before a ceremony is proposed. - if (walletPolicy.value == SubgroupWalletPolicy.UNGUARDED && loaded.onlyGuarded) { - return "This group is guarded, so its subgroups are too." - } - if (walletPolicy.value == SubgroupWalletPolicy.GUARDED && !loaded.canGuard) { - return "This group's own guardian keys can't be read, so it can't guard a subgroup." - } - if (walletPolicy.value == SubgroupWalletPolicy.GUARDED) guardianDelayProblem()?.let { return it } if (loaded.isResolvingKeyPackages) return "Checking who can be added…" @@ -383,13 +290,6 @@ class SelectSubgroupAdminsViewModel( // being in it, and is not theirs to tick. participantPublicKeys = selectedPublicKeys.toSet(), subject = name.value.trim(), - // Carried on the proposal so every admin is told at the join gate, - // and on the session so whoever proposes the certificate proposes - // it under the same one. - walletPolicy = walletPolicy.value, - // The parent's own leaf, and only for a guarded subgroup. - // docs/guardian-delay.md. - guardianDelay = guardianDelay().takeIf { walletPolicy.value == SubgroupWalletPolicy.GUARDED } ) isActionPending.value = false @@ -421,9 +321,6 @@ class SelectSubgroupAdminsViewModel( } companion object { - /** The delays the picker offers: [GuardianDelayInput.PRESETS]. */ - val DELAY_PRESETS: List get() = GuardianDelayInput.PRESETS - private const val TAG = "SelectSubgroupAdminsViewModel" fun factory( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt index dd992b2a..acb5c4e6 100755 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt @@ -1,9 +1,5 @@ package mobi.giza.compose.ui.view.state -import mobi.giza.compose.nostr.wallet.MemberWalletPolicyEvent -import mobi.giza.compose.managers.MemberWalletManager -import mobi.giza.compose.nostr.subgroup.WalletPolicyReading -import mobi.giza.compose.nostr.wallet.GroupWallet import com.vitorpamplona.quartz.nip01Core.core.HexKey import mobi.giza.compose.database.model.GroupKeyState import mobi.giza.compose.managers.SubgroupManager @@ -50,25 +46,6 @@ sealed interface ChatRoomDetailUIState { * really is a subgroup. */ val parentChatRoomId: HexKey? = null, - /** - * What [parentChatRoomId] decided about this room's wallet at its birth, - * or null for a room with no certificate. Shown on the parent row, - * because it is a fact about where the room came from. - */ - val walletPolicy: WalletPolicyReading? = null, - /** - * The delay [parentChatRoomId] gave its own leaf in this room's wallet, - * or null for a room whose certificate grants no keys. - */ - val guardianDelay: Long? = null, - /** - * The wallet this group has opened on the app's network, or null for one - * it has not. The row says only whether it is open; the coins are read on - * `GroupWalletScreen`. - */ - val groupWallet: GroupWallet? = null, - /** Who holds a share of the group's Lightning wallet key, so removing one of them can say what it leaves. */ - val lightningParticipants: Set = emptySet(), /** * Whether this device could open a subgroup here at all. * @@ -83,6 +60,12 @@ sealed interface ChatRoomDetailUIState { * missing and what to do about it. */ val canAddSubgroup: Boolean = false, + /** + * Whether this device could open a subgroup here but for the room's own + * certificate saying `wallet=guarded`: a guarded group's subgroups are + * guarded, and Giza takes no part in wallets. docs/giza-wallet-removal.md, W5. + */ + val subgroupsNeedAWallet: Boolean = false, /** * Whether this device administers a current-profile room: it may remove a * member and disband the group, both commits through the publish gate. A @@ -95,24 +78,6 @@ sealed interface ChatRoomDetailUIState { * and nobody rejoins, so every write entrance is hidden and the room says so. */ val isDisbanded: Boolean = false, - /** - * The member wallets this group guards, and the requests for one still - * waiting for a signer -- `docs/member-guarded-wallets.md`. Its own - * section, never mixed into [subgroups]: a row here is a person. - */ - val memberWallets: List = emptyList(), - /** Whether this profile could ask this group to guard a wallet for it. */ - val canAskForMemberWallet: Boolean = false, - /** Whether this device holds a share, and so can put a member's request to the group. */ - val canSponsor: Boolean = false, - /** - * Whether this group guards its members' wallets, and at what delay -- - * its newest member-wallet policy, or null for one it never signed. - * `docs/member-wallet-delay.md`. - */ - val memberWalletPolicy: MemberWalletPolicyEvent.Policy? = null, - /** Whether to show that at all: a Marmot group, still going. */ - val showsMemberWalletPolicy: Boolean = false, ): ChatRoomDetailUIState data class Error( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SelectSubgroupAdminsUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SelectSubgroupAdminsUIState.kt index 1555b4eb..e3c32986 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SelectSubgroupAdminsUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SelectSubgroupAdminsUIState.kt @@ -1,9 +1,5 @@ package mobi.giza.compose.ui.view.state -import mobi.giza.compose.managers.GuardianDerivation -import mobi.giza.compose.nostr.subgroup.isDecided -import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy -import mobi.giza.compose.nostr.subgroup.WalletPolicyReading import com.vitorpamplona.quartz.nip01Core.core.HexKey import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.database.model.intermdiate.LocalParticipant @@ -33,29 +29,9 @@ sealed interface SelectSubgroupAdminsUIState { val withoutKeyPackage: Set = emptySet(), /** Null while the lookup is still out; a set once it has settled. */ val isResolvingKeyPackages: Boolean = true, - /** - * What the parent's own certificate says of its wallet, or null for a - * parent with none. A parent decided *guarded* can only make guarded - * subgroups -- `docs/subgroup-wallet-policy.md`, D4. - */ - val parentPolicy: WalletPolicyReading? = null, - /** - * The guardian keys the parent's own certificate grants it, or null when - * they do not read -- in which case it cannot grant a child any, and a - * guarded subgroup is refused here rather than after a ceremony. - */ - val parentGuardians: List? = emptyList(), ): SelectSubgroupAdminsUIState data class Error(val message: String): SelectSubgroupAdminsUIState data object Loading: SelectSubgroupAdminsUIState } - -/** Whether this parent may only make guarded subgroups. */ -val SelectSubgroupAdminsUIState.Loaded.onlyGuarded: Boolean - get() = parentPolicy.isDecided(SubgroupWalletPolicy.GUARDED) - -/** Whether this parent can grant a child guardian keys at all. */ -val SelectSubgroupAdminsUIState.Loaded.canGuard: Boolean - get() = parentGuardians != null diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/RetiredKindsTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/RetiredKindsTest.kt new file mode 100644 index 00000000..a1619ed6 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/RetiredKindsTest.kt @@ -0,0 +1,54 @@ +package mobi.giza.compose.nostr + +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 kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * The wallet's kinds stay Bennu's (docs/giza-wallet-removal.md, constraint 4): nothing Giza + * sends, signs or files may sit on one of them. + */ +class RetiredKindsTest { + private val live: Map> = mapOf( + "the key ceremony" to DkgRitualEvents.ALL, + // Less the transaction proposal, which FROST still routes so that it can decline it. + "event signing" to FrostSigningEvents.ALL - RetiredKinds.TRANSACTION_PROPOSAL, + "the chronicle" to setOf(ChronicleEvent.KIND, ChronicleRequestEvent.KIND), + "a key state" to setOf(GroupKeyStateEvent.KIND), + "a birth certificate" to setOf(SubgroupBirthCertificateEvent.KIND), + "a direct message's envelope" to setOf(MarmotDirectMessage.ENVELOPE_KIND), + ) + + @Test + fun `no live kind is a retired one`() { + live.forEach { (what, kinds) -> + val overlap = kinds.filter(RetiredKinds::isRetired) + assertTrue(overlap.isEmpty(), "$what uses retired kinds $overlap") + } + } + + @Test + fun `the ranges are the ones Bennu uses`() { + assertEquals(30331, RetiredKinds.WALLET.first) + assertEquals(30337, RetiredKinds.WALLET.last) + assertEquals(30350, RetiredKinds.GROUP_LIGHTNING.first) + assertEquals(30366, RetiredKinds.GROUP_LIGHTNING.last) + assertTrue(RetiredKinds.isRetired(RetiredKinds.TRANSACTION_PROPOSAL)) + assertTrue(RetiredKinds.ANNOUNCEMENTS.all(RetiredKinds::isRetired)) + } + + @Test + fun `the kinds either side are not retired`() { + assertFalse(RetiredKinds.isRetired(30330)) + assertFalse(RetiredKinds.isRetired(30338)) + assertFalse(RetiredKinds.isRetired(30349)) + assertFalse(RetiredKinds.isRetired(30367)) + } +} 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 fe6dce79..e61d5a47 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 @@ -1,5 +1,7 @@ package mobi.giza.compose.database.model +import mobi.giza.compose.nostr.RetiredKinds + import androidx.room3.Room import com.vitorpamplona.quartz.marmot.GroupEventResult import com.vitorpamplona.quartz.marmot.mip03GroupMessages.GroupEvent @@ -211,4 +213,18 @@ class ProtocolKindDispatchJvmTest { 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 + * raw-JSON bubble: the three that announce a wallet are at most a line saying so, and + * the rest of the traffic is nothing. + */ + @Test + fun `no retired wallet kind is a raw bubble`(): Unit = runBlocking { + (RetiredKinds.WALLET + RetiredKinds.GROUP_LIGHTNING).forEach { kind -> + val (_, line) = arrive(kind, content = """{"wallet":"w"}""") + assertTrue(line?.messageType != "unsupported", "kind $kind is a wallet's, not an unknown kind") + } + } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningCoSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningCoSigningJvmTest.kt deleted file mode 100644 index cee32c2e..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningCoSigningJvmTest.kt +++ /dev/null @@ -1,340 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.database.model.ChatMessage -import mobi.giza.compose.nostr.lightning.GroupLightningAuthorisationEvent -import mobi.giza.compose.nostr.lightning.GroupLightningEvents -import mobi.giza.compose.wallet.GroupLightningRollout -import com.vitorpamplona.quartz.nip01Core.core.toHexKey -import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.PublicKey -import fr.acinq.bitcoin.Satoshi -import fr.acinq.bitcoin.ScriptFlags -import fr.acinq.bitcoin.Transaction -import fr.acinq.bitcoin.TxId -import fr.acinq.bitcoin.byteVector32 -import fr.acinq.bitcoin.utils.Either -import fr.acinq.lightning.CltvExpiry -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.ChannelSpendSignature -import fr.acinq.lightning.channel.CommitParams -import fr.acinq.lightning.channel.Commitments -import fr.acinq.lightning.channel.LocalChannelParams -import fr.acinq.lightning.channel.RemoteChannelParams -import fr.acinq.lightning.crypto.FundingSigner -import fr.acinq.lightning.crypto.IcebergSigningTimeout -import fr.acinq.lightning.crypto.NonceGenerator -import fr.acinq.lightning.crypto.RemoteIcebergFundingSigner -import fr.acinq.lightning.transactions.CommitmentSpec -import fr.acinq.lightning.transactions.IncomingHtlc -import fr.acinq.lightning.transactions.Transactions -import fr.acinq.lightning.utils.msat -import fr.acinq.lightning.wire.OnionRoutingPacket -import fr.acinq.lightning.wire.UpdateAddHtlc -import kotlin.random.Random -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertIs -import kotlin.test.assertTrue -import kotlin.time.Duration -import kotlin.time.Duration.Companion.hours -import kotlin.time.Duration.Companion.seconds -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.async -import kotlinx.coroutines.cancel -import kotlinx.coroutines.delay -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.withTimeout - -/** - * A commitment signed by the group for real: an operator's `RemoteIcebergFundingSigner` asks, four - * devices' co-signers check and echo and answer, and the group's partial signature combines with a stock - * counterparty's into a transaction that spends the funding output (`docs/group-lightning-wallet.md`, - * Phase 9). Then the ways a request must fail. - * - * The channel is built here from its parameters rather than negotiated with a peer: what is under test is - * that every member rebuilds the same transaction from the same context and signs it only if it leaves - * the group what the group agreed to. - */ -abstract class GroupLightningCoSigningCases(chain: Chain) { - private val fixture = GroupLightningFixture(chain = chain) - private val lspKey = PrivateKey(Random.nextBytes(32).byteVector32()) - private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) - - @AfterTest - fun close() { - scope.cancel() - fixture.close() - } - - init { - 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) - } - } - - private inner class Group(val all: List, val wallet: GroupLightningWalletManager.Wallet, val operatorTerm: Long) - - private suspend fun group(): Group { - val all = fixture.group() - fixture.runCeremony(all) - val session = GroupLightningWalletManager.proposeWallet(all[0].db, all[0].room, all[0].publicKey, all[0].privateKey, fixture.chain, lspKey.publicKey().toString()) - fixture.signSession(all, all[0], session.id) - val elected = GroupLightningOperatorManager.nominateSelf(all[0].db, all[0].room, all[0].publicKey, fixture.chain) - fixture.signSession(all, all[0], elected.id) - val wallet = GroupLightningWalletManager.walletFor(all[0].db, fixture.roomId, fixture.chain)!! - return Group(all, wallet, GroupLightningOperatorManager.current(all[0].db, fixture.roomId, fixture.chain)!!.term) - } - - /** A channel with the LSP, as the operator's node would hold it. */ - private inner class Channel(group: Group, ours: Long, theirs: Long, capacity: Satoshi = Satoshi(1_000_000)) { - val seed = ByteVector(group.wallet.seed!!.seed) - val keyManager = GroupLightningCoSigner.keyManagerOf(seed, fixture.chain) - val groupKey = PublicKey.fromHex(group.wallet.statement.icebergKey) - val remoteFundingKey = PrivateKey(Random.nextBytes(32).byteVector32()) - val fundingTxId = TxId(Random.nextBytes(32).byteVector32()) - val input = Transactions.makeFundingInputInfo(fundingTxId, 0, capacity, groupKey, remoteFundingKey.publicKey(), Transactions.CommitmentFormat.SimpleTaprootChannels) - val onchain = fixture.account - val params = ChannelParams( - channelId = Random.nextBytes(32).byteVector32(), - channelConfig = ChannelConfig.standard, - channelFeatures = ChannelFeatures(setOf()), - localParams = LocalChannelParams( - nodeId = PublicKey.fromHex(group.wallet.statement.nodeId), - fundingKeyPath = keyManager.newFundingKeyPath(isChannelOpener = false), - isChannelOpener = false, - paysCommitTxFees = false, - defaultFinalScriptPubKey = GroupWalletDerivation.derive(onchain, GroupWalletDerivation.RECEIVE, 0).pubkeyScript, - features = Features.empty, - ), - remoteParams = RemoteChannelParams( - nodeId = lspKey.publicKey(), - revocationBasepoint = PrivateKey(Random.nextBytes(32).byteVector32()).publicKey(), - paymentBasepoint = PrivateKey(Random.nextBytes(32).byteVector32()).publicKey(), - delayedPaymentBasepoint = PrivateKey(Random.nextBytes(32).byteVector32()).publicKey(), - htlcBasepoint = PrivateKey(Random.nextBytes(32).byteVector32()).publicKey(), - features = Features.empty, - ), - channelFlags = ChannelFlags(announceChannel = false, nonInitiatorPaysCommitFees = false), - ) - val commitParams = CommitParams(Satoshi(546), 1_000_000_000L, 1.msat, CltvExpiryDelta(144), 30) - val keys = keyManager.channelKeys(params.localParams.fundingKeyPath).withGroupBasepoints(group.wallet.basepoints.forChannel) - var spec = CommitmentSpec(setOf(), FeeratePerKw(Satoshi(2_500)), toLocal = theirs.msat, toRemote = ours.msat) - - fun commitment(index: Long, spec: CommitmentSpec, point: PublicKey = PrivateKey(Random.nextBytes(32).byteVector32()).publicKey()): Pair { - val (tx, _) = Commitments.makeRemoteTxs(params, commitParams, keys.remoteCommitmentKeys(params, point), index, groupKey, remoteFundingKey.publicKey(), input, Transactions.CommitmentFormat.SimpleTaprootChannels, spec) - return tx to FundingSigner.SigningContext.RemoteCommitment(params, commitParams, index, point, spec) - } - } - - /** Runs [block] on the operator while every device's messages are pumped, until it returns. */ - private suspend fun whilePumping(group: Group, timeout: Duration = 20.seconds, block: suspend () -> T): T { - val result = scope.async { block() } - withTimeout(timeout) { - while (!result.isCompleted) { - fixture.pump(group.all, GroupLightningEvents.CO_SIGNING) - delay(50) - } - } - return result.await() - } - - private suspend fun operatorSigner(group: Group, deadline: Duration = 10.seconds): Pair { - val operator = group.all[0] - val transport = GroupIcebergTransport.create(operator.db, operator.room, operator.publicKey, group.wallet, group.operatorTerm, scope) - whilePumping(group) { transport.provision(GroupLightningCoSigner.POOL_WINDOW) } - fixture.pump(group.all, GroupLightningEvents.CO_SIGNING) - transport.provision(GroupLightningCoSigner.POOL_WINDOW) - return RemoteIcebergFundingSigner(PublicKey.fromHex(group.wallet.statement.icebergKey), transport, deadline) to transport - } - - /** Signs [tx] as the group and the stock counterparty would, and checks it spends the funding output. */ - private suspend fun groupSigns(group: Group, signer: RemoteIcebergFundingSigner, channel: Channel, tx: Transactions.CommitTx, context: FundingSigner.SigningContext): Either { - val remoteNonce = NonceGenerator.signingNonce(channel.remoteFundingKey.publicKey(), channel.groupKey, channel.fundingTxId) - val groupSig = whilePumping(group) { signer.signWithFreshNonce(tx, channel.remoteFundingKey.publicKey(), mapOf(), channel.fundingTxId, remoteNonce.publicNonce, context) } - if (groupSig is Either.Left) return Either.Left(groupSig.value) - val ours = (groupSig as Either.Right).value - val theirs = (tx.partialSign(channel.remoteFundingKey, channel.groupKey, mapOf(), remoteNonce, listOf(remoteNonce.publicNonce, ours.nonce)) as Either.Right).value - return tx.aggregateSigs(channel.groupKey, channel.remoteFundingKey.publicKey(), ours, theirs, mapOf()) - } - - /** Our own commitment [index], signed as the group would sign it to force-close, with the counterparty's half. */ - private suspend fun localSigns(group: Group, signer: RemoteIcebergFundingSigner, channel: Channel, index: Long, spec: CommitmentSpec): Either { - val (tx, _) = Commitments.makeLocalTxs(channel.params, channel.commitParams, channel.keys.localCommitmentKeys(channel.params, index), index, channel.groupKey, channel.remoteFundingKey.publicKey(), channel.input, Transactions.CommitmentFormat.SimpleTaprootChannels, spec) - val context = FundingSigner.SigningContext.LocalCommitment(channel.params, channel.commitParams, index, spec) - val id = FundingSigner.VerificationNonceId(channel.fundingTxId, channel.remoteFundingKey.publicKey(), index) - val ourNonce = signer.verificationNonce(id) - val remoteNonce = NonceGenerator.signingNonce(channel.remoteFundingKey.publicKey(), channel.groupKey, channel.fundingTxId) - val groupSig = whilePumping(group) { signer.signWithVerificationNonce(tx, channel.remoteFundingKey.publicKey(), mapOf(), id, remoteNonce.publicNonce, context) } - if (groupSig is Either.Left) return Either.Left(groupSig.value) - val ours = (groupSig as Either.Right).value - val theirs = (tx.partialSign(channel.remoteFundingKey, channel.groupKey, mapOf(), remoteNonce, listOf(remoteNonce.publicNonce, ourNonce)) as Either.Right).value - return tx.aggregateSigs(channel.groupKey, channel.remoteFundingKey.publicKey(), ours, theirs, mapOf()) - } - - @Test - fun `our own commitment is signed only once the group authorises a force close, and never a revoked one`() = runBlocking { - val group = group() - val channel = Channel(group, ours = 400_000_000, theirs = 600_000_000) - val (signer, _) = operatorSigner(group, deadline = 3.seconds) - for (index in 0L..2L) { - val (tx, context) = channel.commitment(index, channel.spec) - assertIs>(groupSigns(group, signer, channel, tx, context)) - } - val ours = channel.spec.copy(toLocal = 400_000_000.msat, toRemote = 600_000_000.msat) - assertIs(assertIs>(localSigns(group, signer, channel, 2, ours)).value, "nothing is authorised") - - val action = GroupLightningAuthorisationEvent.ChannelAction(GroupLightningAuthorisationEvent.FORCE_CLOSE, fixture.chain, 0, channel.params.channelId.toHex(), (kotlin.time.Clock.System.now() + 1.hours).epochSeconds) - val template = GroupLightningAuthorisationEvent.template(action) - fixture.sign(group.all, group.all[2], template.kind, template.tags, template.content) - assertEquals(listOf(action), GroupLightningAuthorisations.channelActions(group.all[3].db, fixture.roomId, group.wallet.statement)) - - assertIs>(localSigns(group, signer, channel, 0, ours), "commitment 0 was revoked long ago") - val signed = assertIs>(localSigns(group, signer, channel, 2, ours)).value - Transaction.correctlySpends(signed, mapOf(channel.input.outPoint to channel.input.txOut), ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) - } - - @Test - fun `the group signs the counterparty's commitment, and it spends the funding output`() = runBlocking { - val group = group() - val channel = Channel(group, ours = 400_000_000, theirs = 600_000_000) - val (signer, _) = operatorSigner(group) - val (tx, context) = channel.commitment(0, channel.spec) - val signed = assertIs>(groupSigns(group, signer, channel, tx, context)).value - Transaction.correctlySpends(signed, mapOf(channel.input.outPoint to channel.input.txOut), ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) - - // And a payment arriving: the next commitment, with more for the group, is signed as well. - val (next, nextContext) = channel.commitment(1, channel.spec.copy(toLocal = 550_000_000.msat, toRemote = 450_000_000.msat)) - val signedNext = assertIs>(groupSigns(group, signer, channel, next, nextContext)).value - Transaction.correctlySpends(signedNext, mapOf(channel.input.outPoint to channel.input.txOut), ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) - } - - @Test - fun `on mainnet no member signs for a channel over the rollout's cap`() = runBlocking { - val cap = GroupLightningRollout.channelCapFor(fixture.chain) ?: return@runBlocking - val group = group() - val (signer, _) = operatorSigner(group, deadline = 3.seconds) - val atCap = Channel(group, ours = 400_000_000, theirs = cap.sat * 1000 - 400_000_000, capacity = cap) - val (fits, fitsContext) = atCap.commitment(0, atCap.spec) - assertIs>(groupSigns(group, signer, atCap, fits, fitsContext), "a channel of exactly the cap opens") - val over = Channel(group, ours = 400_000_000, theirs = cap.sat * 1000, capacity = cap + Satoshi(400_000)) - val (big, bigContext) = over.commitment(0, over.spec) - assertIs(assertIs>(groupSigns(group, signer, over, big, bigContext)).value, "a bigger one never gets a signature") - } - - @Test - fun `a transaction its context does not rebuild to is refused by every member`() = runBlocking { - val group = group() - val channel = Channel(group, ours = 400_000_000, theirs = 600_000_000) - val (signer, _) = operatorSigner(group, deadline = 3.seconds) - // The context says the group keeps 400,000 sats; the transaction gives it 100,000. - val (_, honestContext) = channel.commitment(0, channel.spec) - val (lying, _) = channel.commitment(0, channel.spec.copy(toLocal = 900_000_000.msat, toRemote = 100_000_000.msat), honestContext.remotePerCommitmentPoint) - val result = groupSigns(group, signer, channel, lying, honestContext) - assertIs(assertIs>(result).value) - // And each member's device says so, once, to its own owner and nobody else. - group.all.drop(1).forEach { d -> - val refused = fixture.lines(d, ChatMessage.TYPE_LIGHTNING_REFUSED) - assertEquals(1, refused.size, "device ${d.index}") - assertEquals( - "Your device refused to co-sign for the Lightning node: the commitment its context rebuilds to is not the one it asks to sign.", - refused.single().content, - ) - assertTrue(refused.single().isUserMessage) - } - } - - @Test - fun `an outgoing payment the group did not authorise is refused`() = runBlocking { - val group = group() - val channel = Channel(group, ours = 400_000_000, theirs = 600_000_000) - val (signer, _) = operatorSigner(group, deadline = 3.seconds) - val (first, firstContext) = channel.commitment(0, channel.spec) - assertIs>(groupSigns(group, signer, channel, first, firstContext)) - // The operator offers an HTLC for a payment nobody approved. - val onion = OnionRoutingPacket(0, ByteVector(ByteArray(33) { if (it == 0) 2 else 0 }), ByteVector.empty, ByteVector32.Zeroes) - val htlc = IncomingHtlc(UpdateAddHtlc(channel.params.channelId, 0, 50_000_000.msat, Random.nextBytes(32).byteVector32(), CltvExpiry(800_000), onion)) - val (paying, payingContext) = channel.commitment(1, channel.spec.copy(htlcs = setOf(htlc), toRemote = 350_000_000.msat)) - assertIs>(groupSigns(group, signer, channel, paying, payingContext)) - } - - @Test - fun `nobody answers a member who is not the operator`() = runBlocking { - val group = group() - val channel = Channel(group, ours = 400_000_000, theirs = 600_000_000) - val impostor = group.all[1] - val transport = GroupIcebergTransport.create(impostor.db, impostor.room, impostor.publicKey, group.wallet, group.operatorTerm, scope) - whilePumping(group) { transport.provision(GroupLightningCoSigner.POOL_WINDOW) } - val signer = RemoteIcebergFundingSigner(PublicKey.fromHex(group.wallet.statement.icebergKey), transport, 3.seconds) - val (tx, context) = channel.commitment(0, channel.spec) - val result = runCatching { groupSigns(group, signer, channel, tx, context) } - assertTrue(result.isFailure || result.getOrNull() is Either.Left, "a member who was not elected got a signature") - } - - @Test - fun `with too few members online, nothing is signed`() = runBlocking { - val group = group() - val channel = Channel(group, ours = 400_000_000, theirs = 600_000_000) - val (signer, _) = operatorSigner(group, deadline = 3.seconds) - // n - t + 1 = 3 echoes are needed; with two devices offline only the operator and one other echo. - val online = group.all.take(2) - val (tx, context) = channel.commitment(0, channel.spec) - val remoteNonce = NonceGenerator.signingNonce(channel.remoteFundingKey.publicKey(), channel.groupKey, channel.fundingTxId) - val result = scope.async { signer.signWithFreshNonce(tx, channel.remoteFundingKey.publicKey(), mapOf(), channel.fundingTxId, remoteNonce.publicNonce, context) } - withTimeout(20.seconds) { - while (!result.isCompleted) { - fixture.pump(online, GroupLightningEvents.CO_SIGNING) - delay(50) - } - } - assertIs(assertIs>(result.await()).value) - val key = GroupLightningCoSigner.walletKey(fixture.roomId, fixture.chain, 0) - online.forEach { d -> assertEquals(0, d.db.icebergCoSigningDao().sharesFor(key, "any").size) } - online.forEach { d -> - val signedLabels = d.db.marmotInnerEventDao().getByChatRoomAndKinds(fixture.roomId, listOf(GroupLightningEvents.SIGNATURE_SHARE)).filter { it.publicKey == d.publicKey } - assertTrue(signedLabels.isEmpty(), "device ${d.index} signed without enough echoes") - } - } - - @Test - fun `a label is never answered under a second message`() = runBlocking { - val group = group() - val channel = Channel(group, ours = 400_000_000, theirs = 600_000_000) - val (signer, transport) = operatorSigner(group) - val (tx, context) = channel.commitment(0, channel.spec) - assertIs>(groupSigns(group, signer, channel, tx, context)) - // The operator reuses the label it was just answered under, for another commitment. - val key = GroupLightningCoSigner.walletKey(fixture.roomId, fixture.chain, 0) - val answered = group.all[1].db.icebergCoSigningDao().ledgerFor(key, GroupLightningCoSigner.poolLabel(group.wallet.statement.icebergKey, transport.highestAssigned).toHex()) - assertTrue(answered?.signedAt != null) - val reusing = object : fr.acinq.lightning.crypto.IcebergGroupTransport by transport { - override fun nextFreshLabel(fundingTxId: TxId): ByteVector32 = GroupLightningCoSigner.poolLabel(group.wallet.statement.icebergKey, transport.highestAssigned) - } - val again = RemoteIcebergFundingSigner(PublicKey.fromHex(group.wallet.statement.icebergKey), reusing, 3.seconds) - val (other, otherContext) = channel.commitment(1, channel.spec.copy(toLocal = 550_000_000.msat, toRemote = 450_000_000.msat)) - assertIs>(groupSigns(group, again, channel, other, otherContext)) - // Which every member that answered the first is told, once per label, in words. - group.all.drop(1).forEach { d -> - val alarm = fixture.lines(d, ChatMessage.TYPE_LIGHTNING_EQUIVOCATION) - assertEquals(1, alarm.size, "device ${d.index}") - assertEquals(group.all[0].publicKey, alarm.single().senderPublicKey, "attributed to the operator whose node asked") - } - } -} - -/** The cases on regtest, the network every other four-device test runs on. */ -class GroupLightningCoSigningJvmTest : GroupLightningCoSigningCases(Chain.Regtest) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningCoSigningMainnetJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningCoSigningMainnetJvmTest.kt deleted file mode 100644 index f59310f2..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningCoSigningMainnetJvmTest.kt +++ /dev/null @@ -1,9 +0,0 @@ -package mobi.giza.compose.managers - -import fr.acinq.bitcoin.Chain - -/** - * Every co-signing test again, on mainnet: the network the Lightning wallet is opened on, and the one - * where every co-signer holds a channel to the rollout's cap. - */ -class GroupLightningCoSigningMainnetJvmTest : GroupLightningCoSigningCases(Chain.Mainnet) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningLiquidityJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningLiquidityJvmTest.kt deleted file mode 100644 index 33ea9661..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningLiquidityJvmTest.kt +++ /dev/null @@ -1,234 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.database.model.MarmotGroupEvent -import mobi.giza.compose.database.model.NostrEvent -import mobi.giza.compose.network.serialization.CommonJson -import mobi.giza.compose.nostr.lightning.GroupLightningAuthorisationEvent -import mobi.giza.compose.nostr.lightning.GroupLightningEvents -import mobi.giza.compose.wallet.lightning.WalletWire -import mobi.giza.compose.text.ProposedEvent -import mobi.giza.compose.wallet.GroupLightningRollout -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.toHexKey -import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair -import fr.acinq.bitcoin.Chain -import fr.acinq.lightning.Lightning.randomBytes32 -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.cancel -import kotlinx.coroutines.delay -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.withTimeout -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertIs -import kotlin.test.assertNotEquals -import kotlin.test.assertNull -import kotlin.test.assertTrue -import kotlin.time.Clock -import kotlin.time.Duration.Companion.days -import kotlin.time.Duration.Companion.minutes -import kotlin.time.Duration.Companion.seconds - -/** - * The group deciding to buy inbound liquidity (`docs/group-lightning-liquidity.md`, Phase 4): a - * `buy-liquidity` authorisation reads back as what it was, an older build reads it as nothing, the - * proposal says what a signer weighs, and a purchase past the mainnet cap is refused before anyone is asked. - */ -abstract class GroupLightningLiquidityCases(chain: Chain) { - private val fixture = GroupLightningFixture(chain = chain) - private val lsp = "02" + KeyPair().pubKey.toHexKey() - private val channelId = "ab".repeat(32) - - private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) - private val nodes = mutableListOf() - - @AfterTest - fun close() { - scope.cancel() - fixture.close() - } - - /** The operator's node, on a stand-in peer holding one channel of [capacitySat], [live] funding outputs live. */ - private suspend fun runningNode(all: List, live: Int = 1): GroupLightningNode { - val operator = all[1] - val id = randomBytes32().toHex() - operator.db.nostrEventDao().upsert(NostrEvent(id = id, pubKey = operator.publicKey, kind = 445, tags = emptyArray(), content = "", sig = "0".repeat(128))) - operator.db.marmotGroupEventDao().upsert(MarmotGroupEvent(id = id, userPublicKey = operator.publicKey, publicKey = operator.publicKey, chatRoomId = fixture.roomId, signature = "", encryptedContent = "", expiresAt = null, savedAt = Clock.System.now())) - val node = GroupLightningNode( - operator.db, operator.room, operator.publicKey, GroupLightningWalletManager.walletFor(operator.db, fixture.roomId, fixture.chain)!!, scope, - { configuration -> FakeGroupNode(configuration).also { fake -> - fake.channels = listOf(WalletWire.ChannelView(channelId, "Normal", 25_000, 21_900_000, 3_100_000, "ab".repeat(32), 0, 3, liveFundingOutputs = live)) - fake.rates = WalletWire.FundingRates(listOf(WalletWire.FundingRate(10_000, 10_000_000, 400, 100, 100, 1_000)), listOf("from_channel_balance")) - nodes += fake - } }, - handoverCheck = 10.minutes, - minimumPool = 0, - ) - assertIs(node.start()) - return node - } - - private suspend fun authorise(all: List, wallet: GroupLightningWalletManager.Wallet, maxFeeSat: Long = 4_000): GroupLightningAuthorisationEvent.BuyLiquidity { - val buy = GroupLightningAuthorisations.prepareBuyLiquidity(wallet, channelId, 25_000, 200_000, maxFeeSat).getOrThrow() - fixture.signSession(all, all[2], GroupLightningAuthorisations.proposeBuyLiquidity(all[2].db, all[2].room, all[2].publicKey, buy).id) - return buy - } - - private suspend fun reported(all: List, node: GroupLightningNode): WalletWire.Snapshot { - node.report(term = 1, force = true) - fixture.pump(all, setOf(GroupLightningEvents.SNAPSHOT)) - return GroupLightningReports.latest(all[3].db, GroupLightningCoSigner.walletKey(fixture.roomId, fixture.chain, 0))!!.snapshot - } - - private suspend fun opened(): Pair, GroupLightningWalletManager.Wallet> { - 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, fixture.chain, lsp).id) - fixture.signSession(all, all[1], GroupLightningOperatorManager.nominateSelf(all[1].db, all[1].room, all[1].publicKey, fixture.chain).id) - return all to GroupLightningWalletManager.walletFor(all[3].db, fixture.roomId, fixture.chain)!! - } - - @Test - fun `a purchase reads back as what it was, and nothing else reads it`() = runBlocking { - val (_, wallet) = opened() - val buy = GroupLightningAuthorisations.prepareBuyLiquidity(wallet, channelId, capacitySat = 25_000, amountSat = 500_000, maxFeeSat = 7_500).getOrThrow() - assertEquals(500_000, buy.amountSat) - assertEquals(7_500, buy.maxFeeSat) - assertTrue(buy.expiresAt > Clock.System.now().epochSeconds) - val tags = GroupLightningAuthorisationEvent.template(buy).tags - assertEquals(buy, GroupLightningAuthorisationEvent.readBuyLiquidity(tags)) - // An older build, which knows only payments and channel actions, reads it as no authorisation at all. - assertNull(GroupLightningAuthorisationEvent.read(tags)) - assertNull(GroupLightningAuthorisationEvent.readChannelAction(tags)) - // And the purchase reader reads nothing else. - val close = GroupLightningAuthorisationEvent.ChannelAction(GroupLightningAuthorisationEvent.CLOSE, fixture.chain, 0, channelId, buy.expiresAt) - assertNull(GroupLightningAuthorisationEvent.readBuyLiquidity(GroupLightningAuthorisationEvent.template(close).tags)) - - fun with(name: String, value: String) = tags.map { if (it[0] == name) arrayOf(name, value) else it }.toTypedArray() - assertNull(GroupLightningAuthorisationEvent.readBuyLiquidity(with("channel", "cd".repeat(32))), "a channel the identifier does not name") - assertNull(GroupLightningAuthorisationEvent.readBuyLiquidity(with("id", "other")), "an id the identifier does not name") - assertNull(GroupLightningAuthorisationEvent.readBuyLiquidity(with("amount", "0")), "nothing to buy") - assertNull(GroupLightningAuthorisationEvent.readBuyLiquidity(with("maxfee", "-1")), "a negative fee cap") - - // Two purchases for one channel are two events, not one replacing the other. - val again = GroupLightningAuthorisations.prepareBuyLiquidity(wallet, channelId, 25_000, 500_000, 7_500).getOrThrow() - assertNotEquals(GroupLightningAuthorisationEvent.template(buy).tags.first { it[0] == "d" }[1], GroupLightningAuthorisationEvent.template(again).tags.first { it[0] == "d" }[1]) - - val summary = ProposedEvent.summarize(Event("", "", 0, GroupLightningAuthorisationEvent.KIND, tags, "", "")) - assertEquals("Add 500,000 sats of inbound liquidity", summary.label) - assertTrue("7,500 sats" in summary.detail && "after a year" in summary.detail, summary.detail) - } - - @Test - fun `once the group signs, every member reads the open purchase, until it expires`() = runBlocking { - val (all, wallet) = opened() - val buy = GroupLightningAuthorisations.prepareBuyLiquidity(wallet, channelId, 25_000, 200_000, 4_000).getOrThrow() - fixture.signSession(all, all[2], GroupLightningAuthorisations.proposeBuyLiquidity(all[2].db, all[2].room, all[2].publicKey, buy).id) - all.forEach { d -> - val mine = GroupLightningWalletManager.walletFor(d.db, fixture.roomId, fixture.chain)!! - assertEquals(listOf(buy), GroupLightningAuthorisations.liquidityPurchases(d.db, mine), "device ${d.index}") - assertTrue(GroupLightningAuthorisations.liquidityPurchases(d.db, mine, Clock.System.now() + 4.days).isEmpty(), "device ${d.index}: expired") - // A purchase is not a payment budget, nor a close. - assertTrue(GroupLightningAuthorisations.budgets(d.db, mine).isEmpty()) - assertTrue(GroupLightningAuthorisations.channelActions(d.db, fixture.roomId, mine.statement).isEmpty()) - } - } - - @Test - fun `the operator's node buys what the group authorised, once, and every member hears how it went`() = runBlocking { - val (all, wallet) = opened() - val node = runningNode(all) - node.buyAuthorised() - assertTrue(nodes.single().bought.isEmpty(), "nothing is authorised") - val buy = authorise(all, wallet) - node.buyAuthorised() - withTimeout(5.seconds) { while (nodes.single().bought.isEmpty()) delay(20) } - node.buyAuthorised() - delay(200) - assertEquals(listOf(Triple(buy.id, 200_000L, 4_000L)), nodes.single().bought, "bought once, for the amount and cap the group signed") - - val snapshot = reported(all, node) - assertEquals(listOf(WalletWire.LiquidityPurchase(buy.id, channelId, 200_000, WalletWire.PENDING, "cd".repeat(32), 2_521)), snapshot.purchases) - assertEquals(nodes.single().rates, snapshot.fundingRates, "what the LSP sells, for a member to price from") - assertEquals(2L, snapshot.feeratePerByte) - // Once the channel is on the splice's output alone, the purchase reads as locked. - nodes.single().channels = nodes.single().channels.map { it.copy(fundingTxId = "cd".repeat(32), capacitySat = 224_779) } - assertEquals(WalletWire.LOCKED, reported(all, node).purchases.single().state) - node.stop() - } - - @Test - fun `a purchase that would cost more than the cap is never sent, and is not tried again`() = runBlocking { - val (all, wallet) = opened() - val node = runningNode(all) - nodes.single().purchaseFee = 9_000 - val buy = authorise(all, wallet) - node.buyAuthorised() - val failed = withTimeout(5.seconds) { - var p: WalletWire.LiquidityPurchase? = null - while (p?.state != WalletWire.FAILED) { p = reported(all, node).purchases.singleOrNull(); delay(20) } - p - } - assertEquals(buy.id, failed.id) - assertTrue("over the 4000 the group agreed to" in failed.reason!!, failed.reason) - nodes.single().purchaseFee = 2_521 - node.buyAuthorised() - delay(200) - assertTrue(nodes.single().bought.isEmpty(), "a failed purchase waits for the group to ask again") - node.stop() - } - - @Test - fun `while an earlier splice has not locked, the purchase waits, and is made once it has`() = runBlocking { - val (all, wallet) = opened() - val node = runningNode(all, live = 2) - val buy = authorise(all, wallet) - node.buyAuthorised() - delay(200) - assertTrue(nodes.single().bought.isEmpty()) - assertEquals(WalletWire.WAITING, reported(all, node).purchases.single().state) - nodes.single().channels = nodes.single().channels.map { it.copy(liveFundingOutputs = 1) } - node.buyAuthorised() - withTimeout(5.seconds) { while (nodes.single().bought.isEmpty()) delay(20) } - assertEquals(buy.id, nodes.single().bought.single().first) - node.stop() - } - - @Test - fun `a snapshot from a build before purchases still reads, and one with them round-trips`() { - val old = """{"wallet":"w","term":1,"nodeId":"n","sentAt":1,"channels":[{"channelId":"c","state":"Normal","capacitySat":1,"oursMsat":1,"theirsMsat":0,"fundingTxId":"f","fundingIndex":0,"commitIndex":0}],"payments":[{"id":"p","incoming":true,"amountMsat":1,"feesMsat":0,"succeeded":true}]}""" - val read = CommonJson.decodeFromString(WalletWire.Snapshot.serializer(), old) - assertEquals(1, read.channels.single().liveFundingOutputs) - assertEquals(WalletWire.PAYMENT, read.payments.single().kind) - assertTrue(read.purchases.isEmpty() && read.fundingRates == null) - val full = read.copy( - fundingRates = WalletWire.FundingRates(listOf(WalletWire.FundingRate(1, 2, 3, 4, 5, 6)), listOf("from_channel_balance")), - feeratePerByte = 3, - purchases = listOf(WalletWire.LiquidityPurchase("i", "c", 200_000, WalletWire.FAILED, reason = "r")), - payments = listOf(WalletWire.PaymentView("liquidity:t", false, 2_521_000, 2_521_000, succeeded = true, kind = WalletWire.LIQUIDITY, liquiditySat = 200_000)), - ) - assertEquals(full, CommonJson.decodeFromString(WalletWire.Snapshot.serializer(), CommonJson.encodeToString(WalletWire.Snapshot.serializer(), full))) - } - - @Test - fun `a purchase past what a channel may hold is refused before anyone is asked`() = runBlocking { - val (_, wallet) = opened() - fun problem(capacity: Long, amount: Long) = - (GroupLightningAuthorisations.prepareBuyLiquidity(wallet, channelId, capacity, amount, 1_000).exceptionOrNull() as? GroupLightningAuthorisations.LiquidityProblemException)?.problem - assertEquals(GroupLightningAuthorisations.LiquidityProblem.NothingToBuy, problem(25_000, 0)) - val cap = GroupLightningRollout.channelCapFor(fixture.chain) - if (cap == null) { - assertNull(problem(25_000, 10_000_000), "no cap off mainnet") - } else { - assertNull(problem(25_000, cap.sat - 25_000), "up to the cap exactly") - assertIs(problem(25_000, cap.sat - 24_999)) - } - } -} - -class GroupLightningLiquidityJvmTest : GroupLightningLiquidityCases(Chain.Regtest) - -class GroupLightningLiquidityMainnetJvmTest : GroupLightningLiquidityCases(Chain.Mainnet) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningNodeJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningNodeJvmTest.kt deleted file mode 100644 index aa4efb9f..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningNodeJvmTest.kt +++ /dev/null @@ -1,260 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.database.model.ChatMessage -import mobi.giza.compose.database.model.MarmotGroupEvent -import mobi.giza.compose.database.model.NostrEvent -import mobi.giza.compose.network.serialization.CommonJson -import mobi.giza.compose.nostr.lightning.GroupLightningEvents -import mobi.giza.compose.wallet.lightning.GroupLightningNodes -import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair -import com.vitorpamplona.quartz.nip01Core.core.toHexKey -import fr.acinq.bitcoin.PublicKey -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.UnknownFeature -import fr.acinq.lightning.io.TcpSocket -import fr.acinq.lightning.utils.Connection -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.cancel -import kotlinx.coroutines.delay -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.withTimeout -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertIs -import kotlin.test.assertTrue -import kotlin.time.Duration -import kotlin.time.Clock -import kotlin.time.Duration.Companion.milliseconds -import kotlin.time.Duration.Companion.minutes -import kotlin.time.Duration.Companion.seconds - -/** - * The group's node on the operator's device: built with the group's keys, started only by the elected - * operator who has heard from the room recently, and stopped -- with a word to the room -- the moment a - * later term begins (`docs/group-lightning-wallet.md`, Phase 8). The node itself is a stand-in: there is - * no LSP here to connect to. - */ -class GroupLightningNodeJvmTest { - private val fixture = GroupLightningFixture() - private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) - private val lsp = "02" + KeyPair().pubKey.toHexKey() - - @AfterTest - fun close() { - scope.cancel() - fixture.close() - } - - private var configurations = mutableListOf() - private val peers = mutableListOf() - private val factory: suspend (GroupLightningNode.NodeConfiguration) -> GroupLightningNode.PeerHandle = { configuration -> - configurations += configuration - FakeGroupNode(configuration).also { peers += it } - } - - private suspend fun ready(): List { - val all = fixture.group() - fixture.runCeremony(all) - val session = GroupLightningWalletManager.proposeWallet(all[0].db, all[0].room, all[0].publicKey, all[0].privateKey, fixture.chain, lsp) - fixture.signSession(all, all[0], session.id) - return all - } - - private suspend fun elect(all: List, who: GroupLightningFixture.Device) { - val session = GroupLightningOperatorManager.nominateSelf(who.db, who.room, who.publicKey, fixture.chain) - fixture.signSession(all, who, session.id) - } - - /** As if this device had just heard from the room. */ - private suspend fun heardFromRoom(device: GroupLightningFixture.Device) { - // A kind:445 is a nostr event first, and its row hangs off that one. - 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 suspend fun node(device: GroupLightningFixture.Device, reconnectAfter: (Int) -> Duration = { 10.milliseconds }) = GroupLightningNode( - device.db, device.room, device.publicKey, GroupLightningWalletManager.walletFor(device.db, fixture.roomId, fixture.chain)!!, scope, factory, - handoverCheck = 100.milliseconds, - minimumPool = 0, - reconnectAfter = reconnectAfter, - ) - - private suspend fun runningNode(reconnectAfter: (Int) -> Duration = { 10.milliseconds }): Pair { - val all = ready() - elect(all, all[1]) - heardFromRoom(all[1]) - val node = node(all[1], reconnectAfter) - assertIs(node.start()) - return node to peers.single() - } - - @Test - fun `the node runs on the group's keys`() = runBlocking { - val all = ready() - elect(all, all[1]) - heardFromRoom(all[1]) - val node = node(all[1]) - assertIs(node.start()) - val keys = configurations.single().keyManager - val wallet = node.wallet - assertEquals(wallet.statement.nodeId, keys.nodeKeys.nodeKey.publicKey.toString()) - val channelKeys = keys.channelKeys(keys.newFundingKeyPath(isChannelOpener = false)) - assertEquals(PublicKey.fromHex(wallet.statement.icebergKey), channelKeys.fundingPublicKey(0)) - assertEquals(wallet.basepoints.forChannel.payment, channelKeys.paymentBasePoint) - assertEquals(wallet.basepoints.forChannel.delayedPayment, channelKeys.delayedPaymentBasePoint) - assertEquals(GroupWalletDerivation.derive(fixture.account, GroupWalletDerivation.RECEIVE, 0).pubkeyScript, keys.defaultFinalScriptPubKey) - assertTrue(peers.single().connected) - // Starting asked the group for round one ahead of any need. - assertTrue(fixture.outbox(all[1], setOf(GroupLightningEvents.SIGNING_REQUEST)).isNotEmpty()) - assertTrue(fixture.outbox(all[1], setOf(GroupLightningEvents.NONCE_BATCH)).isNotEmpty()) - node.stop() - } - - @Test - fun `only the elected operator, who has heard from the room, may run it`() = runBlocking { - val all = ready() - elect(all, all[1]) - heardFromRoom(all[2]) - assertIs(node(all[2]).start(), "a member who was not elected") - assertIs(node(all[1]).start(), "the operator, who has heard nothing from the room") - assertTrue(peers.isEmpty()) - } - - @Test - fun `a later term stops the node, and the room is told where its channels were`() = runBlocking { - val all = ready() - elect(all, all[1]) - heardFromRoom(all[1]) - val node = node(all[1]) - assertIs(node.start()) - elect(all, all[2]) - withTimeout(5.seconds) { while (node.state.value is GroupLightningNode.State.Running) delay(50) } - assertTrue(peers.single().disconnected) - val stopped = fixture.outbox(all[1], setOf(GroupLightningEvents.STOPPED)).single() - val body = CommonJson.decodeFromString(GroupLightningOperatorManager.Stopped.serializer(), stopped.content) - assertEquals(1, body.term) - assertEquals(mapOf("ab".repeat(32) to 7L), body.commitmentNumbers) - - // The room is told in words too, on every device, by the operator of the term it names. - fixture.pump(all, setOf(GroupLightningEvents.STOPPED)) - all.forEach { d -> - val line = fixture.lines(d, ChatMessage.TYPE_LIGHTNING_OPERATOR_STOPPED).single() - assertEquals(all[1].publicKey, line.senderPublicKey) - assertEquals("stopped running the group's Lightning node.", line.content) - } - // A stop from anybody else is nobody's. - val forged = with(fixture) { stopped.copy(id = "f".repeat(64), publicKey = all[3].publicKey).asEvent() } - all[2].db.marmotInnerEventDao().upsert(stopped.copy(id = "f".repeat(64), publicKey = all[3].publicKey)) - GroupLightningOperatorManager.receiveStopped(all[2].db, all[2].room, forged) - assertEquals(1, fixture.lines(all[2], ChatMessage.TYPE_LIGHTNING_OPERATOR_STOPPED).size) - } - - @Test - fun `the identity's nodes start where it operates and nowhere else`() = runBlocking { - val all = ready() - elect(all, all[3]) - all.forEach { heardFromRoom(it) } - val operatorNodes = GroupLightningNodes(all[3].db, all[3].publicKey, scope, factory, fixture.chain, minimumPool = 0) - val otherNodes = GroupLightningNodes(all[0].db, all[0].publicKey, scope, factory, fixture.chain, minimumPool = 0) - operatorNodes.refresh() - otherNodes.refresh() - assertIs(operatorNodes.nodeFor(fixture.roomId)?.state?.value) - assertEquals(null, otherNodes.nodeFor(fixture.roomId)) - operatorNodes.stop() - assertTrue(peers.single().disconnected) - assertTrue(1.minutes > 0.seconds) - } - - @Test - fun `a node does not connect before the group has sent round one`() = runBlocking { - val all = ready() - elect(all, all[1]) - heardFromRoom(all[1]) - // Nobody answers the provision request here, so the pool never fills. - val node = GroupLightningNode( - all[1].db, all[1].room, all[1].publicKey, GroupLightningWalletManager.walletFor(all[1].db, fixture.roomId, fixture.chain)!!, scope, factory, - minimumPool = 4, poolWait = 1.seconds, - ) - assertIs(node.start()) - assertTrue(peers.isEmpty(), "it never connected") - } - - @Test - fun `a node the LSP drops dials it again`() = runBlocking { - val (node, peer) = runningNode() - assertEquals(1, peer.connects) - peer.drops.send("Connection closed") - withTimeout(5.seconds) { while (peer.connects < 2) delay(10) } - peer.drops.send("Connection closed") - withTimeout(5.seconds) { while (peer.connects < 3) delay(10) } - assertIs(node.state.value) - node.stop() - } - - @Test - fun `connections that drop at once back off further each time`() = runBlocking { - val failures = mutableListOf() - val (node, peer) = runningNode(reconnectAfter = { failures += it; 10.milliseconds }) - repeat(3) { i -> - peer.drops.send("Connection closed") - withTimeout(5.seconds) { while (peer.connects < i + 2) delay(10) } - } - assertEquals(listOf(1, 2, 3), failures) - // Each dial carries its place in the run, for Phoenix's growing timeouts. - assertEquals(listOf(1, 2, 3, 4), peer.attempts) - node.stop() - } - - @Test - fun `a stopped node does not dial again`() = runBlocking { - val (node, peer) = runningNode() - node.stop() - peer.drops.send("Connection closed") - delay(200) - assertEquals(1, peer.connects) - assertTrue(peer.disconnected) - } - - @Test - fun `the backoff doubles from two seconds to five minutes`() { - assertEquals( - listOf(2.seconds, 4.seconds, 8.seconds, 16.seconds, 32.seconds, 64.seconds, 128.seconds, 256.seconds, 5.minutes, 5.minutes), - (1..10).map(GroupLightningNode::reconnectDelay), - ) - assertEquals(5.minutes, GroupLightningNode.reconnectDelay(1_000)) - } - - @Test - fun `the timeouts grow as Phoenix's do, three times as long over Tor`() { - assertEquals(1.seconds to 2.seconds, GroupLightningNode.connectTimeouts(1, torIsEnabled = false)) - assertEquals(4.seconds to 7.seconds, GroupLightningNode.connectTimeouts(5, torIsEnabled = false)) - assertEquals(10.seconds to 15.seconds, GroupLightningNode.connectTimeouts(50, torIsEnabled = false)) - assertEquals(3.seconds to 6.seconds, GroupLightningNode.connectTimeouts(1, torIsEnabled = true)) - } - - @Test - fun `a drop names the feature the LSP would not offer`() { - val ours = Features(Feature.SimpleTaprootChannels to FeatureSupport.Mandatory, Feature.VariableLengthOnion to FeatureSupport.Mandatory) - val closed = Connection.CLOSED(TcpSocket.IOException.ConnectionClosed()) - assertEquals( - "Connection closed: the LSP does not offer simple_taproot_channels, which this node requires", - GroupLightningNode.dropReason(ours, Features(Feature.VariableLengthOnion to FeatureSupport.Mandatory), closed), - ) - assertEquals( - "Connection closed: the LSP requires bit 600, which this node does not know", - GroupLightningNode.dropReason(ours, Features(ours.activated, setOf(UnknownFeature(600), UnknownFeature(601))), closed), - ) - assertEquals("Connection closed", GroupLightningNode.dropReason(ours, ours, closed)) - assertEquals("Connection closed, before the LSP sent its features", GroupLightningNode.dropReason(ours, null, closed)) - assertEquals("closed by this node", GroupLightningNode.dropReason(ours, ours, Connection.CLOSED(null))) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningPaymentsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningPaymentsJvmTest.kt deleted file mode 100644 index 363844a2..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningPaymentsJvmTest.kt +++ /dev/null @@ -1,206 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.database.model.MarmotGroupEvent -import mobi.giza.compose.database.model.NostrEvent -import mobi.giza.compose.nostr.lightning.GroupLightningAuthorisationEvent -import mobi.giza.compose.text.ProposedEvent -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.toHexKey -import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair -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.Lightning.randomBytes32 -import fr.acinq.lightning.payment.Bolt11Invoice -import fr.acinq.lightning.utils.msat -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.cancel -import kotlinx.coroutines.delay -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.withTimeout -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertIs -import kotlin.test.assertNull -import kotlin.test.assertTrue -import kotlin.time.Clock -import kotlin.time.Duration.Companion.days -import kotlin.time.Duration.Companion.hours -import kotlin.time.Duration.Companion.minutes -import kotlin.time.Duration.Companion.seconds - -/** - * Paying from the group's Lightning wallet (`docs/group-lightning-wallet.md`, Phase 12): the group signs an - * authorisation, every co-signer reads it as a budget, and the operator's node pays it once. Nothing the - * group did not sign becomes a budget. - */ -class GroupLightningPaymentsJvmTest { - private val fixture = GroupLightningFixture() - private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) - private val lsp = "02" + KeyPair().pubKey.toHexKey() - private val payee = PrivateKey(randomBytes32()) - private val nodes = mutableListOf() - - @AfterTest - fun close() { - scope.cancel() - fixture.close() - } - - private fun invoice(amountMsat: Long? = 12_000_000, chain: Chain = fixture.chain, signer: PrivateKey = payee, expirySeconds: Long? = null, timestamp: Long = Clock.System.now().epochSeconds) = - Bolt11Invoice.create(chain, amountMsat?.msat, randomBytes32(), signer, Either.Left("coffee"), CltvExpiryDelta(144), INVOICE_FEATURES, expirySeconds = expirySeconds, timestampSeconds = timestamp) - - private suspend fun opened(): Pair, GroupLightningWalletManager.Wallet> { - 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, fixture.chain, lsp).id) - fixture.signSession(all, all[1], GroupLightningOperatorManager.nominateSelf(all[1].db, all[1].room, all[1].publicKey, fixture.chain).id) - return all to GroupLightningWalletManager.walletFor(all[3].db, fixture.roomId, fixture.chain)!! - } - - private suspend fun authorise(all: List, pay: GroupLightningAuthorisationEvent.Pay, proposer: GroupLightningFixture.Device = all[3]) { - fixture.signSession(all, proposer, GroupLightningAuthorisations.propose(proposer.db, proposer.room, proposer.publicKey, pay).id) - } - - @Test - fun `an authorisation reads back as what it was, and refuses to disagree with its invoice`() = runBlocking { - val (_, wallet) = opened() - val pay = GroupLightningAuthorisations.prepare(wallet, "lightning:" + invoice().write(), null, 1_000_000).getOrThrow() - assertEquals(12_000_000, pay.amountMsat) - assertEquals(13_000_000, pay.budgetMsat) - val tags = GroupLightningAuthorisationEvent.template(pay).tags - assertEquals(pay, GroupLightningAuthorisationEvent.read(tags)) - - fun with(name: String, value: String) = tags.map { if (it[0] == name) arrayOf(name, value) else it }.toTypedArray() - assertNull(GroupLightningAuthorisationEvent.read(with("amount", "13000000")), "an amount the invoice does not name") - assertNull(GroupLightningAuthorisationEvent.read(with("hash", "00".repeat(32))), "a hash the invoice does not carry") - assertNull(GroupLightningAuthorisationEvent.read(with("expires", (Clock.System.now() + 2.hours).epochSeconds.toString())), "an expiry past the invoice's") - assertNull(GroupLightningAuthorisationEvent.read(with("action", "splice")), "an action this device does not know") - - val summary = ProposedEvent.summarize(Event("", "", 0, GroupLightningAuthorisationEvent.KIND, tags, "", "")) - assertEquals("Pay 12,000 sats", summary.label) - assertTrue("coffee" in summary.detail && "1,000 sats" in summary.detail, summary.detail) - } - - @Test - fun `what cannot be paid is said before the group is asked`() = runBlocking { - val (_, wallet) = opened() - fun problem(bolt11: String, amount: Long? = null) = - (GroupLightningAuthorisations.prepare(wallet, bolt11, amount, 0).exceptionOrNull() as GroupLightningAuthorisations.ProblemException).problem - assertEquals(GroupLightningAuthorisations.Problem.Unreadable, problem("lnbc1nonsense")) - assertEquals(GroupLightningAuthorisations.Problem.OtherNetwork, problem(invoice(chain = Chain.Mainnet).write())) - assertEquals(GroupLightningAuthorisations.Problem.Expired, problem(invoice(expirySeconds = 60, timestamp = Clock.System.now().epochSeconds - 120).write())) - assertEquals(GroupLightningAuthorisations.Problem.NeedsAmount, problem(invoice(amountMsat = null).write())) - val nodeKey = GroupLightningCoSigner.keyManagerOf(fr.acinq.bitcoin.ByteVector(wallet.seed!!.seed), fixture.chain).nodeKeys.nodeKey.privateKey - assertEquals(GroupLightningAuthorisations.Problem.PaysTheGroup, problem(invoice(signer = nodeKey).write())) - assertEquals(5_000_000, GroupLightningAuthorisations.prepare(wallet, invoice(amountMsat = null).write(), 5_000_000, 0).getOrThrow().amountMsat) - } - - @Test - fun `once the group signs, every co-signer has the budget, and an expired one is closed`() = runBlocking { - val (all, wallet) = opened() - assertTrue(GroupLightningAuthorisations.budgets(all[2].db, wallet).isEmpty(), "nothing is authorised yet") - val pay = GroupLightningAuthorisations.prepare(wallet, invoice().write(), null, 1_000_000).getOrThrow() - authorise(all, pay) - all.forEach { d -> - val mine = GroupLightningWalletManager.walletFor(d.db, fixture.roomId, fixture.chain)!! - assertEquals(mapOf(pay.paymentHash to 13_000_000L), GroupLightningAuthorisations.budgets(d.db, mine), "device ${d.index}") - assertTrue(GroupLightningAuthorisations.expired(d.db, mine).isEmpty()) - assertEquals(listOf(pay), GroupLightningAuthorisations.toPay(d.db, mine)) - } - val later = Clock.System.now() + 2.hours - assertEquals(setOf(pay.paymentHash), GroupLightningAuthorisations.expired(all[2].db, wallet, later)) - assertTrue(GroupLightningAuthorisations.toPay(all[2].db, wallet, later).isEmpty()) - // Still a budget: an HTLC that left before the expiry settles against it. - assertEquals(13_000_000L, GroupLightningAuthorisations.budgets(all[2].db, wallet)[pay.paymentHash]) - } - - @Test - fun `the operator's node pays what the group authorised, once`() = runBlocking { - val (all, _) = opened() - val operator = all[1] - val id = randomBytes32().toHex() - operator.db.nostrEventDao().upsert(NostrEvent(id = id, pubKey = operator.publicKey, kind = 445, tags = emptyArray(), content = "", sig = "0".repeat(128))) - operator.db.marmotGroupEventDao().upsert(MarmotGroupEvent(id = id, userPublicKey = operator.publicKey, publicKey = operator.publicKey, chatRoomId = fixture.roomId, signature = "", encryptedContent = "", expiresAt = null, savedAt = Clock.System.now())) - val node = GroupLightningNode( - operator.db, operator.room, operator.publicKey, GroupLightningWalletManager.walletFor(operator.db, fixture.roomId, fixture.chain)!!, scope, - { configuration -> FakeGroupNode(configuration).also { nodes += it } }, - handoverCheck = 10.minutes, - minimumPool = 0, - ) - assertIs(node.start()) - node.payAuthorised() - assertTrue(nodes.single().paid.isEmpty(), "nothing is authorised") - - val wallet = GroupLightningWalletManager.walletFor(all[3].db, fixture.roomId, fixture.chain)!! - val bolt11 = invoice().write() - authorise(all, GroupLightningAuthorisations.prepare(wallet, bolt11, null, 1_000_000).getOrThrow()) - node.payAuthorised() - withTimeout(5.seconds) { while (nodes.single().paid.isEmpty()) delay(20) } - node.payAuthorised() - delay(200) - assertEquals(listOf(bolt11 to 12_000_000L), nodes.single().paid) - } - - @Test - fun `a payment leaves as the group signs it, not at the next poll`() = runBlocking { - val (all, _) = opened() - val operator = all[1] - val id = randomBytes32().toHex() - operator.db.nostrEventDao().upsert(NostrEvent(id = id, pubKey = operator.publicKey, kind = 445, tags = emptyArray(), content = "", sig = "0".repeat(128))) - operator.db.marmotGroupEventDao().upsert(MarmotGroupEvent(id = id, userPublicKey = operator.publicKey, publicKey = operator.publicKey, chatRoomId = fixture.roomId, signature = "", encryptedContent = "", expiresAt = null, savedAt = Clock.System.now())) - val node = GroupLightningNode( - operator.db, operator.room, operator.publicKey, GroupLightningWalletManager.walletFor(operator.db, fixture.roomId, fixture.chain)!!, scope, - { configuration -> FakeGroupNode(configuration).also { nodes += it } }, - handoverCheck = 10.minutes, - minimumPool = 0, - ) - assertIs(node.start()) - val wallet = GroupLightningWalletManager.walletFor(all[3].db, fixture.roomId, fixture.chain)!! - val bolt11 = invoice().write() - authorise(all, GroupLightningAuthorisations.prepare(wallet, bolt11, null, 1_000_000).getOrThrow()) - withTimeout(5.seconds) { while (nodes.single().paid.isEmpty()) delay(20) } - delay(200) - assertEquals(listOf(bolt11 to 12_000_000L), nodes.single().paid) - node.stop() - } - - @Test - fun `a close the group authorises is made once, to the onchain wallet, and a force close by force`() = runBlocking { - val (all, wallet) = opened() - val operator = all[1] - val id = randomBytes32().toHex() - operator.db.nostrEventDao().upsert(NostrEvent(id = id, pubKey = operator.publicKey, kind = 445, tags = emptyArray(), content = "", sig = "0".repeat(128))) - operator.db.marmotGroupEventDao().upsert(MarmotGroupEvent(id = id, userPublicKey = operator.publicKey, publicKey = operator.publicKey, chatRoomId = fixture.roomId, signature = "", encryptedContent = "", expiresAt = null, savedAt = Clock.System.now())) - val node = GroupLightningNode( - operator.db, operator.room, operator.publicKey, GroupLightningWalletManager.walletFor(operator.db, fixture.roomId, fixture.chain)!!, scope, - { configuration -> FakeGroupNode(configuration).also { nodes += it } }, - handoverCheck = 10.minutes, - minimumPool = 0, - ) - assertIs(node.start()) - val one = "c1".repeat(32) - val two = "c2".repeat(32) - nodes.single().channels = listOf(one, two).map { mobi.giza.compose.wallet.lightning.WalletWire.ChannelView(it, "Normal", 1_000_000, 1, 1, "dd".repeat(32), 0, 0) } - - fixture.signSession(all, all[3], GroupLightningAuthorisations.proposeChannelAction(all[3].db, all[3].room, all[3].publicKey, wallet, one, force = false).id) - fixture.signSession(all, all[2], GroupLightningAuthorisations.proposeChannelAction(all[2].db, all[2].room, all[2].publicKey, wallet, two, force = true).id) - node.closeAuthorised() - node.closeAuthorised() - assertEquals(listOf(one to GroupWalletDerivation.derive(fixture.account, GroupWalletDerivation.RECEIVE, 0).pubkeyScript), nodes.single().closed) - assertEquals(listOf(two), nodes.single().forceClosed) - - val actions = GroupLightningAuthorisations.channelActions(all[0].db, fixture.roomId, wallet.statement) - // Both signed in the same second, so in no particular order. - assertEquals(mapOf(one to GroupLightningAuthorisationEvent.CLOSE, two to GroupLightningAuthorisationEvent.FORCE_CLOSE), actions.associate { it.channelId to it.action }) - val forced = actions.single { it.action == GroupLightningAuthorisationEvent.FORCE_CLOSE } - val summary = ProposedEvent.summarize(Event("", "", 0, GroupLightningAuthorisationEvent.KIND, GroupLightningAuthorisationEvent.template(forced).tags, "", "")) - assertEquals("Force-close a Lightning channel", summary.label) - assertTrue(GroupLightningAuthorisations.channelActions(all[0].db, fixture.roomId, wallet.statement, Clock.System.now() + 4.days).isEmpty(), "both have expired") - assertNull(GroupLightningAuthorisationEvent.read(GroupLightningAuthorisationEvent.template(forced).tags), "a close is not a payment") - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningRekeyJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningRekeyJvmTest.kt deleted file mode 100644 index 2ab62a70..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningRekeyJvmTest.kt +++ /dev/null @@ -1,115 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.database.model.MarmotGroupEvent -import mobi.giza.compose.database.model.NostrEvent -import mobi.giza.compose.database.model.types.IcebergRitualStage -import mobi.giza.compose.nostr.lightning.GroupLightningAuthorisationEvent -import mobi.giza.compose.nostr.lightning.GroupLightningEvents -import mobi.giza.compose.wallet.lightning.GroupLightningNodes -import com.vitorpamplona.quartz.nip01Core.core.toHexKey -import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair -import fr.acinq.lightning.Lightning.randomBytes32 -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.cancel -import kotlinx.coroutines.runBlocking -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertIs -import kotlin.test.assertNotEquals -import kotlin.test.assertNull -import kotlin.test.assertTrue -import kotlin.time.Clock - -/** - * A member leaves a group with a Lightning wallet (`docs/group-lightning-wallet.md`, Phase 14). Iceberg - * cannot reshare, so the group makes a new key without them and opens a second wallet beside the first, - * whose channels it then closes. Five members, so that four remain: a 2-of-n Iceberg key needs n >= 4. - */ -class GroupLightningRekeyJvmTest { - private val fixture = GroupLightningFixture(n = 5, frostThreshold = 3) - private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) - private val lsp = "02" + KeyPair().pubKey.toHexKey() - private val nodes = mutableListOf() - - @AfterTest - fun close() { - scope.cancel() - fixture.close() - } - - 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())) - } - - @Test - fun `the group re-keys without a member who left, and keeps the old wallet until its channels close`() = runBlocking { - 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, fixture.chain, lsp).id) - fixture.signSession(all, all[1], GroupLightningOperatorManager.nominateSelf(all[1].db, all[1].room, all[1].publicKey, fixture.chain, 0).id) - val first = GroupLightningWalletManager.current(all[0].db, fixture.roomId, fixture.chain)!! - assertEquals(0, first.statement.wallet) - assertEquals(5, first.statement.participants.size) - - // The last member is removed; the four who remain apply the commit. - val leaver = all[4] - val remaining = all.take(4) - fixture.remove(leaver.publicKey, remaining) - assertEquals(listOf(leaver.publicKey.lowercase()), GroupLightningWalletManager.departed(all[0].db, first)) - assertEquals(listOf(2), IcebergRitualManager.thresholds(all[0].db, fixture.roomId), "four remain, so 2-of-4") - - // The leaver's device, which never saw its own removal, cannot pull the others into a ceremony with it. - val stale = IcebergRitualManager.proposeCeremony(leaver.db, leaver.room, leaver.publicKey, leaver.privateKey, 2, fixture.chain) - fixture.pump(all, GroupLightningEvents.CEREMONY) - remaining.forEach { assertNull(it.ceremony(stale.id), "device ${it.index} refused a ceremony naming someone who left") } - - val second = fixture.runCeremony(remaining, proposer = remaining[0]) - remaining.forEach { assertEquals(IcebergRitualStage.COMPLETE, it.ceremony(second.id)?.stage) } - assertEquals(4, remaining[0].ceremony(second.id)!!.participants().size) - assertTrue(leaver.publicKey.lowercase() !in remaining[0].ceremony(second.id)!!.participants()) - - fixture.signSession(remaining, remaining[0], GroupLightningWalletManager.proposeWallet(remaining[0].db, remaining[0].room, remaining[0].publicKey, remaining[0].privateKey, fixture.chain, lsp).id) - remaining.forEach { d -> - val wallets = GroupLightningWalletManager.wallets(d.db, fixture.roomId, fixture.chain) - assertEquals(listOf(0L, 1L), wallets.map { it.statement.wallet }, "device ${d.index} believes both") - val current = wallets.last() - assertEquals(second.id, current.statement.ceremonyId) - assertNotEquals(first.statement.nodeId, current.statement.nodeId) - assertTrue(GroupLightningWalletManager.departed(d.db, current).isEmpty()) - assertEquals(null, GroupLightningWalletManager.unusedKey(d.db, fixture.roomId, fixture.chain), "both keys are in use") - } - - // The new wallet gets its own operator; the old one keeps its own until its channels are closed. - fixture.signSession(remaining, remaining[2], GroupLightningOperatorManager.nominateSelf(remaining[2].db, remaining[2].room, remaining[2].publicKey, fixture.chain, 1).id) - assertEquals(remaining[1].publicKey, GroupLightningOperatorManager.current(remaining[0].db, fixture.roomId, fixture.chain, 0)?.publicKey) - assertEquals(remaining[2].publicKey, GroupLightningOperatorManager.current(remaining[0].db, fixture.roomId, fixture.chain, 1)?.publicKey) - val factory: suspend (GroupLightningNode.NodeConfiguration) -> GroupLightningNode.PeerHandle = { FakeGroupNode(it).also { node -> nodes += node } } - remaining.forEach { heardFromRoom(it) } - val oldOperator = GroupLightningNodes(remaining[1].db, remaining[1].publicKey, scope, factory, fixture.chain, minimumPool = 0) - val newOperator = GroupLightningNodes(remaining[2].db, remaining[2].publicKey, scope, factory, fixture.chain, minimumPool = 0) - oldOperator.refresh() - newOperator.refresh() - assertIs(oldOperator.nodeFor(fixture.roomId, 0)?.state?.value) - assertNull(oldOperator.nodeFor(fixture.roomId, 1)) - assertIs(newOperator.nodeFor(fixture.roomId, 1)?.state?.value) - assertEquals(1, newOperator.nodeFor(fixture.roomId)?.wallet?.statement?.wallet, "a room's node is its current wallet's") - - // Closing the old wallet's channels is one decision, whatever their number. - val channels = listOf("a1".repeat(32), "a2".repeat(32)) - val old = GroupLightningWalletManager.walletFor(remaining[3].db, fixture.roomId, fixture.chain, 0)!! - val session = GroupLightningAuthorisations.proposeCloseAll(remaining[3].db, remaining[3].room, remaining[3].publicKey, old, channels) - assertEquals(2, remaining[3].db.frostSigningSessionDao().getItems(session.id).size) - fixture.signSession(remaining, remaining[3], session.id) - val actions = GroupLightningAuthorisations.channelActions(remaining[1].db, fixture.roomId, old.statement) - assertEquals(channels.toSet(), actions.map { it.channelId }.toSet()) - assertTrue(actions.all { it.action == GroupLightningAuthorisationEvent.CLOSE && it.wallet == 0L }) - assertTrue(GroupLightningAuthorisations.channelActions(remaining[1].db, fixture.roomId, GroupLightningWalletManager.walletFor(remaining[1].db, fixture.roomId, fixture.chain, 1)!!.statement).isEmpty(), "the new wallet's channels are not touched") - oldOperator.stop() - newOperator.stop() - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningReportsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningReportsJvmTest.kt deleted file mode 100644 index c1f7b34d..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningReportsJvmTest.kt +++ /dev/null @@ -1,276 +0,0 @@ -package mobi.giza.compose.managers - -import kotlin.time.Instant -import mobi.giza.compose.database.model.ChatMessage -import mobi.giza.compose.database.model.IcebergChannelLedger -import mobi.giza.compose.database.model.MarmotGroupEvent -import mobi.giza.compose.database.model.NostrEvent -import mobi.giza.compose.network.serialization.CommonJson -import mobi.giza.compose.nostr.lightning.GroupLightningEvents -import mobi.giza.compose.wallet.lightning.CoSignerPolicy -import mobi.giza.compose.wallet.lightning.WalletWire -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.toHexKey -import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.PublicKey -import fr.acinq.bitcoin.utils.Either -import fr.acinq.lightning.CltvExpiryDelta -import fr.acinq.lightning.Lightning.randomBytes32 -import fr.acinq.lightning.payment.Bolt11Invoice -import fr.acinq.lightning.payment.OfferManager -import fr.acinq.lightning.utils.msat -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertIs -import kotlin.test.assertNotNull -import kotlin.test.assertNull -import kotlin.time.Clock -import kotlin.time.Duration.Companion.minutes -import kotlin.time.Duration.Companion.seconds -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.cancel -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.first -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.withTimeout - -/** - * What the operator's node tells the room, and what each member makes of it - * (`docs/group-lightning-wallet.md`, Phase 10): a snapshot is believed only from the operator of the term - * it names, every member files it with each channel checked against its own co-signing ledger, and the - * round-one assignments it carries reach whoever operates next. And an invoice a member asks for (Phase 11) - * is made by the operator's node and believed only if it pays the group's node. - */ -class GroupLightningReportsJvmTest { - private val fixture = GroupLightningFixture() - private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) - private val lsp = "02" + KeyPair().pubKey.toHexKey() - private val key = GroupLightningCoSigner.walletKey(fixture.roomId, fixture.chain, 0) - private val nodes = mutableListOf() - - @AfterTest - fun close() { - scope.cancel() - fixture.close() - } - - private val channel = WalletWire.ChannelView("cc".repeat(32), "Normal", 1_000_000, 400_000_000, 600_000_000, "dd".repeat(32), 0, 3) - private val payment = WalletWire.PaymentView("p1", incoming = true, amountMsat = 21_000_000, feesMsat = 0, paymentHash = "ee".repeat(32), description = "lunch", completedAt = 1_700_000_000_000, succeeded = true) - - /** Four devices with a Lightning wallet open, [operator] elected and running the group's node. */ - private suspend fun running(operator: Int = 1): Pair, GroupLightningNode> { - 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, fixture.chain, lsp).id) - val who = all[operator] - fixture.signSession(all, who, GroupLightningOperatorManager.nominateSelf(who.db, who.room, who.publicKey, fixture.chain).id) - val id = randomBytes32().toHex() - who.db.nostrEventDao().upsert(NostrEvent(id = id, pubKey = who.publicKey, kind = 445, tags = emptyArray(), content = "", sig = "0".repeat(128))) - who.db.marmotGroupEventDao().upsert(MarmotGroupEvent(id = id, userPublicKey = who.publicKey, publicKey = who.publicKey, chatRoomId = fixture.roomId, signature = "", encryptedContent = "", expiresAt = null, savedAt = Clock.System.now())) - val node = GroupLightningNode( - who.db, who.room, who.publicKey, GroupLightningWalletManager.walletFor(who.db, fixture.roomId, fixture.chain)!!, scope, - { configuration -> FakeGroupNode(configuration).also { nodes += it } }, - // The tests drive reporting themselves. - handoverCheck = 10.minutes, - minimumPool = 0, - ) - assertIs(node.start()) - return all to node - } - - private fun snapshotEvent(from: GroupLightningFixture.Device, snapshot: WalletWire.Snapshot) = - Event(randomBytes32().toHex(), from.publicKey, Clock.System.now().epochSeconds, GroupLightningEvents.SNAPSHOT, emptyArray(), CommonJson.encodeToString(WalletWire.Snapshot.serializer(), snapshot), "") - - @Test - fun `the operator's snapshot reaches every member, checked against what each one signed`() = runBlocking { - val (all, node) = running() - nodes.single().channels = listOf(channel) - nodes.single().payments += payment - node.report(term = 1) - fixture.pump(all, setOf(GroupLightningEvents.SNAPSHOT)) - - // One member signed the operator's figure, one signed another, one signed nothing for the channel. - fun ledger(oursMsat: Long) = IcebergChannelLedger(key, channel.channelId, "${channel.fundingTxId}:0", lsp, GroupLightningCoSigner.store(CoSignerPolicy.Ledger(3, "tx", oursMsat, emptyMap(), emptyMap(), 0))) - all[2].db.icebergCoSigningDao().upsertChannelLedger(ledger(400_000_000)) - all[3].db.icebergCoSigningDao().upsertChannelLedger(ledger(390_000_000)) - - val reports = all.map { assertNotNull(GroupLightningReports.latest(it.db, key), "device ${it.index} filed the snapshot") } - reports.forEach { - assertEquals(1, it.snapshot.term) - assertEquals(400_000_000, it.snapshot.spendableMsat) - assertEquals(600_000_000, it.snapshot.inboundMsat) - } - assertEquals(listOf(null, null, true, false), reports.map { it.checks.single().agrees }) - all.forEach { d -> - val filed = d.db.groupLightningRecordsDao().observePayments(key).first() - assertEquals(listOf("lunch"), filed.map { it.description }, "device ${d.index} kept the payment") - } - } - - @Test - fun `nothing changed is not sent again until the snapshot is due`() = runBlocking { - val (all, node) = running() - val sent = { runBlocking { fixture.outbox(all[1], setOf(GroupLightningEvents.SNAPSHOT)).size } } - assertEquals(1, sent(), "starting sends one") - node.report(term = 1) - assertEquals(1, sent()) - nodes.single().channels = listOf(channel) - node.report(term = 1) - assertEquals(2, sent()) - } - - @Test - fun `only the operator of the term a snapshot names is believed`() = runBlocking { - val (all, _) = running() - fixture.pump(all, setOf(GroupLightningEvents.SNAPSHOT)) - val wallet = GroupLightningWalletManager.walletFor(all[3].db, fixture.roomId, fixture.chain)!! - val forged = WalletWire.Snapshot(key, 1, wallet.statement.nodeId, Clock.System.now().epochSeconds + 60, listOf(channel.copy(oursMsat = 999_000_000)), emptyList()) - GroupLightningReports.process(all[3].db, all[3].room, snapshotEvent(all[2], forged)) - assertEquals(0, GroupLightningReports.latest(all[3].db, key)!!.snapshot.spendableMsat, "the forged one did not replace the operator's") - - val otherNode = forged.copy(nodeId = "02" + "77".repeat(32)) - GroupLightningReports.process(all[3].db, all[3].room, snapshotEvent(all[1], otherNode)) - assertEquals(0, GroupLightningReports.latest(all[3].db, key)!!.snapshot.spendableMsat, "nor one about some other node") - - // The operator's own, carrying the labels it handed out, files them for whoever operates next. - val handover = forged.copy(assignments = mapOf("verification:x:y:0" to 5L)) - GroupLightningReports.process(all[3].db, all[3].room, snapshotEvent(all[1], handover)) - assertEquals(999_000_000, GroupLightningReports.latest(all[3].db, key)!!.snapshot.spendableMsat) - val assignment = assertNotNull(all[3].db.icebergCoSigningDao().assignmentFor(key, "verification:x:y:0")) - assertEquals(5L, assignment.counter) - assertEquals(GroupLightningCoSigner.poolLabel(wallet.statement.icebergKey, 5).toHex(), assignment.label) - assertNull(all[2].db.icebergCoSigningDao().assignmentFor(key, "verification:x:y:0")) - } - - @Test - fun `a member asks for an invoice, and the operator's node makes one that pays the group's node`() = runBlocking { - val (all, node) = running() - val wallet = GroupLightningWalletManager.walletFor(all[3].db, fixture.roomId, fixture.chain)!! - val requestId = GroupLightningReports.requestInvoice(all[3].db, all[3].room, all[3].publicKey, wallet, 21_000_000, "lunch") - fixture.pump(all, setOf(GroupLightningEvents.INVOICE_REQUEST)) - node.answerInvoiceRequests() - node.answerInvoiceRequests() - assertEquals(1, nodes.single().invoices.size, "a request is answered once") - fixture.pump(all, setOf(GroupLightningEvents.INVOICE)) - - all.forEach { d -> - val row = assertNotNull(d.db.groupLightningRecordsDao().invoice(key, requestId), "device ${d.index} has the invoice") - val invoice = Bolt11Invoice.read(row.bolt11).get() - assertEquals(wallet.statement.nodeId, invoice.nodeId.toString()) - assertEquals(21_000_000.msat, invoice.amount) - assertEquals("lunch", invoice.description) - - // Who asked, for how much, and that the node answered, on every device. - val asked = fixture.lines(d, ChatMessage.TYPE_LIGHTNING_INVOICE_REQUESTED).single() - assertEquals(all[3].publicKey, asked.senderPublicKey) - assertEquals("asked the operator's node for an invoice of 21,000 sats, for \u201clunch\u201d.", asked.content) - val issued = fixture.lines(d, ChatMessage.TYPE_LIGHTNING_INVOICE_ISSUED).single() - assertEquals("The operator's node made @${ChatMessage.memberName(d.db, all[3].publicKey)}'s invoice.", issued.content) - } - } - - @Test - fun `a request is answered as it arrives, not at the next poll`() = runBlocking { - // The poll is ten minutes off: only the node's watch on the room can answer in time. - val (all, _) = running() - val wallet = GroupLightningWalletManager.walletFor(all[3].db, fixture.roomId, fixture.chain)!! - GroupLightningReports.requestInvoice(all[3].db, all[3].room, all[3].publicKey, wallet, 21_000_000, "lunch") - fixture.pump(all, setOf(GroupLightningEvents.INVOICE_REQUEST)) - withTimeout(5.seconds) { while (nodes.single().invoices.isEmpty()) delay(20) } - delay(200) - assertEquals(1, nodes.single().invoices.size, "a request is answered once") - } - - @Test - fun `an invoice is believed only from the operator, and only if it pays the group's node`() = runBlocking { - val (all, _) = running() - val wallet = GroupLightningWalletManager.walletFor(all[3].db, fixture.roomId, fixture.chain)!! - val nodeKey = GroupLightningCoSigner.keyManagerOf(ByteVector(wallet.seed!!.seed), fixture.chain).nodeKeys.nodeKey.privateKey - fun invoice(signer: PrivateKey) = Bolt11Invoice.create(fixture.chain, 1_000.msat, randomBytes32(), signer, Either.Left("x"), CltvExpiryDelta(144), INVOICE_FEATURES).write() - fun reply(from: GroupLightningFixture.Device, requestId: String, bolt11: String) = Event( - randomBytes32().toHex(), from.publicKey, Clock.System.now().epochSeconds, GroupLightningEvents.INVOICE, emptyArray(), - CommonJson.encodeToString(WalletWire.InvoiceReply.serializer(), WalletWire.InvoiceReply(key, requestId, bolt11)), "", - ) - GroupLightningReports.process(all[3].db, all[3].room, reply(all[1], "elsewhere", invoice(PrivateKey(randomBytes32())))) - GroupLightningReports.process(all[3].db, all[3].room, reply(all[2], "not-the-operator", invoice(nodeKey))) - GroupLightningReports.process(all[3].db, all[3].room, reply(all[1], "good", invoice(nodeKey))) - assertNull(all[3].db.groupLightningRecordsDao().invoice(key, "elsewhere"), "an invoice paying another node") - assertNull(all[3].db.groupLightningRecordsDao().invoice(key, "not-the-operator"), "an invoice from a member who is not the operator") - assertNotNull(all[3].db.groupLightningRecordsDao().invoice(key, "good")) - } - - @Test - fun `the node's offer reaches every member, and only the one its seed derives is kept`() = runBlocking { - val (all, _) = running() - fixture.pump(all, setOf(GroupLightningEvents.SNAPSHOT)) - val wallet = GroupLightningWalletManager.walletFor(all[3].db, fixture.roomId, fixture.chain)!! - val expected = GroupLightningReports.offerOf(wallet) - all.forEach { assertEquals(expected, GroupLightningReports.latest(it.db, key)!!.snapshot.offer, "device ${it.index}") } - - val someoneElse = OfferManager.deterministicOffer(fixture.chain.chainHash, PrivateKey(randomBytes32()), PublicKey.fromHex(lsp), null, null, null).offer.encode() - val lying = WalletWire.Snapshot(key, 1, wallet.statement.nodeId, Clock.System.now().epochSeconds + 60, emptyList(), emptyList(), offer = someoneElse) - GroupLightningReports.process(all[3].db, all[3].room, snapshotEvent(all[1], lying)) - assertNull(GroupLightningReports.latest(all[3].db, key)!!.snapshot.offer, "an offer that pays some other node is dropped") - } - - /** - * What the snapshots say happened, said once per fact however many snapshots repeat it - * (docs/group-lightning-transcript.md, Phase 5): a channel opening and closing, a payment - * received, sent and failed -- on every device, the operator's own included. - */ - @Test - fun `what the snapshots say happened is said once, on every device`() = runBlocking { - val (all, node) = running() - // As lightning-kmp reports them: an outgoing amount includes its fee, and a channel's close is - // an outgoing payment with no payment hash. - val sent = WalletWire.PaymentView("p2", incoming = false, amountMsat = 5_001_500, feesMsat = 1_500, paymentHash = "ab".repeat(32), completedAt = 1_700_000_100_000, succeeded = true) - val close = WalletWire.PaymentView("p5", incoming = false, amountMsat = 400_000_000, feesMsat = 0, completedAt = 1_700_000_300_000, succeeded = true) - val failed = WalletWire.PaymentView("p3", incoming = false, amountMsat = 7_000_000, feesMsat = 0, paymentHash = "cd".repeat(32), completedAt = 1_700_000_200_000, succeeded = false) - val pending = WalletWire.PaymentView("p4", incoming = true, amountMsat = 1_000_000, feesMsat = 0, completedAt = null, succeeded = false) - nodes.single().channels = listOf(channel) - nodes.single().payments += listOf(payment, sent, failed, pending, close) - node.report(term = 1) - fixture.pump(all, setOf(GroupLightningEvents.SNAPSHOT)) - // The same facts again, and then the channel closing. - nodes.single().channels = listOf(channel.copy(commitIndex = 4)) - node.report(term = 1) - fixture.pump(all, setOf(GroupLightningEvents.SNAPSHOT)) - nodes.single().channels = listOf(channel.copy(state = "Closing", commitIndex = 5)) - node.report(term = 1) - fixture.pump(all, setOf(GroupLightningEvents.SNAPSHOT)) - - all.forEach { d -> - fun one(type: String) = runBlocking { fixture.lines(d, type) }.also { assertEquals(1, it.size, "device ${d.index}: $type") }.single().content - assertEquals("The group's Lightning node opened a channel of 1,000,000 sats.", one(ChatMessage.TYPE_LIGHTNING_CHANNEL_OPENED)) - assertEquals("A Lightning channel closed. Its 400,000 sats go to the onchain wallet.", one(ChatMessage.TYPE_LIGHTNING_CHANNEL_CLOSED)) - assertEquals("The group's Lightning wallet received 21,000 sats, for \u201clunch\u201d.", one(ChatMessage.TYPE_LIGHTNING_PAYMENT_RECEIVED)) - assertEquals("The group's Lightning wallet sent 5,000 sats, with 2 sats in fees.", one(ChatMessage.TYPE_LIGHTNING_PAYMENT_SENT)) - assertEquals("A Lightning payment of 7,000 sats failed. Nothing left the wallet.", one(ChatMessage.TYPE_LIGHTNING_PAYMENT_FAILED)) - assertEquals( - Instant.fromEpochMilliseconds(payment.completedAt!!), - fixture.lines(d, ChatMessage.TYPE_LIGHTNING_PAYMENT_RECEIVED).single().createdAt, - "a payment's line sits where the payment happened", - ) - } - } - - @Test - fun `a channel a newer snapshot no longer holds has closed`() = runBlocking { - val (all, node) = running() - nodes.single().channels = listOf(channel) - node.report(term = 1) - fixture.pump(all, setOf(GroupLightningEvents.SNAPSHOT)) - // A payment beside it, so this snapshot is not byte for byte the empty one the node - // started with, which in the same second would be the same event. - nodes.single().channels = emptyList() - nodes.single().payments += payment - node.report(term = 1) - fixture.pump(all, setOf(GroupLightningEvents.SNAPSHOT)) - all.forEach { d -> assertEquals(1, fixture.lines(d, ChatMessage.TYPE_LIGHTNING_CHANNEL_CLOSED).size, "device ${d.index}") } - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningSpliceCoSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningSpliceCoSigningJvmTest.kt deleted file mode 100644 index ecdb5666..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningSpliceCoSigningJvmTest.kt +++ /dev/null @@ -1,392 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.database.model.ChatMessage -import mobi.giza.compose.nostr.lightning.GroupLightningAuthorisationEvent -import mobi.giza.compose.nostr.lightning.GroupLightningEvents -import com.vitorpamplona.quartz.nip01Core.core.toHexKey -import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -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.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.byteVector32 -import fr.acinq.bitcoin.utils.Either -import fr.acinq.lightning.CltvExpiry -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.ChannelSpendSignature -import fr.acinq.lightning.channel.CommitParams -import fr.acinq.lightning.channel.Commitments -import fr.acinq.lightning.channel.LocalChannelParams -import fr.acinq.lightning.channel.RemoteChannelParams -import fr.acinq.lightning.crypto.FundingSigner -import fr.acinq.lightning.crypto.IcebergSigningTimeout -import fr.acinq.lightning.crypto.NonceGenerator -import fr.acinq.lightning.crypto.RemoteIcebergFundingSigner -import fr.acinq.lightning.transactions.CommitmentSpec -import fr.acinq.lightning.transactions.IncomingHtlc -import fr.acinq.lightning.transactions.Transactions -import fr.acinq.lightning.utils.msat -import fr.acinq.lightning.utils.sat -import fr.acinq.lightning.utils.toMilliSatoshi -import fr.acinq.lightning.wire.LiquidityAds -import fr.acinq.lightning.wire.OnionRoutingPacket -import fr.acinq.lightning.wire.UpdateAddHtlc -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.async -import kotlinx.coroutines.cancel -import kotlinx.coroutines.delay -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.withTimeout -import kotlin.random.Random -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertIs -import kotlin.test.assertTrue -import kotlin.time.Clock -import kotlin.time.Duration -import kotlin.time.Duration.Companion.hours -import kotlin.time.Duration.Companion.seconds - -/** - * A liquidity purchase signed by the group for real (`docs/group-lightning-liquidity.md`, Phase 5): the - * operator's signer asks for the first commitment on the splice's new funding output and then for the - * shared input, four devices' co-signers check both against the group's `buy-liquidity` and their own - * ledgers, and the group's signature on the shared input combines with the LSP's into a splice the - * script interpreter accepts. Then a payment over both live commitments, and each way a splice must be - * refused. - * - * The splice is built here as the LSP would put it together -- its own input first, ours second, its - * change and the new funding output -- with the amounts Phase 0 measured against eclair. - */ -abstract class GroupLightningSpliceCases(chain: Chain) { - private val fixture = GroupLightningFixture(chain = chain) - private val lspKey = PrivateKey(Random.nextBytes(32).byteVector32()) - private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) - - @AfterTest - fun close() { - scope.cancel() - fixture.close() - } - - init { - 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) - } - } - - private fun key() = PrivateKey(Random.nextBytes(32).byteVector32()) - - private inner class Group(val all: List, val wallet: GroupLightningWalletManager.Wallet, val operatorTerm: Long) - - private suspend fun group(): Group { - 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, fixture.chain, lspKey.publicKey().toString()).id) - fixture.signSession(all, all[0], GroupLightningOperatorManager.nominateSelf(all[0].db, all[0].room, all[0].publicKey, fixture.chain).id) - val wallet = GroupLightningWalletManager.walletFor(all[0].db, fixture.roomId, fixture.chain)!! - return Group(all, wallet, GroupLightningOperatorManager.current(all[0].db, fixture.roomId, fixture.chain)!!.term) - } - - /** A channel of 300,000 sats with the LSP, 100,000 of them the group's: room under the mainnet cap to buy. */ - private inner class Channel(group: Group) { - val seed = ByteVector(group.wallet.seed!!.seed) - val keyManager = GroupLightningCoSigner.keyManagerOf(seed, fixture.chain) - val groupKey = PublicKey.fromHex(group.wallet.statement.icebergKey) - val remoteFundingKey = key() - val fundingTxId = TxId(Random.nextBytes(32).byteVector32()) - val input = Transactions.makeFundingInputInfo(fundingTxId, 0, Satoshi(300_000), groupKey, remoteFundingKey.publicKey(), Transactions.CommitmentFormat.SimpleTaprootChannels) - val params = ChannelParams( - channelId = Random.nextBytes(32).byteVector32(), - channelConfig = ChannelConfig.standard, - channelFeatures = ChannelFeatures(setOf()), - localParams = LocalChannelParams( - nodeId = PublicKey.fromHex(group.wallet.statement.nodeId), - fundingKeyPath = keyManager.newFundingKeyPath(isChannelOpener = false), - isChannelOpener = false, - paysCommitTxFees = false, - defaultFinalScriptPubKey = GroupWalletDerivation.derive(fixture.account, GroupWalletDerivation.RECEIVE, 0).pubkeyScript, - features = Features.empty, - ), - remoteParams = RemoteChannelParams(lspKey.publicKey(), key().publicKey(), key().publicKey(), key().publicKey(), key().publicKey(), Features.empty), - channelFlags = ChannelFlags(announceChannel = false, nonInitiatorPaysCommitFees = false), - ) - val commitParams = CommitParams(Satoshi(546), 1_000_000_000L, 1.msat, CltvExpiryDelta(144), 30) - val keys = keyManager.channelKeys(params.localParams.fundingKeyPath).withGroupBasepoints(group.wallet.basepoints.forChannel) - val spec = CommitmentSpec(setOf(), FeeratePerKw(Satoshi(2_500)), toLocal = 200_000_000.msat, toRemote = 100_000_000.msat) - - /** The counterparty's commitment [index] on [funding], whose other key is [remote]. */ - fun commitment(index: Long, spec: CommitmentSpec, funding: Transactions.InputInfo = input, remote: PublicKey = remoteFundingKey.publicKey(), fundingTxIndex: Long = 0): Pair { - val point = key().publicKey() - val (tx, _) = Commitments.makeRemoteTxs(params, commitParams, keys.remoteCommitmentKeys(params, point), index, groupKey, remote, funding, Transactions.CommitmentFormat.SimpleTaprootChannels, spec) - return tx to FundingSigner.SigningContext.RemoteCommitment(params, commitParams, index, point, spec, fundingTxIndex) - } - } - - /** - * A purchase of [amount] as the LSP puts it together: its input and ours, its change and the new - * funding output, with our share of the mining fee leaving the funding output and the purchase's - * own fees ([miningFee], [serviceFee]) leaving our balance in the first commitment on it. - */ - private inner class Purchase( - val channel: Channel, - val amount: Satoshi = 200_000.sat, - val localContribution: Satoshi = (-221).sat, - val miningFee: Satoshi = 200.sat, - val serviceFee: Satoshi = 2_100.sat, - newFundingKey: PublicKey? = null, - ) { - val lspInputKey = key() - val lspInput = Transactions.InputInfo( - OutPoint(TxId(Random.nextBytes(32).byteVector32()), 1), - TxOut(amount + 50_000.sat, ByteVector(Script.write(Script.pay2tr(lspInputKey.publicKey().xOnly(), Crypto.TaprootTweak.KeyPathTweak)))), - ) - val newRemoteKey = key() - val newAmount = channel.input.txOut.amount + localContribution + amount - private val newScript = Transactions.makeFundingInputInfo(TxId(ByteVector32.Zeroes), 0, newAmount, newFundingKey ?: channel.groupKey, newRemoteKey.publicKey(), Transactions.CommitmentFormat.SimpleTaprootChannels).txOut.publicKeyScript - val tx = Transaction( - version = 2, - txIn = listOf(TxIn(lspInput.outPoint, 0xfffffffdL), TxIn(channel.input.outPoint, 0xfffffffdL)), - txOut = listOf(TxOut(50_000.sat - 400.sat, ByteVector(Script.write(Script.pay2tr(key().publicKey().xOnly(), Crypto.TaprootTweak.KeyPathTweak)))), TxOut(newAmount, newScript)), - lockTime = 0, - ) - val newInput = Transactions.InputInfo(OutPoint(tx.txid, 1), tx.txOut[1]) - val fee: Satoshi get() = -localContribution + miningFee + serviceFee - - /** The first commitment on the new output, at the channel's commitment [index], our balance lower by [taken]. */ - fun firstCommitment(index: Long, taken: Satoshi = fee): Pair { - val ours = channel.spec.toRemote - taken.toMilliSatoshi() - return channel.commitment(index, channel.spec.copy(toRemote = ours, toLocal = newAmount.toMilliSatoshi() - ours), funding = newInput, remote = newRemoteKey.publicKey(), fundingTxIndex = 1) - } - - fun context(purchase: LiquidityAds.Purchase? = LiquidityAds.Purchase.Standard(amount, LiquidityAds.Fees(miningFee, serviceFee), LiquidityAds.PaymentDetails.FromChannelBalance)) = FundingSigner.SigningContext.Splice( - channelParams = channel.params, parentFundingTxIndex = 0, parentFunding = channel.input, fundingTxIndex = 1, fundingOutputIndex = 1, - remoteFundingPubKey = newRemoteKey.publicKey(), localContribution = localContribution, remoteContribution = amount, purchase = purchase, - feerate = FeeratePerKw(500.sat), spentOutputs = mapOf(channel.input.outPoint to channel.input.txOut, lspInput.outPoint to lspInput.txOut), - ) - } - - private suspend fun whilePumping(group: Group, timeout: Duration = 20.seconds, block: suspend () -> T): T { - val result = scope.async { block() } - withTimeout(timeout) { - while (!result.isCompleted) { - fixture.pump(group.all, GroupLightningEvents.CO_SIGNING) - delay(50) - } - } - return result.await() - } - - private suspend fun operatorSigner(group: Group, deadline: Duration = 10.seconds): RemoteIcebergFundingSigner { - val operator = group.all[0] - val transport = GroupIcebergTransport.create(operator.db, operator.room, operator.publicKey, group.wallet, group.operatorTerm, scope) - whilePumping(group) { transport.provision(GroupLightningCoSigner.POOL_WINDOW) } - fixture.pump(group.all, GroupLightningEvents.CO_SIGNING) - transport.provision(GroupLightningCoSigner.POOL_WINDOW) - return RemoteIcebergFundingSigner(PublicKey.fromHex(group.wallet.statement.icebergKey), transport, deadline) - } - - /** The group signs the counterparty's commitment [tx], whose other funding key is [remote]. */ - private suspend fun groupSigns(group: Group, signer: RemoteIcebergFundingSigner, channel: Channel, tx: Transactions.CommitTx, context: FundingSigner.SigningContext, remote: PrivateKey = channel.remoteFundingKey): Either { - val fundingTxId = tx.input.outPoint.txid - val remoteNonce = NonceGenerator.signingNonce(remote.publicKey(), channel.groupKey, fundingTxId) - val groupSig = whilePumping(group) { signer.signWithFreshNonce(tx, remote.publicKey(), mapOf(), fundingTxId, remoteNonce.publicNonce, context) } - if (groupSig is Either.Left) return Either.Left(groupSig.value) - val ours = (groupSig as Either.Right).value - val theirs = (tx.partialSign(remote, channel.groupKey, mapOf(), remoteNonce, listOf(remoteNonce.publicNonce, ours.nonce)) as Either.Right).value - return tx.aggregateSigs(channel.groupKey, remote.publicKey(), ours, theirs, mapOf()) - } - - /** - * The group signs the splice's shared input under a published nonce, the LSP adds its half and signs - * its own input, and the script interpreter judges the whole transaction. - */ - private suspend fun groupSplices(group: Group, signer: RemoteIcebergFundingSigner, purchase: Purchase, context: FundingSigner.SigningContext): Either { - val channel = purchase.channel - val extra = mapOf(purchase.lspInput.outPoint to purchase.lspInput.txOut) - val splice = Transactions.SpliceTx(channel.input, purchase.tx) - val session = signer.publishedNonceSession(channel.fundingTxId, channel.remoteFundingKey.publicKey()) - val remoteNonce = NonceGenerator.signingNonce(channel.remoteFundingKey.publicKey(), channel.groupKey, channel.fundingTxId) - val groupSig = whilePumping(group) { signer.signWithPublishedNonce(splice, channel.remoteFundingKey.publicKey(), extra, session, remoteNonce.publicNonce, context) } - if (groupSig is Either.Left) return Either.Left(groupSig.value) - val ours = (groupSig as Either.Right).value - val theirs = (splice.partialSign(channel.remoteFundingKey, channel.groupKey, extra, remoteNonce, listOf(remoteNonce.publicNonce, ours.nonce)) as Either.Right).value - val shared = when (val s = splice.aggregateSigs(channel.groupKey, channel.remoteFundingKey.publicKey(), ours, theirs, extra)) { - is Either.Left -> return s - is Either.Right -> s.value - } - val spent = listOf(purchase.lspInput.txOut, channel.input.txOut) - val lspSig = Transaction.signInputTaprootKeyPath(purchase.lspInputKey, shared, 0, spent, SigHash.SIGHASH_DEFAULT, null) - val signed = shared.updateWitness(0, ScriptWitness(listOf(lspSig))) - Transaction.correctlySpends(signed, mapOf(channel.input.outPoint to channel.input.txOut, purchase.lspInput.outPoint to purchase.lspInput.txOut), ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) - return Either.Right(signed) - } - - private suspend fun authorise(group: Group, channel: Channel, amountSat: Long = 200_000, maxFeeSat: Long = 5_000): GroupLightningAuthorisationEvent.BuyLiquidity { - val buy = GroupLightningAuthorisationEvent.BuyLiquidity(fixture.chain, 0, channel.params.channelId.toHex(), amountSat, maxFeeSat, (Clock.System.now() + 1.hours).epochSeconds, Random.nextBytes(8).toHexKey()) - val template = GroupLightningAuthorisationEvent.template(buy) - fixture.sign(group.all, group.all[2], template.kind, template.tags, template.content) - return buy - } - - /** A group with a channel whose first commitment it has signed, which pins every co-signer to it. */ - private suspend fun pinned(): Triple { - val group = group() - val channel = Channel(group) - val signer = operatorSigner(group, deadline = 3.seconds) - val (tx, context) = channel.commitment(0, channel.spec) - assertIs>(groupSigns(group, signer, channel, tx, context)) - return Triple(group, channel, signer) - } - - private fun assertRefused(result: Either) = assertIs(assertIs>(result).value) - - private suspend fun refusals(group: Group): List = group.all.drop(1).flatMap { fixture.lines(it, ChatMessage.TYPE_LIGHTNING_REFUSED) }.map { it.content } - - @Test - fun `the group buys the liquidity it authorised, and the splice spends the funding output`() = runBlocking { - val (group, channel, signer) = pinned() - authorise(group, channel) - val purchase = Purchase(channel) - val (first, firstContext) = purchase.firstCommitment(0) - assertIs>(groupSigns(group, signer, channel, first, firstContext, purchase.newRemoteKey), "the first commitment on the new output") - assertIs>(groupSplices(group, signer, purchase, purchase.context()), "the shared input") - - // Every co-signer now holds a ledger for each output, the new one bound to the purchase. - val key = GroupLightningCoSigner.walletKey(fixture.roomId, fixture.chain, 0) - group.all.forEach { d -> - val ledgers = d.db.icebergCoSigningDao().channelLedgers(key, channel.params.channelId.toHex()) - assertEquals(listOf(0L, 1L), ledgers.map { it.fundingTxIndex }, "device ${d.index}") - assertEquals("${channel.input.outPoint.txid}:0", ledgers[1].parentOutPoint) - } - assertTrue(refusals(group).isEmpty(), refusals(group).toString()) - - // A payment arriving while both outputs are live: the group signs one commitment on each, at one number. - val incoming = IncomingHtlc(UpdateAddHtlc(channel.params.channelId, 0, 10_000_000.msat, Random.nextBytes(32).byteVector32(), CltvExpiry(800_000), OnionRoutingPacket(0, ByteVector(ByteArray(33) { if (it == 0) 2 else 0 }), ByteVector.empty, ByteVector32.Zeroes))) - val parentSpec = channel.spec.copy(toLocal = channel.spec.toLocal - 10_000_000.msat) - val (onParent, onParentContext) = channel.commitment(1, parentSpec.copy(htlcs = setOf(fr.acinq.lightning.transactions.OutgoingHtlc(incoming.add)))) - assertIs>(groupSigns(group, signer, channel, onParent, onParentContext)) - val newSpec = firstContext.spec - val (onNew, onNewContext) = channel.commitment(1, newSpec.copy(toLocal = newSpec.toLocal - 10_000_000.msat, htlcs = setOf(fr.acinq.lightning.transactions.OutgoingHtlc(incoming.add))), purchase.newInput, purchase.newRemoteKey.publicKey(), 1) - assertIs>(groupSigns(group, signer, channel, onNew, onNewContext, purchase.newRemoteKey)) - } - - @Test - fun `a payment that settles on both live commitments spends its budget once`() = runBlocking { - val (group, channel, signer) = pinned() - authorise(group, channel) - val purchase = Purchase(channel) - val (first, firstContext) = purchase.firstCommitment(0) - assertIs>(groupSigns(group, signer, channel, first, firstContext, purchase.newRemoteKey)) - assertIs>(groupSplices(group, signer, purchase, purchase.context())) - - // The group authorises paying 40,000 sats, with a budget of exactly that and its fee cap. - val preimage = Random.nextBytes(32).byteVector32() - val invoice = fr.acinq.lightning.payment.Bolt11Invoice.create(fixture.chain, 40_000_000.msat, Crypto.sha256(preimage).byteVector32(), key(), Either.Left("coffee"), CltvExpiryDelta(144), INVOICE_FEATURES) - val pay = GroupLightningAuthorisations.prepare(group.wallet, invoice.write(), null, 1_000_000).getOrThrow() - fixture.signSession(group.all, group.all[3], GroupLightningAuthorisations.propose(group.all[3].db, group.all[3].room, group.all[3].publicKey, pay).id) - val onion = OnionRoutingPacket(0, ByteVector(ByteArray(33) { if (it == 0) 2 else 0 }), ByteVector.empty, ByteVector32.Zeroes) - val htlc = IncomingHtlc(UpdateAddHtlc(channel.params.channelId, 0, 40_000_000.msat, ByteVector32(pay.paymentHash), CltvExpiry(800_000), onion)) - val newSpec = firstContext.spec - - // Offered on both outputs at commitment 1, then settled on both at commitment 2. - for ((index, settled) in listOf(1L to false, 2L to true)) { - val parentSpec = channel.spec.copy(htlcs = if (settled) setOf() else setOf(htlc), toRemote = channel.spec.toRemote - 40_000_000.msat, toLocal = if (settled) channel.spec.toLocal + 40_000_000.msat else channel.spec.toLocal) - val (onParent, onParentContext) = channel.commitment(index, parentSpec) - assertIs>(groupSigns(group, signer, channel, onParent, onParentContext), "the parent's commitment $index") - val childSpec = newSpec.copy(htlcs = if (settled) setOf() else setOf(htlc), toRemote = newSpec.toRemote - 40_000_000.msat, toLocal = if (settled) newSpec.toLocal + 40_000_000.msat else newSpec.toLocal) - val (onNew, onNewContext) = channel.commitment(index, childSpec, purchase.newInput, purchase.newRemoteKey.publicKey(), 1) - assertIs>(groupSigns(group, signer, channel, onNew, onNewContext, purchase.newRemoteKey), "the new output's commitment $index, after its sibling spent the budget") - } - group.all.forEach { d -> - val mine = GroupLightningWalletManager.walletFor(d.db, fixture.roomId, fixture.chain)!! - assertEquals(1_000_000L, GroupLightningAuthorisations.budgets(d.db, mine)[pay.paymentHash], "device ${d.index}: only the fee cap is left, spent once") - } - } - - @Test - fun `without an authorisation, the first commitment on a splice's output is never signed`() = runBlocking { - val (group, channel, signer) = pinned() - val purchase = Purchase(channel) - val (first, firstContext) = purchase.firstCommitment(0) - assertRefused(groupSigns(group, signer, channel, first, firstContext, purchase.newRemoteKey)) - assertTrue(refusals(group).all { "has not authorised buying liquidity" in it }, refusals(group).toString()) - } - - @Test - fun `a splice that takes more than the fee cap from the group is refused`() = runBlocking { - val (group, channel, signer) = pinned() - authorise(group, channel, maxFeeSat = 2_000) - val purchase = Purchase(channel) - val (first, firstContext) = purchase.firstCommitment(0) - assertRefused(groupSigns(group, signer, channel, first, firstContext, purchase.newRemoteKey)) - assertTrue(refusals(group).all { "over the 2000000 the group agreed to pay" in it }, refusals(group).toString()) - } - - @Test - fun `the shared input is never signed before the first commitment on the new output`() = runBlocking { - val (group, channel, signer) = pinned() - authorise(group, channel) - val purchase = Purchase(channel) - assertRefused(groupSplices(group, signer, purchase, purchase.context())) - assertTrue(refusals(group).all { "has not signed the first commitment on the splice's new output" in it }, refusals(group).toString()) - } - - @Test - fun `a splice whose new output is not the group's key is refused`() = runBlocking { - val (group, channel, signer) = pinned() - authorise(group, channel) - val purchase = Purchase(channel, newFundingKey = key().publicKey()) - assertRefused(groupSplices(group, signer, purchase, purchase.context())) - assertTrue(refusals(group).all { "is not the group's key with the LSP's" in it }, refusals(group).toString()) - } - - @Test - fun `a splice that buys other than the group authorised, or pays another way, or costs other than it took, is refused`() = runBlocking { - val (group, channel, signer) = pinned() - authorise(group, channel) - val purchase = Purchase(channel) - val (first, firstContext) = purchase.firstCommitment(0) - assertIs>(groupSigns(group, signer, channel, first, firstContext, purchase.newRemoteKey)) - val fees = LiquidityAds.Fees(purchase.miningFee, purchase.serviceFee) - // Another amount. - assertRefused(groupSplices(group, signer, purchase, purchase.context(LiquidityAds.Purchase.Standard(150_000.sat, fees, LiquidityAds.PaymentDetails.FromChannelBalance)))) - // Paid from future HTLCs. - assertRefused(groupSplices(group, signer, purchase, purchase.context(LiquidityAds.Purchase.Standard(purchase.amount, fees, LiquidityAds.PaymentDetails.FromFutureHtlc(listOf(Random.nextBytes(32).byteVector32())))))) - // Fees that do not add up to what the first commitment took. - assertRefused(groupSplices(group, signer, purchase, purchase.context(LiquidityAds.Purchase.Standard(purchase.amount, LiquidityAds.Fees(purchase.miningFee, 1_000.sat), LiquidityAds.PaymentDetails.FromChannelBalance)))) - val said = refusals(group) - assertTrue(said.any { "not the 200000 the group authorised" in it }, said.toString()) - assertTrue(said.any { "the group pays only from its balance" in it }, said.toString()) - assertTrue(said.any { "took 2521000 msat from the group, not the 1421000 the purchase costs" in it }, said.toString()) - // And the honest shared input still signs: no label was burned by the refusals. - assertIs>(groupSplices(group, signer, purchase, purchase.context())) - } -} - -class GroupLightningSpliceCoSigningJvmTest : GroupLightningSpliceCases(Chain.Regtest) - -class GroupLightningSpliceCoSigningMainnetJvmTest : GroupLightningSpliceCases(Chain.Mainnet) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningSweepJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningSweepJvmTest.kt deleted file mode 100644 index eeda0622..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningSweepJvmTest.kt +++ /dev/null @@ -1,133 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.database.model.types.FrostSigningStage -import mobi.giza.compose.wallet.lightning.GroupSweep -import mobi.giza.compose.wallet.lightning.WalletWire -import com.vitorpamplona.quartz.nip01Core.core.toHexKey -import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Crypto -import fr.acinq.bitcoin.OutPoint -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.Satoshi -import fr.acinq.bitcoin.Script -import fr.acinq.bitcoin.ScriptFlags -import fr.acinq.bitcoin.Transaction -import fr.acinq.bitcoin.TxId -import fr.acinq.bitcoin.TxOut -import fr.acinq.bitcoin.byteVector32 -import fr.acinq.lightning.CltvExpiryDelta -import fr.acinq.lightning.Lightning.randomBytes32 -import fr.acinq.lightning.channel.GroupHeldOutputs -import fr.acinq.lightning.crypto.ChannelKeys -import fr.acinq.lightning.crypto.CommitmentPublicKeys -import fr.acinq.lightning.transactions.Scripts -import fr.acinq.secp256k1.Hex -import kotlinx.coroutines.runBlocking -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertIs -import kotlin.test.assertNotNull -import kotlin.test.assertTrue - -/** - * Sweeping what a closed channel left the group into its onchain wallet (`docs/group-lightning-wallet.md`, - * Phase 13). The outputs are built with lightning-kmp's own scripts, as a published commitment carries - * them; the group signs them with FROST, every member checking the sweep first; and the script - * interpreter judges the result. - */ -class GroupLightningSweepJvmTest { - private val fixture = GroupLightningFixture() - private val lsp = "02" + KeyPair().pubKey.toHexKey() - - @AfterTest - fun close() = fixture.close() - - private suspend fun opened(): Pair, GroupLightningWalletManager.Wallet> { - 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, fixture.chain, lsp).id) - return all to GroupLightningWalletManager.walletFor(all[3].db, fixture.roomId, fixture.chain)!! - } - - private fun key() = PrivateKey(randomBytes32()).publicKey() - private fun keys(remotePayment: fr.acinq.bitcoin.PublicKey = key(), localDelayed: fr.acinq.bitcoin.PublicKey = key()) = - CommitmentPublicKeys(localDelayed, remotePayment, key(), key(), key()) - - /** Our main output in the counterparty's commitment, under the payment basepoint. */ - private fun toRemote(wallet: GroupLightningWalletManager.Wallet, amount: Long): GroupHeldOutputs.Output { - val basepoint = wallet.basepoints.payment.publicKey - val commitment = keys(remotePayment = basepoint) - val leaf = Scripts.Taproot.toRemoteScriptTree(commitment) - val outPoint = OutPoint(TxId(randomBytes32()), 1) - return GroupHeldOutputs.Output(GroupHeldOutputs.Kind.TO_REMOTE, outPoint, TxOut(Satoshi(amount), Script.write(Scripts.Taproot.toRemote(commitment))), basepoint, null, basepoint, Scripts.Taproot.NUMS_POINT.xOnly(), leaf, leaf, 1) - } - - /** Our main output in our own commitment, under the delayed basepoint and a per-commitment point. */ - private fun toLocal(wallet: GroupLightningWalletManager.Wallet, amount: Long, delay: Int = 144): GroupHeldOutputs.Output { - val basepoint = wallet.basepoints.delayedPayment.publicKey - val point = key() - val leafKey = ChannelKeys.remotePerCommitmentPublicKey(basepoint, point) - val commitment = keys(localDelayed = leafKey) - val tree = Scripts.Taproot.toLocalScriptTree(commitment, CltvExpiryDelta(delay)) - val outPoint = OutPoint(TxId(randomBytes32()), 0) - val tweak = Crypto.sha256(point.value + basepoint.value).byteVector32() - return GroupHeldOutputs.Output(GroupHeldOutputs.Kind.TO_LOCAL, outPoint, TxOut(Satoshi(amount), Script.write(Scripts.Taproot.toLocal(commitment, CltvExpiryDelta(delay)))), basepoint, tweak, leafKey, Scripts.Taproot.NUMS_POINT.xOnly(), tree.localDelayed, tree.scriptTree, delay.toLong()) - } - - @Test - fun `the group sweeps both kinds of output into its onchain wallet, and the transaction is valid`() = runBlocking { - val (all, wallet) = opened() - val outputs = listOf(toRemote(wallet, 300_000), toLocal(wallet, 500_000)) - val inputs = outputs.map(GroupSweep::inputOf) - val sweep = assertNotNull(GroupSweep.build(wallet.statement.wallet, inputs, fixture.account, receiveIndex = 0, feeratePerVbyte = 2)) - val session = FrostSigningManager.proposeSweep(all[3].db, all[3].room, all[3].publicKey, sweep, fixture.chain) - fixture.signSession(all, all[3], session.id) - - all.forEach { d -> - assertEquals(FrostSigningStage.COMPLETE, d.db.frostSigningSessionDao().getSessionById(session.id)?.stage, "device ${d.index}") - } - val signed = Transaction.read(assertNotNull(all[0].db.groupTransactionDao().getBySessionId(session.id)?.signedTransaction)) - Transaction.correctlySpends(signed, outputs.associate { it.outPoint to it.txOut }, ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) - assertEquals(GroupWalletDerivation.derive(fixture.account, GroupWalletDerivation.RECEIVE, 0).pubkeyScript, signed.txOut.single().publicKeyScript) - assertEquals(listOf(1L, 144L), signed.txIn.map { it.sequence }, "each input waits its leaf's delay") - val checked = assertNotNull(FrostSigningManager.checkedSweep(all[1].db, session.id)) - assertEquals(800_000 - checked.fee.sat, checked.amount.sat) - assertTrue(checked.feeratePerVbyte in 1..3, "${checked.feeratePerVbyte} sats per vbyte") - - // A proposed sweep's outputs are not offered again. - val report = GroupLightningReports.Report(WalletWire.Snapshot("w", 1, wallet.statement.nodeId, 0, emptyList(), emptyList(), heldOutputs = inputs + GroupSweep.inputOf(toRemote(wallet, 10_000))), emptyList()) - assertEquals(1, GroupLightningSweeps.unswept(all[2].db, fixture.roomId, report).size) - } - - @Test - fun `a sweep that pays anyone else, or signs under a key that is not the group's, is refused`() = runBlocking { - val (_, wallet) = opened() - val input = GroupSweep.inputOf(toLocal(wallet, 500_000)) - val good = assertNotNull(GroupSweep.build(wallet.statement.wallet, listOf(input), fixture.account, 0, 2)) - assertIs(GroupSweep.check(good, wallet.basepoints, fixture.account)) - - fun refused(sweep: GroupSweep.Sweep, why: String) = assertIs(GroupSweep.check(sweep, wallet.basepoints, fixture.account), why) - val tx = Transaction.read(good.tx) - val elsewhere = tx.copy(txOut = listOf(tx.txOut.single().copy(publicKeyScript = ByteVector(Script.write(Script.pay2wpkh(key())))))) - refused(good.copy(tx = Hex.encode(Transaction.write(elsewhere))), "paying an address that is not the wallet's") - refused(good.copy(receiveIndices = listOf(1)), "claiming another receive index") - refused(good.copy(inputs = listOf(input.copy(tweak = null))), "a delayed output with no tweak") - refused(good.copy(inputs = listOf(input.copy(tweak = ByteVector32(randomBytes32()).toHex()))), "a tweak whose key is not the leaf's") - refused(good.copy(inputs = listOf(input.copy(basepoint = GroupSweep.PAYMENT))), "the wrong basepoint for the leaf") - refused(good.copy(inputs = listOf(input.copy(csvDelay = 1))), "a delay the transaction does not wait") - val greedy = tx.copy(txOut = listOf(tx.txOut.single().copy(amount = Satoshi(100_000)))) - refused(good.copy(tx = Hex.encode(Transaction.write(greedy))), "a fee far over the limit") - } - - @Test - fun `the leaf a member rebuilds is the leaf lightning-kmp writes`() = runBlocking { - val (_, wallet) = opened() - val remote = toRemote(wallet, 1_000) - assertEquals(remote.leaf.script, GroupSweep.leafScript(wallet.basepoints.payment.publicKey.xOnly(), 1)) - val local = toLocal(wallet, 1_000, delay = 720) - assertEquals(local.leaf.script, GroupSweep.leafScript(local.leafKey.xOnly(), 720)) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningWalletJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningWalletJvmTest.kt deleted file mode 100644 index 86034813..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupLightningWalletJvmTest.kt +++ /dev/null @@ -1,194 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.database.model.ChatMessage -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 mobi.giza.compose.wallet.GroupLightningRollout -import com.vitorpamplona.quartz.nip01Core.core.toHexKey -import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.Satoshi -import fr.acinq.lightning.crypto.LocalKeyManager -import kotlin.random.Random -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertNotNull -import kotlin.test.assertNull -import kotlin.test.assertTrue -import kotlin.time.Clock -import kotlin.time.Duration.Companion.minutes -import kotlinx.coroutines.runBlocking -import kotlinx.serialization.json.JsonObject -import kotlinx.serialization.json.JsonPrimitive -import kotlinx.serialization.json.jsonObject - -/** - * Opening a group's Lightning wallet and choosing who runs it, between four devices - * (`docs/group-lightning-wallet.md`, Phases 6 and 7). - */ -class GroupLightningWalletJvmTest { - private val fixture = GroupLightningFixture() - private val lsp = KeyPair().pubKey.toHexKey().let { "02$it" } - - @AfterTest - fun close() = fixture.close() - - private suspend fun openLightningWallet(all: List, proposer: GroupLightningFixture.Device = all[0]) { - fixture.runCeremony(all) - val session = GroupLightningWalletManager.proposeWallet(proposer.db, proposer.room, proposer.publicKey, proposer.privateKey, fixture.chain, lsp) - fixture.signSession(all, proposer, session.id) - } - - @Test - fun `the group opens a Lightning wallet, and every member holds its seed`() = runBlocking { - val all = fixture.group() - openLightningWallet(all) - val wallets = all.map { assertNotNull(GroupLightningWalletManager.walletFor(it.db, fixture.roomId, fixture.chain), "device ${it.index}") } - assertEquals(1, wallets.map { it.statement }.toSet().size) - assertEquals(1, wallets.map { it.basepoints.forChannel }.toSet().size, "every device derives the same basepoints") - wallets.forEach { wallet -> - val seed = assertNotNull(wallet.seed, "the seed reached every participant") - assertEquals(wallet.statement.nodeId, seed.nodeId) - } - // The node id is lightning-kmp's own derivation from the seed, not just this manager's. - val seed = ByteVector(wallets[0].seed!!.seed) - val anyTpub = "tpubDAmCFB21J9ExKBRPDcVxSvGs9jtcf8U1wWWbS1xTYmnUsuUHPCoFdCnEGxLE3THSWcQE48GHJnyz8XPbYUivBMbLSMBifFd3G9KmafkM9og" - assertEquals(LocalKeyManager(seed, fixture.chain, anyTpub).nodeKeys.nodeKey.publicKey.toString(), wallets[0].statement.nodeId) - // And the room's transcript says so, on every device. - all.forEach { d -> - val lines = d.db.chatMessageDao().getChatMessagesByChatRoomId(fixture.roomId).map { it.chatMessage.messageType } - assertTrue(ChatMessage.TYPE_GROUP_LIGHTNING_WALLET_OPENED in lines) - // And who handed the seed out: one line, written by the proposer on the way out - // and by everyone else as it arrived. docs/group-lightning-transcript.md, Phase 4. - val seedLine = fixture.lines(d, ChatMessage.TYPE_LIGHTNING_SEED_SHARED).single() - assertEquals(all[0].publicKey, seedLine.senderPublicKey) - assertEquals(d === all[0], seedLine.isUserMessage) - } - // Delivered again, it is not a second line. - all.forEach { it.received.clear() } - fixture.pump(all, setOf(GroupLightningEvents.NODE_SEED)) - all.forEach { assertEquals(1, fixture.lines(it, ChatMessage.TYPE_LIGHTNING_SEED_SHARED).size) } - } - - @Test - fun `a seed that does not produce the node it claims is dropped`() = runBlocking { - val all = fixture.group() - fixture.runCeremony(all) - GroupLightningWalletManager.proposeWallet(all[0].db, all[0].room, all[0].publicKey, all[0].privateKey, fixture.chain, lsp) - val message = fixture.outbox(all[0], setOf(GroupLightningEvents.NODE_SEED)).single() - val body = CommonJson.parseToJsonElement(message.content).jsonObject - val lying = JsonObject(body + ("nodeId" to JsonPrimitive("02" + "ab".repeat(32)))) - val event = with(fixture) { message.copy(content = lying.toString()).asEvent() } - all[1].db.marmotInnerEventDao().upsert(message.copy(content = lying.toString())) - GroupLightningWalletManager.receiveSeed(all[1].db, all[1].room, event, all[1].publicKey, all[1].privateKey) - assertNull(all[1].db.groupLightningSeedDao().get(fixture.roomId, "02" + "ab".repeat(32))) - assertTrue(fixture.lines(all[1], ChatMessage.TYPE_LIGHTNING_SEED_SHARED).isEmpty(), "and the room is not told a seed was shared") - } - - @Test - fun `a statement that disagrees with the ceremony is not believed`() = runBlocking { - val all = fixture.group() - val ceremony = fixture.runCeremony(all) - val honest = all[0].ceremony(ceremony.id)!! - val wrong = GroupLightningWalletStatementEvent.Statement( - chain = fixture.chain, wallet = 0, onchainAccount = 0, - icebergKey = "02" + "cd".repeat(32), ceremonyId = honest.id, threshold = honest.threshold, - participants = honest.participants(), nodeId = "02" + "ef".repeat(32), lspNodeId = lsp, - policy = GroupLightningWalletStatementEvent.Policy.DEFAULT, - ) - val template = GroupLightningWalletStatementEvent.template(wrong) - fixture.sign(all, all[0], template.kind, template.tags, template.content) - all.forEach { assertNull(GroupLightningWalletManager.walletFor(it.db, fixture.roomId, fixture.chain), "device ${it.index} believed a key its ceremony did not make") } - } - - @Test - fun `a Lightning wallet is opened on the node's network, and nowhere else`() = runBlocking { - assertEquals(Chain.Mainnet, GroupLightningRollout.NETWORK) - assertTrue(GroupLightningRollout.allows(Chain.Mainnet)) - assertTrue(GroupLightningRollout.allows(Chain.Regtest), "regtest, for tests and development") - assertTrue(!GroupLightningRollout.allows(Chain.Testnet3) && !GroupLightningRollout.allows(Chain.Signet)) - assertEquals(Satoshi(1_000_000), GroupLightningRollout.channelCapFor(Chain.Mainnet)) - assertEquals(null, GroupLightningRollout.channelCapFor(Chain.Regtest)) - val all = fixture.group() - fixture.runCeremony(all) - val refused = runCatching { GroupLightningWalletManager.proposeWallet(all[0].db, all[0].room, all[0].publicKey, all[0].privateKey, Chain.Testnet3, lsp) } - assertTrue(refused.isFailure) - } - - @Test - fun `members elect themselves, the newest term wins, and only the operator can step down`() = runBlocking { - val all = fixture.group() - openLightningWallet(all) - val first = GroupLightningOperatorManager.nominateSelf(all[1].db, all[1].room, all[1].publicKey, fixture.chain) - fixture.signSession(all, all[1], first.id) - all.forEach { d -> - val current = assertNotNull(GroupLightningOperatorManager.current(d.db, fixture.roomId, fixture.chain)) - assertEquals(all[1].publicKey, current.publicKey) - assertEquals(1, current.term) - // The line says who, which is the one thing it is for. - val elected = fixture.lines(d, ChatMessage.TYPE_GROUP_LIGHTNING_OPERATOR_ELECTED).single() - assertEquals("@${ChatMessage.memberName(d.db, all[1].publicKey)} runs the group's Lightning wallet now.", elected.content) - } - val second = GroupLightningOperatorManager.nominateSelf(all[2].db, all[2].room, all[2].publicKey, fixture.chain) - fixture.signSession(all, all[2], second.id) - all.forEach { d -> - val current = GroupLightningOperatorManager.current(d.db, fixture.roomId, fixture.chain)!! - assertEquals(all[2].publicKey, current.publicKey) - assertEquals(2, current.term) - assertEquals(all[1].publicKey, current.statement.previous) - } - assertTrue(runCatching { GroupLightningOperatorManager.stepDown(all[1].db, all[1].room, all[1].publicKey, fixture.chain) }.isFailure) - val down = GroupLightningOperatorManager.stepDown(all[2].db, all[2].room, all[2].publicKey, fixture.chain) - fixture.signSession(all, all[2], down.id) - all.forEach { d -> - val current = GroupLightningOperatorManager.current(d.db, fixture.roomId, fixture.chain)!! - assertNull(current.publicKey) - assertEquals(3, current.term) - } - } - - @Test - fun `two elections for one term settle the same way on every device`() = runBlocking { - val all = fixture.group() - openLightningWallet(all) - // Both proposed before either is signed: both say term 1. - val a = GroupLightningOperatorManager.nominateSelf(all[1].db, all[1].room, all[1].publicKey, fixture.chain) - val b = GroupLightningOperatorManager.nominateSelf(all[3].db, all[3].room, all[3].publicKey, fixture.chain) - fixture.signSession(all, all[1], a.id) - fixture.signSession(all, all[3], b.id) - val winners = all.map { GroupLightningOperatorManager.current(it.db, fixture.roomId, fixture.chain)!! } - assertEquals(1, winners.map { it.publicKey }.toSet().size, "every device picks the same operator") - assertEquals(1L, winners.first().term) - } - - @Test - fun `only the elected operator, freshly synced, may start the node`() = runBlocking { - val all = fixture.group() - openLightningWallet(all) - val elected = GroupLightningOperatorManager.nominateSelf(all[1].db, all[1].room, all[1].publicKey, fixture.chain) - fixture.signSession(all, all[1], elected.id) - val now = Clock.System.now() - assertTrue(GroupLightningOperatorManager.mayRunNode(all[1].db, fixture.roomId, fixture.chain, all[1].publicKey, lastSyncedAt = now - 1.minutes, now = now)) - assertFalse(GroupLightningOperatorManager.mayRunNode(all[1].db, fixture.roomId, fixture.chain, all[1].publicKey, lastSyncedAt = now - 60.minutes, now = now)) - assertFalse(GroupLightningOperatorManager.mayRunNode(all[1].db, fixture.roomId, fixture.chain, all[1].publicKey, lastSyncedAt = null, now = now)) - assertFalse(GroupLightningOperatorManager.mayRunNode(all[2].db, fixture.roomId, fixture.chain, all[2].publicKey, lastSyncedAt = now, now = now)) - } - - @Test - fun `an operator statement reads back what it says`() { - val statement = GroupLightningOperatorStatementEvent.Statement(Chain.Testnet3, 2, "ab".repeat(32), 7, "cd".repeat(32)) - val template = GroupLightningOperatorStatementEvent.template(statement) - assertEquals(statement, GroupLightningOperatorStatementEvent.read(template.tags)) - val nobody = statement.copy(operator = null, previous = null) - assertEquals(nobody, GroupLightningOperatorStatementEvent.read(GroupLightningOperatorStatementEvent.template(nobody).tags)) - val walletStatement = GroupLightningWalletStatementEvent.Statement(Chain.Testnet3, 0, 0, "02" + "11".repeat(32), "22".repeat(32), 2, listOf("aa".repeat(32), "bb".repeat(32), "cc".repeat(32), "dd".repeat(32)), "03" + "33".repeat(32), "02" + "44".repeat(32), GroupLightningWalletStatementEvent.Policy.DEFAULT) - assertEquals(walletStatement, GroupLightningWalletStatementEvent.read(GroupLightningWalletStatementEvent.template(walletStatement).tags)) - assertNull(GroupLightningWalletStatementEvent.read(GroupLightningWalletStatementEvent.template(walletStatement.copy(participants = walletStatement.participants.reversed())).tags), "an unsorted participant list is not one") - Random.nextInt() - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupSpendSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupSpendSigningJvmTest.kt deleted file mode 100644 index 0cbd2b07..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupSpendSigningJvmTest.kt +++ /dev/null @@ -1,529 +0,0 @@ -package mobi.giza.compose.managers - -import androidx.room3.Room -import mobi.giza.compose.database.GizaDatabase -import mobi.giza.compose.database.builder.getRoomDatabase -import mobi.giza.compose.database.model.ChatMessage -import mobi.giza.compose.database.model.ChatRoom -import mobi.giza.compose.database.model.DkgParticipantMessage -import mobi.giza.compose.database.model.DkgSession -import mobi.giza.compose.database.model.MarmotInnerEvent -import mobi.giza.compose.database.model.NostrEvent -import mobi.giza.compose.database.model.Profile -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.database.model.types.DkgRitualStage -import mobi.giza.compose.database.model.types.FrostSigningStage -import mobi.giza.compose.database.model.types.FrostSigningSubject -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.wallet.GroupWalletStatementEvent -import mobi.giza.compose.wallet.GroupSpend -import mobi.giza.compose.text.ProposedSpend -import mobi.giza.compose.wallet.GroupSpendBuilder -import mobi.giza.compose.wallet.GroupWalletState -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.OutPoint -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.Satoshi -import fr.acinq.bitcoin.Script -import fr.acinq.bitcoin.ScriptFlags -import fr.acinq.bitcoin.SigHash -import fr.acinq.bitcoin.Transaction -import fr.acinq.bitcoin.TxId -import fr.acinq.bitcoin.TxIn -import fr.acinq.bitcoin.TxOut -import fr.acinq.bitcoin.crypto.frost.Frost -import fr.acinq.bitcoin.crypto.frost.KeyMaterial -import fr.acinq.bitcoin.psbt.Psbt -import fr.acinq.lightning.blockchain.electrum.WalletState -import kotlinx.coroutines.runBlocking -import kotlin.random.Random -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.assertNull -import kotlin.test.assertTrue -import kotlin.time.Instant - -/** - * A spend from the group's wallet between two devices, through the real - * signing manager, with the wire between them held by hand -- the harness - * `SignedGroupKeyStateTest` uses, cut down to a Marmot room. - * - * The wallet is opened the way a group opens one, by signing its statement in - * the same harness, so the spend is checked against a statement that went - * through the same session machinery rather than one planted in a table. - * - * The refusals are driven by handing a device a hand-built proposal, which is - * the only way to be a dishonest member here. Each asserts the device made no - * session at all: a proposal refused at acceptance has nothing to approve, so - * nothing of the member's can ever be published for it. - */ -class GroupSpendSigningJvmTest { - private val participants = 3 - private val threshold = 2 - - private val keyMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey(ByteVector32("1c0ffee0000000000000000000000000000000000000000000000000000000a1")), - nParticipants = participants, - threshold = threshold, - ) - private val thresholdPublicKey = keyMaterial.thresholdPublicKey.value.toHex() - private val ceremonyId = "ceremony".padEnd(64, '0') - private val roomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) - private val members = listOf("a", "b", "c").map { it.repeat(64) } - private val hostKeys = listOf("2a", "2b", "2c").map { it.padEnd(66, '0') } - private val chain = Chain.Regtest - private val account = GroupWalletDerivation.account(thresholdPublicKey, chain) - - private val devices = mutableListOf() - - @AfterTest - fun closeDatabases() = devices.forEach { it.db.close() } - - private inner class Device(val publicKey: HexKey, val db: GizaDatabase, val room: LocalChatRoom) { - val received = mutableSetOf() - - suspend fun store(queued: Queued) = db.marmotInnerEventDao().upsert( - MarmotInnerEvent( - id = queued.id, publicKey = queued.publicKey, kind = queued.kind, createdAt = queued.createdAt, - tags = queued.tags, content = queued.content, chatRoomId = roomId, - ) - ) - - suspend fun session(id: String) = db.frostSigningSessionDao().getSessionById(id) - suspend fun transaction(id: String) = db.groupTransactionDao().getBySessionId(id) - } - - private suspend fun device(publicKey: HexKey, signerIndex: Int): Device { - val db = getRoomDatabase(Room.inMemoryDatabaseBuilder()) - members.forEach { member -> - val nostrEventId = "e$member".take(64) - db.nostrEventDao().upsert(NostrEvent(id = nostrEventId, pubKey = member, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) - db.profileDao().upsert(Profile(publicKey = member, nostrEventId = nostrEventId)) - } - val chatRoom = ChatRoom( - id = roomId, userPublicKey = publicKey, subject = "Treasury", - description = SharedKeyDerivation.describe("Treasury."), mlsGroupState = "00", - ) - db.chatRoomDao().upsert(chatRoom) - db.dkgSessionDao().upsert( - DkgSession( - id = ceremonyId, chatRoomId = roomId, coordinatorPublicKey = members.first(), userPublicKey = publicKey, - threshold = threshold, participantCount = participants, stage = DkgRitualStage.COMPLETE, - hostPublicKey = hostKeys[signerIndex], round1Random = "1".repeat(64), round2AuxRandom = "2".repeat(64), - thresholdPublicKey = thresholdPublicKey, - secretShare = keyMaterial.secretShares[signerIndex].value.toHex(), - publicShares = keyMaterial.publicShares.joinToString(",") { it.value.toHex() }, - ) - ) - members.forEachIndexed { index, member -> - db.dkgSessionDao().upsert( - DkgParticipantMessage(sessionId = ceremonyId, participantPublicKey = member, kind = DkgRitualEvents.HOST_KEY, payload = hostKeys[index]) - ) - } - val localChatRoom = db.chatRoomDao().findChatRoomById(roomId) ?: LocalChatRoom(chatRoom = chatRoom) - return Device(publicKey, db, localChatRoom).also { devices += it } - } - - private data class Queued( - val id: HexKey, val publicKey: HexKey, val kind: Int, - val tags: Array>, val content: String, val createdAt: Instant, - ) { - fun toEvent() = Event(id, publicKey, createdAt.epochSeconds, kind, tags, content, "") - } - - private suspend fun outbox(device: Device): List = - device.db.marmotInnerEventDao() - .getByChatRoomAndKinds(chatRoomId = roomId, kinds = FrostSigningEvents.ALL.toList()) - .map { Queued(it.id, it.publicKey, it.kind, it.tags, it.content, it.createdAt) } - .filter { it.publicKey == device.publicKey } - .sortedWith(compareBy({ it.createdAt }, { it.kind })) - - private suspend fun deliver(to: Device, queued: Queued) { - if (!to.received.add(queued.id)) return - to.store(queued) - FrostSigningManager.processSigningPayload(to.db, to.room, queued.toEvent(), to.publicKey) - } - - private suspend fun pump(vararg between: Device) { - var moved = true - while (moved) { - moved = false - for (from in between) for (to in between) { - if (from === to) continue - outbox(from).forEach { queued -> - if (queued.id !in to.received) moved = true - deliver(to, queued) - } - } - } - } - - /** The group opens its wallet the way it would: a statement, proposed and signed by a quorum. */ - private suspend fun openWallet(proposer: Device, other: Device) { - val template = GroupWalletStatementEvent.template(account) - val session = FrostSigningManager.proposeSigning( - proposer.db, proposer.room, proposer.publicKey, template.kind, template.tags, template.content, - ) - pump(proposer, other) - FrostSigningManager.approve(other.db, other.room, session.id) - pump(proposer, other) - listOf(proposer, other).forEach { - assertNotNull(GroupWalletManager.walletFor(it.db, roomId, chain), "the statement opens the wallet on every device") - } - } - - private val first = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, 0) - private val second = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, 1) - private val change = GroupWalletDerivation.derive(account, GroupWalletDerivation.CHANGE, 0) - - private val funding = Transaction( - version = 2, - txIn = listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 0x42 })), 0), ByteVector.empty, 0xffffffffL)), - txOut = listOf(TxOut(Satoshi(60_000), first.pubkeyScript), TxOut(Satoshi(40_000), second.pubkeyScript)), - lockTime = 0, - ) - - private val elsewhere = Script.write(Script.pay2wpkh(PrivateKey(ByteVector32(ByteArray(32) { 9 })).publicKey())).let(::ByteVector) - - private fun spendTx(fee: Long = 1_000, sequence: Long = 0xfffffffdL) = Transaction( - version = 2, - txIn = listOf( - TxIn(OutPoint(funding, 0), ByteVector.empty, sequence), - TxIn(OutPoint(funding, 1), ByteVector.empty, sequence), - ), - txOut = listOf(TxOut(Satoshi(70_000), elsewhere), TxOut(Satoshi(30_000 - fee), change.pubkeyScript)), - lockTime = 0, - ) - - private fun psbt(tx: Transaction = spendTx(), changeAt: Map = mapOf(1 to change)): Psbt = - GroupSpend.psbtOf(tx, listOf(funding.txOut[0] to first, funding.txOut[1] to second), changeAt, account) - - /** A 30332 from member 0, built by hand, under [sessionId]. */ - private fun proposalOf(content: String, sessionId: String = Random.nextBytes(32).toHex(), walletTags: Array> = FrostSigningEvents.walletTags("regtest", 0)): Queued { - val tags = FrostSigningEvents.assembleTags(sessionId = sessionId, dkgSessionId = ceremonyId) + walletTags - val createdAt = 1_700_000_000L - return Queued( - id = EventHasher.hashId(members[0], createdAt, FrostSigningEvents.TRANSACTION_PROPOSAL, tags, content), - publicKey = members[0], kind = FrostSigningEvents.TRANSACTION_PROPOSAL, tags = tags, content = content, - createdAt = Instant.fromEpochSeconds(createdAt), - ) - } - - private fun sessionIdOf(queued: Queued) = FrostSigningEvents.parseSessionId(queued.tags)!! - - // ---- The spend, end to end ------------------------------------------ - - @Test - fun `a quorum spends the group's coins, and both devices hold the transaction`() = runBlocking { - val proposer = device(members[0], signerIndex = 0) - val other = device(members[1], signerIndex = 1) - openWallet(proposer, other) - - val session = FrostSigningManager.proposeSpend(proposer.db, proposer.room, proposer.publicKey, psbt(), chain) - pump(proposer, other) - - assertEquals(FrostSigningSubject.TRANSACTION, other.session(session.id)?.subject) - assertNull(other.transaction(session.id)?.signedTransaction, "nothing is signed before the member approves") - - FrostSigningManager.approve(other.db, other.room, session.id) - pump(proposer, other) - - listOf(proposer, other).forEach { device -> - assertEquals(FrostSigningStage.COMPLETE, device.session(session.id)?.stage) - val signed = Transaction.read(assertNotNull(device.transaction(session.id)?.signedTransaction)) - // The network's question, asked of each device's copy. - signed.correctlySpends( - funding.txOut.mapIndexed { i, out -> OutPoint(funding, i.toLong()) to out }.toMap(), - ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS, - ) - assertEquals(spendTx().txid, signed.txid, "the txid fixed at proposal is the one that was signed") - } - - // Each input its own instance: every positive assertion above still - // passes if two share a nonce, and what sharing costs is the share. - val items = proposer.db.frostSigningSessionDao().getItems(session.id) - assertEquals(listOf(0, 1), items.map { it.inputIndex }) - assertNotEquals(items[0].aggregatedNonce, items[1].aggregatedNonce) - assertNotEquals(items[0].nonceRandom, items[1].nonceRandom) - } - - // ---- What a member refuses ------------------------------------------ - - @Test - fun `a spend from a wallet the group never opened is refused`() = runBlocking { - val other = device(members[1], signerIndex = 1) - - val proposal = proposalOf(GroupSpend.encode(psbt())) - deliver(other, proposal) - - assertNull(other.session(sessionIdOf(proposal))) - } - - @Test - fun `each check refuses the proposal outright`() = runBlocking { - val proposer = device(members[0], signerIndex = 0) - val other = device(members[1], signerIndex = 1) - openWallet(proposer, other) - - val stranger = GroupWalletDerivation.derive(GroupWalletDerivation.account( - PrivateKey(ByteVector32(ByteArray(32) { 5 })).publicKey().toString(), chain), 0, 0) - - val refusals = mapOf( - // 2. an input that is not the group's: the claim names /0/0, the coin is a stranger's. - "a foreign input" to GroupSpend.psbtOf(spendTx(), listOf(TxOut(Satoshi(60_000), stranger.pubkeyScript) to first, funding.txOut[1] to second), mapOf(1 to change), account), - // 3. a sighash that would let whoever holds the signatures redirect the money. - "a sighash other than the default" to psbt().let { p -> - p.copy(inputs = p.inputs.mapIndexed { i, input -> - if (i == 0) (input as fr.acinq.bitcoin.psbt.Input.WitnessInput.PartiallySignedWitnessInput).copy(sighashType = SigHash.SIGHASH_ALL) else input - }) - }, - // 4. a spend that cannot be replaced. - "a final sequence" to psbt(spendTx(sequence = 0xffffffffL)), - // 5. an output called change that is not where its claim says. - "a mislabelled change output" to psbt(changeAt = mapOf(0 to change)), - // 6. outputs worth more than the coins: no fee, and no transaction. - "a spend paying out more than it spends" to psbt(spendTx(fee = -1_000)), - ) - - refusals.forEach { (name, bad) -> - val proposal = proposalOf(GroupSpend.encode(bad)) - deliver(other, proposal) - assertNull(other.session(sessionIdOf(proposal)), "$name must be refused") - } - - // And a wallet the proposal names but the room never opened. - val otherAccount = proposalOf(GroupSpend.encode(psbt()), walletTags = FrostSigningEvents.walletTags("regtest", 1)) - deliver(other, otherAccount) - assertNull(other.session(sessionIdOf(otherAccount)), "an account the group did not open") - } - - @Test - fun `a second proposal under the same id changes nothing`() = runBlocking { - val proposer = device(members[0], signerIndex = 0) - val other = device(members[1], signerIndex = 1) - openWallet(proposer, other) - - val sessionId = Random.nextBytes(32).toHex() - deliver(other, proposalOf(GroupSpend.encode(psbt()), sessionId = sessionId)) - val before = other.db.frostSigningSessionDao().getItems(sessionId).map { it.message } - val psbtBefore = other.transaction(sessionId)?.psbt - - // Every item's seed is committed to its sighash. A different transaction - // under the same id would have those seeds sign a second message. - deliver(other, proposalOf(GroupSpend.encode(psbt(spendTx(fee = 2_000))), sessionId = sessionId).copy(id = Random.nextBytes(32).toHex())) - - assertEquals(before, other.db.frostSigningSessionDao().getItems(sessionId).map { it.message }) - assertEquals(psbtBefore, other.transaction(sessionId)?.psbt) - } - - @Test - fun `a feerate past the ceiling is refused, and one under it is not`() { - // One coin large enough that the ceiling is reachable: about 110 vbytes - // at 2,000 sats each is a fee of roughly 220,000 sats. - val big = Transaction(2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 7 })), 0), ByteVector.empty, 0xffffffffL)), - listOf(TxOut(Satoshi(10_000_000), first.pubkeyScript)), 0) - fun spending(fee: Long) = GroupSpend.psbtOf( - Transaction(2, listOf(TxIn(OutPoint(big, 0), ByteVector.empty, 0xfffffffdL)), listOf(TxOut(Satoshi(10_000_000 - fee), elsewhere)), 0), - listOf(big.txOut[0] to first), emptyMap(), account, - ) - - kotlin.test.assertIs(GroupSpend.check(spending(fee = 1_000_000), account)) - kotlin.test.assertIs(GroupSpend.check(spending(fee = 5_000), account)) - } - - @Test - fun `a member reads the spend as checked, and its coins are reserved until it fails`() = runBlocking { - val proposer = device(members[0], signerIndex = 0) - val other = device(members[1], signerIndex = 1) - openWallet(proposer, other) - - val session = FrostSigningManager.proposeSpend(proposer.db, proposer.room, proposer.publicKey, psbt(), chain) - pump(proposer, other) - - // What the approval screen draws, read off the member's own copy. - val spend = assertNotNull(FrostSigningManager.checkedSpend(other.db, session.id)) - assertEquals(Satoshi(70_000), spend.amountSent) - assertEquals(Satoshi(1_000), spend.fee) - assertEquals(listOf(false, true), spend.outputs.map { it.isChange }) - - val coins = setOf(OutPoint(funding, 0), OutPoint(funding, 1)) - assertEquals(coins, FrostSigningManager.reservedOutPoints(other.db, roomId)) - assertEquals(setOf(0L), FrostSigningManager.reservedChangeIndices(other.db, roomId, account), "and its change address") - - // Abandoned however it was -- the stage is all the reservation reads. - other.db.frostSigningSessionDao().upsert(other.session(session.id)!!.copy(stage = FrostSigningStage.FAILED)) - assertEquals(emptySet(), FrostSigningManager.reservedOutPoints(other.db, roomId), "a failed spend releases its coins") - assertEquals(emptySet(), FrostSigningManager.reservedChangeIndices(other.db, roomId, account), "and its change address") - } - - /** The wallet as Electrum would report it holding [funding], with [changeWindow] change addresses watched and unused. */ - private fun fundedState(changeWindow: Int = 3): GroupWalletState { - fun derived(branch: Long, index: Int) = GroupWalletDerivation.derive(account, branch, index.toLong()) - val receive = listOf(first, second).mapIndexed { index, derivation -> - val meta = WalletState.AddressMeta.Derived(index) - derivation.address(chain) to WalletState.AddressState( - meta, alreadyUsed = true, utxos = listOf(WalletState.Utxo(funding.txid, index, 100, funding, meta)), - ) - }.toMap() - val change = (0 until changeWindow).associate { index -> - derived(GroupWalletDerivation.CHANGE, index).address(chain) to - WalletState.AddressState(WalletState.AddressMeta.Derived(index), alreadyUsed = false, utxos = emptyList()) - } - return GroupWalletState(account, WalletState(receive), WalletState(change), tipHeight = 110) - } - - @Test - fun `an amount the form built is signed by the group, its change is the group's on every device, and it comes back`() = runBlocking { - val proposer = device(members[0], signerIndex = 0) - val other = device(members[1], signerIndex = 1) - openWallet(proposer, other) - - // A first spend is open and holds change index 0, so the form pays past it. - FrostSigningManager.proposeSpend(proposer.db, proposer.room, proposer.publicKey, psbt(), chain) - pump(proposer, other) - val heldChange = FrostSigningManager.reservedChangeIndices(proposer.db, roomId, account) - assertEquals(setOf(0L), heldChange) - - // The second spends coins the first does not hold: a fresh funding of its own. - val more = Transaction( - 2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 0x43 })), 0), ByteVector.empty, 0xffffffffL)), - listOf(TxOut(Satoshi(80_000), first.pubkeyScript)), 0, - ) - val wallet = fundedState().let { state -> - val meta = WalletState.AddressMeta.Derived(0) - val receive = state.receive.addresses + (first.address(chain) to WalletState.AddressState( - meta, alreadyUsed = true, utxos = listOf(WalletState.Utxo(more.txid, 0, 100, more, meta)), - )) - state.copy(receive = WalletState(receive)) - } - val reserved = FrostSigningManager.reservedOutPoints(proposer.db, roomId) - val built = assertIs( - GroupSpendBuilder.send(wallet, ProposedSpend.addressOf(elsewhere, chain), Satoshi(30_000), 3, reserved, heldChange) - ) - - val session = FrostSigningManager.proposeSpend(proposer.db, proposer.room, proposer.publicKey, built.psbt, chain) - pump(proposer, other) - FrostSigningManager.approve(other.db, other.room, session.id) - pump(proposer, other) - - // On the device that did not build it: the change derives, so it is change. - val seen = assertNotNull(FrostSigningManager.checkedSpend(other.db, session.id)) - val changeOutput = seen.outputs.single { it.isChange } - assertEquals(1L, changeOutput.change!!.index, "past the index the open spend holds") - assertEquals(built.change, changeOutput.txOut.amount) - assertEquals(Satoshi(30_000), seen.amountSent) - assertEquals(setOf(0L, 1L), FrostSigningManager.reservedChangeIndices(other.db, roomId, account)) - - listOf(proposer, other).forEach { device -> - assertEquals(FrostSigningStage.COMPLETE, device.session(session.id)?.stage) - val signed = Transaction.read(assertNotNull(device.transaction(session.id)?.signedTransaction)) - signed.correctlySpends(mapOf(OutPoint(more, 0) to more.txOut[0]), ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) - } - - // Confirmed, the change is a coin the wallet counts, on the branch it watches. - val signed = Transaction.read(other.transaction(session.id)!!.signedTransaction!!) - val changeMeta = WalletState.AddressMeta.Derived(1) - val changeAddress = changeOutput.change!!.address(chain) - val after = wallet.copy( - receive = WalletState(wallet.receive.addresses - first.address(chain)), - change = WalletState(wallet.change.addresses + (changeAddress to WalletState.AddressState( - changeMeta, alreadyUsed = true, utxos = listOf(WalletState.Utxo(signed.txid, changeOutput.index, 111, signed, changeMeta)), - ))), - ) - assertEquals(changeOutput.change, after.derivationOf(changeOutput.txOut.publicKeyScript)) - assertEquals(Satoshi(40_000) + built.change!!, after.confirmedBalance, "the second funding coin, and the change") - - // The transcript says what left the group: the payment, never the change with it. - FrostSigningManager.recordConfirmed(other.db, session.id) - val lines = other.db.chatMessageDao().getChatMessagesByChatRoomId(roomId).map { it.chatMessage } - val signedLine = lines.single { it.messageType == ChatMessage.TYPE_FROST_COMPLETE && it.content.startsWith("The group signed a transaction") } - assertTrue(signedLine.content.startsWith("The group signed a transaction sending 30000 sats, with ${seen.fee.sat} sats in fees."), signedLine.content) - val confirmedLine = lines.single { it.messageType == ChatMessage.TYPE_GROUP_TRANSACTION_CONFIRMED } - assertEquals("The group's transaction confirmed: 30000 sats sent.", confirmedLine.content) - } - - // ---- A guarded wallet ----------------------------------------------- - - /** - * Files the room's key state as a subgroup's, under a certificate granting - * one guardian -- signed by a parent whose key the test holds, since - * `certifies` asks only that the room it names as parent signed it. - */ - private suspend fun fileGuardedParentage(device: Device): GroupWalletManager.GuardedOpening { - val parentKey = PrivateKey(ByteVector32(ByteArray(32) { 0x0b })) - val parentRoomId = parentKey.publicKey().xOnly().value.toString() - val guardians = GuardianDerivation.grant( - PrivateKey(ByteVector32(ByteArray(32) { 0x0c })).publicKey().toString(), parentRoomId, emptyList(), roomId, - ) - val tags = mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent.assembleTags( - subgroupChatRoomId = roomId, parentChatRoomId = parentRoomId, thresholdPublicKey = thresholdPublicKey, - adminPublicKeys = members, name = "Treasury", guardians = guardians, - ) - val id = EventHasher.hashId(parentRoomId, 1_700_000_000, 30329, tags, roomId) - val certificate = Event(id, parentRoomId, 1_700_000_000, 30329, tags, roomId, - fr.acinq.bitcoin.Crypto.signSchnorr(ByteVector32(id), parentKey, null).toString()) - - device.db.groupKeyStateDao().upsert( - mobi.giza.compose.database.model.GroupKeyState( - chatRoomId = roomId, dkgSessionId = ceremonyId, thresholdPublicKey = thresholdPublicKey, - derivationPath = SharedKeyDerivation.formatPath(), announcedBy = roomId, - announcedAt = Instant.fromEpochSeconds(1_700_000_000), - parentChatRoomId = parentRoomId, birthCertificateJson = certificate.toJson(), - ) - ) - return assertNotNull(GroupWalletManager.guardedAccountFor(device.db, roomId, chain)) - } - - @Test - fun `a guarded wallet is opened by its quorum, and its own spends stay on the key path`() = runBlocking { - val proposer = device(members[0], signerIndex = 0) - val other = device(members[1], signerIndex = 1) - val opening = fileGuardedParentage(proposer) - fileGuardedParentage(other) - - val template = GroupWalletStatementEvent.template(opening.account, opening.certificate) - val statement = FrostSigningManager.proposeSigning(proposer.db, proposer.room, proposer.publicKey, template.kind, template.tags, template.content) - pump(proposer, other) - FrostSigningManager.approve(other.db, other.room, statement.id) - pump(proposer, other) - - val guarded = assertNotNull(GroupWalletManager.walletFor(other.db, roomId, chain)).account - assertTrue(guarded.isGuarded) - assertEquals(opening.account, guarded) - - val first = GroupWalletDerivation.derive(guarded, GroupWalletDerivation.RECEIVE, 0) - val change = GroupWalletDerivation.derive(guarded, GroupWalletDerivation.CHANGE, 0) - val funding = Transaction(2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 0x47 })), 0), ByteVector.empty, 0xffffffffL)), - listOf(TxOut(Satoshi(60_000), first.pubkeyScript)), 0) - val tx = Transaction(2, listOf(TxIn(OutPoint(funding, 0), ByteVector.empty, 0xfffffffdL)), - listOf(TxOut(Satoshi(40_000), elsewhere), TxOut(Satoshi(19_000), change.pubkeyScript)), 0) - val psbt = GroupSpend.psbtOf(tx, listOf(funding.txOut[0] to first), mapOf(1 to change), guarded) - - // The plain account's check refuses the guarded coin: same internal key, another output. - assertIs(GroupSpend.check(psbt, account)) - - val session = FrostSigningManager.proposeSpend(proposer.db, proposer.room, proposer.publicKey, psbt, chain) - pump(proposer, other) - assertEquals(listOf(false, true), assertNotNull(FrostSigningManager.checkedSpend(other.db, session.id)).outputs.map { it.isChange }) - FrostSigningManager.approve(other.db, other.room, session.id) - pump(proposer, other) - - listOf(proposer, other).forEach { device -> - assertEquals(FrostSigningStage.COMPLETE, device.session(session.id)?.stage) - val signed = Transaction.read(assertNotNull(device.transaction(session.id)?.signedTransaction)) - signed.correctlySpends(mapOf(OutPoint(funding, 0) to funding.txOut[0]), ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) - assertEquals(1, signed.txIn[0].witness.stack.size, "a key-path spend: one signature, no script, no control block") - } - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GuardedWalletForwardJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GuardedWalletForwardJvmTest.kt deleted file mode 100644 index 975ecaae..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GuardedWalletForwardJvmTest.kt +++ /dev/null @@ -1,328 +0,0 @@ -package mobi.giza.compose.managers - -import androidx.room3.Room -import mobi.giza.compose.database.GizaDatabase -import mobi.giza.compose.database.builder.getRoomDatabase -import mobi.giza.compose.database.model.GroupSignedEvent -import mobi.giza.compose.managers.GroupFixtures.birthCertificate -import mobi.giza.compose.managers.GroupFixtures.fileKeyState -import mobi.giza.compose.managers.GroupFixtures.keyMaterial -import mobi.giza.compose.managers.GroupFixtures.roomOf -import mobi.giza.compose.managers.GroupFixtures.signedAsRoom -import mobi.giza.compose.managers.GroupFixtures.signingRoom -import mobi.giza.compose.managers.GroupFixtures.thresholdKeyOf -import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent -import mobi.giza.compose.nostr.wallet.GuardedWalletNoticeEvent -import mobi.giza.compose.nostr.wallet.MemberWalletCertificateEvent -import mobi.giza.compose.nostr.wallet.MemberWalletRequestEvent -import com.vitorpamplona.quartz.nip01Core.core.Event -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.crypto.frost.KeyMaterial -import fr.acinq.secp256k1.Hex -import kotlinx.coroutines.runBlocking -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertTrue - -/** - * Telling the groups above about a guarded wallet, as a function: upward only, - * never a group that already holds it, never as another profile, and -- when - * a wallet has only just arrived -- only by the device elected to send at once. - * `docs/guarded-wallet-forwarding.md`, Phase 2. - * - * A root `R`, its guarded subgroup `M`, and `M`'s guarded subgroup `G`, which - * guards a member's wallet: the wallet's guardians are `G`, `M` and `R`. - */ -class GuardedWalletForwardJvmTest { - private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) - - @AfterTest - fun closeDb() = db.close() - - private val chain = Chain.Regtest - - private fun privateKey(seed: Long): PrivateKey = PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))) - - private val root = keyMaterial("7007") - private val middle = keyMaterial("9a9e") - private val group = keyMaterial("6a0b") - private val rootRoom = roomOf(root) - private val middleRoom = roomOf(middle) - private val groupRoom = roomOf(group) - - /** `M`'s certificate from `R`, and `G`'s from `M` with `R`'s key passed one step further. */ - private val middleCertificate = birthCertificate(root, middle, GuardianDerivation.grant(thresholdKeyOf(root), rootRoom, emptyList(), middleRoom)) - private val groupCertificate = birthCertificate( - middle, group, - GuardianDerivation.grant(thresholdKeyOf(middle), middleRoom, SubgroupBirthCertificateEvent.parseGuardians(middleCertificate.tags)!!, groupRoom), - ) - - private val member = privateKey(0x3e3be7) - private val memberPublicKey = member.xOnlyPublicKey().value.toHex() - private val walletPrivateKey = privateKey(0xa11ce) - private val walletId = MemberWalletDerivation.walletId(walletPrivateKey.publicKey()) - - private val certificate: Event = run { - val grant = GuardianDerivation.grant(thresholdKeyOf(group), groupRoom, SubgroupBirthCertificateEvent.parseGuardians(groupCertificate.tags)!!, walletId) - val request = MemberWalletRequestEvent.build( - memberPrivateKey = member, - groupChatRoomId = groupRoom, - walletPrivateKey = walletPrivateKey, - account = MemberWalletDerivation.account(walletPrivateKey.publicKey(), chain, grant), - label = null, - createdAt = 1_700_000_000, - ) - val template = MemberWalletCertificateEvent.template(request) - signedAsRoom(group, template.kind, template.tags, template.content, template.createdAt) - } - - /** A member whose key sorts above this device's own, so this device stays the elected sender. */ - private val laterMember = "f".repeat(64) - - /** This device in [material]'s room, with its key state, and [members] beside it. */ - private suspend fun inRoom(material: KeyMaterial, certificate: Event?, members: List = listOf(memberPublicKey, laterMember)) { - signingRoom(db, material, members = members, subject = "#" + roomOf(material).take(4), holdsShare = false) - fileKeyState(db, material, certificate) - } - - private suspend fun inAllThree() { - inRoom(group, groupCertificate) - inRoom(middle, middleCertificate) - inRoom(root, null) - } - - private suspend fun signedInGroup() = - db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(certificate, chatRoomId = groupRoom, derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path), frostSigningSessionId = null)) - - private suspend fun noticesIn(chatRoomId: String): List = - db.marmotInnerEventDao().getByChatRoomAndKinds(chatRoomId, listOf(GuardedWalletNoticeEvent.KIND)).mapNotNull { Event.fromJsonOrNull(it.content) } - - @Test - fun `from the group that signed it, every group above is told, and the group is not`(): Unit = runBlocking { - inAllThree() - signedInGroup() - - val told = GuardianManager.forward(db, certificate, groupRoom, whenElected = false).map { it.chatRoom.id } - assertEquals(listOf(middleRoom, rootRoom), told) - assertEquals(listOf(certificate.id), noticesIn(middleRoom).map { it.id }) - assertTrue(noticesIn(groupRoom).isEmpty(), "the group holds what it signed") - assertTrue(GuardianManager.told(db, groupRoom, certificate.id), "a signed event counts as told") - - assertTrue(GuardianManager.forward(db, certificate, groupRoom, whenElected = false).isEmpty(), "told once") - } - - @Test - fun `from a group above, only the groups above it`(): Unit = runBlocking { - inAllThree() - signedInGroup() - // As though the middle group had been told by somebody else, and the - // root not yet. - GuardianManager.share(db, certificate, listOfNotNull(db.chatRoomDao().findChatRoomById(middleRoom)), memberPublicKey) - - assertEquals(listOf(rootRoom), GuardianManager.forward(db, certificate, middleRoom, whenElected = false).map { it.chatRoom.id }) - assertTrue(GuardianManager.forward(db, certificate, rootRoom, whenElected = false).isEmpty(), "nothing goes back down") - } - - @Test - fun `the button offers only what goes up`(): Unit = runBlocking { - inAllThree() - signedInGroup() - // Carrying the group's birth certificate, as every share from this build - // does: a notice without it would be offered once more, so the name - // reaches the groups above. docs/member-wallet-guarding-group.md, D5. - GuardianManager.share(db, certificate, listOfNotNull(db.chatRoomDao().findChatRoomById(middleRoom), db.chatRoomDao().findChatRoomById(rootRoom)), memberPublicKey, certificate = groupCertificate) - - // The root holds it as a notice, the middle group too, and the group signed it. - assertTrue(GuardianManager.shareableFrom(db, rootRoom, chain).isEmpty(), "the root has nobody above it to tell") - assertTrue(GuardianManager.shareableFrom(db, middleRoom, chain).isEmpty()) - assertTrue(GuardianManager.shareableFrom(db, groupRoom, chain).isEmpty()) - } - - @Test - fun `a group above that belongs to another profile on the device is never told`(): Unit = runBlocking { - inRoom(group, groupCertificate) - inRoom(middle, middleCertificate) - signedInGroup() - val other = "0f".repeat(32) - GroupFixtures.seedProfile(db, other) - val middleRow = db.chatRoomDao().findChatRoomById(middleRoom)!!.chatRoom - db.chatRoomDao().upsert(middleRow.copy(userPublicKey = other)) - - assertTrue(GuardianManager.forward(db, certificate, groupRoom, whenElected = false).isEmpty()) - assertTrue(noticesIn(middleRoom).isEmpty()) - } - - @Test - fun `when a wallet has only just arrived, only the elected device sends`(): Unit = runBlocking { - // A member whose key sorts below this device's sits in both rooms. - val earlier = "00".repeat(31) + "01" - inRoom(group, groupCertificate, members = listOf(memberPublicKey, earlier)) - inRoom(middle, middleCertificate, members = listOf(earlier)) - signedInGroup() - - assertTrue(GuardianManager.forward(db, certificate, groupRoom, whenElected = true).isEmpty(), "the earlier member sends") - assertEquals(listOf(middleRoom), GuardianManager.forward(db, certificate, groupRoom, whenElected = false).map { it.chatRoom.id }, "and the catch-up sends what is left") - } - - @Test - fun `the elected device sends at once`(): Unit = runBlocking { - inRoom(group, groupCertificate) - inRoom(middle, middleCertificate) - signedInGroup() - - assertEquals(listOf(middleRoom), GuardianManager.forward(db, certificate, groupRoom, whenElected = true).map { it.chatRoom.id }) - } - - @Test - fun `nothing it does not believe is forwarded anywhere`(): Unit = runBlocking { - inAllThree() - val forged = Event(certificate.id, certificate.pubKey, certificate.createdAt, certificate.kind, certificate.tags, certificate.content, "0".repeat(128)) - assertTrue(GuardianManager.forward(db, forged, groupRoom, whenElected = false).isEmpty()) - assertFalse(noticesIn(middleRoom).isNotEmpty()) - } - - // ---- Phase 3: on arrival, with nobody calling share ------------------- - - /** [event] arriving in [chatRoomId] as the inbound path and a completed signing session both deliver it. */ - private suspend fun arrives(event: Event, chatRoomId: String) { - mobi.giza.compose.database.model.ChatMessage.applyInnerEvent( - database = db, - groupId = chatRoomId, - event = event, - marmotGroupEventId = null, - marmotInnerEventId = null, - senderPublicKey = chatRoomId, - isUserMessage = false, - createdAt = kotlin.time.Instant.fromEpochSeconds(event.createdAt), - ) - } - - @Test - fun `a member's certificate signed in the group reaches the root two generations up`(): Unit = runBlocking { - inAllThree() - signedInGroup() - - arrives(certificate, groupRoom) - assertEquals(listOf(certificate.id), noticesIn(middleRoom).map { it.id }, "the group's devices told the middle group") - assertEquals(listOf(certificate.id), noticesIn(rootRoom).map { it.id }, "and, being in the root too, the root") - - // The notice arriving in the middle group goes on, and not back down. - GuardianManager.forwardOnArrival(db, noticesIn(middleRoom).single(), middleRoom) - assertEquals(1, noticesIn(rootRoom).size, "the root was told once") - assertTrue(noticesIn(groupRoom).isEmpty()) - } - - @Test - fun `a notice arriving in the middle group is carried to the root`(): Unit = runBlocking { - // This device sits in the middle group and the root, not in the group below. - inRoom(middle, middleCertificate) - inRoom(root, null) - GuardianManager.share(db, certificate, listOfNotNull(db.chatRoomDao().findChatRoomById(middleRoom)), memberPublicKey) - - GuardianManager.forwardOnArrival(db, certificate, middleRoom) - assertEquals(listOf(certificate.id), noticesIn(rootRoom).map { it.id }) - assertEquals(1, GuardianManager.guardedWalletsOf(db, rootRoom).size, "and the root lists it") - } - - @Test - fun `a subgroup's own guarded wallet reaches every group above it`(): Unit = runBlocking { - inAllThree() - val guardians = SubgroupBirthCertificateEvent.parseGuardians(groupCertificate.tags)!! - val account = GroupWalletDerivation.account(thresholdKeyOf(group), chain, 0, guardians) - val template = mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent.template(account, groupCertificate) - val statement = signedAsRoom(group, template.kind, template.tags, template.content, template.createdAt) - - arrives(statement, groupRoom) - assertEquals(listOf(statement.id), noticesIn(middleRoom).map { it.id }) - assertEquals(listOf(statement.id), noticesIn(rootRoom).map { it.id }) - } - - @Test - fun `a plain wallet statement is told to nobody`(): Unit = runBlocking { - inAllThree() - val template = mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent.template(GroupWalletDerivation.account(thresholdKeyOf(middle), chain)) - arrives(signedAsRoom(middle, template.kind, template.tags, template.content, template.createdAt), middleRoom) - assertTrue(noticesIn(rootRoom).isEmpty()) - } - - // ---- Phase 4: the catch-up --------------------------------------------- - - @Test - fun `a certificate filed before forwarding existed is told the first time its group is opened`(): Unit = runBlocking { - // A lower-keyed member in both rooms: on arrival this device would have - // waited for them, and nobody sent anything. - val earlier = "00".repeat(31) + "01" - inRoom(group, groupCertificate, members = listOf(memberPublicKey, earlier)) - inRoom(middle, middleCertificate, members = listOf(earlier)) - signedInGroup() - assertTrue(noticesIn(middleRoom).isEmpty()) - - assertEquals(1, GuardianManager.forwardAll(db, groupRoom)) - assertEquals(listOf(certificate.id), noticesIn(middleRoom).map { it.id }) - assertEquals(0, GuardianManager.forwardAll(db, groupRoom), "and not again") - } - - @Test - fun `the catch-up through the repository, as opening the room runs it`(): Unit = runBlocking { - inAllThree() - signedInGroup() - val repository = mobi.giza.compose.database.repository.DatabaseChatRepository(db, kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.IO)) - - assertEquals(2, repository.forwardGuardedWallets(groupRoom), "the middle group and the root") - assertEquals(0, repository.forwardGuardedWallets(middleRoom), "the root has heard, and the group signed it") - } - - // ---- Phase 5: the transcript ------------------------------------------ - - private suspend fun sharedLinesIn(chatRoomId: String) = - db.chatMessageDao().getChatMessagesByChatRoomId(chatRoomId).map { it.chatMessage } - .filter { it.messageType == mobi.giza.compose.database.model.ChatMessage.TYPE_GUARDED_WALLET_SHARED } - - /** A notice of [statement] from [forwarder], filed in [chatRoomId] as the inbound path files one. */ - private suspend fun noticeFrom(forwarder: String, chatRoomId: String, statement: Event, at: Long): Event { - val tags = arrayOf(arrayOf("h", chatRoomId)) - val id = com.vitorpamplona.quartz.nip01Core.crypto.EventHasher.hashId(forwarder, at, GuardedWalletNoticeEvent.KIND, tags, statement.toJson()) - db.marmotInnerEventDao().upsert( - mobi.giza.compose.database.model.MarmotInnerEvent( - id = id, publicKey = forwarder, kind = GuardedWalletNoticeEvent.KIND, - createdAt = kotlin.time.Instant.fromEpochSeconds(at), tags = tags, content = statement.toJson(), chatRoomId = chatRoomId, - ) - ) - return Event(id, forwarder, at, GuardedWalletNoticeEvent.KIND, tags, statement.toJson(), "") - } - - @Test - fun `two forwarders' notices of one wallet give the group one line`(): Unit = runBlocking { - GroupFixtures.seedProfile(db, memberPublicKey, name = "alice") - inRoom(middle, middleCertificate) - - val first = noticeFrom("a1".repeat(32), middleRoom, certificate, 1_700_000_100) - assertEquals("Shared @alice's guarded wallet with this group.", GuardianManager.describeNotice(db, middleRoom, first)) - - val second = noticeFrom("b2".repeat(32), middleRoom, certificate, 1_700_000_200) - assertEquals(null, GuardianManager.describeNotice(db, middleRoom, second), "the second is filed and silent") - assertEquals(1, GuardianManager.guardedWalletsOf(db, middleRoom).size, "and the wallet listed once") - } - - @Test - fun `the forwarder sees its own line in the group it told`(): Unit = runBlocking { - GroupFixtures.seedProfile(db, memberPublicKey, name = "alice") - inRoom(group, groupCertificate) - inRoom(middle, middleCertificate) - signedInGroup() - - GuardianManager.forward(db, certificate, groupRoom, whenElected = false) - val lines = sharedLinesIn(middleRoom) - assertEquals(1, lines.size) - assertTrue(lines.single().isUserMessage) - assertEquals("Shared @alice's guarded wallet with this group.", lines.single().content) - assertTrue(sharedLinesIn(groupRoom).isEmpty(), "nothing in the group that signed it") - - // Another member's notice of the same wallet, arriving afterwards, writes nothing more. - assertEquals(null, GuardianManager.describeNotice(db, middleRoom, noticeFrom("b2".repeat(32), middleRoom, certificate, 1_800_000_000))) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GuardianSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GuardianSigningJvmTest.kt deleted file mode 100644 index c4c3677e..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GuardianSigningJvmTest.kt +++ /dev/null @@ -1,814 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.ui.view.state.GuardedWalletRow -import mobi.giza.compose.database.model.GroupKeyState -import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy -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.MarmotInnerEvent -import mobi.giza.compose.database.model.NostrEvent -import mobi.giza.compose.database.model.Profile -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.database.model.types.DkgRitualStage -import mobi.giza.compose.database.model.types.FrostSigningStage -import mobi.giza.compose.extensions.toHex -import mobi.giza.compose.nostr.dkg.DkgRitualEvents -import mobi.giza.compose.nostr.frost.FrostSigningEvents -import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.crypto.frost.Frost -import fr.acinq.bitcoin.crypto.frost.KeyMaterial -import kotlinx.coroutines.runBlocking -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertNotNull -import kotlin.test.assertNull -import kotlin.time.Instant -import mobi.giza.compose.database.model.GroupSignedEvent -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import mobi.giza.compose.nostr.wallet.GuardedWalletNoticeEvent -import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.crypto.frost.IndividualNonce -import fr.acinq.bitcoin.crypto.frost.SecretNonce -import fr.acinq.bitcoin.crypto.frost.Session -import kotlin.test.assertTrue -import mobi.giza.compose.wallet.GroupSpend -import mobi.giza.compose.wallet.GroupSpendBuilder -import mobi.giza.compose.wallet.GroupWalletState -import mobi.giza.compose.database.model.types.FrostSigningSubject -import fr.acinq.bitcoin.OutPoint -import fr.acinq.bitcoin.Satoshi -import fr.acinq.bitcoin.Script -import fr.acinq.bitcoin.ScriptFlags -import fr.acinq.bitcoin.Transaction -import fr.acinq.bitcoin.TxId -import fr.acinq.bitcoin.TxIn -import fr.acinq.bitcoin.TxOut -import fr.acinq.lightning.blockchain.electrum.WalletState -import kotlin.test.assertIs - -/** - * A group's guardian keys through the real signing manager, between two of its - * devices, with the wire held by hand -- the harness `GroupSpendSigningJvmTest` - * uses. - * - * The group here is the *ancestor*. What is under test is what its members' - * devices agree to: a certificate is only signed when the guardian keys in it - * are the ones the group grants, whoever proposed it. - */ -class GuardianSigningJvmTest { - private val participants = 3 - private val threshold = 2 - - private val keyMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey(ByteVector32("6a2d1a".padEnd(62, '0') + "a1")), - nParticipants = participants, - threshold = threshold, - ) - private val thresholdPublicKey = keyMaterial.thresholdPublicKey.value.toHex() - private val ceremonyId = "ceremony".padEnd(64, '0') - private val roomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) - private val members = listOf("a", "b", "c").map { it.repeat(64) } - private val hostKeys = listOf("2a", "2b", "2c").map { it.padEnd(66, '0') } - - private val childKey = PrivateKey(ByteVector32(ByteArray(32) { 0x3c })).publicKey().toString() - private val childRoomId = SharedKeyDerivation.marmotGroupId(childKey) - - private val devices = mutableListOf() - - @AfterTest - fun closeDatabases() = devices.forEach { it.db.close() } - - private inner class Device(val publicKey: HexKey, val db: GizaDatabase, val room: LocalChatRoom) { - val received = mutableSetOf() - - suspend fun store(queued: Queued) = db.marmotInnerEventDao().upsert( - MarmotInnerEvent( - id = queued.id, publicKey = queued.publicKey, kind = queued.kind, createdAt = queued.createdAt, - tags = queued.tags, content = queued.content, chatRoomId = roomId, - ) - ) - - suspend fun session(id: String) = db.frostSigningSessionDao().getSessionById(id) - } - - private suspend fun device(publicKey: HexKey, signerIndex: Int): Device { - val db = getRoomDatabase(Room.inMemoryDatabaseBuilder()) - members.forEach { member -> - val nostrEventId = "e$member".take(64) - db.nostrEventDao().upsert(NostrEvent(id = nostrEventId, pubKey = member, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) - db.profileDao().upsert(Profile(publicKey = member, nostrEventId = nostrEventId)) - } - val chatRoom = ChatRoom( - id = roomId, userPublicKey = publicKey, subject = "Council", - description = SharedKeyDerivation.describe("Council."), mlsGroupState = "00", - ) - db.chatRoomDao().upsert(chatRoom) - db.dkgSessionDao().upsert( - DkgSession( - id = ceremonyId, chatRoomId = roomId, coordinatorPublicKey = members.first(), userPublicKey = publicKey, - threshold = threshold, participantCount = participants, stage = DkgRitualStage.COMPLETE, - hostPublicKey = hostKeys[signerIndex], round1Random = "1".repeat(64), round2AuxRandom = "2".repeat(64), - thresholdPublicKey = thresholdPublicKey, - secretShare = keyMaterial.secretShares[signerIndex].value.toHex(), - publicShares = keyMaterial.publicShares.joinToString(",") { it.value.toHex() }, - ) - ) - members.forEachIndexed { index, member -> - db.dkgSessionDao().upsert( - DkgParticipantMessage(sessionId = ceremonyId, participantPublicKey = member, kind = DkgRitualEvents.HOST_KEY, payload = hostKeys[index]) - ) - } - val localChatRoom = db.chatRoomDao().findChatRoomById(roomId) ?: LocalChatRoom(chatRoom = chatRoom) - return Device(publicKey, db, localChatRoom).also { devices += it } - } - - private data class Queued( - val id: HexKey, val publicKey: HexKey, val kind: Int, - val tags: Array>, val content: String, val createdAt: Instant, - ) { - fun toEvent() = Event(id, publicKey, createdAt.epochSeconds, kind, tags, content, "") - } - - private suspend fun outbox(device: Device): List = - device.db.marmotInnerEventDao() - .getByChatRoomAndKinds(chatRoomId = roomId, kinds = FrostSigningEvents.ALL.toList()) - .map { Queued(it.id, it.publicKey, it.kind, it.tags, it.content, it.createdAt) } - .filter { it.publicKey == device.publicKey } - .sortedWith(compareBy({ it.createdAt }, { it.kind })) - - private suspend fun deliver(to: Device, queued: Queued) { - if (!to.received.add(queued.id)) return - to.store(queued) - FrostSigningManager.processSigningPayload(to.db, to.room, queued.toEvent(), to.publicKey) - } - - private suspend fun pump(vararg between: Device) { - var moved = true - while (moved) { - moved = false - for (from in between) for (to in between) { - if (from === to) continue - outbox(from).forEach { queued -> - if (queued.id !in to.received) moved = true - deliver(to, queued) - } - } - } - } - - private fun certificateTags(guardians: List) = SubgroupBirthCertificateEvent.assembleTags( - subgroupChatRoomId = childRoomId, - parentChatRoomId = roomId, - thresholdPublicKey = childKey, - adminPublicKeys = members, - name = "Translation team", - guardians = guardians, - ) - - private suspend fun proposeCertificate(proposer: Device, guardians: List) = - FrostSigningManager.proposeSigning( - proposer.db, proposer.room, proposer.publicKey, SubgroupBirthCertificateEvent.KIND, certificateTags(guardians), childRoomId, - ) - - // ---- The certificate's guardian keys -------------------------------- - - @Test - fun `a certificate granting the group's own key is signed, and carries it`(): Unit = runBlocking { - val proposer = device(members[0], signerIndex = 0) - val other = device(members[1], signerIndex = 1) - val granted = GuardianDerivation.grant(thresholdPublicKey, roomId, emptyList(), childRoomId) - - val session = proposeCertificate(proposer, granted) - pump(proposer, other) - assertNotNull(other.session(session.id), "the other member is asked") - FrostSigningManager.approve(other.db, other.room, session.id) - pump(proposer, other) - - listOf(proposer, other).forEach { device -> - assertEquals(FrostSigningStage.COMPLETE, device.session(session.id)?.stage) - val certificate = assertNotNull(SubgroupManager.certificateFor(device.db, childRoomId, roomId)).toEvent() - assertEquals(granted, SubgroupBirthCertificateEvent.parseGuardians(certificate.tags)) - } - } - - @Test - fun `a certificate granting any other key is never put to the member`(): Unit = runBlocking { - val proposer = device(members[0], signerIndex = 0) - val other = device(members[1], signerIndex = 1) - val coordinators = PrivateKey(ByteVector32(ByteArray(32) { 0x66 })).publicKey().toString() - - // The coordinator's own key dressed as the group's guardian key. - val session = proposeCertificate(proposer, GuardianDerivation.grant(coordinators, roomId, emptyList(), childRoomId)) - pump(proposer, other) - - assertNull(other.session(session.id), "refused at acceptance, so nothing of the member's is ever published for it") - } - - // ---- The parent's decision: docs/subgroup-wallet-policy.md ------------ - - /** A parent of this room, as a key whose certificate this test files without signing. */ - private val decidingParentKey = PrivateKey(ByteVector32(ByteArray(32) { 0x4d })).publicKey().toString() - private val decidingParentRoomId = SharedKeyDerivation.marmotGroupId(decidingParentKey) - private val grantedToRoom = GuardianDerivation.grant(decidingParentKey, decidingParentRoomId, emptyList(), roomId) - - /** - * This room as a subgroup its parent made under [policy], filed on [device] - * the way a verified key state leaves it. The policy is read off the - * certificate's tags; whether the parent signed it was `stateFrom`'s - * question, asked before the row was written. - */ - private suspend fun madeUnder(device: Device, policy: SubgroupWalletPolicy?): Event { - val tags = SubgroupBirthCertificateEvent.assembleTags( - subgroupChatRoomId = roomId, - parentChatRoomId = decidingParentRoomId, - thresholdPublicKey = thresholdPublicKey, - adminPublicKeys = members, - name = "Council", - guardians = if (policy == SubgroupWalletPolicy.UNGUARDED) emptyList() else grantedToRoom, - walletPolicy = policy, - ) - val certificate = Event("d".repeat(64), decidingParentRoomId, 1_700_000_000, SubgroupBirthCertificateEvent.KIND, tags, roomId, "f".repeat(128)) - device.db.groupKeyStateDao().upsert( - GroupKeyState( - chatRoomId = roomId, - dkgSessionId = ceremonyId, - thresholdPublicKey = thresholdPublicKey, - derivationPath = SharedKeyDerivation.formatPath(SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH), - announcedBy = roomId, - announcedAt = Instant.fromEpochSeconds(1_700_000_000), - parentChatRoomId = decidingParentRoomId, - birthCertificateJson = certificate.toJson(), - ) - ) - return certificate - } - - private suspend fun proposeStatement(proposer: Device, guarded: Boolean, certificate: Event) = run { - val template = if (guarded) { - GroupWalletStatementEvent.template( - GroupWalletDerivation.account(thresholdPublicKey, Chain.Regtest, guardians = grantedToRoom), - certificate, - ) - } else { - GroupWalletStatementEvent.template(GroupWalletDerivation.account(thresholdPublicKey, Chain.Regtest)) - } - FrostSigningManager.proposeSigning(proposer.db, proposer.room, proposer.publicKey, template.kind, template.tags, template.content) - } - - @Test - fun `a plain wallet is never put to a member whose parent decided guarded`(): Unit = runBlocking { - val proposer = device(members[0], signerIndex = 0) - val other = device(members[1], signerIndex = 1) - madeUnder(proposer, SubgroupWalletPolicy.GUARDED) - val certificate = madeUnder(other, SubgroupWalletPolicy.GUARDED) - - // What an older build, or a skipped screen, would propose. - val plain = proposeStatement(proposer, guarded = false, certificate) - val guarded = proposeStatement(proposer, guarded = true, certificate) - pump(proposer, other) - - assertNull(other.session(plain.id), "refused before it is shown") - assertNotNull(other.session(guarded.id), "the guarded one is asked") - } - - @Test - fun `a guarded wallet is never put to a member whose parent decided unguarded`(): Unit = runBlocking { - val proposer = device(members[0], signerIndex = 0) - val other = device(members[1], signerIndex = 1) - madeUnder(proposer, SubgroupWalletPolicy.UNGUARDED) - madeUnder(other, SubgroupWalletPolicy.UNGUARDED) - - // A certificate granting keys, as a modified client might carry; the - // room's own decided none. - val guarded = proposeStatement(proposer, guarded = true, madeUnder(device(members[2], signerIndex = 2), SubgroupWalletPolicy.GUARDED)) - val plain = proposeStatement(proposer, guarded = false, madeUnder(proposer, SubgroupWalletPolicy.UNGUARDED)) - pump(proposer, other) - - assertNull(other.session(guarded.id)) - assertNotNull(other.session(plain.id)) - } - - @Test - fun `an undecided room is asked about either, as before`(): Unit = runBlocking { - val proposer = device(members[0], signerIndex = 0) - val other = device(members[1], signerIndex = 1) - madeUnder(proposer, null) - val certificate = madeUnder(other, null) - - val plain = proposeStatement(proposer, guarded = false, certificate) - val guarded = proposeStatement(proposer, guarded = true, certificate) - pump(proposer, other) - - assertNotNull(other.session(plain.id)) - assertNotNull(other.session(guarded.id)) - } - - // ---- Telling an ancestor about a guarded wallet ----------------------- - - /** The child as a group of its own, so its room can sign its statement. */ - private val childMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey(ByteVector32("c41d".padEnd(62, '0') + "b2")), - nParticipants = participants, - threshold = threshold, - ) - private val guardedChildKey = childMaterial.thresholdPublicKey.value.toHex() - private val guardedChildRoomId = SharedKeyDerivation.marmotGroupId(guardedChildKey) - - /** [material]'s room signing [id], as a quorum of its trusted-dealer shares. */ - private fun roomSignature(material: KeyMaterial, id: String): String { - val cache = SharedKeyDerivation.derive(material.thresholdPublicKey.value.toHex()).cache - val message = ByteVector(id.hexToByteArray()) - val signerIds = listOf(0, 1) - val nonces = signerIds.map { signerId -> - SecretNonce.generate( - sessionRandom = ByteVector32("b".repeat(63) + "${signerId + 1}"), - secretShare = material.secretShares[signerId], - publicShare = material.publicShares[signerId], - tweakedThresholdPublicKey = cache.tweakedPublicKey, - message = message, - extraInput = null, - ) - } - val session = Session.create( - aggregatedNonce = IndividualNonce.aggregate(nonces.map { it.second }).right!!, - signerIds = signerIds.map { it.toUInt() }, - signerPublicShares = signerIds.map { material.publicShares[it] }, - nParticipants = participants, - threshold = threshold, - tweakCache = cache, - message = message, - ) - val partials = signerIds.mapIndexed { position, signerId -> - session.sign(nonces[position].first, material.secretShares[signerId], signerId.toUInt()).right!! - } - return session.aggregateSigs(partials).right!!.toByteArray().toHex() - } - - private fun signedBy(material: KeyMaterial, kind: Int, tags: Array>, content: String, createdAt: Long = 1_700_000_000): Event { - val author = SharedKeyDerivation.marmotGroupId(material.thresholdPublicKey.value.toHex()) - val id = EventHasher.hashId(author, createdAt, kind, tags, content) - return Event(id, author, createdAt, kind, tags, content, roomSignature(material, id)) - } - - /** The ancestor certifies the child with [guardians], and the child signs a guarded statement under them. */ - private fun guardedStatement( - guardians: List = GuardianDerivation.grant(thresholdPublicKey, roomId, emptyList(), guardedChildRoomId), - createdAt: Long = 1_700_000_000, - ): Event { - val certificate = signedBy( - keyMaterial, SubgroupBirthCertificateEvent.KIND, - SubgroupBirthCertificateEvent.assembleTags( - subgroupChatRoomId = guardedChildRoomId, parentChatRoomId = roomId, thresholdPublicKey = guardedChildKey, - adminPublicKeys = members, name = "Translation team", guardians = guardians, - ), - guardedChildRoomId, - ) - val account = GroupWalletDerivation.account(guardedChildKey, Chain.Regtest, guardians = guardians) - val template = GroupWalletStatementEvent.template(account, certificate, createdAt) - return signedBy(childMaterial, template.kind, template.tags, template.content, createdAt) - } - - private suspend fun tell(device: Device, statement: Event, from: HexKey = members[2], createdAt: Long = 1_700_000_100) { - val content = statement.toJson() - device.db.marmotInnerEventDao().upsert( - MarmotInnerEvent( - id = EventHasher.hashId(from, createdAt, GuardedWalletNoticeEvent.KIND, emptyArray(), content), - publicKey = from, kind = GuardedWalletNoticeEvent.KIND, createdAt = Instant.fromEpochSeconds(createdAt), - tags = emptyArray(), content = content, chatRoomId = roomId, - ) - ) - } - - @Test - fun `an ancestor believes a statement naming a key its own walk reaches, and nothing else`() { - val statement = guardedStatement() - - val wallet = assertNotNull(GuardianManager.verify(statement, roomId, thresholdPublicKey)) - assertEquals(guardedChildRoomId, wallet.descendantChatRoomId) - assertEquals(listOf(guardedChildRoomId), wallet.lineage) - assertEquals("Translation team", wallet.name) - assertTrue(wallet.account.isGuarded) - - val strangerKey = PrivateKey(ByteVector32(ByteArray(32) { 0x55 })).publicKey().toString() - val refusals = mapOf( - "a group that is not among its guardians" to GuardianManager.verify(statement, guardedChildRoomId, guardedChildKey), - "a key the ancestor's walk does not reach" to GuardianManager.verify( - guardedStatement(GuardianDerivation.grant(strangerKey, roomId, emptyList(), guardedChildRoomId)), roomId, thresholdPublicKey, - ), - "a statement the child's room did not sign" to GuardianManager.verify(Event(statement.id, statement.pubKey, statement.createdAt, statement.kind, statement.tags, statement.content, "0".repeat(128)), roomId, thresholdPublicKey), - "a plain statement" to run { - val plain = GroupWalletStatementEvent.template(GroupWalletDerivation.account(guardedChildKey, Chain.Regtest)) - GuardianManager.verify(signedBy(childMaterial, plain.kind, plain.tags, plain.content), roomId, thresholdPublicKey) - }, - ) - refusals.forEach { (name, verified) -> assertNull(verified, name) } - } - - @Test - fun `a notice in the ancestor's room is a guarded wallet it holds, under its first guardians`(): Unit = runBlocking { - val ancestor = device(members[0], signerIndex = 0) - val first = guardedStatement(createdAt = 1_700_000_000) - tell(ancestor, first) - // A later statement for the same account, naming other guardians, cannot - // move what the ancestor watches -- the earliest decides. - val second = guardedStatement( - GuardianDerivation.grant(thresholdPublicKey, roomId, emptyList(), guardedChildRoomId).map { it.copy(delay = 13) }, - createdAt = 1_700_000_500, - ) - tell(ancestor, second, createdAt = 1_700_000_600) - // And nonsense is read past, not believed. - ancestor.db.marmotInnerEventDao().upsert( - MarmotInnerEvent(id = "f".repeat(64), publicKey = members[2], kind = GuardedWalletNoticeEvent.KIND, - createdAt = Instant.fromEpochSeconds(1), tags = emptyArray(), content = "not an event", chatRoomId = roomId) - ) - - val held = GuardianManager.guardedWalletsOf(ancestor.db, roomId) - assertEquals(listOf(first.id), held.map { it.statement.id }) - assertEquals( - "Shared the guarded wallet of Translation team with this group.", - // The notice as it was filed: a second notice of the same statement - // would be filed and silent (docs/guarded-wallet-forwarding.md, D6). - ancestor.db.marmotInnerEventDao().getByChatRoomAndKinds(roomId, listOf(GuardedWalletNoticeEvent.KIND)) - .first { Event.fromJsonOrNull(it.content)?.id == first.id } - .let { GuardianManager.describeNotice(ancestor.db, roomId, Event(it.id, it.publicKey, it.createdAt.epochSeconds, it.kind, it.tags, it.content, "")) } - ) - } - - @Test - fun `a member in both rooms carries the child's statement up, once`(): Unit = runBlocking { - val member = device(members[0], signerIndex = 0) - // This device is also in the child's room, and holds its signed statement there. - member.db.chatRoomDao().upsert(ChatRoom(id = guardedChildRoomId, userPublicKey = member.publicKey, subject = "Translation team", description = null, mlsGroupState = "00")) - member.db.groupKeyStateDao().upsert( - mobi.giza.compose.database.model.GroupKeyState( - chatRoomId = guardedChildRoomId, dkgSessionId = "child-ceremony", thresholdPublicKey = guardedChildKey, - derivationPath = SharedKeyDerivation.formatPath(), announcedBy = guardedChildRoomId, - announcedAt = Instant.fromEpochSeconds(1_700_000_000), - ) - ) - val statement = guardedStatement() - member.db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(statement, chatRoomId = guardedChildRoomId)) - - val shareable = GuardianManager.shareableFrom(member.db, guardedChildRoomId, Chain.Regtest).single() - assertEquals(statement.id, shareable.statement.id) - assertEquals(listOf(roomId), shareable.rooms.map { it.chatRoom.id }) - - assertEquals(1, GuardianManager.share(member.db, shareable.statement, shareable.rooms, member.publicKey)) - val queued = member.db.marmotInnerEventDao().getByChatRoomAndKinds(roomId, listOf(GuardedWalletNoticeEvent.KIND)).single() - assertEquals(member.publicKey, queued.publicKey) - assertNull(queued.marmotGroupEventId, "queued for the outbound pipeline, not yet sent") - - // Told is told: nothing left to share, and the ancestor's own device reads it back. - assertEquals(emptyList(), GuardianManager.shareableFrom(member.db, guardedChildRoomId, Chain.Regtest)) - assertEquals(listOf(statement.id), GuardianManager.guardedWalletsOf(member.db, roomId).map { it.statement.id }) - } - - @Test - fun `a grandchild's statement told to its parent and grandparent at once reaches both`(): Unit = runBlocking { - val member = device(members[0], signerIndex = 0) - val grandparentRoomId = "9".repeat(64) - member.db.chatRoomDao().upsert(ChatRoom(id = grandparentRoomId, userPublicKey = member.publicKey, subject = "Assembly", description = null, mlsGroupState = "00")) - val rooms = listOf(roomId, grandparentRoomId).map { assertNotNull(member.db.chatRoomDao().findChatRoomById(it)) } - - // One statement, one sharer, one second: only the room tells the two notices apart. - assertEquals(2, GuardianManager.share(member.db, guardedStatement(), rooms, member.publicKey, createdAt = 1_700_000_100)) - - val told = listOf(roomId, grandparentRoomId).associateWith { room -> - member.db.marmotInnerEventDao().getByChatRoomAndKinds(room, listOf(GuardedWalletNoticeEvent.KIND)).single() - } - told.forEach { (room, notice) -> assertEquals(listOf(listOf("h", room)), notice.tags.map { it.toList() }) } - assertEquals(2, told.values.map { it.id }.toSet().size) - } - - // ---- Spending from a guarded wallet ------------------------------------ - - private val chain = Chain.Regtest - private val elsewhere = ByteVector(Script.write(Script.pay2wpkh(PrivateKey(ByteVector32(ByteArray(32) { 9 })).publicKey()))) - - /** Somebody else's money paying the child's first guarded receive address. */ - private fun fundingOf(guarded: GroupWalletDerivation.Account) = Transaction( - 2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 0x61 })), 0), ByteVector.empty, 0xffffffffL)), - listOf(TxOut(Satoshi(50_000), GroupWalletDerivation.derive(guarded, GroupWalletDerivation.RECEIVE, 0).pubkeyScript)), 0, - ) - - /** The child's wallet as Electrum would report it holding [funding], confirmed at [height], with the tip at [tip]. */ - private fun fundedState(guarded: GroupWalletDerivation.Account, funding: Transaction, height: Int, tip: Int): GroupWalletState { - val meta = WalletState.AddressMeta.Derived(0) - val address = GroupWalletDerivation.derive(guarded, GroupWalletDerivation.RECEIVE, 0).address(chain) - val receive = WalletState(mapOf(address to WalletState.AddressState(meta, alreadyUsed = true, utxos = listOf(WalletState.Utxo(funding.txid, 0, height.toLong(), funding, meta))))) - val change = WalletState((0 until 3).associate { index -> - GroupWalletDerivation.derive(guarded, GroupWalletDerivation.CHANGE, index.toLong()).address(chain) to - WalletState.AddressState(WalletState.AddressMeta.Derived(index), alreadyUsed = false, utxos = emptyList()) - }) - return GroupWalletState(guarded, receive, change, tipHeight = tip) - } - - @Test - fun `the builder waits out the leaf's lock, and puts it on every input`() { - val guarded = assertNotNull(GuardianManager.verify(guardedStatement(), roomId, thresholdPublicKey)) - val funding = fundingOf(guarded.account) - val address = fr.acinq.bitcoin.Bitcoin.addressFromPublicKeyScript(chain.chainHash, elsewhere.toByteArray()).right!! - - // Eleven confirmations: the owner could spend it, the guardian cannot yet. - val young = fundedState(guarded.account, funding, height = 100, tip = 110) - assertIs(GroupSpendBuilder.sendAll(young, address, 2, emptySet())) - assertEquals(GroupSpendBuilder.Result.NothingToSpend, GroupSpendBuilder.sendAll(young, address, 2, emptySet(), guarded.spender())) - - val old = fundedState(guarded.account, funding, height = 100, tip = 111) - val built = assertIs(GroupSpendBuilder.sendAll(old, address, 2, emptySet(), guarded.spender())) - assertEquals(listOf(12L), built.psbt.global.tx.txIn.map { it.sequence }) - - // What the builder charged for is what a signer weighs it at. - val checked = assertIs(GroupSpend.check(built.psbt, guarded.account, guarded.spender(thresholdPublicKey))).checked - assertEquals(built.fee.sat, 2 * ((checked.weight + 3) / 4).toLong()) - } - - /** - * The builder and the check read each leaf's own delay, at the edges of its - * encoding: a coin one block short of the lock is the owner's alone, at the - * lock it is the guardian's too, and every input carries exactly that lock. - * docs/guardian-delay.md, Phase 2. - */ - @Test - fun `the builder and the check follow a chosen delay, not the default`() { - val address = fr.acinq.bitcoin.Bitcoin.addressFromPublicKeyScript(chain.chainHash, elsewhere.toByteArray()).right!! - listOf(6L, 17L, 128L, 32_768L, 65_535L).forEach { delay -> - val guardians = GuardianDerivation.grant(thresholdPublicKey, roomId, emptyList(), guardedChildRoomId, delay = delay) - val guarded = assertNotNull(GuardianManager.verify(guardedStatement(guardians), roomId, thresholdPublicKey), "a delay of $delay") - val funding = fundingOf(guarded.account) - - // Confirmed at height 100, so `delay` confirmations at tip 99 + delay. - val young = fundedState(guarded.account, funding, height = 100, tip = 98 + delay.toInt()) - assertEquals(GroupSpendBuilder.Result.NothingToSpend, GroupSpendBuilder.sendAll(young, address, 2, emptySet(), guarded.spender()), "a delay of $delay") - - val old = fundedState(guarded.account, funding, height = 100, tip = 99 + delay.toInt()) - val built = assertIs(GroupSpendBuilder.sendAll(old, address, 2, emptySet(), guarded.spender())) - assertEquals(listOf(delay), built.psbt.global.tx.txIn.map { it.sequence }) - assertIs(GroupSpend.check(built.psbt, guarded.account, guarded.spender(thresholdPublicKey))) - - // The default's lock on a leaf that chose another is refused. - val atDefault = built.psbt.global.tx.copy(txIn = built.psbt.global.tx.txIn.map { it.copy(sequence = GuardianDerivation.DEFAULT_DELAY) }) - val refused = GroupSpend.check(built.psbt.copy(global = built.psbt.global.copy(tx = atDefault)), guarded.account, guarded.spender(thresholdPublicKey)) - if (delay != GuardianDerivation.DEFAULT_DELAY) assertIs(refused, "a delay of $delay") - } - } - - /** - * Two ancestors who gave the same wallet different delays: a coin 100 blocks - * deep is within the reach of the one at 12 and not the one at 4,320. - * docs/guardian-delay.md, Phase 7. - */ - @Test - fun `a guarded wallet's reach is each ancestor's own delay`() { - val farKey = PrivateKey(ByteVector32(ByteArray(32) { 0x5e })).publicKey().toString() - val farRoom = SharedKeyDerivation.marmotGroupId(farKey) - val inherited = GuardianDerivation.grant(farKey, farRoom, emptyList(), roomId, delay = 4_320) - val guardians = GuardianDerivation.grant(thresholdPublicKey, roomId, inherited, guardedChildRoomId, delay = 12) - val near = assertNotNull(GuardianManager.verify(guardedStatement(guardians), roomId, thresholdPublicKey)) - val far = near.copy(ancestorChatRoomId = farRoom) - assertEquals(12L, near.delay) - assertEquals(4_320L, far.delay) - - val state = fundedState(near.account, fundingOf(near.account), height = 100, tip = 199) - assertEquals(Satoshi(50_000), GuardedWalletRow(near, state).withinReach) - assertEquals(Satoshi(0), GuardedWalletRow(far, state).withinReach) - // And what is arriving is the rest of it, by the same leaf's lock. - assertEquals(Satoshi(0), GuardedWalletRow(near, state).arriving) - assertEquals(Satoshi(50_000), GuardedWalletRow(far, state).arriving) - } - - @Test - fun `an ancestor's quorum spends a descendant's coin through its leaf, on every device`(): Unit = runBlocking { - val proposer = device(members[0], signerIndex = 0) - val other = device(members[1], signerIndex = 1) - val statement = guardedStatement() - tell(proposer, statement) - tell(other, statement) - - val guarded = assertNotNull(GuardianManager.guardedWalletFor(proposer.db, roomId, guardedChildRoomId, chain, 0)) - val funding = fundingOf(guarded.account) - val built = assertIs( - GroupSpendBuilder.send(fundedState(guarded.account, funding, 100, 200), fr.acinq.bitcoin.Bitcoin.addressFromPublicKeyScript(chain.chainHash, elsewhere.toByteArray()).right!!, - Satoshi(30_000), 2, emptySet(), emptySet(), guarded.spender()) - ) - - val session = FrostSigningManager.proposeGuardianSpend(proposer.db, proposer.room, proposer.publicKey, built.psbt, guardedChildRoomId, chain) - pump(proposer, other) - assertEquals(FrostSigningSubject.TRANSACTION, other.session(session.id)?.subject) - val seen = assertNotNull(FrostSigningManager.checkedSpend(other.db, session.id)) - assertIs(seen.spender) - assertEquals(listOf(false, true), seen.outputs.map { it.isChange }, "the change goes back to the child") - - FrostSigningManager.approve(other.db, other.room, session.id) - pump(proposer, other) - - listOf(proposer, other).forEach { device -> - assertEquals(FrostSigningStage.COMPLETE, device.session(session.id)?.stage) - val row = assertNotNull(device.db.groupTransactionDao().getBySessionId(session.id)) - assertEquals(guardedChildRoomId, row.guardedChatRoomId) - val signed = Transaction.read(assertNotNull(row.signedTransaction)) - signed.correctlySpends(mapOf(OutPoint(funding, 0) to funding.txOut[0]), ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) - assertEquals(3, signed.txIn[0].witness.stack.size, "a signature, the leaf, and its control block") - } - } - - @Test - fun `the child reads off the chain which guardian took its coins, and says so once`(): Unit = runBlocking { - val proposer = device(members[0], signerIndex = 0) - val other = device(members[1], signerIndex = 1) - val statement = guardedStatement() - tell(proposer, statement) - tell(other, statement) - - val guarded = assertNotNull(GuardianManager.guardedWalletFor(proposer.db, roomId, guardedChildRoomId, chain, 0)) - val funding = fundingOf(guarded.account) - val built = assertIs( - GroupSpendBuilder.sendAll(fundedState(guarded.account, funding, 100, 200), fr.acinq.bitcoin.Bitcoin.addressFromPublicKeyScript(chain.chainHash, elsewhere.toByteArray()).right!!, 2, emptySet(), guarded.spender()) - ) - val session = FrostSigningManager.proposeGuardianSpend(proposer.db, proposer.room, proposer.publicKey, built.psbt, guardedChildRoomId, chain) - pump(proposer, other) - FrostSigningManager.approve(other.db, other.room, session.id) - pump(proposer, other) - val signed = Transaction.read(assertNotNull(proposer.db.groupTransactionDao().getBySessionId(session.id)?.signedTransaction)) - - // What the child's device knows: its own coin, and the transaction that spent it. - val coins = mapOf(OutPoint(funding, 0) to (funding.txOut[0] to GroupWalletDerivation.derive(guarded.account, 0, 0))) - val taken = GuardianManager.takenIn(signed, guarded.account, coins) - assertEquals(listOf(GuardianManager.Taken(signed.txid, guarded.account.guardians[0], Satoshi(50_000))), taken) - - // The child's own key-path spend names nobody. - val ownSpend = signed.updateWitness(0, fr.acinq.bitcoin.ScriptWitness(listOf(ByteVector(ByteArray(64))))) - assertEquals(emptyList(), GuardianManager.takenIn(ownSpend, guarded.account, coins)) - - // The line, written once, in the child's room -- the ancestor's name from - // this device's own copy of its room. - proposer.db.chatRoomDao().upsert(ChatRoom(id = guardedChildRoomId, userPublicKey = proposer.publicKey, subject = "Translation team", description = null, mlsGroupState = "00")) - assertEquals(1, GuardianManager.recordTaken(proposer.db, guardedChildRoomId, taken)) - assertEquals(0, GuardianManager.recordTaken(proposer.db, guardedChildRoomId, taken), "a second reading of the chain writes nothing") - val line = proposer.db.chatMessageDao().getChatMessagesByChatRoomId(guardedChildRoomId).map { it.chatMessage } - .single { it.messageType == mobi.giza.compose.database.model.ChatMessage.TYPE_GUARDIAN_SPEND } - assertTrue(line.content.startsWith("Council took 50000 sats from this wallet through its guardian leaf"), line.content) - } - - @Test - fun `a guardian's spend is refused for a wallet the room was not told about, or without the lock`(): Unit = runBlocking { - val proposer = device(members[0], signerIndex = 0) - val other = device(members[1], signerIndex = 1) - val statement = guardedStatement() - tell(proposer, statement) - // The other device was never told: it has no wallet to check the spend against. - - val guarded = assertNotNull(GuardianManager.guardedWalletFor(proposer.db, roomId, guardedChildRoomId, chain, 0)) - val funding = fundingOf(guarded.account) - val built = assertIs( - GroupSpendBuilder.sendAll(fundedState(guarded.account, funding, 100, 200), fr.acinq.bitcoin.Bitcoin.addressFromPublicKeyScript(chain.chainHash, elsewhere.toByteArray()).right!!, 2, emptySet(), guarded.spender()) - ) - val session = FrostSigningManager.proposeGuardianSpend(proposer.db, proposer.room, proposer.publicKey, built.psbt, guardedChildRoomId, chain) - pump(proposer, other) - assertNull(other.session(session.id), "a device not told about the wallet has nothing to sign it against") - - // And the proposer's own device will not propose one that skips the lock. - val unlocked = built.psbt.global.tx.let { tx -> tx.copy(txIn = tx.txIn.map { it.copy(sequence = GroupSpend.MAX_SEQUENCE) }) } - val psbt = GroupSpend.psbtOf(unlocked, listOf(funding.txOut[0] to GroupWalletDerivation.derive(guarded.account, 0, 0)), emptyMap(), guarded.account) - assertIs(GroupSpend.check(psbt, guarded.account, guarded.spender(thresholdPublicKey))) - } - - // ---- Funding a descendant's guarded wallet ------------------------------- - - /** The room opens its own plain wallet, signed by a quorum, so it has coins to fund with. */ - private suspend fun openOwnWallet(proposer: Device, other: Device): GroupWalletDerivation.Account { - val own = GroupWalletDerivation.account(thresholdPublicKey, chain) - val template = GroupWalletStatementEvent.template(own) - val session = FrostSigningManager.proposeSigning(proposer.db, proposer.room, proposer.publicKey, template.kind, template.tags, template.content) - pump(proposer, other) - FrostSigningManager.approve(other.db, other.room, session.id) - pump(proposer, other) - listOf(proposer, other).forEach { assertNotNull(GroupWalletManager.walletFor(it.db, roomId, chain), "the room's own wallet is open") } - return own - } - - /** The room's own wallet holding one confirmed coin at its first receive address. */ - private fun ownState(own: GroupWalletDerivation.Account): GroupWalletState { - val coin = GroupWalletDerivation.derive(own, GroupWalletDerivation.RECEIVE, 0) - val paid = Transaction( - 2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 0x71 })), 0), ByteVector.empty, 0xffffffffL)), - listOf(TxOut(Satoshi(80_000), coin.pubkeyScript)), 0, - ) - val meta = WalletState.AddressMeta.Derived(0) - val receive = WalletState(mapOf(coin.address(chain) to WalletState.AddressState(meta, alreadyUsed = true, utxos = listOf(WalletState.Utxo(paid.txid, 0, 100, paid, meta))))) - val change = WalletState((0 until 3).associate { index -> - GroupWalletDerivation.derive(own, GroupWalletDerivation.CHANGE, index.toLong()).address(chain) to - WalletState.AddressState(WalletState.AddressMeta.Derived(index), alreadyUsed = false, utxos = emptyList()) - }) - return GroupWalletState(own, receive, change, tipHeight = 110) - } - - private fun fundingTo(guarded: GuardianManager.GuardedWallet, index: Long) = - GroupSpendBuilder.Destination.Funding(guarded.account, GroupWalletDerivation.derive(guarded.account, GroupWalletDerivation.RECEIVE, index)) - - @Test - fun `a funding is read as one by every device holding the wallet, and its address is held`(): Unit = runBlocking { - val proposer = device(members[0], signerIndex = 0) - val other = device(members[1], signerIndex = 1) - val statement = guardedStatement() - tell(proposer, statement) - tell(other, statement) - val own = openOwnWallet(proposer, other) - - val guarded = assertNotNull(GuardianManager.guardedWalletFor(proposer.db, roomId, guardedChildRoomId, chain, 0)) - val built = assertIs( - GroupSpendBuilder.send(ownState(own), fundingTo(guarded, 2), Satoshi(30_000), 2, emptySet()) - ) - val session = FrostSigningManager.proposeSpend(proposer.db, proposer.room, proposer.publicKey, built.psbt, chain) - pump(proposer, other) - - val seen = assertNotNull(FrostSigningManager.checkedSpend(other.db, session.id)) - val funding = seen.fundings.single() - assertEquals(guardedChildRoomId, funding.wallet.descendantChatRoomId) - assertEquals(2L, funding.derived.index) - assertEquals( - mobi.giza.compose.text.ProposedEvent.Summary( - "Fund Translation team's guarded wallet", - "Send 30,000 sats to Translation team's guarded wallet, address 2", - ), - mobi.giza.compose.text.ProposedSpend.summarize(seen, chain), - ) - assertEquals(setOf(2L), FrostSigningManager.reservedFundingIndices(other.db, roomId, guarded.account)) - - // A bump keeps the claim, or it would read as a payment to a bare address. - val bumped = assertIs(GroupSpendBuilder.bump(seen, 5)) - assertEquals(setOf(2L), GroupSpend.claimedFundingIndices(bumped.psbt, guarded.account)) - assertEquals(2L, bumped.funded?.derived?.index) - - // Abandoned, it lets the address go. - other.db.frostSigningSessionDao().upsert(other.session(session.id)!!.copy(stage = FrostSigningStage.FAILED)) - assertEquals(emptySet(), FrostSigningManager.reservedFundingIndices(other.db, roomId, guarded.account)) - } - - @Test - fun `a funding claiming an address it does not pay is refused by every device that can tell`(): Unit = runBlocking { - val proposer = device(members[0], signerIndex = 0) - val other = device(members[1], signerIndex = 1) - // Only the other device holds the wallet, so only it can check the claim. - tell(other, guardedStatement()) - val own = openOwnWallet(proposer, other) - - val guarded = assertNotNull(GuardianManager.guardedWalletFor(other.db, roomId, guardedChildRoomId, chain, 0)) - val honest = assertIs( - GroupSpendBuilder.send(ownState(own), fundingTo(guarded, 2), Satoshi(30_000), 2, emptySet()) - ) - // Pays address 2, says address 3. - val claimed = GroupWalletDerivation.derive(guarded.account, GroupWalletDerivation.RECEIVE, 3) - val coin = GroupWalletDerivation.derive(own, GroupWalletDerivation.RECEIVE, 0) - val lying = GroupSpend.psbtOf( - honest.psbt.global.tx, - listOf(TxOut(Satoshi(80_000), coin.pubkeyScript) to coin), - mapOf(1 to GroupWalletDerivation.derive(own, GroupWalletDerivation.CHANGE, 0)), - own, - funding = mapOf(0 to (guarded.account to claimed)), - ) - assertIs( - GroupSpend.fundingsOf(assertIs(GroupSpend.check(lying, own)).checked, listOf(guarded)) - ) - - val session = FrostSigningManager.proposeSpend(proposer.db, proposer.room, proposer.publicKey, lying, chain) - pump(proposer, other) - assertNull(other.session(session.id), "the device that holds the wallet never puts it to the member") - } - - @Test - fun `a device never told about the wallet reads a funding as the bare address it pays`(): Unit = runBlocking { - val proposer = device(members[0], signerIndex = 0) - val other = device(members[1], signerIndex = 1) - tell(proposer, guardedStatement()) - val own = openOwnWallet(proposer, other) - - val guarded = assertNotNull(GuardianManager.guardedWalletFor(proposer.db, roomId, guardedChildRoomId, chain, 0)) - val destination = fundingTo(guarded, 2) - val built = assertIs( - GroupSpendBuilder.send(ownState(own), destination, Satoshi(30_000), 2, emptySet()) - ) - val session = FrostSigningManager.proposeSpend(proposer.db, proposer.room, proposer.publicKey, built.psbt, chain) - pump(proposer, other) - - val seen = assertNotNull(FrostSigningManager.checkedSpend(other.db, session.id), "accepted: the address is the truth") - assertEquals(emptyList(), seen.fundings) - assertEquals( - "Send 30,000 sats to ${destination.derived.address(chain)}", - mobi.giza.compose.text.ProposedSpend.summarize(seen, chain).detail, - ) - assertEquals(1, assertNotNull(FrostSigningManager.checkedSpend(proposer.db, session.id)).fundings.size, "and the proposer's own device still names it") - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/IcebergCeremonyJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/IcebergCeremonyJvmTest.kt deleted file mode 100644 index a353a9bd..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/IcebergCeremonyJvmTest.kt +++ /dev/null @@ -1,420 +0,0 @@ -package mobi.giza.compose.managers - -import androidx.room3.Room -import mobi.giza.compose.database.GizaDatabase -import mobi.giza.compose.database.builder.getRoomDatabase -import mobi.giza.compose.database.model.ChatMessage -import mobi.giza.compose.database.model.ChatRoom -import mobi.giza.compose.database.model.DkgParticipantMessage -import mobi.giza.compose.database.model.DkgSession -import mobi.giza.compose.database.model.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.database.model.types.IcebergApprovalStep -import mobi.giza.compose.database.model.types.IcebergRitualStage -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.EventHasher -import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Chain -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.frost.Frost -import fr.acinq.bitcoin.crypto.frost.KeyMaterial -import fr.acinq.bitcoin.crypto.iceberg.Iceberg -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 kotlinx.coroutines.runBlocking -import kotlin.random.Random -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertNotNull -import kotlin.test.assertNull -import kotlin.test.assertTrue -import kotlin.time.Clock -import kotlin.time.Duration.Companion.seconds -import kotlin.time.Instant - -/** - * An Iceberg key ceremony between four devices, each with its own database, over the messages the - * manager queues for the room -- the seam `SubgroupCeremonyInParentRoomTest` uses: what is under test is - * what each device stores, publishes and refuses, not whether MLS encrypts it. - * - * The four hold a 3-of-4 FROST key for the room and have opened an onchain wallet under it, which is - * what a Lightning wallet needs before it can have a key of its own (decisions D1 and D2). - */ -class IcebergCeremonyJvmTest { - private val n = 4 - private val keyMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey(ByteVector32("1ceb".padEnd(62, '0') + "a1")), - nParticipants = n, - threshold = 3, - ) - private val thresholdPublicKey = keyMaterial.thresholdPublicKey.value.toHex() - private val onchainCeremonyId = "onchain".padEnd(64, '0') - private val roomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) - private val chain = Chain.Regtest - private val account = GroupWalletDerivation.account(thresholdPublicKey, chain) - - private val keys = (1..n).map { KeyPair() } - private val members = keys.map { it.pubKey.toHexKey() } - private val hostKeys = (1..n).map { "02" + "2${it}".padEnd(64, '0') } - - private val devices = mutableListOf() - - @AfterTest - fun close() = devices.forEach { it.db.close() } - - private 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) = db.icebergKeySessionDao().getSessionById(id) - } - - private 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) - // Everyone is in the room: a ceremony is over the onchain key's holders who still are. - 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 = 3, 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 } - } - - private suspend fun outbox(from: Device, kinds: Set) = from.db.marmotInnerEventDao() - .getByChatRoomAndKinds(chatRoomId = roomId, kinds = kinds.toList()) - .filter { it.publicKey == from.publicKey } - .sortedWith(compareBy({ it.createdAt }, { it.kind })) - - private fun MarmotInnerEvent.asEvent() = Event(id, publicKey, createdAt.epochSeconds, kind, tags, content, "") - - /** Moves every queued message of [kinds] to every other device until nothing new moves. */ - private 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)) - when (queued.kind) { - in FrostSigningEvents.ALL -> FrostSigningManager.processSigningPayload(to.db, to.room, queued.asEvent(), to.publicKey) - in GroupLightningEvents.CEREMONY -> IcebergRitualManager.processCeremonyPayload(to.db, to.room, queued.asEvent(), to.publicKey, to.privateKey) - } - } - } - } - } - } - - private suspend fun openOnchainWallet(all: List) { - val template = GroupWalletStatementEvent.template(account) - val session = FrostSigningManager.proposeSigning(all[0].db, all[0].room, all[0].publicKey, template.kind, template.tags, template.content) - pump(all, FrostSigningEvents.ALL) - all.drop(1).forEach { FrostSigningManager.approve(it.db, it.room, session.id) } - pump(all, FrostSigningEvents.ALL) - all.forEach { assertNotNull(GroupWalletManager.walletFor(it.db, roomId, chain), "device ${it.index} has the onchain wallet") } - } - - private suspend fun group(): List = (0 until n).map { device(it) }.also { openOnchainWallet(it) } - - /** Runs the ceremony from [proposer], each other device approving when it is asked: joining, only. */ - private 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 - } - - private fun signsWithStockCosigner(sessions: List, signers: List): Boolean { - val s0 = sessions.first() - val groupKey = PublicKey.fromHex(s0.groupPublicKey!!) - val shares = sessions.map { IcebergRitualManager.shareOf(it)!! } - val byIndex = shares.associateBy { it.toByteArray()[3].toInt() } - val cosigner = PrivateKey(Random.nextBytes(32).byteVector32()) - val msg = Random.nextBytes(32).byteVector32() - val sid = Random.nextBytes(32).byteVector32() - val (aggregateKey, cache) = KeyAggCache.create(listOf(groupKey, cosigner.publicKey())) - val contributions = signers.map { Iceberg.generateNonce(byIndex.getValue(it), null, sid) } - val groupNonce = (Iceberg.aggregateNonces(contributions, s0.participantCount, s0.threshold, groupKey) as Either.Right).value - val (secret, public) = SecretNonce.generate(Random.nextBytes(32).byteVector32(), Either.Left(cosigner), msg, cache, null) - val session = Session.create((IndividualNonce.aggregate(listOf(groupNonce, public)) as Either.Right).value, msg, cache) - val cosignerAgg = (IndividualNonce.aggregate(listOf(public)) as Either.Right).value - val signatureShares = signers.map { (Iceberg.partialSign(byIndex.getValue(it), null, sid, contributions, groupKey, cache, msg, cosignerAgg) as Either.Right).value } - val groupPartial = (Iceberg.aggregatePartialSignatures(signatureShares, s0.participantCount, s0.threshold) as Either.Right).value - val sig = (session.aggregateSigs(listOf(groupPartial, (session.sign(secret, cosigner) as Either.Right).value)) as Either.Right).value - return Crypto.verifySignatureSchnorr(msg, sig, aggregateKey) - } - - @Test - fun `four devices make one 2-of-4 key, and it signs`() = runBlocking { - val all = group() - val proposed = runCeremony(all) - val sessions = all.map { assertNotNull(it.ceremony(proposed.id), "device ${it.index} has the ceremony") } - sessions.forEach { assertEquals(IcebergRitualStage.COMPLETE, it.stage, "device ${it.userPublicKey.take(8)}: ${it.failureReason}") } - assertEquals(1, sessions.map { it.groupPublicKey }.toSet().size, "every device has the same key") - assertEquals(1, sessions.map { it.publicShares }.toSet().size) - sessions.forEach { assertNull(it.root, "the random root is dropped once the share exists") } - assertTrue(signsWithStockCosigner(sessions, listOf(1, 2, 3))) - assertTrue(signsWithStockCosigner(sessions, listOf(2, 3, 4))) - // Each device wrote the ceremony's lines from what it received, ending with the key. - all.forEach { d -> - val lines = d.db.chatMessageDao().getChatMessagesByChatRoomId(roomId).map { it.chatMessage }.filter { it.messageType in ChatMessage.ICEBERG_TYPES } - assertEquals(1, lines.count { it.messageType == ChatMessage.TYPE_ICEBERG_COMPLETE }) - assertEquals(n, lines.count { it.messageType == ChatMessage.TYPE_ICEBERG_COMMITTED }) - assertTrue(ChatMessage.answeredRequests(lines).size == lines.count { it.messageType in ChatMessage.ICEBERG_REQUEST_TYPES }, "every request this device was asked is answered") - } - } - - @Test - fun `nothing of a member's goes out before they join, and joining is the only approval`() = runBlocking { - val all = group() - val proposed = IcebergRitualManager.proposeCeremony(all[0].db, all[0].room, all[0].publicKey, all[0].privateKey, 2, chain) - pump(all, GroupLightningEvents.CEREMONY) - val other = all[1] - assertEquals(IcebergApprovalStep.JOIN, IcebergRitualManager.pendingApproval(other.db, other.ceremony(proposed.id)!!)) - assertTrue(outbox(other, GroupLightningEvents.CEREMONY).isEmpty(), "a member who has not joined has published nothing") - - // Three of four join: commitments go out, and nothing more, while one is missing. - all.drop(1).dropLast(1).forEach { IcebergRitualManager.approve(it.db, it.room, proposed.id, IcebergApprovalStep.JOIN, it.privateKey) } - pump(all, GroupLightningEvents.CEREMONY) - assertEquals(setOf(GroupLightningEvents.DKG_ROUND_1), outbox(other, GroupLightningEvents.CEREMONY).map { it.kind }.toSet(), "joining publishes commitments and nothing more") - - // The last joins, and the ceremony runs to its key with nobody asked anything else. - IcebergRitualManager.approve(all[3].db, all[3].room, proposed.id, IcebergApprovalStep.JOIN, all[3].privateKey) - pump(all, GroupLightningEvents.CEREMONY) - all.forEach { d -> - val session = d.ceremony(proposed.id)!! - assertEquals(IcebergRitualStage.COMPLETE, session.stage, "device ${d.index}: ${session.failureReason}") - val asked = d.db.chatMessageDao().getChatMessagesByChatRoomId(roomId).map { it.chatMessage.messageType } - assertTrue(ChatMessage.TYPE_ICEBERG_APPROVAL_NEEDED_REVEAL !in asked && ChatMessage.TYPE_ICEBERG_APPROVAL_NEEDED_CONFIRM !in asked) - } - } - - /** - * A ceremony a member never joins is abandoned by the first device past its deadline, naming them, - * and the failure that device sends ends it on every other. Then the room can open another. - */ - @Test - fun `a ceremony past its deadline is abandoned, naming who had not taken part`() = runBlocking { - val all = group() - val proposed = IcebergRitualManager.proposeCeremony(all[0].db, all[0].room, all[0].publicKey, all[0].privateKey, 2, chain) - pump(all, GroupLightningEvents.CEREMONY) - all.drop(1).dropLast(1).forEach { IcebergRitualManager.approve(it.db, it.room, proposed.id, IcebergApprovalStep.JOIN, it.privateKey) } - pump(all, GroupLightningEvents.CEREMONY) - - val deadline = IcebergRitualManager.deadlineOf(all[1].ceremony(proposed.id)!!) - IcebergRitualManager.abandonOverdue(all[1].db, all[1].publicKey, now = deadline - 1.seconds) - assertEquals(IcebergRitualStage.COLLECTING_COMMITMENTS, all[1].ceremony(proposed.id)!!.stage, "not before its deadline") - - IcebergRitualManager.abandonOverdue(all[1].db, all[1].publicKey, now = deadline) - val name = ChatMessage.memberName(all[1].db, all[3].publicKey) - val expected = "@$name didn't take their part within 24 hours of it being proposed." - assertEquals(expected, all[1].ceremony(proposed.id)!!.failureReason) - - pump(all, GroupLightningEvents.CEREMONY) - all.forEach { d -> - val session = d.ceremony(proposed.id)!! - assertEquals(IcebergRitualStage.FAILED, session.stage, "device ${d.index}") - assertEquals(expected, session.failureReason, "device ${d.index} keeps the sentence it was sent") - } - val again = IcebergRitualManager.proposeCeremony(all[0].db, all[0].room, all[0].publicKey, all[0].privateKey, 2, chain) - assertTrue(again.id != proposed.id, "the room is free for a new ceremony") - } - - @Test - fun `any participant can abandon a ceremony, and it ends for everyone`() = runBlocking { - val all = group() - val proposed = IcebergRitualManager.proposeCeremony(all[0].db, all[0].room, all[0].publicKey, all[0].privateKey, 2, chain) - pump(all, GroupLightningEvents.CEREMONY) - - assertTrue(IcebergRitualManager.abandon(all[2].db, all[2].room, proposed.id)) - assertTrue(!IcebergRitualManager.abandon(all[2].db, all[2].room, proposed.id), "a ceremony is abandoned once") - pump(all, GroupLightningEvents.CEREMONY) - val expected = "@${ChatMessage.memberName(all[2].db, all[2].publicKey)} abandoned it." - all.forEach { d -> - val session = d.ceremony(proposed.id)!! - assertEquals(IcebergRitualStage.FAILED, session.stage, "device ${d.index}") - assertEquals(expected, session.failureReason) - assertNull(session.root, "the random root goes with it") - } - } - - /** A proposal read after its deadline -- by a device reading the room again, say -- is not filed. */ - @Test - fun `a proposal past its deadline is not filed`() = runBlocking { - val all = group() - val tags = members.drop(1).map { arrayOf("p", it) } + listOf( - arrayOf("iceberg_session", Random.nextBytes(32).toHex()), arrayOf("threshold", "2"), arrayOf("onchain_dkg", onchainCeremonyId), - ) - val createdAt = (Clock.System.now() - IcebergRitualManager.DEADLINE - 1.seconds).epochSeconds - val event = Event(EventHasher.hashId(pubKey = members[0], createdAt = createdAt, kind = GroupLightningEvents.CEREMONY_PROPOSAL, tags = tags.toTypedArray(), content = ""), members[0], createdAt, GroupLightningEvents.CEREMONY_PROPOSAL, tags.toTypedArray(), "", "") - IcebergRitualManager.processCeremonyPayload(all[1].db, all[1].room, event, all[1].publicKey, all[1].privateKey) - assertTrue(all[1].db.icebergKeySessionDao().getSessionsForChatRoom(roomId).isEmpty()) - } - - @Test - fun `a contribution travels only as ciphertext`() = runBlocking { - val all = group() - val proposed = runCeremony(all) - val reveal = outbox(all[1], setOf(GroupLightningEvents.DKG_ROUND_2)).single() - val shareHex = all[1].ceremony(proposed.id)!!.share!! - // No seed a member holds appears in what it sent: only ciphertext addressed to each other member. - (0 until (shareHex.length - 8) / 64).map { shareHex.substring(8 + 64 * it, 72 + 64 * it) }.forEach { seed -> - assertTrue(seed !in reveal.content) - } - members.filter { it != all[1].publicKey }.forEach { assertTrue(it in reveal.content, "a ciphertext for each other member") } - } - - @Test - fun `messages delivered twice, or before the proposal, change nothing`() = runBlocking { - val all = group() - val proposed = runCeremony(all) - val before = all.map { it.ceremony(proposed.id) } - // Deliver everything to everyone again. - all.forEach { it.received.clear() } - pump(all, GroupLightningEvents.CEREMONY) - assertEquals(before, all.map { it.ceremony(proposed.id) }) - - // A fifth reading of the room by a device that hears round one before the proposal: it files - // the early messages and replays them once the proposal arrives. - val late = device(3) - val proposal = outbox(all[0], setOf(GroupLightningEvents.CEREMONY_PROPOSAL)).single() - val early = all.flatMap { outbox(it, setOf(GroupLightningEvents.DKG_ROUND_1)) } - early.forEach { late.db.marmotInnerEventDao().upsert(it) } - early.forEach { IcebergRitualManager.processCeremonyPayload(late.db, late.room, it.asEvent(), late.publicKey, late.privateKey) } - assertNull(late.ceremony(proposed.id), "nothing is filed before the proposal") - late.db.marmotInnerEventDao().upsert(proposal) - IcebergRitualManager.processCeremonyPayload(late.db, late.room, proposal.asEvent(), late.publicKey, late.privateKey) - assertEquals(n, late.db.icebergKeySessionDao().countMessagesByKind(proposed.id, GroupLightningEvents.DKG_ROUND_1), "the early commitments were replayed") - } - - @Test - fun `a proposal naming people who do not hold the onchain key is dropped`() = runBlocking { - val all = group() - val outsider = KeyPair().pubKey.toHexKey() - val tags = (members.drop(1).dropLast(1) + outsider).map { arrayOf("p", it) } + listOf( - arrayOf("iceberg_session", Random.nextBytes(32).toHex()), arrayOf("threshold", "2"), arrayOf("onchain_dkg", onchainCeremonyId), - ) - val createdAt = 1_700_000_000L - val event = Event(EventHasher.hashId(pubKey = members[0], createdAt = createdAt, kind = GroupLightningEvents.CEREMONY_PROPOSAL, tags = tags.toTypedArray(), content = ""), members[0], createdAt, GroupLightningEvents.CEREMONY_PROPOSAL, tags.toTypedArray(), "", "") - IcebergRitualManager.processCeremonyPayload(all[1].db, all[1].room, event, all[1].publicKey, all[1].privateKey) - assertTrue(all[1].db.icebergKeySessionDao().getSessionsForChatRoom(roomId).isEmpty()) - } - - @Test - fun `an undeployable threshold is refused at both ends`() = runBlocking { - val all = group() - val refused = runCatching { IcebergRitualManager.proposeCeremony(all[0].db, all[0].room, all[0].publicKey, all[0].privateKey, 3, chain) } - assertTrue(refused.isFailure, "3-of-4 cannot be expressed") - val tags = members.drop(1).map { arrayOf("p", it) } + listOf( - arrayOf("iceberg_session", Random.nextBytes(32).toHex()), arrayOf("threshold", "3"), arrayOf("onchain_dkg", onchainCeremonyId), - ) - val event = Event(EventHasher.hashId(pubKey = members[0], createdAt = 1L, kind = GroupLightningEvents.CEREMONY_PROPOSAL, tags = tags.toTypedArray(), content = ""), members[0], 1L, GroupLightningEvents.CEREMONY_PROPOSAL, tags.toTypedArray(), "", "") - IcebergRitualManager.processCeremonyPayload(all[1].db, all[1].room, event, all[1].publicKey, all[1].privateKey) - assertTrue(all[1].db.icebergKeySessionDao().getSessionsForChatRoom(roomId).isEmpty()) - } - - @Test - fun `there is no ceremony without an onchain wallet`() = runBlocking { - val lone = (0 until n).map { device(it) } - val refused = runCatching { IcebergRitualManager.proposeCeremony(lone[0].db, lone[0].room, lone[0].publicKey, lone[0].privateKey, 2, chain) } - assertTrue(refused.isFailure) - assertTrue(refused.exceptionOrNull()!!.message!!.contains("onchain wallet")) - } - - /** Opening a ceremony is agreeing to be in it, so its opener is never asked to join it. */ - @Test - fun `the member who opened a ceremony is not asked to join it`() = runBlocking { - val all = group() - val proposed = IcebergRitualManager.proposeCeremony(all[0].db, all[0].room, all[0].publicKey, all[0].privateKey, 2, chain) - pump(all, GroupLightningEvents.CEREMONY) - - fun joinRequests(d: Device) = runBlocking { - d.db.chatMessageDao().getChatMessagesByChatRoomId(roomId).map { it.chatMessage } - .filter { it.messageType == ChatMessage.TYPE_ICEBERG_APPROVAL_NEEDED_JOIN && it.dkgSessionId == proposed.id } - } - assertTrue(joinRequests(all[0]).isEmpty(), "the opener has nothing to approve") - all.drop(1).forEach { assertEquals(1, joinRequests(it).size, "device ${it.index} is asked once") } - } - - /** - * A fault is said as a sentence naming the member at fault -- not their index in an order of - * keys nobody sees, and not an exception's message -- and that sentence is what the other - * devices are sent and keep. docs/group-lightning-transcript.md, Phase 3. - */ - @Test - fun `an abandoned ceremony says why in a sentence, naming the member`() = runBlocking { - val all = group() - val proposed = IcebergRitualManager.proposeCeremony(all[0].db, all[0].room, all[0].publicKey, all[0].privateKey, 2, chain) - pump(all, GroupLightningEvents.CEREMONY) - val session = all[1].ceremony(proposed.id)!! - val accused = session.participants()[1] - val name = ChatMessage.memberName(all[1].db, accused) - - val reason = IcebergRitualManager.describe(all[1].db, session, IcebergDkg.Fault.BadReveal(2)) - assertEquals("@$name sent a contribution that does not match what they committed to.", reason) - assertEquals("Something went wrong on this device.", IcebergRitualManager.describe(all[1].db, session, IllegalStateException("index 7 out of bounds"))) - - // Device 1 stops the ceremony with that reason; device 2 hears it. - val tags = arrayOf(arrayOf("iceberg_session", proposed.id)) - val createdAt = 1_700_000_000L - val failure = Event( - EventHasher.hashId(pubKey = all[1].publicKey, createdAt = createdAt, kind = GroupLightningEvents.CEREMONY_FAILURE, tags = tags, content = reason), - all[1].publicKey, createdAt, GroupLightningEvents.CEREMONY_FAILURE, tags, reason, "", - ) - IcebergRitualManager.processCeremonyPayload(all[2].db, all[2].room, failure, all[2].publicKey, all[2].privateKey) - - val failed = all[2].ceremony(proposed.id)!! - assertEquals(IcebergRitualStage.FAILED, failed.stage) - assertEquals(reason, failed.failureReason, "the sender's sentence, with no key prefix in front of it") - val line = all[2].db.chatMessageDao().getChatMessagesByChatRoomId(roomId).map { it.chatMessage } - .single { it.messageType == ChatMessage.TYPE_ICEBERG_FAILED } - assertEquals(all[1].publicKey, line.senderPublicKey, "the line names who stopped it") - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/SubgroupManagerJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/SubgroupManagerJvmTest.kt index 0ad440ba..f6cd1a01 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/SubgroupManagerJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/SubgroupManagerJvmTest.kt @@ -1,8 +1,5 @@ package mobi.giza.compose.managers -import mobi.giza.compose.nostr.subgroup.SubgroupParentage -import mobi.giza.compose.nostr.frost.GroupKeyStateEvent -import mobi.giza.compose.nostr.subgroup.tags.WalletPolicyTag import mobi.giza.compose.nostr.subgroup.WalletPolicyReading import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy import androidx.room3.Room @@ -41,7 +38,6 @@ import mobi.giza.compose.database.model.DkgSession import mobi.giza.compose.database.model.types.DkgRitualStage import mobi.giza.compose.database.model.GroupKeyState import mobi.giza.compose.database.model.GroupSignedEvent -import mobi.giza.compose.nostr.subgroup.tags.GuardianTag import mobi.giza.compose.database.model.NostrEvent import mobi.giza.compose.database.model.Participant import mobi.giza.compose.database.model.Profile @@ -525,72 +521,7 @@ class SubgroupManagerJvmTest { } } - @Test - fun `a certificate grants the child the parent's guardian key`(): Unit = runBlocking { - val parentRoom = parentWith(listOf(alice, bob)) - - val proposed = proposedCertificate(parentRoom) - - // A parent with no parent of its own grants one key: its own, one step on. - assertEquals( - GuardianDerivation.grant(parentMaterial.thresholdPublicKey.value.toHex(), parentRoomId, emptyList(), childRoomId), - SubgroupBirthCertificateEvent.parseGuardians(proposed.tags) - ) - assertNull(SubgroupManager.refuseCertificate(db, parentRoomId, parentMaterial.thresholdPublicKey.value.toHex(), proposed)) - } - - @Test - fun `a subgroup passes on the keys its own parent granted it, one step further`(): Unit = runBlocking { - val parentRoom = parentWith(listOf(alice, bob)) - // The parent is itself a subgroup of a grandparent, whose key reached it - // through the parent's own certificate. - val grandparentKey = strangerMaterial.thresholdPublicKey.value.toHex() - val grandparentRoomId = roomOf(strangerMaterial) - val inherited = GuardianDerivation.grant(grandparentKey, grandparentRoomId, emptyList(), parentRoomId) - fileParentage(inherited) - - val granted = assertNotNull(SubgroupBirthCertificateEvent.parseGuardians(proposedCertificate(parentRoom).tags)) - - assertEquals(listOf(parentRoomId, grandparentRoomId), granted.map { it.chatRoomId }) - assertEquals(inherited[0].grantedTo(childRoomId), granted[1]) - assertEquals( - GuardianDerivation.root(grandparentKey).extendedPublicKey - .derivePublicKey(GuardianDerivation.childIndex(parentRoomId)) - .derivePublicKey(GuardianDerivation.childIndex(childRoomId)) - .publicKey, - granted[1].publicKey, - "the grandparent's key in the grandchild is R / i(parent) / i(child)" - ) - } - - @Test - fun `a signer refuses guardian keys the group does not grant`(): Unit = runBlocking { - val parentRoom = parentWith(listOf(alice, bob)) - val parentKey = parentMaterial.thresholdPublicKey.value.toHex() - val proposed = proposedCertificate(parentRoom) - val granted = assertNotNull(SubgroupBirthCertificateEvent.parseGuardians(proposed.tags)) - val coordinators = GuardianDerivation.grant(strangerMaterial.thresholdPublicKey.value.toHex(), parentRoomId, emptyList(), childRoomId) - - fun withGuardians(guardians: List) = certificate( - tags = proposed.tags.filterNot { it[0] == GuardianTag.TAG_NAME }.toTypedArray() + - guardians.map(GuardianTag::assemble) - ) - - val refusals = mapOf( - "a key of the coordinator's own" to withGuardians(coordinators), - "an extra ancestor" to withGuardians(granted + coordinators), - "the key not stepped for this child" to withGuardians(listOf(granted[0].copy(publicKey = GuardianDerivation.root(parentKey).publicKey))), - "a shorter delay" to withGuardians(listOf(granted[0].copy(delay = 1))), - ) - refusals.forEach { (name, certificate) -> - assertNotNull(SubgroupManager.refuseCertificate(db, parentRoomId, parentKey, certificate), name) - } - - // An older proposer's certificate carries none, and grants nothing. - assertNull(SubgroupManager.refuseCertificate(db, parentRoomId, parentKey, certificate())) - } - - // ---- the wallet policy: docs/subgroup-wallet-policy.md ----------------- + // ---- no wallet: docs/giza-wallet-removal.md, Phase 1 ------------------ /** The parent made a subgroup of a grandparent, under [policy]. */ private suspend fun parentIs(policy: SubgroupWalletPolicy?) { @@ -606,223 +537,41 @@ class SubgroupManagerJvmTest { private fun ceremonyUnder(policy: SubgroupWalletPolicy?) = completedChildCeremony().copy(walletPolicy = policy?.tagValue) - private val guardedReading = WalletPolicyReading.Decided(SubgroupWalletPolicy.GUARDED) - private val unguardedReading = WalletPolicyReading.Decided(SubgroupWalletPolicy.UNGUARDED) + private fun walletTagsOf(certificate: Event) = + certificate.tags.filter { it.firstOrNull() == "wallet" || it.firstOrNull() == "guardian" || it.firstOrNull() == "guardian_delay" } @Test - fun `a guarded ceremony is certified guarded, with the grant`(): Unit = runBlocking { - val proposed = proposedCertificate(parentWith(listOf(alice, bob)), ceremonyUnder(SubgroupWalletPolicy.GUARDED)) - - assertEquals(guardedReading, SubgroupBirthCertificateEvent.parseWalletPolicy(proposed.tags)) - assertEquals(1, SubgroupBirthCertificateEvent.parseGuardians(proposed.tags)?.size) - } - - @Test - fun `an unguarded ceremony is certified unguarded, with no keys`(): Unit = runBlocking { - val proposed = proposedCertificate(parentWith(listOf(alice, bob)), ceremonyUnder(SubgroupWalletPolicy.UNGUARDED)) - - assertEquals(unguardedReading, SubgroupBirthCertificateEvent.parseWalletPolicy(proposed.tags)) - assertEquals(emptyList(), SubgroupBirthCertificateEvent.parseGuardians(proposed.tags)) - } - - @Test - fun `an older build's ceremony is certified as it always was`(): Unit = runBlocking { + fun `a certificate carries no wallet policy and no guardian keys`(): Unit = runBlocking { val proposed = proposedCertificate(parentWith(listOf(alice, bob)), ceremonyUnder(null)) - - assertEquals(WalletPolicyReading.Undecided, SubgroupBirthCertificateEvent.parseWalletPolicy(proposed.tags)) - assertEquals(1, SubgroupBirthCertificateEvent.parseGuardians(proposed.tags)?.size) + assertEquals(emptyList(), walletTagsOf(proposed)) } @Test - fun `under a guarded parent an older build's ceremony is certified guarded`(): Unit = runBlocking { - val parentRoom = parentWith(listOf(alice, bob)) - parentIs(SubgroupWalletPolicy.GUARDED) - - val proposed = proposedCertificate(parentRoom, ceremonyUnder(null)) - - assertEquals(guardedReading, SubgroupBirthCertificateEvent.parseWalletPolicy(proposed.tags)) - assertEquals(2, SubgroupBirthCertificateEvent.parseGuardians(proposed.tags)?.size, "its own key and the grandparent's") + fun `a ceremony an older build proposed as guarded is still certified plain`(): Unit = runBlocking { + val proposed = proposedCertificate(parentWith(listOf(alice, bob)), ceremonyUnder(SubgroupWalletPolicy.GUARDED)) + assertEquals(emptyList(), walletTagsOf(proposed)) } @Test - fun `under a guarded parent an unguarded ceremony is refused, and nothing is proposed`(): Unit = runBlocking { - val parentRoom = parentWith(listOf(alice, bob)) - parentIs(SubgroupWalletPolicy.GUARDED) - - val refused = runCatching { proposedCertificate(parentRoom, ceremonyUnder(SubgroupWalletPolicy.UNGUARDED)) } - - assertTrue(refused.exceptionOrNull() is IllegalStateException) - assertTrue("Start the subgroup again" in refused.exceptionOrNull()?.message.orEmpty(), "the remedy is in the reason") - assertTrue(db.frostSigningSessionDao().getSessionsForChatRoom(parentRoomId).isEmpty()) - } - - @Test - fun `under an unguarded parent an unguarded ceremony is certified`(): Unit = runBlocking { + fun `under an unguarded parent a subgroup is certified plain`(): Unit = runBlocking { val parentRoom = parentWith(listOf(alice, bob)) parentIs(SubgroupWalletPolicy.UNGUARDED) - val proposed = proposedCertificate(parentRoom, ceremonyUnder(SubgroupWalletPolicy.UNGUARDED)) - - assertEquals(unguardedReading, SubgroupBirthCertificateEvent.parseWalletPolicy(proposed.tags)) + val proposed = proposedCertificate(parentRoom, ceremonyUnder(null)) + assertEquals(emptyList(), walletTagsOf(proposed)) } + /** A Bennu signer refuses an unguarded child of a guarded parent, so it is never proposed (W5). */ @Test - fun `a signer refuses a certificate whose policy does not read or contradicts its keys`(): Unit = runBlocking { - val parentRoom = parentWith(listOf(alice, bob)) - val parentKey = parentMaterial.thresholdPublicKey.value.toHex() - val guarded = proposedCertificate(parentRoom, ceremonyUnder(SubgroupWalletPolicy.GUARDED)) - val withoutPolicy = guarded.tags.filterNot { it[0] == WalletPolicyTag.TAG_NAME }.toTypedArray() - - val refusals = mapOf( - "unguarded with keys" to certificate(tags = withoutPolicy + WalletPolicyTag.assemble(SubgroupWalletPolicy.UNGUARDED)), - "guarded with no keys" to certificate( - tags = withoutPolicy.filterNot { it[0] == GuardianTag.TAG_NAME }.toTypedArray() + - WalletPolicyTag.assemble(SubgroupWalletPolicy.GUARDED) - ), - "a policy that does not read" to certificate(tags = withoutPolicy + arrayOf(WalletPolicyTag.TAG_NAME, "maybe")), - ) - refusals.forEach { (name, certificate) -> - assertNotNull(SubgroupManager.refuseCertificate(db, parentRoomId, parentKey, certificate), name) - } - - assertNull(SubgroupManager.refuseCertificate(db, parentRoomId, parentKey, guarded)) - assertNull( - SubgroupManager.refuseCertificate(db, parentRoomId, parentKey, proposedCertificate(parentRoom, ceremonyUnder(SubgroupWalletPolicy.UNGUARDED))), - "an unguarded certificate of a root group's child is signable", - ) - } - - @Test - fun `an older proposer's certificate is still signable under any parent but a guarded one`(): Unit = runBlocking { - val parentKey = parentMaterial.thresholdPublicKey.value.toHex() - parentWith(listOf(alice, bob)) - - // No keys and no policy: what a build before guardians proposed. - assertNull(SubgroupManager.refuseCertificate(db, parentRoomId, parentKey, certificate()), "under a root group") - - listOf(SubgroupWalletPolicy.UNGUARDED, null).forEach { policy -> - parentIs(policy) - assertNull(SubgroupManager.refuseCertificate(db, parentRoomId, parentKey, certificate()), "under a parent decided $policy") - } - } - - /** - * D4, at the signers. The picker stops a coordinator choosing this; the - * signers are what stop one who skipped the picker. The undecided case is the - * one a reviewer will want to loosen -- an older proposer's certificate, keys - * and all -- and is here to fail if anybody does: an undecided child is - * offered the plain wallet a guarded parent's subgroups may not have. - */ - @Test - fun `a guarded group's signers refuse anything but a guarded certificate`(): Unit = runBlocking { - val parentRoom = parentWith(listOf(alice, bob)) - val parentKey = parentMaterial.thresholdPublicKey.value.toHex() - // Proposed while this device still read the parent as a root group -- the - // coordinator's device that saw no parent certificate. - val unguarded = proposedCertificate(parentRoom, ceremonyUnder(SubgroupWalletPolicy.UNGUARDED)) - val undecided = proposedCertificate(parentRoom, ceremonyUnder(null)) - - // The signer's own device holds the parent's certificate. - parentIs(SubgroupWalletPolicy.GUARDED) - - assertEquals( - "would make an unguarded subgroup of a guarded group", - SubgroupManager.refuseCertificate(db, parentRoomId, parentKey, unguarded), - ) - assertEquals( - "would make an unguarded subgroup of a guarded group", - SubgroupManager.refuseCertificate(db, parentRoomId, parentKey, undecided), - ) - assertNull( - SubgroupManager.refuseCertificate( - db, parentRoomId, parentKey, - proposedCertificate(parentRoom, ceremonyUnder(SubgroupWalletPolicy.GUARDED).copy(id = "second-child-ceremony", thresholdPublicKey = siblingMaterial.thresholdPublicKey.value.toHex())), - ), - "a guarded one, with the parent's keys passed on, is signable", - ) - } - - /** A child key state carrying [certificate], unsigned -- the refusal reads its tags and nothing else. */ - private fun keyStateCarrying(certificate: Event) = Event( - id = "e".repeat(64), - pubKey = childRoomId, - createdAt = 1_700_000_000, - kind = GroupKeyStateEvent.KIND, - tags = GroupKeyStateEvent.assembleTags( - chatRoomId = childRoomId, - dkgSessionId = "child-ceremony", - path = path, - parent = SubgroupParentage(parentRoomId, certificate), - ), - content = "", - sig = "", - ) - - @Test - fun `a child signer refuses a certificate under a policy its ceremony did not announce`(): Unit = runBlocking { - val parentRoom = parentWith(listOf(alice, bob)) - val unguarded = proposedCertificate(parentRoom, ceremonyUnder(SubgroupWalletPolicy.UNGUARDED)) - val guarded = proposedCertificate(parentRoom, ceremonyUnder(SubgroupWalletPolicy.GUARDED)) - val undecided = proposedCertificate(parentRoom, ceremonyUnder(null)) - - // The admins joined a guarded subgroup. - val ceremony = ceremonyUnder(SubgroupWalletPolicy.GUARDED) - assertNotNull(SubgroupManager.refuseKeyState(ceremony, keyStateCarrying(unguarded))) - assertNotNull(SubgroupManager.refuseKeyState(ceremony, keyStateCarrying(undecided)), "undecided is not what they agreed to either") - assertNull(SubgroupManager.refuseKeyState(ceremony, keyStateCarrying(guarded))) - - // An older build's ceremony announced nothing, and has nothing to hold a certificate to. - assertNull(SubgroupManager.refuseKeyState(ceremonyUnder(null), keyStateCarrying(unguarded))) - } - - // ---- the guardian delay: docs/guardian-delay.md, Phase 6 -------------- - - @Test - fun `a guarded ceremony's delay is the parent's own leaf's in the certificate`(): Unit = runBlocking { + fun `under a guarded parent nothing is proposed`(): Unit = runBlocking { val parentRoom = parentWith(listOf(alice, bob)) parentIs(SubgroupWalletPolicy.GUARDED) - val proposed = proposedCertificate(parentRoom, ceremonyUnder(SubgroupWalletPolicy.GUARDED).copy(guardianDelay = 4_320)) + val refused = runCatching { proposedCertificate(parentRoom, ceremonyUnder(null)) } - val granted = assertNotNull(SubgroupBirthCertificateEvent.parseGuardians(proposed.tags)) - assertEquals(listOf(4_320L, GuardianDerivation.DEFAULT_DELAY), granted.map { it.delay }, "the grandparent's keeps its own") - assertNull(SubgroupManager.refuseCertificate(db, parentRoomId, parentMaterial.thresholdPublicKey.value.toHex(), proposed)) - } - - @Test - fun `an older guarded ceremony is certified at the default delay`(): Unit = runBlocking { - val proposed = proposedCertificate(parentWith(listOf(alice, bob)), ceremonyUnder(SubgroupWalletPolicy.GUARDED)) - - assertEquals(GuardianDerivation.DEFAULT_DELAY, SubgroupBirthCertificateEvent.parseGuardians(proposed.tags)?.single()?.delay) - } - - @Test - fun `a signer refuses a certificate that changes an ancestor's delay`(): Unit = runBlocking { - val parentRoom = parentWith(listOf(alice, bob)) - val parentKey = parentMaterial.thresholdPublicKey.value.toHex() - parentIs(SubgroupWalletPolicy.GUARDED) - val proposed = proposedCertificate(parentRoom, ceremonyUnder(SubgroupWalletPolicy.GUARDED).copy(guardianDelay = 144)) - val granted = assertNotNull(SubgroupBirthCertificateEvent.parseGuardians(proposed.tags)) - - // The grandparent's leaf brought closer, which was never this group's to do. - val shortened = certificate( - tags = proposed.tags.filterNot { it[0] == GuardianTag.TAG_NAME }.toTypedArray() + - listOf(granted[0], granted[1].copy(delay = 6)).map(GuardianTag::assemble) - ) - assertEquals("grants guardian keys this group does not", SubgroupManager.refuseCertificate(db, parentRoomId, parentKey, shortened)) - } - - @Test - fun `a child signer refuses a certificate under a delay its ceremony did not announce`(): Unit = runBlocking { - val parentRoom = parentWith(listOf(alice, bob)) - val atDefault = proposedCertificate(parentRoom, ceremonyUnder(SubgroupWalletPolicy.GUARDED)) - val atMonth = proposedCertificate(parentRoom, ceremonyUnder(SubgroupWalletPolicy.GUARDED).copy(guardianDelay = 4_320)) - - val ceremony = ceremonyUnder(SubgroupWalletPolicy.GUARDED).copy(guardianDelay = 4_320) - assertNotNull(SubgroupManager.refuseKeyState(ceremony, keyStateCarrying(atDefault))) - assertNull(SubgroupManager.refuseKeyState(ceremony, keyStateCarrying(atMonth))) - // A ceremony that announced none holds the certificate to no delay. - assertNull(SubgroupManager.refuseKeyState(ceremonyUnder(SubgroupWalletPolicy.GUARDED), keyStateCarrying(atMonth))) + assertTrue(refused.exceptionOrNull() is IllegalStateException) + assertTrue("guarded wallets" in refused.exceptionOrNull()?.message.orEmpty(), "the reason says why") + assertTrue(db.frostSigningSessionDao().getSessionsForChatRoom(parentRoomId).isEmpty()) } // ---- fixtures ---------------------------------------------------------- diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/WalletDeclineJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/WalletDeclineJvmTest.kt new file mode 100644 index 00000000..b5675e9e --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/WalletDeclineJvmTest.kt @@ -0,0 +1,243 @@ +package mobi.giza.compose.managers + +import androidx.room3.Room +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.crypto.frost.Frost +import fr.acinq.bitcoin.crypto.frost.KeyMaterial +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.DkgParticipantMessage +import mobi.giza.compose.database.model.DkgSession +import mobi.giza.compose.database.model.FrostSigningItem +import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.database.model.types.DkgRitualStage +import mobi.giza.compose.database.model.types.FrostSigningSubject +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.subgroup.SubgroupBirthCertificateEvent + +/** + * Giza declines what is a wallet's to sign, out loud (docs/giza-wallet-removal.md, + * Phase 1). + * + * A Bennu member can put a wallet to a group Giza is in. Giza can no longer check one, + * and a device that signs what it cannot check is a rubber stamp, so it declines. It + * used to drop a proposal it refused without a word, which the group cannot tell from a + * phone in a pocket; a decline is counted, so the members who can sign know where they + * stand. + * + * Each proposal here is a real one, made on Alice's device -- which stands in for a + * Bennu member's, since proposing checks nothing -- and handed to Bob's through the + * inbound path, because the event ids are rebuilt there and a fabricated proposal would + * be dropped before the check under test ran. + */ +class WalletDeclineJvmTest { + private val participants = 3 + private val threshold = 2 + + private val keyMaterial: KeyMaterial = Frost.trustedDealerKeygen( + thresholdSecretKey = PrivateKey( + ByteVector32("1c0ffee0000000000000000000000000000000000000000000000000000000a1") + ), + nParticipants = participants, + threshold = threshold + ) + + private val thresholdPublicKey = keyMaterial.thresholdPublicKey.value.toHex() + private val roomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) + private val ceremonyId = "ceremony".padEnd(64, '0') + private val members = listOf("a", "b", "c").map { it.repeat(64) } + private val hostKeys = listOf("2a", "2b", "2c").map { it.padEnd(66, '0') } + + private val alice = members[0] + private val bob = members[1] + + private lateinit var db: GizaDatabase + private lateinit var room: LocalChatRoom + + @AfterTest + fun closeDatabase() { + if (::db.isInitialized) db.close() + } + + private suspend fun openDevice(owner: HexKey) { + if (::db.isInitialized) db.close() + db = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + val index = members.indexOf(owner) + val nostrEventId = "e$owner".take(64) + db.nostrEventDao().upsert( + NostrEvent(id = nostrEventId, pubKey = owner, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128)) + ) + db.profileDao().upsert(Profile(publicKey = owner, nostrEventId = nostrEventId)) + + val chatRoom = ChatRoom( + id = roomId, + userPublicKey = owner, + subject = "#Ekklesia", + description = SharedKeyDerivation.describe("Admins of the group."), + mlsGroupState = null + ) + db.chatRoomDao().upsert(chatRoom) + + db.dkgSessionDao().upsert( + DkgSession( + id = ceremonyId, + chatRoomId = roomId, + coordinatorPublicKey = alice, + userPublicKey = owner, + threshold = threshold, + participantCount = participants, + stage = DkgRitualStage.COMPLETE, + hostPublicKey = hostKeys[index], + round1Random = "1".repeat(64), + round2AuxRandom = "2".repeat(64), + thresholdPublicKey = thresholdPublicKey, + secretShare = keyMaterial.secretShares[index].value.toHex(), + publicShares = keyMaterial.publicShares.joinToString(",") { it.value.toHex() } + ) + ) + members.forEachIndexed { i, member -> + db.dkgSessionDao().upsert( + DkgParticipantMessage(sessionId = ceremonyId, participantPublicKey = member, kind = DkgRitualEvents.HOST_KEY, payload = hostKeys[i]) + ) + } + + room = LocalChatRoom(chatRoom = chatRoom) + } + + /** What this device has queued for the group, of one kind. The room is NIP-17 here. */ + private suspend fun queued(kind: Kind) = db.giftWrapPayloadDao() + .getByChatRoomAndKinds(roomId, listOf(kind)) + .filter { it.publicKey == room.chatRoom.userPublicKey } + + /** + * Alice's device proposes one event of [kind]; Bob's device receives the proposal. + * Returns the session id, with [db] and [room] left on Bob's device. + */ + private suspend fun proposalReachesBob(kind: Kind, tags: Array> = arrayOf(), content: String = "{}"): String { + openDevice(alice) + val session = FrostSigningManager.proposeSigning( + database = db, + localChatRoom = room, + userPublicKey = alice, + kind = kind, + tags = tags, + content = content + ) + val proposal = queued(FrostSigningEvents.PROPOSAL).single().content + + openDevice(bob) + FrostSigningManager.processSigningPayload( + database = db, + localChatRoom = room, + innerEvent = Event( + id = "proposal".padEnd(64, '0'), + pubKey = alice, + createdAt = Clock.System.now().epochSeconds, + kind = FrostSigningEvents.PROPOSAL, + tags = FrostSigningEvents.assembleTags(sessionId = session.id, dkgSessionId = ceremonyId), + content = proposal, + sig = "" + ), + userPublicKey = bob + ) + return session.id + } + + private suspend fun assertDeclinedAsWallet(sessionId: String) { + val session = db.frostSigningSessionDao().getSessionById(sessionId) + assertNotNull(session, "declined, not dropped: the session is filed so the decline can go out") + assertNotNull(session.signDeclinedAt) + assertNull(session.signApprovedAt) + assertFalse(FrostSigningManager.isAwaitingApproval(session, db.frostSigningSessionDao().getItems(sessionId)), "and nobody is asked") + + val declines = queued(FrostSigningEvents.DECLINE) + assertEquals(1, declines.size, "the decline is published, so the group counts it") + assertEquals(WalletRefusal.REASON, declines.single().content) + assertEquals(emptyList(), queued(FrostSigningEvents.NONCE), "and nothing of the signature goes out") + } + + @Test + fun `a group wallet statement is declined on arrival, out loud`() = runBlocking { + assertDeclinedAsWallet(proposalReachesBob(30331)) + } + + @Test + fun `a member wallet certificate is declined on arrival`() = runBlocking { + assertDeclinedAsWallet(proposalReachesBob(30334)) + } + + @Test + fun `a Lightning wallet authorisation is declined on arrival`() = runBlocking { + assertDeclinedAsWallet(proposalReachesBob(30363)) + } + + @Test + fun `a birth certificate that makes a guarded subgroup is declined`() = runBlocking { + assertDeclinedAsWallet( + proposalReachesBob(SubgroupBirthCertificateEvent.KIND, tags = arrayOf(arrayOf("wallet", "guarded"))) + ) + } + + @Test + fun `a birth certificate that grants guardian keys is declined`() = runBlocking { + assertDeclinedAsWallet( + proposalReachesBob(SubgroupBirthCertificateEvent.KIND, tags = arrayOf(arrayOf("guardian", "02".padEnd(66, '0'), "12"))) + ) + } + + @Test + fun `an ordinary event is still put to the member`() = runBlocking { + val sessionId = proposalReachesBob(kind = 1, content = "Something for the group to say") + + val session = db.frostSigningSessionDao().getSessionById(sessionId) + assertNotNull(session) + assertNull(session.signDeclinedAt) + assertTrue(FrostSigningManager.isAwaitingApproval(session, db.frostSigningSessionDao().getItems(sessionId))) + assertEquals(emptyList(), queued(FrostSigningEvents.DECLINE)) + } + + @Test + fun `approving a wallet's session declines it instead`() = runBlocking { + openDevice(bob) + val session = FrostSigningSession( + id = "s".repeat(64), + chatRoomId = roomId, + coordinatorPublicKey = alice, + userPublicKey = bob, + dkgSessionId = ceremonyId, + threshold = threshold, + participantCount = participants, + signerId = members.indexOf(bob), + derivationPath = SharedKeyDerivation.formatPath(SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH), + subject = FrostSigningSubject.TRANSACTION, + ) + db.frostSigningSessionDao().upsert(session) + db.frostSigningSessionDao().upsertItems( + listOf(FrostSigningItem(sessionId = session.id, itemIndex = 0, unsignedEventJson = "{}", eventId = "e".repeat(64), nonceRandom = "f".repeat(64))) + ) + + FrostSigningManager.approve(db, room, session.id) + + assertDeclinedAsWallet(session.id) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailWithoutWalletsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailWithoutWalletsJvmTest.kt new file mode 100644 index 00000000..7218f2b7 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailWithoutWalletsJvmTest.kt @@ -0,0 +1,111 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.ComposeUiTest +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.repository.ChatRepository +import mobi.giza.compose.repository.NostrRepository +import mobi.giza.compose.ui.composable.GroupSignedWorkFixtures.activeUserPublicKey +import mobi.giza.compose.ui.composable.GroupSignedWorkFixtures.chatRoomId +import mobi.giza.compose.ui.composable.widgets.ProvideSnackbarHost +import mobi.giza.compose.ui.theme.GizaTheme +import mobi.giza.compose.ui.view.state.ChatRoomDetailUIState +import kotlin.test.Test + +/** + * The group's screen with no wallet on it (docs/giza-wallet-removal.md, Phase 1). + * + * It had a row for the group's on-chain wallet, one for its Lightning wallet and a + * section of the wallets it guards for its members. Giza takes part in none of them, + * so none is offered -- and a group whose own certificate makes its subgroups guarded + * says why it cannot make one, rather than offering a ceremony every Bennu signer + * would refuse (W5). + */ +@OptIn(ExperimentalTestApi::class) +class ChatRoomDetailWithoutWalletsJvmTest { + + @Test + fun `a group with a key offers no wallet`() = render(state()) { + onNodeWithText("onchain wallet", substring = true).assertDoesNotExist() + onNodeWithText("Lightning wallet").assertDoesNotExist() + onNodeWithText("Members' guarded wallets").assertDoesNotExist() + onNodeWithText("Ask this group to guard", substring = true).assertDoesNotExist() + + // The rest of the screen is there, so the rows' absence is an absence + // rather than a screen that failed to draw. + onNodeWithText("Subgroups").assertIsDisplayed() + } + + @Test + fun `the group's screen has no nostr profile, relays, posts or paste`() = render(state()) { + onNodeWithText("Nostr profile").assertDoesNotExist() + onNodeWithText("Relays").assertDoesNotExist() + onNodeWithText("Posts").assertDoesNotExist() + onNodeWithText("Propose event").assertDoesNotExist() + onNodeWithText("Subgroups").assertIsDisplayed() + } + + @Test + fun `a group that can sign offers a subgroup`() = render(state(canAddSubgroup = true)) { + onNodeWithText("Add subgroup").assertIsDisplayed() + onNodeWithText("must keep guarded wallets", substring = true).assertDoesNotExist() + } + + @Test + fun `a guarded group says why it cannot add a subgroup, and offers none`() = render( + state(subgroupsNeedAWallet = true) + ) { + onNodeWithText("Add subgroup").assertDoesNotExist() + onNodeWithText("This group's subgroups must keep guarded wallets", substring = true).assertIsDisplayed() + } + + private fun state( + canAddSubgroup: Boolean = false, + subgroupsNeedAWallet: Boolean = false, + ) = ChatRoomDetailUIState.Loaded( + localChatRoom = GroupSignedWorkFixtures.localChatRoom("state"), + groupKeyState = GroupSignedWorkFixtures.groupKeyState, + canAddSubgroup = canAddSubgroup, + subgroupsNeedAWallet = subgroupsNeedAWallet, + ) + + /** + * The screen at a phone's width and a window tall enough to compose the whole + * of it, since a `LazyColumn` does not lay out what it would not show. + * + * The state is passed in rather than loaded, so the NO_OP repositories are + * never asked for anything: `initiateChatRoomDetail` only runs for a screen + * that arrives in [ChatRoomDetailUIState.Loading]. + */ + private fun render( + uiState: ChatRoomDetailUIState, + assertions: ComposeUiTest.() -> Unit + ) = runDesktopComposeUiTest(width = 400, height = 4000) { + setContent { + GizaTheme { + ProvideSnackbarHost { + Box(modifier = Modifier.fillMaxSize()) { + ChatRoomDetailScreen( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + relayHint = null, + initialChatRoomDetailUIState = uiState, + nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + onNavigateToRoute = {}, + onPopBackToRoute = {}, + onNavigateBack = {}, + ) + } + } + } + } + + assertions() + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt deleted file mode 100644 index dc903cc3..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt +++ /dev/null @@ -1,188 +0,0 @@ -package mobi.giza.compose.ui.composable - -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.ui.Modifier -import androidx.compose.ui.test.ComposeUiTest -import androidx.compose.ui.test.ExperimentalTestApi -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.getBoundsInRoot -import androidx.compose.ui.test.hasText -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import androidx.compose.ui.test.runDesktopComposeUiTest -import mobi.giza.compose.database.model.GroupSignedEvent -import mobi.giza.compose.managers.GroupWalletDerivation -import mobi.giza.compose.nostr.wallet.GroupWallet -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import mobi.giza.compose.repository.ChatRepository -import mobi.giza.compose.repository.NostrRepository -import mobi.giza.compose.ui.composable.GroupSignedWorkFixtures.activeUserPublicKey -import mobi.giza.compose.ui.composable.GroupSignedWorkFixtures.chatRoomId -import mobi.giza.compose.ui.composable.navigation.routes.GroupLightningWalletRoute -import mobi.giza.compose.ui.composable.navigation.routes.GroupWalletRoute -import mobi.giza.compose.ui.composable.navigation.routes.Route -import mobi.giza.compose.ui.composable.widgets.ProvideSnackbarHost -import mobi.giza.compose.ui.theme.GizaTheme -import mobi.giza.compose.ui.view.state.ChatRoomDetailUIState -import mobi.giza.compose.wallet.GroupLightningRollout -import mobi.giza.compose.wallet.GroupWalletRollout -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.secp256k1.Hex -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertNull -import kotlin.test.assertTrue -import kotlin.time.Instant - -/** - * The row on the group's screen that stands for its signed work, and what it - * opens. - * - * The group's nostr profile, relay lists and posts had rows here, and a paste - * for proposing any of them; they are gone, and the wallet is what is left. - */ -@OptIn(ExperimentalTestApi::class) -class GroupSignedWorkRowsJvmTest { - - @Test - fun `the wallet row sits under the signing key and above the subgroups`() = render(state()) { - if (!GroupWalletRollout.ENABLED) return@render - - val signingKey = onNodeWithText("Signing key").getBoundsInRoot().top - val wallet = onNodeWithText(WALLET_ROW).getBoundsInRoot().top - val subgroups = onNodeWithText("Subgroups").getBoundsInRoot().top - - assertTrue(signingKey < wallet, "the wallet row climbed above the signing key row") - assertTrue(wallet < subgroups, "the wallet row fell below the group's subgroups") - } - - @Test - fun `the wallet row opens the wallet`() { - if (!GroupWalletRollout.ENABLED) return - - var opened: Route? = null - - render(state(), onNavigateToRoute = { opened = it }) { - onNode(hasText(WALLET_ROW) and hasText("Not opened yet")).assertIsDisplayed() - onNodeWithText(WALLET_ROW).performClick() - } - - assertEquals(GroupWalletRoute(activeUserPublicKey, chatRoomId, relayHint = null), opened) - } - - @Test - fun `the Lightning wallet's row opens it, and there is no second onchain wallet`() { - if (!GroupWalletRollout.ENABLED || !GroupLightningRollout.ENABLED) return - var opened: Route? = null - - render(state(groupWallet = onchainWallet), onNavigateToRoute = { opened = it }) { - onNode(hasText("Lightning wallet") and hasText(GroupWalletStatementEvent.chainName(GroupLightningRollout.NETWORK))).assertIsDisplayed() - onNodeWithText("Group onchain wallet on", substring = true).assertDoesNotExist() - onNodeWithText("Lightning wallet").performClick() - } - - assertEquals(GroupLightningWalletRoute(activeUserPublicKey, chatRoomId), opened) - } - - /** It closes to the onchain wallet, so until there is one it says so and opens nothing. */ - @Test - fun `the Lightning wallet's row waits for an onchain wallet`() { - if (!GroupWalletRollout.ENABLED || !GroupLightningRollout.ENABLED) return - var opened: Route? = null - - render(state(), onNavigateToRoute = { opened = it }) { - onNode(hasText("Lightning wallet") and hasText("Lightning is only available once the group has an onchain wallet.")).assertIsDisplayed() - onNodeWithText("Lightning wallet").performClick() - } - - assertNull(opened) - } - - @Test - fun `the group's screen has no nostr profile, relays, posts or paste`() = render(state()) { - onNodeWithText("Nostr profile").assertDoesNotExist() - onNodeWithText("Relays").assertDoesNotExist() - onNodeWithText("Posts").assertDoesNotExist() - onNodeWithText("Propose event").assertDoesNotExist() - - // The rest of the screen is there, so the rows' absence is an absence - // rather than a screen that failed to draw. - onNodeWithText("Subgroups").assertIsDisplayed() - } - - @Test - fun `a NIP-17 room has no key to sign with and so no wallet row`() = render( - state(mlsGroupState = null) - ) { - onNodeWithText(WALLET_ROW).assertDoesNotExist() - onNodeWithText("Subgroups").assertIsDisplayed() - } - - /** The wallet row is named for its room: the fixture's subject. */ - private val WALLET_ROW = "Translation room onchain wallet" - - private fun state(mlsGroupState: String? = "state", groupWallet: GroupWallet? = null) = ChatRoomDetailUIState.Loaded( - localChatRoom = GroupSignedWorkFixtures.localChatRoom(mlsGroupState), - groupKeyState = GroupSignedWorkFixtures.groupKeyState, - groupWallet = groupWallet, - ) - - /** An onchain wallet on the Lightning wallet's network; only its presence matters to these rows. */ - private val onchainWallet: GroupWallet by lazy { - val account = GroupWalletDerivation.account( - PrivateKey(ByteVector32(Hex.decode("1c0ffee".padStart(64, '0')))).publicKey().toString(), - GroupLightningRollout.NETWORK, - ) - GroupWallet( - signedEvent = GroupSignedEvent( - id = "e".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = GroupWalletStatementEvent.KIND, - tags = GroupWalletStatementEvent.template(account).tags, - content = account.xpub, - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000), - ), - account = account, - ) - } - - /** - * The screen at a phone's width and a window tall enough to compose the whole - * of it, since a `LazyColumn` does not lay out what it would not show. - * - * The state is passed in rather than loaded, so the NO_OP repositories are - * never asked for anything: `initiateChatRoomDetail` only runs for a screen - * that arrives in [ChatRoomDetailUIState.Loading]. - */ - private fun render( - uiState: ChatRoomDetailUIState, - onNavigateToRoute: (Route) -> Unit = {}, - assertions: ComposeUiTest.() -> Unit - ) = runDesktopComposeUiTest(width = 400, height = 4000) { - setContent { - GizaTheme { - ProvideSnackbarHost { - Box(modifier = Modifier.fillMaxSize()) { - ChatRoomDetailScreen( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = null, - initialChatRoomDetailUIState = uiState, - nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - onNavigateToRoute = onNavigateToRoute, - onPopBackToRoute = {}, - onNavigateBack = {}, - ) - } - } - } - } - - assertions() - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ProfilePreviewScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ProfilePreviewScreenJvmTest.kt index 79505b0a..8bc490b6 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ProfilePreviewScreenJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ProfilePreviewScreenJvmTest.kt @@ -21,11 +21,6 @@ import mobi.giza.compose.database.model.Profile import mobi.giza.compose.database.model.SynchronizeNostrEventRequest import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.repository.ChatRepository -import mobi.giza.compose.repository.MemberWalletRepository -import mobi.giza.compose.managers.LineageExample -import mobi.giza.compose.managers.MemberWalletManager -import androidx.compose.ui.test.onAllNodesWithText -import androidx.compose.ui.test.onNodeWithContentDescription import mobi.giza.compose.extensions.hexToNpubHrp import mobi.giza.compose.repository.NostrRepository import mobi.giza.compose.ui.composable.navigation.routes.ChatRoomMessagingRoute @@ -199,7 +194,6 @@ class ProfilePreviewScreenJvmTest { canSign: Boolean = true, nostrRepository: NostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, chatRepository: ChatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - memberWalletRepository: MemberWalletRepository = MemberWalletRepository.NO_OP, onStartChat: (Route) -> Unit = {}, assertions: ComposeUiTest.() -> Unit, ) = runDesktopComposeUiTest(width = 400, height = 1200) { @@ -216,7 +210,6 @@ class ProfilePreviewScreenJvmTest { chatRepository = chatRepository, onStartChat = onStartChat, onNavigateBack = {}, - memberWalletRepository = memberWalletRepository, ) } } @@ -226,29 +219,4 @@ class ProfilePreviewScreenJvmTest { assertions() } - - // --- the wallets this profile's groups guard: docs/member-wallet-guarding-group.md, D7 --- - - @OptIn(ExperimentalTestApi::class) - @Test - fun `a wallet held by two groups here is one entry, guarded by the group that signed it`() { - val held = listOf( - MemberWalletManager.GuardedHere(LineageExample.heldBy(LineageExample.r, LineageExample.savings, LineageExample.savingsGuardians, label = "Savings", ownerPublicKey = profilePublicKey, branchName = "#P"), holderName = "#R", canSpend = false), - MemberWalletManager.GuardedHere(LineageExample.heldBy(LineageExample.p, LineageExample.savings, LineageExample.savingsGuardians, label = "Savings", ownerPublicKey = profilePublicKey, guardianName = "#M", branchName = "#M"), holderName = "#P", canSpend = true), - ) - val repository = object : MemberWalletRepository by MemberWalletRepository.NO_OP { - override suspend fun guardedByGroupsHere(ownerPublicKey: String): List = held - } - - render(ProfilePreviewUIState.Loaded(profile = alice, readiness = Readiness.CanStartChat), memberWalletRepository = repository) { - waitUntil(timeoutMillis = 5_000) { onAllNodesWithText("Savings").fetchSemanticsNodes().isNotEmpty() } - onNodeWithText("Wallets your groups guard").assertIsDisplayed() - assertEquals(1, onAllNodesWithText("Savings").fetchSemanticsNodes().size, "one entry for the wallet") - onNodeWithText("Guarded by #M").assertIsDisplayed() - onNodeWithText("#P: after 12 blocks").assertIsDisplayed() - onNodeWithText("#R: after 12 blocks").assertIsDisplayed() - onNodeWithContentDescription("Spend from Savings as #P").assertIsDisplayed() - onNodeWithContentDescription("Spend from Savings as #R").assertDoesNotExist() - } - } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/LightningCeremonyAwaitingYouJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/LightningCeremonyAwaitingYouJvmTest.kt deleted file mode 100644 index 2f46213c..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/LightningCeremonyAwaitingYouJvmTest.kt +++ /dev/null @@ -1,171 +0,0 @@ -package mobi.giza.compose.ui.view.model - -import mobi.giza.compose.database.model.ChatRoom -import mobi.giza.compose.database.model.FrostSigningItem -import mobi.giza.compose.database.model.FrostSigningSession -import mobi.giza.compose.database.model.IcebergKeySession -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.database.model.intermdiate.LocalFrostSigningSession -import mobi.giza.compose.database.model.types.FrostSigningStage -import mobi.giza.compose.database.model.types.IcebergApprovalStep -import mobi.giza.compose.database.model.types.IcebergRitualStage -import mobi.giza.compose.nostr.lightning.GroupLightningWalletStatementEvent -import mobi.giza.compose.repository.ChatRepository -import mobi.giza.compose.repository.DkgRepository -import mobi.giza.compose.repository.FrostSigningRepository -import mobi.giza.compose.repository.GroupLightningRepository -import mobi.giza.compose.repository.NostrRepository -import mobi.giza.compose.ui.view.state.ChatMessageListUIState -import mobi.giza.compose.wallet.GroupLightningRollout -import fr.acinq.bitcoin.Chain -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.Flow -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.withTimeoutOrNull -import kotlin.test.AfterTest -import kotlin.test.BeforeTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertTrue - -/** - * The Lightning wallet's key ceremony, in the notice above the composer - * (docs/group-lightning-transcript.md, Phase 2): asked of the member at each of its - * gates, and of the member who opened it once the key is made and no wallet uses it. - */ -@OptIn(ExperimentalCoroutinesApi::class) -class LightningCeremonyAwaitingYouJvmTest { - @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 them = "b".repeat(64) - private val localChatRoom = LocalChatRoom(chatRoom = ChatRoom(id = chatRoomId, userPublicKey = me, subject = "Treasury", description = null, mlsGroupState = "state")) - - private fun ceremony( - stage: IcebergRitualStage, - coordinator: String = them, - id: String = "ab".repeat(32), - ) = IcebergKeySession( - id = id, chatRoomId = chatRoomId, coordinatorPublicKey = coordinator, userPublicKey = me, threshold = 2, participantCount = 4, - participantPublicKeys = IcebergKeySession.formatParticipants(listOf(me, them, "c".repeat(64), "d".repeat(64))), - onchainDkgSessionId = "x", stage = stage, - share = if (stage == IcebergRitualStage.COMPLETE) "00" else null, - ) - - private class Lightning( - val ceremonies: List, - val gate: IcebergApprovalStep? = null, - val unused: IcebergKeySession? = null, - ) : GroupLightningRepository by GroupLightningRepository.NO_OP_GROUP_LIGHTNING_REPOSITORY { - override fun observeCeremonies(chatRoomId: String): Flow> = flowOf(ceremonies) - override suspend fun pendingApproval(session: IcebergKeySession): IcebergApprovalStep? = - gate.takeIf { session.stage != IcebergRitualStage.COMPLETE } - override suspend fun unusedKey(chatRoomId: String, chain: Chain): IcebergKeySession? = unused - } - - private class Signings(val sessions: List) : - FrostSigningRepository by FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY { - override fun observeSessionsForChatRoom(chatRoomId: String): Flow> = flowOf(sessions) - } - - /** A signing session proposing a wallet statement over [ceremonyId]. */ - private fun statementBeingSigned(ceremonyId: String): LocalFrostSigningSession { - val statement = GroupLightningWalletStatementEvent.Statement( - GroupLightningRollout.NETWORK, 0, 0, "02" + "11".repeat(32), ceremonyId, 2, - listOf(me, them), "02" + "33".repeat(32), "02" + "44".repeat(32), GroupLightningWalletStatementEvent.Policy.DEFAULT, - ) - val template = GroupLightningWalletStatementEvent.template(statement, createdAt = 1) - val tags = template.tags.joinToString(",", "[", "]") { tag -> tag.joinToString(",", "[", "]") { "\"$it\"" } } - return LocalFrostSigningSession( - session = FrostSigningSession( - id = "s1", chatRoomId = chatRoomId, coordinatorPublicKey = them, userPublicKey = me, dkgSessionId = "x", - threshold = 2, participantCount = 4, signerId = 1, stage = FrostSigningStage.COLLECTING_NONCES, - ), - unorderedItems = listOf( - FrostSigningItem( - sessionId = "s1", itemIndex = 0, eventId = "e".repeat(64), nonceRandom = "00".repeat(32), - unsignedEventJson = """{"id":"${"e".repeat(64)}","pubkey":"$chatRoomId","created_at":1,""" + - """"kind":${GroupLightningWalletStatementEvent.KIND},"tags":$tags,"content":"","sig":""}""", - ), - ), - ) - } - - private fun awaiting( - lightning: GroupLightningRepository, - signings: List = emptyList(), - expectNone: Boolean = false, - ): List { - val viewModel = ChatMessageListViewModel( - initialChatMessageListUIState = ChatMessageListUIState.Loading, - localChatRoom = localChatRoom, - nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = Signings(signings), - dkgRepository = DkgRepository.NO_OP_DKG_REPOSITORY, - lightningRepository = lightning, - ) - viewModel.initiate() - return runBlocking { - // Settles on the IO dispatcher. Nothing to wait for when the answer is none, - // so a short wait that finds nothing is the pass. - withTimeoutOrNull(if (expectNone) 500 else 5_000) { - while (viewModel.ceremoniesAwaitingYou.isEmpty()) delay(10) - } - viewModel.ceremoniesAwaitingYou - } - } - - @Test - fun `each of the ceremony's gates is asked of the member above the composer`() { - IcebergApprovalStep.entries.forEach { step -> - val running = ceremony(IcebergRitualStage.COLLECTING_REVEALS) - val asked = awaiting(Lightning(listOf(running), gate = step)).single() - - assertEquals(running.id, asked.sessionId) - assertEquals(ChatMessageListViewModel.Ask.LightningKeyStep(step), asked.ask) - assertEquals(false, asked.isSubgroup) - } - } - - @Test - fun `a ceremony waiting on others, or abandoned, asks nothing`() { - assertTrue(awaiting(Lightning(listOf(ceremony(IcebergRitualStage.COLLECTING_COMMITMENTS))), expectNone = true).isEmpty()) - assertTrue(awaiting(Lightning(listOf(ceremony(IcebergRitualStage.FAILED)), gate = IcebergApprovalStep.JOIN), expectNone = true).isEmpty()) - } - - @Test - fun `a finished key no wallet uses is asked of whoever opened the ceremony`() { - val mine = ceremony(IcebergRitualStage.COMPLETE, coordinator = me) - val asked = awaiting(Lightning(listOf(mine), unused = mine)).single() - - assertEquals(mine.id, asked.sessionId) - assertEquals(ChatMessageListViewModel.Ask.LightningWalletOpening, asked.ask) - } - - @Test - fun `and of nobody else`() { - val theirs = ceremony(IcebergRitualStage.COMPLETE, coordinator = them) - assertTrue(awaiting(Lightning(listOf(theirs), unused = theirs), expectNone = true).isEmpty()) - } - - @Test - fun `nor once a wallet statement for it is being signed`() { - val mine = ceremony(IcebergRitualStage.COMPLETE, coordinator = me) - assertTrue( - awaiting(Lightning(listOf(mine), unused = mine), signings = listOf(statementBeingSigned(mine.id)), expectNone = true).isEmpty(), - "the key has been put to the group; asking again would start a second proposal", - ) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/SelectSubgroupAdminsViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/SelectSubgroupAdminsViewModelJvmTest.kt index f1ba09e5..59e497e0 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/SelectSubgroupAdminsViewModelJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/SelectSubgroupAdminsViewModelJvmTest.kt @@ -1,11 +1,5 @@ package mobi.giza.compose.ui.view.model -import kotlin.test.assertTrue -import kotlin.test.assertFalse -import kotlin.test.assertNull -import mobi.giza.compose.managers.GuardianDerivation -import mobi.giza.compose.nostr.subgroup.WalletPolicyReading -import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy import com.vitorpamplona.quartz.nip01Core.core.HexKey import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -82,8 +76,6 @@ class SelectSubgroupAdminsViewModelJvmTest { private fun failed( parentChatRoomId: String? = this.parentChatRoomId, - walletPolicy: SubgroupWalletPolicy? = null, - guardianDelay: Long? = null, ) = DkgSession( id = failedId, chatRoomId = this.parentChatRoomId, @@ -98,23 +90,12 @@ class SelectSubgroupAdminsViewModelJvmTest { round1Random = "aa".repeat(32), round2AuxRandom = "bb".repeat(32), parentChatRoomId = parentChatRoomId, - walletPolicy = walletPolicy?.tagValue, - guardianDelay = guardianDelay, ) - private fun chatRepository( - parentPolicy: WalletPolicyReading? = null, - parentGuardians: List? = emptyList(), - ) = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { + private fun chatRepository() = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { override suspend fun getChatRoomByIdentifier(id: HexKey): LocalChatRoom? = parent.takeIf { id == parentChatRoomId } - override suspend fun walletPolicyOf(chatRoomId: String): WalletPolicyReading? = - parentPolicy.takeIf { chatRoomId == parentChatRoomId } - - override suspend fun guardiansOf(chatRoomId: String): List? = - parentGuardians.takeIf { chatRoomId == parentChatRoomId } - // Never answers, so the lookup is still out while the test looks: what is // under test is what the form starts from, not who has a key package. override suspend fun observeMarmotKeyPackageForPublicKey( @@ -182,164 +163,4 @@ class SelectSubgroupAdminsViewModelJvmTest { assertEquals("", viewModel.name.value) assertEquals(emptySet(), viewModel.selectedPublicKeys.toSet()) } - - private val guarded = WalletPolicyReading.Decided(SubgroupWalletPolicy.GUARDED) - - /** A guarded parent's view model, loaded, with a name typed so a refusal is about the policy. */ - private suspend fun underGuardedParent(session: DkgSession? = null) = - viewModel(session, chatRepository = chatRepository(parentPolicy = guarded)).apply { - initiate() - awaitLoaded() - setName("Tapscript") - } - - @Test - fun `a subgroup is guarded unless the coordinator says otherwise`(): Unit = runBlocking { - val viewModel = viewModel(null, retrying = null) - viewModel.initiate() - viewModel.awaitLoaded() - - assertEquals(SubgroupWalletPolicy.GUARDED, viewModel.walletPolicy.value) - - viewModel.setWalletPolicy(SubgroupWalletPolicy.UNGUARDED) - assertEquals(SubgroupWalletPolicy.UNGUARDED, viewModel.walletPolicy.value, "a root group may make either") - } - - @Test - fun `a guarded parent's subgroup is guarded, and stays so`(): Unit = runBlocking { - val viewModel = underGuardedParent() - - assertEquals(SubgroupWalletPolicy.GUARDED, viewModel.walletPolicy.value) - viewModel.setWalletPolicy(SubgroupWalletPolicy.UNGUARDED) - assertEquals(SubgroupWalletPolicy.GUARDED, viewModel.walletPolicy.value, "D4: the choice is not the coordinator's") - assertNull(viewModel.refusal()?.takeIf { "guarded" in it }) - } - - @Test - fun `a guarded parent refuses an unguarded subgroup that got past the screen`(): Unit = runBlocking { - val viewModel = underGuardedParent() - - // The state forced, as a bug or a skipped screen would leave it. - viewModel.walletPolicy.value = SubgroupWalletPolicy.UNGUARDED - - assertEquals("This group is guarded, so its subgroups are too.", viewModel.refusal()) - } - - @Test - fun `a retry of an unguarded ceremony under a guarded parent comes back guarded`(): Unit = runBlocking { - val viewModel = underGuardedParent(failed(walletPolicy = SubgroupWalletPolicy.UNGUARDED)) - - assertEquals("Tapscript", viewModel.name.value) - assertEquals(SubgroupWalletPolicy.GUARDED, viewModel.walletPolicy.value) - } - - @Test - fun `a retry starts from the failed ceremony's wallet policy`(): Unit = runBlocking { - val viewModel = viewModel(failed(walletPolicy = SubgroupWalletPolicy.UNGUARDED)) - viewModel.initiate() - viewModel.awaitLoaded() - - assertEquals(SubgroupWalletPolicy.UNGUARDED, viewModel.walletPolicy.value) - } - - @Test - fun `an unguarded or undecided parent may make either`(): Unit = runBlocking { - listOf(WalletPolicyReading.Decided(SubgroupWalletPolicy.UNGUARDED), WalletPolicyReading.Undecided).forEach { policy -> - val viewModel = viewModel(null, retrying = null, chatRepository = chatRepository(parentPolicy = policy)) - viewModel.initiate() - viewModel.awaitLoaded() - - viewModel.setWalletPolicy(SubgroupWalletPolicy.UNGUARDED) - assertEquals(SubgroupWalletPolicy.UNGUARDED, viewModel.walletPolicy.value, "under $policy") - viewModel.setWalletPolicy(SubgroupWalletPolicy.GUARDED) - assertEquals(SubgroupWalletPolicy.GUARDED, viewModel.walletPolicy.value, "under $policy") - } - } - - @Test - fun `a parent whose guardian keys do not read cannot make a guarded subgroup`(): Unit = runBlocking { - val viewModel = viewModel(null, retrying = null, chatRepository = chatRepository(parentGuardians = null)) - viewModel.initiate() - viewModel.awaitLoaded() - viewModel.setName("Tapscript") - - assertEquals(SubgroupWalletPolicy.UNGUARDED, viewModel.walletPolicy.value) - viewModel.setWalletPolicy(SubgroupWalletPolicy.GUARDED) - assertEquals(SubgroupWalletPolicy.UNGUARDED, viewModel.walletPolicy.value) - - viewModel.walletPolicy.value = SubgroupWalletPolicy.GUARDED - assertEquals( - "This group's own guardian keys can't be read, so it can't guard a subgroup.", - viewModel.refusal(), - "refused here, not after a ceremony", - ) - } - - // ---- the guardian delay: docs/guardian-delay.md, Phase 5 --------------- - - private suspend fun loadedWithName(session: DkgSession? = null) = viewModel(session).apply { - initiate() - awaitLoaded() - setName("Tapscript") - } - - @Test - fun `a guarded subgroup's delay starts at the default`(): Unit = runBlocking { - val viewModel = loadedWithName() - - assertEquals(12L, viewModel.guardianDelay()) - assertFalse(viewModel.isCustomDelay.value) - assertNull(viewModel.guardianDelayProblem()) - } - - @Test - fun `a preset and a typed delay are what refusal judges`(): Unit = runBlocking { - val viewModel = loadedWithName() - - viewModel.setGuardianDelay(4_320) - assertEquals(4_320L, viewModel.guardianDelay()) - assertNull(viewModel.refusal()?.takeIf { "delay" in it }) - - viewModel.useCustomDelay() - viewModel.setGuardianDelayInput("2,016") - assertEquals(2_016L, viewModel.guardianDelay(), "grouping is dropped as it is typed") - assertTrue(viewModel.isCustomDelay.value) - } - - @Test - fun `a delay below six or above 65535 is refused with its reason`(): Unit = runBlocking { - val viewModel = loadedWithName() - viewModel.useCustomDelay() - - viewModel.setGuardianDelayInput("5") - assertEquals("A delay is at least 6 blocks.", viewModel.refusal()) - - viewModel.setGuardianDelayInput("65536") - assertEquals(65_536L, viewModel.guardianDelay(), "kept as typed, so the field can say what is wrong with it") - assertEquals("A delay is at most 65,535 blocks.", viewModel.refusal()) - - viewModel.setGuardianDelayInput("") - assertEquals("Give the delay in blocks.", viewModel.refusal()) - } - - @Test - fun `an unguarded subgroup is not held to a delay`(): Unit = runBlocking { - val viewModel = loadedWithName() - viewModel.useCustomDelay() - viewModel.setGuardianDelayInput("5") - viewModel.setWalletPolicy(SubgroupWalletPolicy.UNGUARDED) - - assertNull(viewModel.refusal()?.takeIf { "delay" in it }) - } - - @Test - fun `a retry starts from the failed ceremony's delay`(): Unit = runBlocking { - val preset = loadedWithName(failed(walletPolicy = SubgroupWalletPolicy.GUARDED, guardianDelay = 1_008)) - assertEquals(1_008L, preset.guardianDelay()) - assertFalse(preset.isCustomDelay.value, "a preset comes back as the preset") - - val typed = loadedWithName(failed(walletPolicy = SubgroupWalletPolicy.GUARDED, guardianDelay = 2_016)) - assertEquals(2_016L, typed.guardianDelay()) - assertTrue(typed.isCustomDelay.value, "anything else comes back in the field") - } } diff --git a/docs/giza-wallet-removal.md b/docs/giza-wallet-removal.md index 92b224d8..3a52cde7 100644 --- a/docs/giza-wallet-removal.md +++ b/docs/giza-wallet-removal.md @@ -19,7 +19,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 | Paths below are under +| 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 `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. @@ -35,6 +36,15 @@ Read these first: explain why a profile's key is not the wallet's, and how close the code already is to treating it that way. +Where the build chose differently from the phases as written: + +| what the plan said | what it turned out to be | +|---|---| +| 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` | +| 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 | area | where | main lines |