diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index d3e3bf33..4b089534 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -563,7 +563,6 @@ While the wallet is new, a spend on mainnet can send at most %1$s sats. - Guarded wallet The subgroup's wallet will be guarded: this group can spend any coin in it once it has waited %1$s, and each group above it after the delay it chose. The subgroup's wallet will not be guarded: only the subgroup can spend from it. The group above this one decided this group's wallet is guarded. Each group above it can spend any coin in it that has waited as long as its own delay, without this group agreeing: @@ -610,53 +609,6 @@ - New guarded wallet - A group - Choose a group to guard it - None of your groups guards members' wallets yet. A group's signers can turn it on from the group's page. - A wallet only you can spend from, guarded by %1$s - %1$s can take any coin in it that has waited %2$s, without asking you. - %1$s can take any coin in it that has waited %2$s, and the group above it any coin that has waited %3$s, without asking you. - %1$s can take any coin in it that has waited %2$s, and each of the %3$d groups above it after the delay it chose, the shortest %4$s, without asking you. - Members of the groups that guard it will see its balance, and that it's yours. - If you lose this device, those groups can still move your coins for you. - Label (optional) - Ask %1$s - Asked %1$s to guard a wallet. - Couldn't ask the group to guard a wallet. - This profile can only look, so it can't sign a request. - Only a group with a shared key can guard a wallet. - This device doesn't know what this group signs with yet, so it can't work out the group's leaves. - Ask the group for its key - Asked. A member who holds the group's key will answer when their device next reads the room. - This group's guardian keys can't be read by this version of the app. - Guarded wallets for members aren't offered on this network yet. - %1$s would refuse this request: it was asked before the group said it guards members' wallets. Asking again makes a new one. - %1$s has changed its delay since you asked. Asking again makes a new request at the new delay. - %1$s has stopped guarding members' wallets, so this request won't be signed. You can discard it. - %1$s would refuse this request. Asking again makes a new one. - Guards members' wallets - Doesn't guard members' wallets - Stopped guarding new members' wallets - After %1$s - How long before this group can take a coin from a member's wallet - A coin the member moves starts waiting again, so a long delay lets them keep their coins out of reach by moving them. - Wallets already guarded keep the delay they were guarded at. - Members whose app is older than this one can only be guarded at 12 blocks, and don't know this group can close. - Ask the group - Stop guarding new wallets - Stop guarding new members' wallets? - Wallets already guarded stay guarded, and this group can still take their coins after their delay. - Stop - Couldn't ask the group. - This group doesn't guard members' wallets. - This group has stopped guarding members' wallets. - You have no guarded wallets. - Waiting for someone in %1$s to put it to the group - %1$s is signing - %1$s didn't sign. Ask again, or discard it. - Key on another device - You're no longer in %1$s. It still guards this wallet. Guarded by %1$s Guarded by %1$s, below %2$s this group @@ -676,36 +628,10 @@ Spend from %1$s's guarded wallet “%2$s” Fund %1$s's wallet guarded by %2$s Spend from %1$s's wallet guarded by %2$s - Discard - Discard this wallet? - Its key is forgotten. No address of it was ever offered, so nothing can have been paid to it. - Export key - Export this wallet's key? - Whoever holds these descriptors can spend every coin in this wallet. Keep them where only you can reach them. - Show key - Receive descriptor - Change descriptor - Copied. - Copy Finding your coins… - %1$s took %2$s sats through its guardian leaf, in %3$s. - Taken by guardians - This wallet's key is on another of your devices, so it can be watched here but not spent from. - Couldn't ask again. - Couldn't discard the wallet. %1$s sats come back to this wallet as change. This wallet has nothing confirmed to spend. This wallet doesn't have that much confirmed. - Send from your guarded wallet - You sign this alone, and it is sent as soon as you press the button. - Sending needs this wallet's key on this device, a group's certificate for it, and a wallet of this profile's own to watch the chain with. - Sign and send - Sent. - Couldn't send. - Your spends - Sent, waiting for the network to report it - In the mempool @%1$s - Members' guarded wallets This device tells the groups above about these on its own when it can. Share now if a group above hasn't heard. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt index a6ba95b2..7d37883b 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt @@ -15,7 +15,6 @@ import mobi.giza.compose.database.model.IcebergParticipantMessage import mobi.giza.compose.database.model.IcebergKeySession import mobi.giza.compose.database.model.GroupTransaction import mobi.giza.compose.database.dao.GroupTransactionDao -import mobi.giza.compose.database.dao.MemberWalletDao import androidx.room3.ColumnTypeConverters import androidx.room3.AutoMigration import androidx.room3.ConstructedBy @@ -452,7 +451,6 @@ abstract class GizaDatabase: RoomDatabase() { abstract fun groupTransactionDao(): GroupTransactionDao - abstract fun memberWalletDao(): MemberWalletDao abstract fun connectionDao(): ConnectionDao diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MemberWalletDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MemberWalletDao.kt deleted file mode 100644 index d6e3c721..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MemberWalletDao.kt +++ /dev/null @@ -1,46 +0,0 @@ -package mobi.giza.compose.database.dao - -import androidx.room3.Dao -import androidx.room3.Query -import androidx.room3.Upsert -import mobi.giza.compose.database.model.MemberWallet -import mobi.giza.compose.database.model.MemberWalletSpend -import kotlinx.coroutines.flow.Flow - -@Dao -abstract class MemberWalletDao { - @Query("SELECT * FROM MemberWallet WHERE ownerPublicKey = :ownerPublicKey ORDER BY createdAt DESC") - abstract suspend fun getByOwner(ownerPublicKey: String): List - - @Query("SELECT * FROM MemberWallet WHERE ownerPublicKey = :ownerPublicKey ORDER BY createdAt DESC") - abstract fun observeByOwner(ownerPublicKey: String): Flow> - - @Query("SELECT * FROM MemberWallet WHERE walletId = :walletId") - abstract suspend fun getById(walletId: String): MemberWallet? - - @Query("SELECT * FROM MemberWallet WHERE guardingChatRoomId = :chatRoomId ORDER BY createdAt DESC") - abstract suspend fun getByGuardingChatRoomId(chatRoomId: String): List - - @Upsert - abstract suspend fun upsert(wallet: MemberWallet) - - /** - * Deletes a wallet's key. `MemberWalletManager.discard` is the only caller, - * and only for a wallet no group has certified: before then no address was - * ever offered, so no coin can be behind the key. - */ - @Query("DELETE FROM MemberWallet WHERE walletId = :walletId") - abstract suspend fun delete(walletId: String) - - @Query("SELECT * FROM MemberWalletSpend WHERE walletId = :walletId ORDER BY createdAt DESC") - abstract suspend fun getSpends(walletId: String): List - - @Query("SELECT * FROM MemberWalletSpend WHERE walletId = :walletId ORDER BY createdAt DESC") - abstract fun observeSpends(walletId: String): Flow> - - @Query("SELECT * FROM MemberWalletSpend WHERE txid = :txid") - abstract suspend fun getSpend(txid: String): MemberWalletSpend? - - @Upsert - abstract suspend fun upsertSpend(spend: MemberWalletSpend) -} 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 f9773854..9f2e570b 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 @@ -3,8 +3,6 @@ package mobi.giza.compose.database.model import mobi.giza.compose.nostr.RetiredKinds import mobi.giza.compose.text.describe -import mobi.giza.compose.text.BlockDuration -import mobi.giza.compose.nostr.wallet.MemberWalletPolicyEvent import androidx.room3.Entity import androidx.room3.ForeignKey import androidx.room3.Index @@ -17,8 +15,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.nostr.wallet.MemberWalletCertificateEvent -import mobi.giza.compose.nostr.wallet.MemberWalletRequestEvent import mobi.giza.compose.managers.GroupKeyStateManager import mobi.giza.compose.managers.GroupWalletManager import mobi.giza.compose.managers.GuardianManager @@ -1402,75 +1398,6 @@ data class ChatMessage( ) } - // A member asking the group to guard a wallet of theirs. The - // inner event carries the signed request whole; only a request - // that checks out and asks this room gets a line, and it is a - // line and nothing more -- the group decides when a signer puts - // it to the quorum. docs/member-guarded-wallets.md. - MemberWalletRequestEvent.KIND -> { - val request = MemberWalletRequestEvent.carried(event) ?: return null - val reading = MemberWalletRequestEvent.verified(request)?.reading ?: return null - if (!reading.groupChatRoomId.equals(groupId, ignoreCase = true)) return null - - ChatMessage( - giftWrapPayloadId = null, - messageType = TYPE_MEMBER_WALLET_REQUESTED, - marmotGroupEventId = marmotGroupEventId, - marmotInnerEventId = marmotInnerEventId, - senderPublicKey = senderPublicKey, - isUserMessage = isUserMessage, - chatRoomId = groupId, - createdAt = createdAt, - content = "@${memberName(database, reading.memberPublicKey)} asked this group to guard a wallet", - ) - } - - // The group agreeing to guard a member's wallet. Checked whole -- - // the room's signature and the request inside -- because the line - // says the group made a promise about somebody's money. It is - // filed as a `GroupSignedEvent` either way, and every reader - // checks it there again. - MemberWalletCertificateEvent.KIND -> { - val verified = MemberWalletCertificateEvent.verify(event, groupId) ?: return null - - ChatMessage( - giftWrapPayloadId = null, - messageType = TYPE_MEMBER_WALLET_GUARDED, - marmotGroupEventId = marmotGroupEventId, - marmotInnerEventId = marmotInnerEventId, - senderPublicKey = senderPublicKey, - isUserMessage = isUserMessage, - chatRoomId = groupId, - createdAt = createdAt, - content = "This group now guards a wallet for @${memberName(database, verified.memberPublicKey)}", - ) - } - - // The group saying whether it guards its members' wallets, and at - // what delay. Checked as the room's own signature, which is all a - // policy needs; one that does not verify gets no line, and is - // ignored where it is filed too. docs/member-wallet-delay.md. - MemberWalletPolicyEvent.KIND -> { - val policy = MemberWalletPolicyEvent.verify(event, groupId) ?: return null - - ChatMessage( - giftWrapPayloadId = null, - messageType = TYPE_MEMBER_WALLET_POLICY, - marmotGroupEventId = marmotGroupEventId, - marmotInnerEventId = marmotInnerEventId, - senderPublicKey = senderPublicKey, - isUserMessage = isUserMessage, - chatRoomId = groupId, - createdAt = createdAt, - content = when (policy) { - is MemberWalletPolicyEvent.Policy.Open -> - "The group guards members' wallets, after ${BlockDuration.describe(policy.delay)}" - is MemberWalletPolicyEvent.Policy.Closed -> - "The group has stopped guarding new members' wallets" - }, - ) - } - // The group opening a wallet. Checked the whole way -- the room's // signature, and the statement rederiving from the room's own key -- // because a line saying "the group opened a wallet" is a line people diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseMemberWalletRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseMemberWalletRepository.kt deleted file mode 100644 index e2e9f5b1..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseMemberWalletRepository.kt +++ /dev/null @@ -1,153 +0,0 @@ -package mobi.giza.compose.database.repository - -import mobi.giza.compose.nostr.wallet.MemberWalletPolicyEvent -import co.touchlab.kermit.Logger -import mobi.giza.compose.database.GizaDatabase -import mobi.giza.compose.database.model.FrostSigningSession -import mobi.giza.compose.database.model.MemberWallet -import mobi.giza.compose.managers.GuardianManager -import com.vitorpamplona.quartz.nip01Core.core.Event -import mobi.giza.compose.database.model.MemberWalletSpend -import fr.acinq.bitcoin.Transaction -import fr.acinq.bitcoin.psbt.Psbt -import kotlinx.coroutines.flow.Flow -import kotlin.time.Instant -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.identity.Identity -import mobi.giza.compose.managers.MemberWalletManager -import mobi.giza.compose.repository.MemberWalletRepository -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.Chain -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow - -class DatabaseMemberWalletRepository( - private val database: GizaDatabase, - private val activeIdentity: StateFlow = MutableStateFlow(null), -) : MemberWalletRepository { - private val logger = Logger.withTag(TAG) - - override suspend fun groupsOf(ownerPublicKey: HexKey): List = try { - MemberWalletManager.groupsOf(database, ownerPublicKey) - } catch (e: Throwable) { - logger.e("Error reading the groups that could guard a wallet", e) - emptyList() - } - - override suspend fun refusal(chatRoomId: String, chain: Chain): MemberWalletManager.Refusal? = try { - MemberWalletManager.refusal(database, chatRoomId, canSign = activeIdentity.value?.canSign == true, chain = chain) - } catch (e: Throwable) { - logger.e("Error reading whether $chatRoomId can guard a wallet", e) - MemberWalletManager.Refusal.KEY_UNKNOWN - } - - override suspend fun reachOf(chatRoomId: String): Int? = try { - MemberWalletManager.reachOf(database, chatRoomId) - } catch (e: Throwable) { - logger.e("Error reading how far $chatRoomId's guard reaches", e) - null - } - - override suspend fun delaysOf(chatRoomId: String): List? = try { - MemberWalletManager.delaysOf(database, chatRoomId) - } catch (e: Throwable) { - logger.e("Error reading how far $chatRoomId's guard reaches", e) - null - } - - override suspend fun askForGroupKey(chatRoomId: String): Boolean { - val identity = activeIdentity.value ?: return false - return MemberWalletManager.askForGroupKey(database, chatRoomId, identity.nostrPublicKey) - } - - override suspend fun request(chatRoomId: String, chain: Chain, label: String?): MemberWallet { - val key = activeIdentity.value?.nostrPrivateKey ?: throw IllegalStateException("This profile cannot sign") - return MemberWalletManager.request(database, chatRoomId, key, chain, label) - } - - override suspend fun walletsOf(ownerPublicKey: HexKey): List = try { - MemberWalletManager.walletsOf(database, ownerPublicKey) - } catch (e: Throwable) { - // A profile that lists no wallets is wrong and survivable; one that will - // not open because reading them threw is neither. - logger.e("Error reading $ownerPublicKey's guarded wallets", e) - emptyList() - } - - override suspend fun walletOf(ownerPublicKey: HexKey, walletId: String): MemberWalletManager.MemberWalletRow? = try { - MemberWalletManager.walletOf(database, ownerPublicKey, walletId) - } catch (e: Throwable) { - logger.e("Error reading guarded wallet $walletId", e) - null - } - - override suspend fun askAgain(walletId: String): String { - val wallet = database.memberWalletDao().getById(walletId) ?: throw IllegalStateException("No key for $walletId here") - check(wallet.ownerPublicKey == activeIdentity.value?.nostrPublicKey) { "Not this profile's wallet" } - val key = activeIdentity.value?.nostrPrivateKey ?: throw IllegalStateException("This profile cannot sign") - return MemberWalletManager.askAgain(database, wallet, key).walletId - } - - override suspend fun discard(walletId: String) { - val wallet = database.memberWalletDao().getById(walletId) ?: return - check(wallet.ownerPublicKey == activeIdentity.value?.nostrPublicKey) { "Not this profile's wallet" } - MemberWalletManager.discard(database, walletId) - } - - override suspend fun exportKey(walletId: String): Pair? { - val owner = activeIdentity.value?.nostrPublicKey ?: return null - return MemberWalletManager.exportKey(database, owner, walletId) - } - - override suspend fun roomName(chatRoomId: String): String? = - database.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom?.subject?.takeIf { it.isNotBlank() } - - override suspend fun signSpend(walletId: String, psbt: Psbt): Transaction { - val owner = activeIdentity.value?.nostrPublicKey ?: throw IllegalStateException("No profile is active") - return MemberWalletManager.signSpend(database, owner, walletId, psbt) - } - - override suspend fun recordChain(txid: String, confirmations: Int?, broadcastAt: Instant?) = - MemberWalletManager.recordChain(database, txid, confirmations, broadcastAt) - - override fun observeSpends(walletId: String): Flow> = database.memberWalletDao().observeSpends(walletId) - - override suspend fun couldGuard(chatRoomId: String): Boolean = try { - database.chatRoomDao().findChatRoomById(chatRoomId)?.let { MemberWalletManager.couldGuard(database, it) } == true - } catch (e: Throwable) { - logger.e("Error reading whether $chatRoomId could guard a wallet", e) - false - } - - override suspend fun policyOf(chatRoomId: String): MemberWalletPolicyEvent.Policy? = try { - MemberWalletManager.policyFor(database, chatRoomId) - } catch (e: Throwable) { - logger.e("Error reading $chatRoomId's member-wallet policy", e) - null - } - - override suspend fun memberWalletsOf(chatRoomId: String): List = try { - MemberWalletManager.memberWalletsOf(database, chatRoomId) - } catch (e: Throwable) { - logger.e("Error reading the member wallets $chatRoomId guards", e) - emptyList() - } - - override suspend fun putToGroup(chatRoomId: String, request: Event): FrostSigningSession { - val identity = activeIdentity.value ?: throw IllegalStateException("No profile is active") - val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: throw IllegalStateException("No such group here") - return MemberWalletManager.putToGroup(database, room, identity.nostrPublicKey, request) - } - - override suspend fun guardedByGroupsHere(ownerPublicKey: HexKey): List = try { - val viewer = activeIdentity.value?.nostrPublicKey ?: return emptyList() - MemberWalletManager.guardedByGroupsHere(database, viewer, ownerPublicKey) - } catch (e: Throwable) { - logger.e("Error reading the wallets of $ownerPublicKey this profile's groups guard", e) - emptyList() - } - - companion object { - private const val TAG = "DatabaseMemberWalletRepository" - } -} 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 d679a773..e1648c22 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt @@ -6,7 +6,6 @@ import fr.acinq.bitcoin.OutPoint import mobi.giza.compose.database.model.GroupTransaction import mobi.giza.compose.database.model.types.FrostSigningSubject import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import mobi.giza.compose.nostr.wallet.MemberWalletCertificateEvent import mobi.giza.compose.wallet.GroupSpend import fr.acinq.bitcoin.ByteVector64 import fr.acinq.bitcoin.Chain @@ -660,37 +659,6 @@ object FrostSigningManager { } } - // A member wallet's certificate is this group agreeing to guard one - // member's key, so it has to be exactly what that member asked for, asked - // by a member, with exactly the guardian keys this group grants -- the - // list a guarded subgroup of it would get. Recomputed from this device's - // own key state, never taken from the sponsor who proposed it. - // docs/member-guarded-wallets.md, Phase 7. - unsignedEvents.forEach { rebuilt -> - if (rebuilt.kind != MemberWalletCertificateEvent.KIND) return@forEach - val reason = thresholdPublicKey - ?.let { MemberWalletManager.refuseCertificate(database, rebuilt.pubKey, it, rebuilt) } - ?: if (thresholdPublicKey == null) "cannot be checked without the group's key" else null - reason?.let { - logger.w("Signing proposal $sessionId carries a member wallet certificate that $it; dropping") - return null - } - } - - // A subgroup's key state carries its birth certificate, and the - // certificate's wallet policy has to be the one this group was made - // under: every admin was shown it at the join gate, so joining was - // agreeing to it. A certificate proposed later, by a parent admin - // resuming the flow, under another one would be the child signing a - // decision none of its members agreed to. [key] is the child's own - // ceremony here, which is where the policy was filed. - // `docs/subgroup-wallet-policy.md`, Phase 5. - // A wallet statement has to be one the room's parent allows: a subgroup - // decided guarded opens a guarded wallet and nothing else, and one decided - // unguarded a plain one. Read off this device's own certificate for the - // room, never the proposal's, and refused before it is shown -- a member - // should not be asked to approve what their device already knows the - // room has ruled out. docs/subgroup-wallet-policy.md, Phase 7. unsignedEvents.forEach { rebuilt -> if (rebuilt.kind != GroupWalletStatementEvent.KIND) return@forEach val guarded = GroupWalletStatementEvent.read(rebuilt.tags, rebuilt.content)?.guardians?.isNotEmpty() ?: return@forEach diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GuardianManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GuardianManager.kt index 5de30965..3fb7a27e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GuardianManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GuardianManager.kt @@ -10,7 +10,6 @@ import mobi.giza.compose.nostr.frost.GroupKeyStateEvent import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent import mobi.giza.compose.nostr.wallet.GuardedWalletNoticeEvent -import mobi.giza.compose.nostr.wallet.MemberWalletCertificateEvent import mobi.giza.compose.wallet.GroupSpend import mobi.giza.compose.wallet.GroupWalletRollout import com.vitorpamplona.quartz.nip01Core.core.Event @@ -185,21 +184,8 @@ object GuardianManager { * and descriptors all rederive from it -- `Reading.verifiedAgainst`, which * also checks the certificate certifies the room and grants exactly those * guardians. - * - * Or a member wallet certificate the guarding group signed over the member's - * own request -- `MemberWalletCertificateEvent.verify`. */ fun believable(statement: Event): Believable? = runCatching { - if (statement.kind == MemberWalletCertificateEvent.KIND) { - val verified = MemberWalletCertificateEvent.verify(statement, statement.pubKey) ?: return null - return Believable( - statement = statement, - descendantId = verified.walletId, - account = verified.account, - certificate = statement, - subject = GuardedSubject.Member(verified.walletId, verified.memberPublicKey, verified.label), - ) - } if (statement.kind != GroupWalletStatementEvent.KIND) return null val descendantChatRoomId = statement.pubKey if (!GroupKeyStateEvent.isSignedByRoom(statement, descendantChatRoomId)) return null @@ -367,9 +353,6 @@ object GuardianManager { val notices = database.marmotInnerEventDao() .getByChatRoomAndKinds(ancestorChatRoomId, listOf(GuardedWalletNoticeEvent.KIND)) val told = notices.mapNotNull { row -> Event.fromJsonOrNull(row.content) } - val signed = database.groupSignedEventDao() - .getByChatRoomIdAndKind(ancestorChatRoomId, MemberWalletCertificateEvent.KIND) - .map { it.toEvent() } // Birth certificates the room was handed: the one a subgroup's statement // carries, and the guardian's a member wallet's notice carries. Pooled, @@ -379,7 +362,7 @@ object GuardianManager { .mapNotNull { GroupWalletStatementEvent.read(it.tags, it.content)?.certificate } + notices.mapNotNull { GuardedWalletNoticeEvent.certificateIn(it.tags) } - return (told + signed) + return told .mapNotNull { verify(it, ancestorChatRoomId, thresholdPublicKey) } .map { named(database, it, known) } .groupBy { Triple(it.descendantChatRoomId, it.chain, it.account.account) } @@ -488,15 +471,8 @@ object GuardianManager { * Null for a subgroup's statement, which carries its own. * `docs/member-wallet-guarding-group.md`, D4. */ - private suspend fun guardianCertificateFor(database: GizaDatabase, statement: Event, chatRoomId: String): Event? { - if (statement.kind != MemberWalletCertificateEvent.KIND) return null - val guardians = believable(statement)?.guardians ?: return null - val parent = guardians.getOrNull(1) ?: return null - val carried = database.marmotInnerEventDao() - .getByChatRoomAndKinds(chatRoomId, listOf(GuardedWalletNoticeEvent.KIND)) - .mapNotNull { GuardedWalletNoticeEvent.certificateIn(it.tags) } - return foundingCertificateOf(database, guardians.first().chatRoomId, parent.chatRoomId, carried) - } + @Suppress("UNUSED_PARAMETER") + private suspend fun guardianCertificateFor(database: GizaDatabase, statement: Event, chatRoomId: String): Event? = null /** * Tells every group above [chatRoomId] that this device can tell, and that diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MemberWalletDerivation.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MemberWalletDerivation.kt deleted file mode 100644 index 24d18c20..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MemberWalletDerivation.kt +++ /dev/null @@ -1,148 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.wallet.GroupSpend -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray -import com.vitorpamplona.quartz.nip01Core.core.toHexKey -import com.vitorpamplona.quartz.utils.RandomInstance -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.ByteVector64 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.Crypto -import fr.acinq.bitcoin.Descriptor -import fr.acinq.bitcoin.DeterministicWallet -import fr.acinq.bitcoin.KeyPath -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.PublicKey - -/** - * The keys of a wallet one member holds and a group guards: a guarded wallet - * whose key path is the member's own key rather than a group's threshold key. - * - * Everything public is the group wallet's derivation with the member's key in - * the threshold key's place, and the guardian derivation with the wallet's id in - * a child room's place: - * - * ``` - * k random, generated on the member's device and never sent - * P_W = k·G the wallet key - * W = taggedHash("bennu/member-wallet/id/v1", serP(P_W)) the wallet's id - * account = GroupWalletDerivation.account(P_W, chain, 0, grant) - * grant = GuardianDerivation.grant(K_G, G, guardians(G), W) - * ``` - * - * So a member's wallet under G is guarded exactly as a guarded subgroup of G - * would be. What is new is only the private side: the member holds `k`, so - * every tweak the account and the address add to the point is added to the - * scalar too, and a spend is one Schnorr signature. See - * `docs/member-guarded-wallets.md`. - * - * ### Why `W` is a hash and not the key - * - * A room id here is a public key, and `GroupKeyStateEvent.isSignedByRoom` asks - * whether that key signed something. A `W` nobody holds a key for cannot be - * mistaken for a room by anything that checks signatures. - * - * ### The rule this inherits - * - * Every step below `P_W` is an unhardened public tweak, and every guardian holds - * the account xpub. A guardian who learns the private key of one address can - * therefore recover `k`. That is why `k` is random and good for one wallet only: - * never the nostr key, never a key from the profile's seed. - */ -object MemberWalletDerivation { - /** - * The tag of a wallet id's hash. Frozen the moment a certificate carries one: a rename moves every leaf. - * The `bennu/` prefix included -- see [GroupWalletDerivation]'s account tag. - */ - private const val ID_TAG = "bennu/member-wallet/id/v1" - - /** - * The account a member wallet always opens at. One wallet is one key, so a - * second account would be a second wallet under a key that already has one. - */ - const val ACCOUNT: Long = 0L - - /** A fresh wallet key, from the platform's secure random. */ - fun generate(): PrivateKey { - while (true) { - val candidate = PrivateKey(ByteVector32(RandomInstance.bytes(32))) - if (candidate.isValid()) return candidate - } - } - - /** `W`: the tagged hash of the wallet key's compressed form, hex. */ - fun walletId(walletKey: PublicKey): String = - Crypto.taggedHash(walletKey.value.toByteArray(), ID_TAG).toByteArray().toHexKey() - - fun walletId(walletKey: HexKey): String = walletId(PublicKey(walletKey.hexToByteArray())) - - /** - * The account [walletKey] opens on [chain] under [guardians]: - * `GroupWalletDerivation.account` over the member's key. - */ - fun account(walletKey: PublicKey, chain: Chain, guardians: List): GroupWalletDerivation.Account = - GroupWalletDerivation.account(walletKey.toString(), chain, ACCOUNT, guardians) - - /** - * The account key as a private extended key: [walletPrivateKey] plus the - * scalar `GroupWalletDerivation.account` adds to the point, with the same - * chain code. Plain addition, so there is no parity to get wrong until the - * taproot tweak at the very end. - */ - fun accountPrivateKey(walletPrivateKey: PrivateKey, chain: Chain): DeterministicWallet.ExtendedPrivateKey { - val (tweak, chainCode) = GroupWalletDerivation.accountStep(walletPrivateKey.publicKey(), chain, ACCOUNT) - return DeterministicWallet.ExtendedPrivateKey( - secretkeybytes = (walletPrivateKey + PrivateKey(tweak)).value, - chaincode = chainCode, - depth = 0, - path = KeyPath.empty, - parent = 0L, - ) - } - - /** The private key of the internal key at `change/index`: CKDpriv twice below [accountPrivateKey]. */ - fun privateKeyAt(walletPrivateKey: PrivateKey, chain: Chain, change: Long, index: Long): PrivateKey { - require(change == GroupWalletDerivation.RECEIVE || change == GroupWalletDerivation.CHANGE) { "change must be 0 or 1, not $change" } - require(index in 0L..GroupWalletDerivation.MAX_INDEX) { "index $index is not an unhardened index" } - return accountPrivateKey(walletPrivateKey, chain).derivePrivateKey(listOf(change, index)).privateKey - } - - /** - * The receive and change descriptors of [account] with the account's private - * key in place of its xpub -- what any wallet that imports taproot - * descriptors can sweep the coins with. The member's backup of last resort, - * shown only behind a confirmation: whoever holds these holds the coins. - */ - fun privateDescriptors(walletPrivateKey: PrivateKey, account: GroupWalletDerivation.Account): Pair { - val extended = accountPrivateKey(walletPrivateKey, account.chain) - require(extended.extendedPublicKey == account.extendedPublicKey) { "this key does not open this account" } - val xprv = extended.encode(if (account.chain.isMainnet()) DeterministicWallet.xprv else DeterministicWallet.tprv) - - fun swap(descriptor: String): String { - val body = descriptor.substringBefore('#').replaceFirst(account.xpub, xprv) - return "$body#${Descriptor.checksum(body)}" - } - return swap(account.receiveDescriptor) to swap(account.changeDescriptor) - } - - /** - * The signature [input] of a checked spend needs from the wallet's own key: - * the address's private key under the address's taproot tweak, over the - * input's key-path sighash. - * - * Refuses a guardian's input -- the member never signs through a leaf -- and - * an input whose address is not one this key reaches, so a signature made - * here always verifies against the key the coin is at. - */ - fun sign(walletPrivateKey: PrivateKey, chain: Chain, input: GroupSpend.SpentInput): ByteVector64 { - require(input.leaf == null) { "a member signs on the key path, never through a guardian's leaf" } - val derivation = input.derivation - val privateKey = privateKeyAt(walletPrivateKey, chain, derivation.change, derivation.index) - require(privateKey.xOnlyPublicKey() == derivation.internalKey) { "this key does not reach the address at ${derivation.change}/${derivation.index}" } - - val signature = Crypto.signSchnorr(input.sighash, privateKey, derivation.taprootTweak) - require(Crypto.verifySignatureSchnorr(input.sighash, signature, input.signingKey)) { "the signature does not verify against the coin's key" } - return signature - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MemberWalletManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MemberWalletManager.kt deleted file mode 100644 index c562ac92..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MemberWalletManager.kt +++ /dev/null @@ -1,863 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.database.model.types.ChatRoomType -import mobi.giza.compose.nostr.wallet.MemberWalletPolicyEvent -import co.touchlab.kermit.Logger -import mobi.giza.compose.database.GizaDatabase -import mobi.giza.compose.database.model.FrostSigningSession -import mobi.giza.compose.database.model.MemberWallet -import mobi.giza.compose.database.model.MemberWalletSpend -import mobi.giza.compose.wallet.GroupSpend -import fr.acinq.bitcoin.ScriptFlags -import fr.acinq.bitcoin.Transaction -import fr.acinq.bitcoin.psbt.Psbt -import fr.acinq.secp256k1.Hex -import mobi.giza.compose.database.model.MarmotInnerEvent -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.database.model.types.FrostSigningStage -import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent -import mobi.giza.compose.nostr.wallet.GroupKeyNoticeEvent -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import mobi.giza.compose.nostr.wallet.MemberWalletCertificateEvent -import mobi.giza.compose.nostr.wallet.MemberWalletRequestEvent -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import mobi.giza.compose.wallet.GroupWalletRollout -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.PrivateKey -import kotlin.time.Clock -import kotlin.time.Instant - -/** - * A member's guarded wallet, from the asking to the guarding: - * `docs/member-guarded-wallets.md`. - * - * The member's device makes a random key, works out every ancestor leaf, stores - * the key and only then asks the group. A signer puts the request to the group, - * the group's quorum signs a certificate saying it guards that key for that - * person, and the certificate is what every device opens the wallet on. - */ -object MemberWalletManager { - private const val TAG = "MemberWalletManager" - - private val logger = Logger.withTag(TAG) - - /** - * The key [chatRoomId] signs with and the certificate it was born with -- - * what a member's grant is worked out from -- or null when this device knows - * neither. - * - * This device's own verified key state first. Behind it, the newest answer to - * a key notice in the room that checks out: a member welcomed after the - * founding holds no key state, and asks (`askForGroupKey`). Never filed as - * key state -- see [GroupKeyNoticeEvent]. - */ - suspend fun groupKeyFor(database: GizaDatabase, chatRoomId: String): GroupKeyNoticeEvent.GroupKey? { - GroupKeyStateManager.keyStateFor(database, chatRoomId)?.takeIf { it.verifies() }?.let { state -> - return GroupKeyNoticeEvent.GroupKey( - chatRoomId = state.chatRoomId, - thresholdPublicKey = state.thresholdPublicKey, - certificate = state.birthCertificateJson?.let { Event.fromJsonOrNull(it) }, - ) - } - - return noticesIn(database, chatRoomId) - .sortedByDescending { it.createdAt } - .firstNotNullOfOrNull { GroupKeyNoticeEvent.read(it, chatRoomId) } - } - - /** - * Whether [chatRoomId] guards its members' wallets, and at what delay: the - * newest policy its own room signed, open or closed, among the ones this - * device holds -- `docs/member-wallet-delay.md`. Null when it holds none, - * which means the group has not opened (D8), or that this device has not - * yet been told. - * - * The one reader, used by the member's device when it builds a request and - * by every signer when it judges one. - */ - suspend fun policyFor(database: GizaDatabase, chatRoomId: String): MemberWalletPolicyEvent.Policy? = - MemberWalletPolicyEvent.newestAmong( - database.groupSignedEventDao() - .getByChatRoomIdAndKind(chatRoomId, MemberWalletPolicyEvent.KIND) - .map { it.toEvent() } + - // A late member's only way to it: carried in a key answer, and - // checked again here as the room's own signature. - noticesIn(database, chatRoomId).mapNotNull { GroupKeyNoticeEvent.read(it, chatRoomId)?.policy?.event }, - chatRoomId, - ) - - /** - * Asks [chatRoomId] for its key, as [userPublicKey]. Returns false, asking - * nothing, when this device already knows it or has asked and not been - * answered: a second question would get the same answer. - */ - suspend fun askForGroupKey(database: GizaDatabase, chatRoomId: String, userPublicKey: HexKey): Boolean { - if (groupKeyFor(database, chatRoomId) != null) return false - - val notices = noticesIn(database, chatRoomId) - val answered = notices.mapNotNull { GroupKeyNoticeEvent.answers(it) }.toSet() - if (notices.any { GroupKeyNoticeEvent.isAsking(it) && it.pubKey == userPublicKey && it.id !in answered }) return false - - queue(database, chatRoomId, userPublicKey, GroupKeyNoticeEvent.askingTags(chatRoomId), content = "") - logger.i("Asked $chatRoomId for its key") - return true - } - - /** - * Answers [request], an asking notice that arrived in [chatRoomId], as - * [userPublicKey] -- when this device holds the room's verified key state and - * nobody has answered it yet. Returns whether it answered. - * - * Any member holding the state may answer, and none is elected to: a - * duplicate answer costs bandwidth and nothing else, since every answer is - * checked on its own and they all say the same thing. The chronicle's - * request is answered the same way. - */ - suspend fun answerKeyRequest(database: GizaDatabase, chatRoomId: String, request: Event, userPublicKey: HexKey): Boolean { - if (!GroupKeyNoticeEvent.isAsking(request) || request.pubKey == userPublicKey) return false - val state = GroupKeyStateManager.keyStateFor(database, chatRoomId)?.takeIf { it.verifies() } ?: return false - val path = state.pathIndices() ?: return false - if (noticesIn(database, chatRoomId).any { GroupKeyNoticeEvent.answers(it) == request.id }) return false - - val groupKey = GroupKeyNoticeEvent.GroupKey( - chatRoomId = state.chatRoomId, - thresholdPublicKey = state.thresholdPublicKey, - certificate = state.birthCertificateJson?.let { Event.fromJsonOrNull(it) }, - // The other thing a late member cannot read for themselves. - // docs/member-wallet-delay.md, Phase 3. - policy = policyFor(database, chatRoomId), - ) - queue(database, chatRoomId, userPublicKey, GroupKeyNoticeEvent.answeringTags(request.id, groupKey, path), content = state.thresholdPublicKey) - logger.i("Answered ${request.pubKey.take(8)}'s request for $chatRoomId's key") - return true - } - - // ---- The member's side ----------------------------------------------- - - /** Why a member cannot ask a group to guard a wallet for them here, said as a reason the screen can name. */ - enum class Refusal { - /** A read-only profile: it cannot sign the request. */ - CANNOT_SIGN, - - /** The room is not a Marmot group, so there is no quorum to sign and no room to carry it. */ - NOT_A_GROUP, - - /** This device does not know what the group signs with -- [askForGroupKey] is the way on. */ - KEY_UNKNOWN, - - /** The group's certificate carries guardian keys this build cannot read. */ - GUARDIANS_UNREADABLE, - - /** Member wallets are not offered on this network yet: `GroupWalletRollout.offersMemberWalletsOn`. */ - NOT_ON_THIS_NETWORK, - - /** - * The group has not said it guards members' wallets: no policy, as far as - * this device knows. `docs/member-wallet-delay.md`, D8. - */ - NOT_OFFERED, - - /** The group's newest policy closed it to new members' wallets. D9. */ - CLOSED, - } - - /** - * The groups [ownerPublicKey] is in that could guard a wallet for them: Marmot - * rooms, whether or not their key is known yet -- but not a direct chat. - * - * A direct chat is a Marmot room too, of exactly two people, and it never has - * a key: a key ceremony needs at least `ChatRoomType.MINIMUM_ROBUST_GROUP_SIZE` - * participants. Listed, it would ask for a key nobody can ever answer with. - * So a room of fewer than three members is left out unless this device knows - * its key -- a real group can shrink to two after its ceremony, and still sign - * if the two make its quorum. The same "the two of us" the direct-message - * lookup uses (`ChatRepository.findDirectMessageRoom`). - */ - suspend fun groupsOf(database: GizaDatabase, ownerPublicKey: HexKey): List = - database.chatRoomDao().getChatRoomListByUserPublicKey(ownerPublicKey).filter { couldGuard(database, it) } - - /** Whether [room] is a group that could guard a member's wallet: [groupsOf]'s one rule, for a room on its own page too. */ - suspend fun couldGuard(database: GizaDatabase, room: LocalChatRoom): Boolean { - if (room.chatRoom.mlsGroupState == null) return false - val members = room.localParticipants.map { it.participant.participantPublicKey.lowercase() }.toSet() - return members.size >= ChatRoomType.MINIMUM_ROBUST_GROUP_SIZE || groupKeyFor(database, room.chatRoom.id) != null - } - - /** Why [chatRoomId] cannot guard a wallet for this profile on [chain], or null when it can. */ - suspend fun refusal(database: GizaDatabase, chatRoomId: String, canSign: Boolean, chain: Chain): Refusal? { - if (!canSign) return Refusal.CANNOT_SIGN - if (!GroupWalletRollout.offersMemberWalletsOn(chain)) return Refusal.NOT_ON_THIS_NETWORK - val room = database.chatRoomDao().findChatRoomById(chatRoomId) - if (room?.chatRoom?.mlsGroupState == null) return Refusal.NOT_A_GROUP - val groupKey = groupKeyFor(database, chatRoomId) ?: return Refusal.KEY_UNKNOWN - if (groupKey.certificate != null && SubgroupBirthCertificateEvent.parseGuardians(groupKey.certificate.tags) == null) { - return Refusal.GUARDIANS_UNREADABLE - } - // Only a group that has opened guards members' wallets, at the delay it - // chose -- and a late member learns it with the key, so no key and no - // policy is KEY_UNKNOWN above, with its button to ask. - return when (policyFor(database, chatRoomId)) { - null -> Refusal.NOT_OFFERED - is MemberWalletPolicyEvent.Policy.Closed -> Refusal.CLOSED - is MemberWalletPolicyEvent.Policy.Open -> null - } - } - - /** - * How many groups a wallet guarded by [chatRoomId] would be guarded by: the - * group, and every group above it whose key it passes down. Null when this - * device does not know the group's key. - */ - suspend fun reachOf(database: GizaDatabase, chatRoomId: String): Int? = - groupKeyFor(database, chatRoomId)?.let { it.guardians.size + 1 } - - /** - * How long a coin in a wallet [chatRoomId] guards would wait for each of its - * guardians, nearest first: the group's own leaf at the delay its open policy - * sets, and every group above it at the delay it chose -- the same list the - * grant in [request] carries. Null when this device does not know the - * group's key, or the group is not open. `docs/member-wallet-delay.md`. - */ - suspend fun delaysOf(database: GizaDatabase, chatRoomId: String): List? { - val key = groupKeyFor(database, chatRoomId) ?: return null - val policy = policyFor(database, chatRoomId) as? MemberWalletPolicyEvent.Policy.Open ?: return null - return listOf(policy.delay) + key.guardians.map { it.delay } - } - - /** - * Steps 1 and 2: makes a random key, works out every ancestor's leaf and - * both descriptors, stores the key, and only then asks [chatRoomId] to - * guard the wallet, as the member [memberPrivateKey] holds. - * - * The row is written before the request is queued, so a crash between the - * two leaves a key and no request rather than a request and no key. The - * request is checked the way every signer will check it before it goes, so - * a quorum is never shown one this device would refuse. A member who holds a - * share of the group's key puts it to the group in the same breath; anybody - * else waits for a signer to. - * - * @throws IllegalStateException with the [Refusal] when it cannot be asked - */ - suspend fun request( - database: GizaDatabase, - chatRoomId: String, - memberPrivateKey: PrivateKey, - chain: Chain, - label: String?, - createdAt: Instant = Clock.System.now(), - ): MemberWallet { - refusal(database, chatRoomId, canSign = true, chain)?.let { throw IllegalStateException("Cannot ask: $it") } - val groupKey = groupKeyFor(database, chatRoomId) ?: throw IllegalStateException("Cannot ask: ${Refusal.KEY_UNKNOWN}") - val memberPublicKey = memberPrivateKey.xOnlyPublicKey().value.toHex() - - // The group's own leaf at the delay its newest policy sets, which the - // request carries so every signer judges it by what the group signed. - // refusal() has already refused a group that is not open. - val policy = policyFor(database, chatRoomId) as? MemberWalletPolicyEvent.Policy.Open - ?: throw IllegalStateException("Cannot ask: ${Refusal.NOT_OFFERED}") - - val walletPrivateKey = MemberWalletDerivation.generate() - val walletId = MemberWalletDerivation.walletId(walletPrivateKey.publicKey()) - val grant = GuardianDerivation.grant(groupKey.thresholdPublicKey, chatRoomId.lowercase(), groupKey.guardians, walletId, policy.delay) - val account = MemberWalletDerivation.account(walletPrivateKey.publicKey(), chain, grant) - - val request = MemberWalletRequestEvent.build( - memberPrivateKey = memberPrivateKey, - groupChatRoomId = chatRoomId, - walletPrivateKey = walletPrivateKey, - account = account, - label = label, - createdAt = createdAt.epochSeconds, - policy = policy.event, - ) - checkNotNull(MemberWalletRequestEvent.verified(request)) { "The request this device built does not check out" } - - val wallet = MemberWallet( - walletId = walletId, - ownerPublicKey = memberPublicKey, - guardingChatRoomId = chatRoomId, - chain = GroupWalletStatementEvent.chainName(chain), - walletPrivateKey = walletPrivateKey.value.toHex(), - label = MemberWalletRequestEvent.read(request)?.label, - requestJson = request.toJson(), - // The request's own second: the row and the event it carries agree on when. - createdAt = Instant.fromEpochSeconds(request.createdAt), - ) - database.memberWalletDao().upsert(wallet) - send(database, chatRoomId, request) - logger.i("Asked $chatRoomId to guard wallet ${walletId.take(8)}") - - sponsorIfSigner(database, chatRoomId, memberPublicKey, request) - return wallet - } - - /** - * Asks again -- for a request no signer put to the group, or one the group - * did not sign. With the request [wallet] was asked with, unchanged, when - * the group would still accept it; otherwise with a new one under the - * group's newest policy and a new key, as the member [memberPrivateKey] - * holds, and the old key discarded: no address of it was ever offered. - * `docs/member-wallet-delay.md`, Phase 5. - * - * Returns the wallet now asked for -- [wallet] itself, or its replacement. - * - * @throws IllegalStateException when a new request is needed and this group - * cannot be asked now, with the [Refusal] - */ - suspend fun askAgain(database: GizaDatabase, wallet: MemberWallet, memberPrivateKey: PrivateKey): MemberWallet { - val request = Event.fromJsonOrNull(wallet.requestJson) ?: throw IllegalStateException("The stored request does not read") - if (judgePolicy(database, wallet.guardingChatRoomId, request) is PolicyJudgement.At) { - send(database, wallet.guardingChatRoomId, request) - sponsorIfSigner(database, wallet.guardingChatRoomId, wallet.ownerPublicKey, request) - return wallet - } - - val chain = MemberWalletRequestEvent.read(request)?.chain ?: throw IllegalStateException("The stored request does not read") - val replacement = request(database, wallet.guardingChatRoomId, memberPrivateKey, chain, wallet.label) - discard(database, wallet.walletId) - logger.i("Asked ${wallet.guardingChatRoomId} again for a new wallet in place of ${wallet.walletId.take(8)}") - return replacement - } - - /** - * Forgets [walletId]'s key. Refused once a group has certified the wallet: - * from then on its addresses may have been paid. Before, none was ever - * offered, so no coin can be behind the key. - */ - suspend fun discard(database: GizaDatabase, walletId: String) { - val wallet = database.memberWalletDao().getById(walletId) ?: return - check(certificatesOf(database, wallet.guardingChatRoomId).none { it.walletId == walletId }) { - "A group guards this wallet: its key is not discarded" - } - database.memberWalletDao().delete(walletId) - } - - /** The request into [chatRoomId], whole, as an inner event's content: see `MemberWalletRequestEvent`. */ - private suspend fun send(database: GizaDatabase, chatRoomId: String, request: Event) { - queue( - database = database, - chatRoomId = chatRoomId, - userPublicKey = request.pubKey, - tags = arrayOf(arrayOf("h", chatRoomId.lowercase())), - content = request.toJson(), - kind = MemberWalletRequestEvent.KIND, - ) - } - - private suspend fun sponsorIfSigner(database: GizaDatabase, chatRoomId: String, memberPublicKey: HexKey, request: Event) { - if (!FrostSigningManager.canSign(database, chatRoomId)) return - val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return - runCatching { putToGroup(database, room, memberPublicKey, request) } - .onFailure { logger.w("Asked $chatRoomId, and could not put it to the group: ${it.message}") } - } - - /** Where a member's wallet has got to, as one fact the profile shows. */ - enum class WalletState { - /** A key and a request here; nobody has put it to the group yet. */ - ASKED, - - /** A session is running over its certificate. */ - SIGNING, - - /** The session failed or was declined, and the group has not certified it. */ - NOT_SIGNED, - - /** Certified, and the key is on this device. */ - OPEN, - - /** Certified, and the key is on another device of this profile's. */ - WATCH_ONLY, - } - - /** One of a member's guarded wallets, as their profile lists it. */ - data class MemberWalletRow( - val walletId: String, - val groupChatRoomId: String, - /** The guarding group's room on this device, or null when this device is not in it. */ - val groupRoom: LocalChatRoom?, - val label: String?, - val chain: Chain, - /** The account the wallet opens: rederived from the request, guardians and all. */ - val account: GroupWalletDerivation.Account, - val state: WalletState, - /** Whether the member is still a member of the guarding group, as far as this device can see. */ - val isMember: Boolean, - /** The stored key's row, for a wallet whose key is here. Never handed to a screen. */ - internal val stored: MemberWallet?, - /** - * Why the group would refuse this wallet's request as it stands, for one - * not yet guarded -- [judgePolicy] -- or null when it would not. Asking - * again then makes a new request. `docs/member-wallet-delay.md`. - */ - val refusedBecause: Why? = null, - ) { - val isCertified: Boolean get() = state == WalletState.OPEN || state == WalletState.WATCH_ONLY - } - - /** - * Every guarded wallet of [ownerPublicKey]'s this device knows about, newest - * first: the ones whose key is here, and the ones a group this device is in - * has certified for this profile -- which includes wallets made on another - * of its devices. - */ - suspend fun walletsOf(database: GizaDatabase, ownerPublicKey: HexKey): List { - val stored = database.memberWalletDao().getByOwner(ownerPublicKey) - val certified = database.groupSignedEventDao().getByKind(MemberWalletCertificateEvent.KIND) - .filter { MemberWalletCertificateEvent.memberOf(it.toEvent()).equals(ownerPublicKey, ignoreCase = true) } - .mapNotNull { MemberWalletCertificateEvent.verify(it.toEvent(), it.chatRoomId) } - .distinctBy { it.walletId } - .associateBy { it.walletId } - - val fromKeys = stored.mapNotNull { wallet -> - val request = Event.fromJsonOrNull(wallet.requestJson) ?: return@mapNotNull null - val verified = MemberWalletRequestEvent.verified(request) ?: return@mapNotNull null - val state = when { - certified.containsKey(wallet.walletId) -> WalletState.OPEN - openSessionFor(database, wallet.guardingChatRoomId, request) != null -> WalletState.SIGNING - wasNotSigned(database, wallet.guardingChatRoomId, request) -> WalletState.NOT_SIGNED - else -> WalletState.ASKED - } - row(database, wallet.walletId, wallet.guardingChatRoomId, wallet.label, verified.account, state, ownerPublicKey, wallet) - .let { row -> - if (row.isCertified) row - else row.copy(refusedBecause = (judgePolicy(database, wallet.guardingChatRoomId, request) as? PolicyJudgement.Refused)?.why) - } - } - val elsewhere = certified.values - .filter { cert -> stored.none { it.walletId == cert.walletId } } - .map { row(database, it.walletId, it.groupChatRoomId, it.label, it.account, WalletState.WATCH_ONLY, ownerPublicKey, null) } - - return (fromKeys + elsewhere).sortedByDescending { it.stored?.createdAt?.epochSeconds ?: 0L } - } - - private suspend fun row( - database: GizaDatabase, - walletId: String, - groupChatRoomId: String, - label: String?, - account: GroupWalletDerivation.Account, - state: WalletState, - ownerPublicKey: HexKey, - stored: MemberWallet?, - ): MemberWalletRow { - val room = database.chatRoomDao().findChatRoomById(groupChatRoomId) - val isMember = room == null || database.participantDao().findParticipantsByChatRoomId(groupChatRoomId) - .any { it.participantPublicKey.equals(ownerPublicKey, ignoreCase = true) } - return MemberWalletRow(walletId, groupChatRoomId, room, label, account.chain, account, state, isMember, stored) - } - - /** [ownerPublicKey]'s wallet [walletId], or null when this device knows of none. */ - suspend fun walletOf(database: GizaDatabase, ownerPublicKey: HexKey, walletId: String): MemberWalletRow? = - walletsOf(database, ownerPublicKey).firstOrNull { it.walletId == walletId } - - /** - * [walletId]'s descriptors with its private key in them, or null when the key - * is not on this device. See `MemberWalletDerivation.privateDescriptors`. - */ - suspend fun exportKey(database: GizaDatabase, ownerPublicKey: HexKey, walletId: String): Pair? { - val row = walletOf(database, ownerPublicKey, walletId) ?: return null - val key = row.stored?.walletPrivateKey?.let { PrivateKey.fromHex(it) } ?: return null - return MemberWalletDerivation.privateDescriptors(key, row.account) - } - - /** - * Signs [psbt] as [walletId]'s own key and files the spend, returning the - * finished transaction for the caller to broadcast. - * - * Checked the way a group member checks a group spend -- `GroupSpend.check` - * against the account the wallet rederives to, never against the PSBT's own - * claims -- because the builder is shared and so are its mistakes; and then - * `correctlySpends`, the last word on whether the network will take it. - * - * @throws IllegalStateException when the key is not here, the wallet is not - * certified, the spend fails a check or is over the cap - */ - suspend fun signSpend(database: GizaDatabase, ownerPublicKey: HexKey, walletId: String, psbt: Psbt, at: Instant = Clock.System.now()): Transaction { - val row = walletOf(database, ownerPublicKey, walletId) ?: throw IllegalStateException("No such wallet") - check(row.state == WalletState.OPEN) { "Only a certified wallet whose key is here can spend" } - val key = PrivateKey.fromHex(checkNotNull(row.stored).walletPrivateKey) - - val checked = when (val result = GroupSpend.check(psbt, row.account, GroupSpend.Spender.Owner)) { - is GroupSpend.Result.Ok -> result.checked - is GroupSpend.Result.Refused -> throw IllegalStateException("This spend ${result.reason}") - } - GroupWalletRollout.memberCapFor(row.chain)?.let { cap -> - check(checked.amountSent <= cap) { "This spend sends more than the ${cap.sat} sats one spend may send on mainnet" } - } - - val signed = checked.witnessed(checked.inputs.map { MemberWalletDerivation.sign(key, row.chain, it) }) - signed.correctlySpends(checked.inputs.associate { it.outPoint to it.txOut }, ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) - - database.memberWalletDao().upsertSpend( - MemberWalletSpend( - txid = signed.txid.toString(), - walletId = walletId, - psbt = GroupSpend.encode(psbt), - signedTransaction = Hex.encode(Transaction.write(signed)), - createdAt = at, - ) - ) - logger.i("Signed ${signed.txid} from wallet ${walletId.take(8)}") - return signed - } - - /** - * Files what the chain said of [txid]: handed to Electrum at [broadcastAt], - * and -- with [confirmations] non-null -- seen, and confirmed once it is at - * least one deep. - */ - suspend fun recordChain(database: GizaDatabase, txid: String, confirmations: Int?, broadcastAt: Instant? = null, at: Instant = Clock.System.now()) { - val spend = database.memberWalletDao().getSpend(txid) ?: return - val updated = spend.copy( - broadcastAt = broadcastAt ?: spend.broadcastAt, - seenAt = spend.seenAt ?: at.takeIf { confirmations != null }, - confirmedAt = spend.confirmedAt ?: at.takeIf { (confirmations ?: 0) >= 1 }, - ) - if (updated != spend) database.memberWalletDao().upsertSpend(updated) - } - - // ---- The group's side ------------------------------------------------ - - /** - * Every certificate [chatRoomId] holds that verifies as its own: the member - * wallets this group guards, newest first. One per wallet -- the `d` tag makes - * two certificates for one wallet replacements, and they say the same thing. - */ - suspend fun certificatesOf(database: GizaDatabase, chatRoomId: String): List = - database.groupSignedEventDao() - .getByChatRoomIdAndKind(chatRoomId, MemberWalletCertificateEvent.KIND) - .mapNotNull { MemberWalletCertificateEvent.verify(it.toEvent(), chatRoomId) } - .sortedByDescending { it.certificate.createdAt } - .distinctBy { it.walletId } - - /** - * Every request a member has put into [chatRoomId] that checks out and asks - * this room, newest first, one per wallet. - */ - suspend fun requestsIn(database: GizaDatabase, chatRoomId: String): List = - database.marmotInnerEventDao() - .getByChatRoomAndKinds(chatRoomId, listOf(MemberWalletRequestEvent.KIND)) - .mapNotNull { MemberWalletRequestEvent.carried(it.asEvent()) } - .mapNotNull { MemberWalletRequestEvent.verified(it) } - .filter { it.reading.groupChatRoomId.equals(chatRoomId, ignoreCase = true) } - .sortedByDescending { it.request.createdAt } - .distinctBy { it.reading.walletId } - - /** - * The event id a certificate for [request] signed in [chatRoomId] will have. - * The room's id is the author, and the request fixes everything else -- which - * is what lets two sponsors find each other's session. - */ - fun certificateIdFor(chatRoomId: String, request: Event): HexKey { - val template = MemberWalletCertificateEvent.template(request) - return EventHasher.hashId(chatRoomId.lowercase(), template.createdAt, template.kind, template.tags, template.content) - } - - /** The session open in [chatRoomId] over [request]'s certificate, if one is still running. */ - suspend fun openSessionFor(database: GizaDatabase, chatRoomId: String, request: Event): FrostSigningSession? { - val certificateId = certificateIdFor(chatRoomId, request) - return database.frostSigningSessionDao().getSessionsForChatRoom(chatRoomId) - .filter { it.stage != FrostSigningStage.FAILED && it.stage != FrostSigningStage.COMPLETE } - .firstOrNull { session -> database.frostSigningSessionDao().getItems(session.id).any { it.eventId == certificateId } } - } - - /** Whether the latest session over [request]'s certificate in [chatRoomId] failed -- declined, or abandoned. */ - suspend fun wasNotSigned(database: GizaDatabase, chatRoomId: String, request: Event): Boolean { - val certificateId = certificateIdFor(chatRoomId, request) - val sessions = database.frostSigningSessionDao().getSessionsForChatRoom(chatRoomId) - .filter { session -> database.frostSigningSessionDao().getItems(session.id).any { it.eventId == certificateId } } - return sessions.isNotEmpty() && sessions.all { it.stage == FrostSigningStage.FAILED } - } - - /** - * The requests in [chatRoomId] still waiting for somebody to put them to the - * group: no certificate for the wallet, and no session running over one. - */ - suspend fun awaitingSponsor(database: GizaDatabase, chatRoomId: String): List { - val certified = certificatesOf(database, chatRoomId).map { it.walletId }.toSet() - return requestsIn(database, chatRoomId) - .filter { it.reading.walletId !in certified } - .filter { openSessionFor(database, chatRoomId, it.request) == null } - } - - /** - * Why [chatRoomId], signing as [thresholdPublicKey], should not sign a - * proposed member wallet [certificate] -- or null when it may. - * - * The check every signer makes before agreeing to guard a member's wallet, - * refused before anything is shown, for the reason a mismatched id is: - * - * - it is not exactly the certificate the request it carries asks for, or - * the request does not check out, or it asked another group; - * - the person asking is not a member of this room; - * - its guardians are not the ones this group grants: `SubgroupManager.grantFor` - * with the wallet's id in a child room's place -- the same list a guarded - * subgroup of this group would get. A coordinator who slipped a key in, - * dropped an ancestor or reordered the leaves is refused here. - * - * The group's own wallet policy decides only which keys the grant carries. - * It never refuses a member's wallet: an unguarded group guards its members - * with its own key alone. `docs/member-guarded-wallets.md`, Phase 7. - * - * The group's *member-wallet* policy decides whether it guards one at all, - * and the delay on its own leaf: [judgePolicy], `docs/member-wallet-delay.md`. - */ - suspend fun refuseCertificate( - database: GizaDatabase, - chatRoomId: String, - thresholdPublicKey: HexKey, - certificate: Event, - ): String? { - val verified = MemberWalletCertificateEvent.verify(certificate, chatRoomId, signed = false) - ?: return "is not a certificate this group could have been asked for" - - val member = database.participantDao().findParticipantsByChatRoomId(chatRoomId) - .any { it.participantPublicKey.equals(verified.memberPublicKey, ignoreCase = true) } - if (!member) return "was asked by somebody who is not a member" - - val delay = when (val judged = judgePolicy(database, chatRoomId, verified.request)) { - is PolicyJudgement.Refused -> return judged.reason - is PolicyJudgement.At -> judged.delay - } - - val expected = runCatching { SubgroupManager.grantFor(database, chatRoomId, thresholdPublicKey, verified.walletId, delay) }.getOrNull() - ?: return "grants keys this device cannot check" - return if (verified.account.guardians == expected) null else "grants guardian keys this group does not" - } - - /** What a signer makes of the policy a request was built under: the delay to judge it at, or why not. */ - sealed interface PolicyJudgement { - data class At(val delay: Long) : PolicyJudgement - data class Refused(val reason: String, val why: Why) : PolicyJudgement - } - - /** Why a request's policy will not do, said as a reason the member's screen can name. */ - enum class Why { - /** Built before policies, or under none: the group never said it guards members' wallets. */ - NO_POLICY, - - /** It carries a policy, but not an open one the group signed. */ - NOT_THE_GROUPS, - - /** The group has a newer delay; the request was built under an older one. */ - DELAY_CHANGED, - - /** The group has since stopped guarding members' wallets. */ - CLOSED, - } - - /** - * The delay [chatRoomId]'s own leaf must have in the wallet [request] asks - * for, or why the request cannot be signed -- `docs/member-wallet-delay.md`, - * D6. `held` is this device's newest policy, `carried` the one the request - * was built under: - * - * - carried, an open policy the group signed, and nothing held newer: at - * its delay. Newer than what this device holds is fine -- the group - * signed it, and this device missed it; - * - carried, but a newer open one held: stale, *asked under a delay the - * group has since changed*; - * - carried, but a newer closed one held: stale, *the group has stopped*; - * - carried and not an open policy the group signed: refused; - * - none carried: refused. A request from before policies never asked for - * the delay the group chose, or of a group that chose to guard members. - * - * Read from the request, not the certificate, so the member's screen and a - * sponsor's device can ask it before there is a certificate to check. - */ - suspend fun judgePolicy(database: GizaDatabase, chatRoomId: String, request: Event): PolicyJudgement { - val reading = MemberWalletRequestEvent.read(request) - ?: return PolicyJudgement.Refused("is not a request this group could have been asked", Why.NOT_THE_GROUPS) - val carried = reading.policy - ?: return PolicyJudgement.Refused("does not say the group guards members' wallets", Why.NO_POLICY) - val open = MemberWalletPolicyEvent.verify(carried, chatRoomId) as? MemberWalletPolicyEvent.Policy.Open - ?: return PolicyJudgement.Refused("carries a policy this group did not sign open", Why.NOT_THE_GROUPS) - - val held = policyFor(database, chatRoomId) - if (held != null && MemberWalletPolicyEvent.ORDER.compare(held, open) > 0) { - return when (held) { - is MemberWalletPolicyEvent.Policy.Open -> - PolicyJudgement.Refused("was asked under a delay the group has since changed", Why.DELAY_CHANGED) - is MemberWalletPolicyEvent.Policy.Closed -> - PolicyJudgement.Refused("was asked of a group that has since stopped guarding members' wallets", Why.CLOSED) - } - } - return PolicyJudgement.At(open.delay) - } - - /** - * Puts [request] to [groupRoom]'s quorum, as [userPublicKey]: a signing - * session over the certificate the request determines, which this device's - * proposing counts as approving. Returns the session already running over it - * instead, when another signer got there first. - * - * @throws IllegalStateException when the wallet is already certified, or this - * device would refuse the certificate itself -- a quorum should never be asked - * for what the proposer's own device knows is wrong. - */ - suspend fun putToGroup(database: GizaDatabase, groupRoom: LocalChatRoom, userPublicKey: HexKey, request: Event): FrostSigningSession { - val chatRoomId = groupRoom.chatRoom.id - val reading = MemberWalletRequestEvent.verified(request)?.reading - ?: throw IllegalStateException("This request does not check out") - check(certificatesOf(database, chatRoomId).none { it.walletId == reading.walletId }) { "This group already guards that wallet" } - openSessionFor(database, chatRoomId, request)?.let { return it } - - val thresholdPublicKey = GroupWalletManager.thresholdKeyFor(database, chatRoomId) - ?: throw IllegalStateException("This group has no shared key to sign with") - val template = MemberWalletCertificateEvent.template(request) - val unsigned = Event(certificateIdFor(chatRoomId, request), chatRoomId.lowercase(), template.createdAt, template.kind, template.tags, template.content, "") - refuseCertificate(database, chatRoomId, thresholdPublicKey, unsigned)?.let { reason -> - throw IllegalStateException("This group would refuse it: it $reason") - } - - logger.i("Putting ${reading.memberPublicKey.take(8)}'s wallet ${reading.walletId.take(8)} to $chatRoomId") - return FrostSigningManager.proposeSigning( - database = database, - localChatRoom = groupRoom, - userPublicKey = userPublicKey, - kind = template.kind, - tags = template.tags, - content = template.content, - createdAt = template.createdAt, - ) - } - - // ---- Shown from the group, and from the person ----------------------- - - /** A member's wallet as the guarding group's page lists it: certified, or asked for and not yet put to the group. */ - data class GroupMemberWallet( - val walletId: String, - val ownerPublicKey: HexKey, - /** The member's profile name on this device, or null. */ - val ownerName: String?, - val label: String?, - val request: Event, - val isCertified: Boolean, - ) - - /** - * The member wallets [chatRoomId] guards, and the requests still waiting for - * a signer to put them to it -- the group's page's *Members' guarded - * wallets*, which is never mixed into its subgroups: a row there is a - * person, not a room. - */ - suspend fun memberWalletsOf(database: GizaDatabase, chatRoomId: String): List { - suspend fun nameOf(publicKey: HexKey) = database.profileDao().getProfileByPublicKey(publicKey)?.humanReadableNameOrPubkey() - val certified = certificatesOf(database, chatRoomId).map { - GroupMemberWallet(it.walletId, it.memberPublicKey, nameOf(it.memberPublicKey), it.label, it.request, isCertified = true) - } - val waiting = awaitingSponsor(database, chatRoomId).map { - GroupMemberWallet(it.reading.walletId, it.reading.memberPublicKey, nameOf(it.reading.memberPublicKey), it.reading.label, it.request, isCertified = false) - } - return certified + waiting - } - - /** - * Every guarded wallet of [ownerPublicKey]'s that a group [viewerPublicKey] - * is in on this device guards, as that group holds it -- the person's page's *Wallets your - * groups guard*. One entry per guarding group: a wallet guarded by a group - * and its parent, both here, is two ways in, each spending through its own - * leaf. - */ - suspend fun guardedByGroupsHere(database: GizaDatabase, viewerPublicKey: HexKey, ownerPublicKey: HexKey): List = - database.chatRoomDao().getChatRoomListByUserPublicKey(viewerPublicKey) - .filter { it.chatRoom.mlsGroupState != null } - .flatMap { room -> - val wallets = runCatching { GuardianManager.guardedWalletsOf(database, room.chatRoom.id) }.getOrDefault(emptyList()) - .filter { (it.subject as? GuardianManager.GuardedSubject.Member)?.ownerPublicKey.equals(ownerPublicKey, ignoreCase = true) } - if (wallets.isEmpty()) return@flatMap emptyList() - val canSpend = FrostSigningManager.canSign(database, room.chatRoom.id) - wallets.map { GuardedHere(it, room.chatRoom.subject?.takeIf { name -> name.isNotBlank() }, canSpend) } - } - - /** A member's wallet as one of the guarding groups on this device holds it. */ - data class GuardedHere( - val wallet: GuardianManager.GuardedWallet, - /** - * The holding group's room name here -- the group with a leaf in it, which - * is not always the one that directly guards it: that is - * `GuardedSubject.Member.guardianName`. - */ - val holderName: String?, - /** Whether this device holds a share of that group's key, and so can propose a spend through its leaf. */ - val canSpend: Boolean, - ) - - /** - * One of a member's wallets on their page, with every group here that holds - * a leaf in it -- `docs/member-wallet-guarding-group.md`, D7. The page used to - * draw a row per holder, so a wallet held by a group and its parent appeared - * twice, each row calling its holder the guardian. - */ - data class GuardedHereWallet( - val walletId: String, - val label: String?, - /** The group that directly guards it, as any holder here can name it, or null. */ - val guardianName: String?, - /** Where no holder can name it: a group it is known to sit below, or null. */ - val below: String?, - /** The groups here holding a leaf in it, nearest first. */ - val holders: List, - ) - - /** [rows] -- one per holding group, as [guardedByGroupsHere] gives them -- as one entry per wallet. */ - fun byWallet(rows: List): List = - rows.groupBy { it.wallet.descendantChatRoomId.lowercase() }.map { (_, held) -> - val holders = held.sortedBy { it.wallet.position } - val members = holders.mapNotNull { it.wallet.subject as? GuardianManager.GuardedSubject.Member } - GuardedHereWallet( - walletId = holders.first().wallet.descendantChatRoomId, - label = members.firstNotNullOfOrNull { it.label }, - guardianName = members.firstNotNullOfOrNull { it.guardianName }, - // The nearest holder's own child it sits under, or the holder - // itself: either is a group it is truly below. - below = holders.firstNotNullOfOrNull { holder -> - (holder.wallet.subject as? GuardianManager.GuardedSubject.Member)?.branchName ?: holder.holderName?.takeUnless { holder.wallet.isGuardedHere } - }, - holders = holders, - ) - } - - private suspend fun noticesIn(database: GizaDatabase, chatRoomId: String): List = - database.marmotInnerEventDao() - .getByChatRoomAndKinds(chatRoomId, listOf(GroupKeyNoticeEvent.KIND)) - .map { it.asEvent() } - - /** - * A stored inner event as the event it was, unsigned: an inner event's - * authority is the MLS frame it arrived in, not a signature, so `sig` is - * empty here as it is everywhere inner events are read back. - */ - internal fun MarmotInnerEvent.asEvent(): Event = - Event(id = id, pubKey = publicKey, createdAt = createdAt.epochSeconds, kind = kind, tags = tags, content = content, sig = "") - - /** - * Queues one inner event in [chatRoomId] for the outbound pipeline, the way - * every inner event is: a row, which `encryptAndSendMarmotInnerEvent` sends. - */ - internal suspend fun queue( - database: GizaDatabase, - chatRoomId: String, - userPublicKey: HexKey, - tags: Array>, - content: String, - kind: Int = GroupKeyNoticeEvent.KIND, - createdAt: Instant = Clock.System.now(), - ): HexKey { - val id = EventHasher.hashId(userPublicKey, createdAt.epochSeconds, kind, tags, content) - database.marmotInnerEventDao().upsert( - MarmotInnerEvent( - id = id, - publicKey = userPublicKey, - kind = kind, - createdAt = createdAt, - tags = tags, - content = content, - chatRoomId = chatRoomId, - ) - ) - return id - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/wallet/GroupKeyNoticeEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/wallet/GroupKeyNoticeEvent.kt deleted file mode 100644 index cfd24b1b..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/wallet/GroupKeyNoticeEvent.kt +++ /dev/null @@ -1,150 +0,0 @@ -package mobi.giza.compose.nostr.wallet - -import mobi.giza.compose.managers.GuardianDerivation -import mobi.giza.compose.managers.SharedKeyDerivation -import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent -import mobi.giza.compose.nostr.subgroup.tags.SubgroupBirthCertificateTag -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.Kind - -/** - * A member asking the group for its key, and a member answering -- the two - * things a guarded wallet's grant is worked out from. - * - * A member's guarded wallet carries the group's leaf and its ancestors' leaves, - * and the member's own device works them out before it asks the group to guard - * anything: `GuardianDerivation.grant` over the group's threshold key and the - * guardian keys in the group's own birth certificate. Both are read off the - * group's verified key state, which only ceremony participants hold. A member - * welcomed later has neither. See `docs/member-guarded-wallets.md`, D4. - * - * ``` - * member without a key state --[ 30336, no content ]-> the room "what does this group sign with?" - * member holding one --[ 30336, the key + its cert ]-> the room - * the asking device checks the answer on its own - * ``` - * - * ### Nothing the answerer says is taken on its word - * - * The answer carries the threshold key, the path, and the certificate if the - * group has one, and every one of them checks itself: the key at the path - * rederives the room's id, and the certificate certifies that room and names - * that key. A forged answer cannot name another key, and one that leaves out or - * swaps the certificate gives a grant every signer refuses, because each signer - * works the grant out again from its own key state. - * - * The signed key state itself is not carried: its row keeps what it said and not - * the event, and nothing in it is needed beyond what checks itself. - * - * ### The group's policy on members' wallets, too - * - * An answer also carries, whole, the newest `MemberWalletPolicyEvent` the - * answering device holds -- the other thing a late member needs before asking - * for a wallet, and one MLS will not let them read from before their welcome. - * It checks itself as well: the group's own room signed it. See - * `docs/member-wallet-delay.md`, Phase 3. - * - * ### Never filed as key state - * - * An answer is read in one place, for one purpose, every time it is used. Filing - * it into `GroupKeyState` would give every late member a key state and quietly - * change what `GroupWalletManager.thresholdKeyFor` answers for them across the - * app. - * - * ### Why 30336 - * - * After the member wallet's certificate (30334) and request (30335). - */ -object GroupKeyNoticeEvent { - val KIND: Kind = 30336 - - private const val ROOM_TAG = "h" - private const val REQUEST_TAG = "e" - private const val PATH_TAG = "frost_path" - private const val POLICY_TAG = "member_wallet_policy" - - /** What a group signs with, as a member's device has checked it. */ - data class GroupKey( - val chatRoomId: String, - val thresholdPublicKey: HexKey, - /** The group's own birth certificate, or null for a group nobody's subgroup. */ - val certificate: Event?, - /** - * The group's newest policy on its members' wallets as the answer carried - * it, verified, or null when the answering device held none. Never read - * off a key state: `MemberWalletManager.policyFor` reads the group's own. - */ - val policy: MemberWalletPolicyEvent.Policy? = null, - ) { - /** The guardian keys the group's certificate grants it, nearest first: what it passes down. */ - val guardians: List - get() = certificate?.let { SubgroupBirthCertificateEvent.parseGuardians(it.tags) }.orEmpty() - } - - /** The asking shape's tags. */ - fun askingTags(chatRoomId: String): Array> = arrayOf(arrayOf(ROOM_TAG, chatRoomId)) - - /** The answering shape's tags, answering [requestId]. The content is [GroupKey.thresholdPublicKey]. */ - fun answeringTags(requestId: HexKey, groupKey: GroupKey, path: List): Array> = - listOfNotNull( - arrayOf(ROOM_TAG, groupKey.chatRoomId), - arrayOf(REQUEST_TAG, requestId), - arrayOf(PATH_TAG, SharedKeyDerivation.formatPath(path)), - groupKey.certificate?.let { SubgroupBirthCertificateTag.assemble(it) }, - groupKey.policy?.let { arrayOf(POLICY_TAG, it.event.toJson()) }, - ).toTypedArray() - - /** Whether [event] asks rather than answers. */ - fun isAsking(event: Event): Boolean = event.kind == KIND && event.content.isBlank() - - /** The asking notice [event] answers, or null when it answers none. */ - fun answers(event: Event): HexKey? = - event.takeIf { it.kind == KIND && it.content.isNotBlank() }?.tags - ?.firstOrNull { it.size >= 2 && it[0] == REQUEST_TAG }?.get(1) - - /** - * The key [event] says [chatRoomId] signs with, or null when it is not an - * answer or does not check out: - * - * 1. it is an answer, and names [chatRoomId]; - * 2. the key at the path it names rederives [chatRoomId]; - * 3. a certificate it carries certifies [chatRoomId], names that key, and - * reads -- its guardian keys and its wallet policy both. One present and - * unreadable is refused rather than read as none, for the reason - * `GroupKeyStateManager.stateFrom` refuses it; - * 4. a member-wallet policy it carries is [chatRoomId]'s own, signed by - * the room. The same rule: present and unreadable is not "no policy". - */ - fun read(event: Event, chatRoomId: String): GroupKey? = runCatching { - if (event.kind != KIND || event.content.isBlank()) return null - fun value(name: String): String? = event.tags.firstOrNull { it.size >= 2 && it[0] == name }?.get(1) - if (!value(ROOM_TAG).equals(chatRoomId, ignoreCase = true)) return null - - val thresholdPublicKey = event.content.trim().lowercase() - val path = value(PATH_TAG)?.let { SharedKeyDerivation.parsePathString(it) } ?: return null - if (!SharedKeyDerivation.marmotGroupId(thresholdPublicKey, path).equals(chatRoomId, ignoreCase = true)) return null - - val certificateTags = event.tags.filter { it.isNotEmpty() && it[0] == SubgroupBirthCertificateTag.TAG_NAME } - if (certificateTags.size > 1) return null - val certificate = certificateTags.singleOrNull()?.let { tag -> - SubgroupBirthCertificateTag.parse(tag)?.certificate ?: return null - } - if (certificate != null) { - val parentChatRoomId = SubgroupBirthCertificateEvent.parseParentChatRoomId(certificate.tags) ?: return null - if (!SubgroupBirthCertificateEvent.certifies(certificate, chatRoomId, parentChatRoomId)) return null - if (!SubgroupBirthCertificateEvent.parseThresholdPublicKey(certificate.tags).equals(thresholdPublicKey, ignoreCase = true)) return null - SubgroupBirthCertificateEvent.parseGuardians(certificate.tags) ?: return null - SubgroupBirthCertificateEvent.parseWalletPolicy(certificate.tags) ?: return null - } - - val policyTags = event.tags.filter { it.isNotEmpty() && it[0] == POLICY_TAG } - if (policyTags.size > 1) return null - val policy = policyTags.singleOrNull()?.let { tag -> - val carried = tag.getOrNull(1)?.let { Event.fromJsonOrNull(it) } ?: return null - MemberWalletPolicyEvent.verify(carried, chatRoomId) ?: return null - } - - GroupKey(chatRoomId = chatRoomId.lowercase(), thresholdPublicKey = thresholdPublicKey, certificate = certificate, policy = policy) - }.getOrNull() -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/wallet/MemberWalletCertificateEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/wallet/MemberWalletCertificateEvent.kt deleted file mode 100644 index c1d6e3a6..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/wallet/MemberWalletCertificateEvent.kt +++ /dev/null @@ -1,158 +0,0 @@ -package mobi.giza.compose.nostr.wallet - -import mobi.giza.compose.managers.GroupWalletDerivation -import mobi.giza.compose.nostr.frost.GroupKeyStateEvent -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.Kind -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate - -/** - * A group saying it guards a wallet for one of its members: the group's - * signature over the member's request, and what every device opens the wallet - * on. - * - * ``` - * member --[ 30335 request, signed by them ]-> the group's room - * any signer --[ 30320 proposal over a 30334 ]-> the group's room - * ...a signing session... - * everyone holds the signed 30334 "this group guards W for this person" - * ``` - * - * ``` - * kind: 30334 - * pubkey: G set by the signing session - * created_at: the request's created_at so every sponsor proposes one event id - * content: W - * tags: - * ["d", W] - * ["p", ] - * ["wallet_key", ] - * ["chain", …] - * ["guardian", …] as in the request - * ["descriptor", …, "receive"] - * ["descriptor", …, "change"] - * ["label", …] if the request had one - * ["request", ] - * ``` - * - * ### Not a birth certificate - * - * A `SubgroupBirthCertificateEvent` says *this room is my child*, and every - * reader of 30329 assumes a room -- its `certifies` rederives one from the key, - * `SubgroupManager.subgroupsOf` lists one, the transcript announces one being - * born. A member's wallet is not a room, so it has its own kind and none of the - * lineage meaning. `docs/member-guarded-wallets.md`, "Should it be a birth - * certificate?". - * - * ### Built from the request and nothing else - * - * [template] is the only way a certificate is made, and [verify] checks one is - * exactly [template] of the request it carries. So the sponsor who puts a - * request to the group chooses nothing, two sponsors propose one event id, and - * no tag can say one thing in the request and another in the certificate. - * - * The request is embedded rather than looked up, as a guarded statement embeds - * its birth certificate: an ancestor who was never in the group's room can - * check that the member asked, from the group's signature alone. - * - * ### Never on a relay - * - * It carries an xpub. - * - * ### Why 30334 - * - * The first free number past the guarded-wallet notice (30333), which carries - * it upward to the groups above. - */ -object MemberWalletCertificateEvent { - val KIND: Kind = 30334 - - private const val D_TAG = "d" - private const val MEMBER_TAG = "p" - private const val REQUEST_TAG = "request" - - /** A certificate believed: who it guards a wallet for, and the wallet it opens. */ - data class Verified( - val certificate: Event, - val request: Event, - val groupChatRoomId: String, - val memberPublicKey: HexKey, - val walletId: String, - val label: String?, - /** The account the request rederived to, guardians and all. */ - val account: GroupWalletDerivation.Account, - ) - - /** - * The certificate [request] asks for: the request's own tags, minus the - * possession signature it already carries whole, under the wallet id. - */ - fun template(request: Event): EventTemplate<*> { - val reading = requireNotNull(MemberWalletRequestEvent.read(request)) { "not a request" } - val carried = request.tags.filterNot { it.isNotEmpty() && it[0] in setOf("h", "wallet", "possession") } - - return EventTemplate( - createdAt = request.createdAt, - kind = KIND, - tags = ( - listOf( - arrayOf(D_TAG, reading.walletId), - arrayOf(MEMBER_TAG, reading.memberPublicKey), - ) + carried + listOf(arrayOf(REQUEST_TAG, request.toJson())) - ).toTypedArray(), - content = reading.walletId, - ) - } - - /** The request [certificate] carries, or null. Nothing is verified here. */ - fun requestOf(certificate: Event): Event? = - certificate.tags.filter { it.size >= 2 && it[0] == REQUEST_TAG }.singleOrNull()?.let { Event.fromJsonOrNull(it[1]) } - - /** The member [certificate] names, or null. Nothing is verified here. */ - fun memberOf(certificate: Event): HexKey? = - certificate.tags.firstOrNull { it.size >= 2 && it[0] == MEMBER_TAG }?.get(1) - - /** - * [certificate] believed as [groupChatRoomId]'s, with no database: - * - * 1. it is a 30334, and the room signed it; - * 2. the request it carries is believed (`MemberWalletRequestEvent.verified`) - * and asked this room; - * 3. it is exactly [template] of that request -- every tag, the content and - * the time; - * 4. so its `p` is the member who asked. - * - * Whether the guardians are the ones the group grants is what the group's - * signers checked before signing. A reader trusts the group's quorum for - * that, and it is no new trust: that quorum can already take every coin. - * - * [signed] false is for a certificate still being proposed, which has no - * signature yet: everything else is checked, and its author has to be the - * room the session will sign as. - */ - fun verify(certificate: Event, groupChatRoomId: String, signed: Boolean = true): Verified? = runCatching { - if (certificate.kind != KIND) return null - if (signed && !GroupKeyStateEvent.isSignedByRoom(certificate, groupChatRoomId)) return null - if (!signed && !certificate.pubKey.equals(groupChatRoomId, ignoreCase = true)) return null - - val request = requestOf(certificate) ?: return null - val verified = MemberWalletRequestEvent.verified(request) ?: return null - if (!verified.reading.groupChatRoomId.equals(groupChatRoomId, ignoreCase = true)) return null - - val expected = template(request) - if (certificate.createdAt != expected.createdAt) return null - if (certificate.content != expected.content) return null - if (certificate.tags.map { it.toList() } != expected.tags.map { it.toList() }) return null - - Verified( - certificate = certificate, - request = request, - groupChatRoomId = groupChatRoomId.lowercase(), - memberPublicKey = verified.reading.memberPublicKey, - walletId = verified.reading.walletId, - label = verified.reading.label, - account = verified.account, - ) - }.getOrNull() -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/wallet/MemberWalletPolicyEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/wallet/MemberWalletPolicyEvent.kt deleted file mode 100644 index 3b5beeec..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/wallet/MemberWalletPolicyEvent.kt +++ /dev/null @@ -1,136 +0,0 @@ -package mobi.giza.compose.nostr.wallet - -import mobi.giza.compose.managers.GuardianDerivation -import mobi.giza.compose.nostr.frost.GroupKeyStateEvent -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.Kind -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import kotlin.time.Clock - -/** - * A group saying, with a quorum, whether it guards its members' wallets and at - * what delay -- `docs/member-wallet-delay.md`. - * - * ``` - * open: ["d", "member-wallets"], ["guardian_delay", ""] - * closed: ["d", "member-wallets"], ["closed"] - * ``` - * - * Signed by the group's own quorum in its own room, about its own leaf: the - * delay on the group's leaf in every wallet a member asks it to guard from now - * on. Every group above keeps the delay it chose for the group, as it does in a - * subgroup's wallet. - * - * ### The group's opt-in - * - * No policy means the group does not guard members' wallets. A closed one means - * it has stopped: no new member wallets until a newer open one. Closing never - * releases a wallet already guarded -- the group's leaf is in every one of its - * addresses -- and a later policy never changes one, since each wallet's delay - * is fixed in its certificate. - * - * ### Not the birth certificate - * - * The certificate is the parent's statement about the group, signed once at its - * birth, and a root group has none. This is the group's decision about its own - * leaf, which the group can change. See the note's *Where the delay should live*. - * - * ### Why 30337 - * - * After the key notice (30336), the last of the member-wallet kinds. - */ -object MemberWalletPolicyEvent { - val KIND: Kind = 30337 - - /** The `d` tag: one policy about members' wallets per group, the newest winning. */ - const val IDENTIFIER = "member-wallets" - - private const val D_TAG = "d" - private const val DELAY_TAG = "guardian_delay" - private const val CLOSED_TAG = "closed" - - /** The group guards members' wallets, its own leaf at [delay] blocks. */ - fun open(delay: Long, createdAt: Long = Clock.System.now().epochSeconds): EventTemplate<*> { - require(delay in GuardianDerivation.DELAY_RANGE) { - "a guardian's delay is ${GuardianDerivation.MIN_DELAY} to ${GuardianDerivation.MAX_DELAY} blocks, not $delay" - } - return EventTemplate( - createdAt = createdAt, - kind = KIND, - tags = arrayOf(arrayOf(D_TAG, IDENTIFIER), arrayOf(DELAY_TAG, delay.toString())), - content = "", - ) - } - - /** The group takes no new members' wallets. */ - fun closed(createdAt: Long = Clock.System.now().epochSeconds): EventTemplate<*> = EventTemplate( - createdAt = createdAt, - kind = KIND, - tags = arrayOf(arrayOf(D_TAG, IDENTIFIER), arrayOf(CLOSED_TAG)), - content = "", - ) - - /** What a policy says, as its group signed it. */ - sealed interface Policy { - val event: Event - val createdAt: Long get() = event.createdAt - - /** The group guards members' wallets, its own leaf at [delay] blocks. */ - data class Open(val delay: Long, override val event: Event) : Policy - - /** The group has stopped taking new members' wallets. */ - data class Closed(override val event: Event) : Policy - } - - /** - * [event] as [chatRoomId]'s policy, or null when it is not one: - * - * 1. the kind, and the `d` tag; - * 2. exactly one of a `guardian_delay` that reads and is in - * `GuardianDerivation.DELAY_RANGE`, or a bare `closed` -- a policy that - * says both, or neither, says nothing a device can act on; - * 3. signed by [chatRoomId] itself, which any device can check holding the - * room's id alone. - */ - fun verify(event: Event, chatRoomId: String): Policy? = runCatching { - val policy = read(event) ?: return null - if (!GroupKeyStateEvent.isSignedByRoom(event, chatRoomId)) return null - policy - }.getOrNull() - - /** - * What [event] says, by its shape alone -- checks 1 and 2 of [verify], and - * not the signature. For a proposal the group has not signed yet, which a - * signer reads before agreeing to it; anything that acts on a policy goes - * through [verify]. - */ - fun read(event: Event): Policy? = runCatching { - if (event.kind != KIND) return null - if (event.tags.count { it.size >= 2 && it[0] == D_TAG && it[1] == IDENTIFIER } != 1) return null - if (event.tags.any { it.isNotEmpty() && it[0] == D_TAG && (it.size < 2 || it[1] != IDENTIFIER) }) return null - - val delays = event.tags.filter { it.isNotEmpty() && it[0] == DELAY_TAG } - val closed = event.tags.filter { it.isNotEmpty() && it[0] == CLOSED_TAG } - val policy = when { - delays.size == 1 && closed.isEmpty() -> { - val delay = delays.single().getOrNull(1)?.toLongOrNull()?.takeIf { it in GuardianDerivation.DELAY_RANGE } - ?: return null - Policy.Open(delay, event) - } - delays.isEmpty() && closed.size == 1 -> Policy.Closed(event) - else -> return null - } - policy - }.getOrNull() - - /** - * The newest of [events] that is [chatRoomId]'s policy, open or closed -- - * by the group's own timestamp, the id breaking a tie, so two devices that - * read the same events in another order agree. - */ - fun newestAmong(events: List, chatRoomId: String): Policy? = - events.mapNotNull { verify(it, chatRoomId) }.maxWithOrNull(ORDER) - - /** The order policies are compared in: [newestAmong]'s, and the signers' staleness check. */ - val ORDER: Comparator = compareBy({ it.createdAt }, { it.event.id }) -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/wallet/MemberWalletRequestEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/wallet/MemberWalletRequestEvent.kt deleted file mode 100644 index 8c6ada34..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/wallet/MemberWalletRequestEvent.kt +++ /dev/null @@ -1,262 +0,0 @@ -package mobi.giza.compose.nostr.wallet - -import mobi.giza.compose.managers.GroupWalletDerivation -import mobi.giza.compose.managers.GuardianDerivation -import mobi.giza.compose.managers.MemberWalletDerivation -import mobi.giza.compose.nostr.frost.GroupKeyStateEvent -import mobi.giza.compose.nostr.subgroup.tags.GuardianTag -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.Kind -import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.ByteVector64 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.Crypto -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.PublicKey -import kotlin.time.Clock - -/** - * A member asking their group to guard a wallet only they can spend from. - * - * The member's device has already made the wallet's key, worked out every - * ancestor's leaf and both descriptors, and stored the key. This is the first - * thing that leaves the device, and it carries all of it, so the group signs off - * on a wallet the member has already built rather than one it builds for them. - * See `docs/member-guarded-wallets.md`, Phase 3. - * - * ``` - * kind: 30335 - * pubkey: - * content: - * tags: - * ["h", G] the group asked - * ["wallet", W] - * ["wallet_key", ] - * ["chain", "mainnet" | "signet" | …] - * ["guardian", , , , "12"] one per guardian, nearest first - * ["descriptor", tr(…,{…}), "receive"] - * ["descriptor", tr(…,{…}), "change"] - * ["label", "Savings"] optional - * ["possession", ] - * ``` - * - * ### Signed twice - * - * By the member's nostr key, so it is bound to who asked, and -- in the - * `possession` tag -- by the wallet key itself, over [possessionMessage], so the - * member is shown to hold the key they are asking about. Without the second, Bob - * could ask for a certificate on Alice's wallet key under his own name. - * - * `k` signs exactly that one message, under its own tagged hash. It is never an - * output key: the account step always tweaks it first. - * - * ### Carried whole - * - * An inner event is an unsigned rumor -- its authority is the MLS frame -- and the - * row it travels in keeps no signature. This one's signature has to survive the - * room, because the group's certificate embeds it for ancestors who were never - * in the room. So the room carries an inner event of this kind whose content is - * the signed request, whole, as a 30333 notice carries a statement: [carried]. - * - * ### Never on a relay - * - * It carries an xpub, which is every address and the whole balance. - * - * ### Why 30335 - * - * After the certificate it asks for, at 30334. - */ -object MemberWalletRequestEvent { - val KIND: Kind = 30335 - - private const val ROOM_TAG = "h" - private const val WALLET_TAG = "wallet" - private const val WALLET_KEY_TAG = "wallet_key" - private const val CHAIN_TAG = "chain" - private const val DESCRIPTOR_TAG = "descriptor" - private const val RECEIVE_MARKER = "receive" - private const val CHANGE_MARKER = "change" - private const val LABEL_TAG = "label" - private const val POSSESSION_TAG = "possession" - private const val POLICY_TAG = "member_wallet_policy" - - /** The tag of the possession signature's message. Frozen once a request carries one, `bennu/` prefix included. */ - private const val POSSESSION_HASH_TAG = "bennu/member-wallet/possession/v1" - - /** The longest label a request carries: a name for a wallet, not a note. */ - const val MAX_LABEL_LENGTH = 64 - - /** What a request says, read but not yet believed. [verified] is what believes it. */ - data class Reading( - val memberPublicKey: HexKey, - val groupChatRoomId: String, - val walletId: String, - val walletKey: PublicKey, - val chain: Chain, - val xpub: String, - val receiveDescriptor: String, - val changeDescriptor: String, - val guardians: List, - val label: String?, - val possession: ByteVector64, - /** - * The group's member-wallet policy the request was built under, whole and - * unverified -- or null for a request from before policies, which every - * signer now refuses and every reader of an old certificate still - * accepts. See `docs/member-wallet-delay.md`. - */ - val policy: Event? = null, - ) - - /** A request that checks out on everything a reader can check without the group's key. */ - data class Verified( - val request: Event, - val reading: Reading, - /** The account the request opens, rederived from the wallet key -- never what it said. */ - val account: GroupWalletDerivation.Account, - /** The open policy it was built under, verified as the group's own; null for a request from before policies. */ - val policy: MemberWalletPolicyEvent.Policy.Open? = null, - ) - - /** - * What `k` signs: the member, the group, the wallet key and the network -- - * everything that has to bind one key to one person in one group on one chain. - */ - fun possessionMessage(memberPublicKey: HexKey, groupChatRoomId: String, walletKey: PublicKey, chain: Chain): ByteVector32 = - Crypto.taggedHash( - memberPublicKey.lowercase().hexToByteArray() + - groupChatRoomId.lowercase().hexToByteArray() + - walletKey.value.toByteArray() + - chain.chainHash.value.toByteArray(), - POSSESSION_HASH_TAG, - ) - - /** - * The request for [account] -- opened under the wallet key [walletPrivateKey] - * holds -- of [groupChatRoomId], signed as the member [memberPrivateKey] holds. - */ - fun build( - memberPrivateKey: PrivateKey, - groupChatRoomId: String, - walletPrivateKey: PrivateKey, - account: GroupWalletDerivation.Account, - label: String?, - createdAt: Long = Clock.System.now().epochSeconds, - /** The group's open policy the grant was worked out under, carried whole. */ - policy: Event? = null, - ): Event { - val memberPublicKey = memberPrivateKey.xOnlyPublicKey().value.toHex() - val walletKey = walletPrivateKey.publicKey() - require(account.extendedPublicKey == MemberWalletDerivation.account(walletKey, account.chain, account.guardians).extendedPublicKey) { - "the account is not the wallet key's" - } - val possession = Crypto.signSchnorr(possessionMessage(memberPublicKey, groupChatRoomId, walletKey, account.chain), walletPrivateKey, null) - - val tags = listOfNotNull( - arrayOf(ROOM_TAG, groupChatRoomId.lowercase()), - arrayOf(WALLET_TAG, MemberWalletDerivation.walletId(walletKey)), - arrayOf(WALLET_KEY_TAG, walletKey.toString()), - arrayOf(CHAIN_TAG, GroupWalletStatementEvent.chainName(account.chain)), - *account.guardians.map(GuardianTag::assemble).toTypedArray(), - arrayOf(DESCRIPTOR_TAG, account.receiveDescriptor, RECEIVE_MARKER), - arrayOf(DESCRIPTOR_TAG, account.changeDescriptor, CHANGE_MARKER), - label?.trim()?.takeIf { it.isNotEmpty() }?.let { arrayOf(LABEL_TAG, it.take(MAX_LABEL_LENGTH)) }, - policy?.let { arrayOf(POLICY_TAG, it.toJson()) }, - arrayOf(POSSESSION_TAG, possession.toHex()), - ).toTypedArray() - - val id = EventHasher.hashId(memberPublicKey, createdAt, KIND, tags, account.xpub) - val sig = Crypto.signSchnorr(ByteVector32(id), memberPrivateKey, null) - return Event(id = id, pubKey = memberPublicKey, createdAt = createdAt, kind = KIND, tags = tags, content = account.xpub, sig = sig.toHex()) - } - - /** The request's fields, or null when any is missing, doubled or the wrong shape. Nothing is verified here. */ - fun read(event: Event): Reading? = runCatching { - if (event.kind != KIND) return null - fun single(name: String): String? = - event.tags.filter { it.isNotEmpty() && it[0] == name }.takeIf { it.size == 1 }?.single()?.takeIf { it.size >= 2 }?.get(1) - fun descriptor(marker: String): String? = - event.tags.filter { it.size >= 3 && it[0] == DESCRIPTOR_TAG && it[2] == marker }.singleOrNull()?.get(1) - - val labels = event.tags.filter { it.isNotEmpty() && it[0] == LABEL_TAG } - if (labels.size > 1) return null - val label = labels.singleOrNull()?.getOrNull(1)?.takeIf { it.isNotBlank() && it.length <= MAX_LABEL_LENGTH } - if (labels.isNotEmpty() && label == null) return null - - // Present and unreadable is not "built under no policy". - val policies = event.tags.filter { it.isNotEmpty() && it[0] == POLICY_TAG } - if (policies.size > 1) return null - val policy = policies.singleOrNull()?.let { tag -> tag.getOrNull(1)?.let { Event.fromJsonOrNull(it) } ?: return null } - - Reading( - memberPublicKey = event.pubKey.lowercase(), - groupChatRoomId = single(ROOM_TAG)?.lowercase() ?: return null, - walletId = single(WALLET_TAG)?.lowercase() ?: return null, - walletKey = single(WALLET_KEY_TAG)?.let { PublicKey.fromHex(it) }?.takeIf { it.isValid() } ?: return null, - chain = single(CHAIN_TAG)?.let(GroupWalletStatementEvent::chainNamed) ?: return null, - xpub = event.content.takeIf { it.isNotBlank() } ?: return null, - receiveDescriptor = descriptor(RECEIVE_MARKER) ?: return null, - changeDescriptor = descriptor(CHANGE_MARKER) ?: return null, - guardians = GuardianTag.parseAll(event.tags)?.takeIf { it.isNotEmpty() } ?: return null, - label = label, - possession = single(POSSESSION_TAG)?.let { ByteVector64(it) } ?: return null, - policy = policy, - ) - }.getOrNull() - - /** - * [event] believed, on everything a reader can check without the group's key: - * - * 1. it is a request, signed by the member it names; - * 2. its wallet id is the wallet key's; - * 3. the wallet key signed the possession message; - * 4. its nearest guardian is the group it asks, so a request cannot leave - * out the one group it is asking; - * 5. the wallet key, under those guardians, rederives the xpub and both - * descriptors byte for byte; - * 6. a policy it carries is an open one the group it asks signed, and its - * nearest guardian's delay is that policy's -- `docs/member-wallet-delay.md`. - * A request carrying none still reads: certificates signed before - * policies embed one, and their wallets are guarded all the same. That - * a *new* request must carry one is the signers' rule, not a reader's. - * - * Whether the guardians are the ones the group grants is not here: only a - * device holding the group's key can say, and the group's signers do. - */ - fun verified(event: Event): Verified? = runCatching { - val reading = read(event) ?: return null - if (!GroupKeyStateEvent.isSignedByRoom(event, reading.memberPublicKey)) return null - if (MemberWalletDerivation.walletId(reading.walletKey) != reading.walletId) return null - - val message = possessionMessage(reading.memberPublicKey, reading.groupChatRoomId, reading.walletKey, reading.chain) - if (!Crypto.verifySignatureSchnorr(message, reading.possession, reading.walletKey.xOnly())) return null - - if (!reading.guardians.first().chatRoomId.equals(reading.groupChatRoomId, ignoreCase = true)) return null - - val account = MemberWalletDerivation.account(reading.walletKey, reading.chain, reading.guardians) - if (account.xpub != reading.xpub || account.receiveDescriptor != reading.receiveDescriptor || account.changeDescriptor != reading.changeDescriptor) return null - - val policy = reading.policy?.let { carried -> - val open = MemberWalletPolicyEvent.verify(carried, reading.groupChatRoomId) as? MemberWalletPolicyEvent.Policy.Open ?: return null - if (reading.guardians.first().delay != open.delay) return null - open - } - - Verified(request = event, reading = reading, account = account, policy = policy) - }.getOrNull() - - /** - * The signed request an inner event of this kind carries -- or null when its - * content is not one, or was sent by somebody other than the member who - * signed it. A request is passed on by nobody: whoever puts it in the room - * is the one asking. - */ - fun carried(inner: Event): Event? { - if (inner.kind != KIND) return null - val request = Event.fromJsonOrNull(inner.content)?.takeIf { it.kind == KIND } ?: return null - return request.takeIf { it.pubKey.equals(inner.pubKey, ignoreCase = true) } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/MemberWalletRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/MemberWalletRepository.kt deleted file mode 100644 index b67a2561..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/MemberWalletRepository.kt +++ /dev/null @@ -1,115 +0,0 @@ -package mobi.giza.compose.repository - -import mobi.giza.compose.nostr.wallet.MemberWalletPolicyEvent -import mobi.giza.compose.database.model.FrostSigningSession -import mobi.giza.compose.database.model.MemberWallet -import mobi.giza.compose.managers.GuardianManager -import com.vitorpamplona.quartz.nip01Core.core.Event -import mobi.giza.compose.database.model.MemberWalletSpend -import fr.acinq.bitcoin.Transaction -import fr.acinq.bitcoin.psbt.Psbt -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.flowOf -import kotlin.time.Instant -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.managers.MemberWalletManager -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.Chain - -/** - * A member's guarded wallets, for the screens: asking a group to guard one, and - * -- from the group's side -- the requests and certificates in a room. - * `docs/member-guarded-wallets.md`. The key-holding identity is the - * repository's, never the screen's: nothing above this layer touches a key. - */ -interface MemberWalletRepository { - /** The groups [ownerPublicKey] is in that could guard a wallet: Marmot rooms, whether or not their key is known yet. */ - suspend fun groupsOf(ownerPublicKey: HexKey): List - - /** Why [chatRoomId] cannot guard a wallet for the active profile on [chain], or null when it can. */ - suspend fun refusal(chatRoomId: String, chain: Chain): MemberWalletManager.Refusal? - - /** How many groups a wallet guarded by [chatRoomId] would be guarded by, or null while its key is unknown. */ - suspend fun reachOf(chatRoomId: String): Int? - - /** Each guardian's delay for a wallet [chatRoomId] would guard, nearest first, or null while its key is unknown. */ - suspend fun delaysOf(chatRoomId: String): List? - - /** Asks [chatRoomId] what it signs with, for a member who holds no key state. Whether it asked. */ - suspend fun askForGroupKey(chatRoomId: String): Boolean - - /** Makes the key, works out the leaves, stores the key, and asks [chatRoomId] to guard it. */ - suspend fun request(chatRoomId: String, chain: Chain, label: String?): MemberWallet - - /** Every guarded wallet of [ownerPublicKey]'s this device knows about, newest first. */ - suspend fun walletsOf(ownerPublicKey: HexKey): List - - /** One of them, or null. */ - suspend fun walletOf(ownerPublicKey: HexKey, walletId: String): MemberWalletManager.MemberWalletRow? - - /** Asks the group again, with the request the wallet was first asked with. */ - /** Asks again for [walletId]; returns the wallet now asked for, a new one when the old request would be refused. */ - suspend fun askAgain(walletId: String): String - - /** Forgets a wallet's key -- refused once a group guards it. */ - suspend fun discard(walletId: String) - - /** The wallet's receive and change descriptors with its private key in them, or null when the key is not here. */ - suspend fun exportKey(walletId: String): Pair? - - /** What [chatRoomId] is called on this device, or null when it has no room for it. */ - suspend fun roomName(chatRoomId: String): String? - - /** Signs [psbt] as [walletId]'s own key, files the spend, and returns the transaction to broadcast. */ - suspend fun signSpend(walletId: String, psbt: Psbt): Transaction - - /** Files what the chain said of a member's spend. */ - suspend fun recordChain(txid: String, confirmations: Int?, broadcastAt: Instant? = null) - - /** The spends the member signed from [walletId], newest first. */ - fun observeSpends(walletId: String): Flow> - - /** The member wallets [chatRoomId] guards, and the requests waiting for a signer to put them to it. */ - suspend fun memberWalletsOf(chatRoomId: String): List - - /** [chatRoomId]'s newest member-wallet policy this device holds, or null. See `MemberWalletManager.policyFor`. */ - suspend fun policyOf(chatRoomId: String): MemberWalletPolicyEvent.Policy? - - /** Whether [chatRoomId] is a group that could guard a member's wallet -- not a direct chat. See `MemberWalletManager.couldGuard`. */ - suspend fun couldGuard(chatRoomId: String): Boolean - - /** Puts a member's request to [chatRoomId]'s quorum as the active profile, which counts as its approval. */ - suspend fun putToGroup(chatRoomId: String, request: Event): FrostSigningSession - - /** Every wallet of [ownerPublicKey]'s a group the active profile is in guards. */ - suspend fun guardedByGroupsHere(ownerPublicKey: HexKey): List - - companion object { - val NO_OP = object : MemberWalletRepository { - override suspend fun groupsOf(ownerPublicKey: HexKey): List = emptyList() - override suspend fun refusal(chatRoomId: String, chain: Chain): MemberWalletManager.Refusal? = MemberWalletManager.Refusal.CANNOT_SIGN - override suspend fun reachOf(chatRoomId: String): Int? = null - - override suspend fun delaysOf(chatRoomId: String): List? = null - override suspend fun askForGroupKey(chatRoomId: String): Boolean = false - override suspend fun request(chatRoomId: String, chain: Chain, label: String?): MemberWallet = - throw UnsupportedOperationException("no repository") - override suspend fun walletsOf(ownerPublicKey: HexKey): List = emptyList() - override suspend fun walletOf(ownerPublicKey: HexKey, walletId: String): MemberWalletManager.MemberWalletRow? = null - override suspend fun askAgain(walletId: String): String = walletId - override suspend fun discard(walletId: String) = Unit - override suspend fun exportKey(walletId: String): Pair? = null - override suspend fun roomName(chatRoomId: String): String? = null - override suspend fun signSpend(walletId: String, psbt: Psbt): Transaction = throw UnsupportedOperationException("no repository") - override suspend fun recordChain(txid: String, confirmations: Int?, broadcastAt: Instant?) = Unit - override fun observeSpends(walletId: String): Flow> = flowOf(emptyList()) - override suspend fun memberWalletsOf(chatRoomId: String): List = emptyList() - - override suspend fun policyOf(chatRoomId: String): MemberWalletPolicyEvent.Policy? = null - - override suspend fun couldGuard(chatRoomId: String): Boolean = false - override suspend fun putToGroup(chatRoomId: String, request: Event): FrostSigningSession = throw UnsupportedOperationException("no repository") - override suspend fun guardedByGroupsHere(ownerPublicKey: HexKey): List = emptyList() - } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt index 116691c2..4bcf3bb2 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt @@ -1,19 +1,15 @@ package mobi.giza.compose.text -import mobi.giza.compose.nostr.wallet.MemberWalletPolicyEvent import mobi.giza.compose.nostr.subgroup.WalletPolicyReading import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey -import mobi.giza.compose.nostr.wallet.MemberWalletCertificateEvent -import mobi.giza.compose.nostr.wallet.MemberWalletRequestEvent import mobi.giza.compose.managers.SharedKeyDerivation import mobi.giza.compose.managers.WalletRefusal import mobi.giza.compose.nostr.RetiredKinds import mobi.giza.compose.nostr.frost.GroupKeyStateEvent import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import fr.acinq.bitcoin.Satoshi /** * An event a group is being asked to sign, said in words. @@ -109,50 +105,6 @@ object ProposedEvent { } ?: "A wallet statement this device cannot read" ) - // The group agreeing to guard one member's wallet. What a signer weighs - // is whose wallet, and what the group can do with it: take any coin that - // has sat for its leaf's delay, alongside every group above it after - // theirs, while only the member can spend before then. The keys are their device's to check. - // The group deciding whether it guards its members' wallets, and at what - // delay. A signer weighs the delay, and that it reaches only wallets - // asked for from now on; closing leaves every guarded wallet guarded. - // docs/member-wallet-delay.md. - MemberWalletPolicyEvent.KIND -> Summary( - label = "Members' guarded wallets", - detail = when (val policy = MemberWalletPolicyEvent.read(event)) { - is MemberWalletPolicyEvent.Policy.Open -> - "this group after ${BlockDuration.describe(policy.delay)} · for wallets asked for from now on" - is MemberWalletPolicyEvent.Policy.Closed -> - "no new ones · wallets already guarded stay guarded" - null -> "A policy this device cannot read" - } - ) - - MemberWalletCertificateEvent.KIND -> Summary( - label = "Guard a member's wallet", - detail = MemberWalletCertificateEvent.requestOf(event) - ?.let { MemberWalletRequestEvent.read(it) } - ?.let { reading -> - // Each guardian's own delay, nearest first: the group's own - // leaf, and every group above it at the delay it chose. - // docs/guardian-delay.md. - val delays = reading.guardians.map { BlockDuration.describe(it.delay) } - val reach = when (delays.size) { - 1 -> "this group can take its coins after ${delays[0]}" - 2 -> "this group can take its coins after ${delays[0]}, and the one above it after ${delays[1]}" - else -> "this group can take its coins after ${delays[0]}, and the ${delays.size - 1} above it after ${delays.drop(1).joinToString(", ")}" - } - listOfNotNull( - nameOf(reading.memberPublicKey)?.let { "For @$it" }, - reading.label, - "on ${GroupWalletStatementEvent.chainName(reading.chain)}", - reach, - "only the member can spend from it before then", - ).joinToString(" · ") - } - ?: "A member wallet this device cannot read" - ) - // A Bennu wallet's: declined on arrival, and said as what it is rather than // as a number. docs/giza-wallet-removal.md. in RetiredKinds.WALLET, in RetiredKinds.GROUP_LIGHTNING -> diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberSendScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberSendScreen.kt deleted file mode 100644 index d6e8fe6c..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberSendScreen.kt +++ /dev/null @@ -1,154 +0,0 @@ -package mobi.giza.compose.ui.composable - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.AccountBalanceWallet -import androidx.compose.material.icons.filled.Send -import androidx.compose.material3.Button -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextOverflow -import androidx.lifecycle.viewmodel.compose.viewModel -import mobi.giza.compose.resources.Res -import mobi.giza.compose.resources.couldn_t_send -import mobi.giza.compose.resources.send_from_your_guarded_wallet -import mobi.giza.compose.resources.sending_from_this_wallet_needs_its_key_and_a_node -import mobi.giza.compose.resources.sent -import mobi.giza.compose.resources.sign_and_send -import mobi.giza.compose.resources.signed_by_you_alone_and_sent_at_once -import mobi.giza.compose.repository.MemberWalletRepository -import mobi.giza.compose.ui.composable.widgets.Decorative -import mobi.giza.compose.ui.composable.widgets.EmptyState -import mobi.giza.compose.ui.composable.widgets.ErrorState -import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator -import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState -import mobi.giza.compose.ui.composable.widgets.NavigateBackButton -import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition -import mobi.giza.compose.ui.composable.widgets.rememberNotifier -import mobi.giza.compose.ui.theme.readableContent -import mobi.giza.compose.ui.theme.spacing -import mobi.giza.compose.ui.view.model.MemberSendViewModel -import mobi.giza.compose.ui.view.state.MemberSendUIState -import mobi.giza.compose.wallet.GroupOnchainWallets -import mobi.giza.compose.wallet.GroupSpendBuilder -import mobi.giza.compose.wallet.GroupWalletRollout -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.Chain -import org.jetbrains.compose.resources.stringResource - -/** - * A spend from the member's own guarded wallet: the group's send form, and a - * button that signs with the member's key alone and sends. There is no quorum - * to stop a mistake after this, which the line above the button says. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun MemberSendScreen( - activeUserPublicKey: HexKey, - walletId: String, - chain: Chain, - initialUIState: MemberSendUIState = MemberSendUIState.Loading, - memberWalletRepository: MemberWalletRepository, - wallets: GroupOnchainWallets, - onNavigateBack: () -> Unit, -) { - val viewModel: MemberSendViewModel = viewModel( - factory = MemberSendViewModel.factory( - ownerPublicKey = activeUserPublicKey, - walletId = walletId, - chain = chain, - initialUIState = initialUIState, - memberWalletRepository = memberWalletRepository, - wallets = wallets, - ) - ) - - LaunchedEffect(true) { - if (initialUIState == MemberSendUIState.Loading) viewModel.initiate() - } - - // The caller's scope, so "sent" outlives the screen going back. - val notify = rememberNotifier(rememberCoroutineScope()) - val sent = stringResource(Res.string.sent) - val couldNotSend = stringResource(Res.string.couldn_t_send) - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { Text(stringResource(Res.string.send_from_your_guarded_wallet), maxLines = 1, overflow = TextOverflow.Ellipsis) }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - } - ) { padding -> - ScreenStateTransition(viewModel.uiState) { uiState -> - when (val state = uiState) { - // Nothing to retry: the wallet came from a navigation argument. - is MemberSendUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = state.message, onRetry = null) - - MemberSendUIState.Loading -> LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding)) - - MemberSendUIState.Unavailable -> EmptyState( - modifier = Modifier.padding(padding).readableContent(), - message = stringResource(Res.string.sending_from_this_wallet_needs_its_key_and_a_node), - icon = Icons.Default.AccountBalanceWallet, - ) - - is MemberSendUIState.Ready -> Column( - modifier = Modifier.padding(padding).readableContent().fillMaxSize() - .verticalScroll(rememberScrollState()) - .padding(MaterialTheme.spacing.screenMargin), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - ) { - val preview = viewModel.preview() - - SpendForm( - addressField = viewModel.addressField, - amountField = viewModel.amountField, - feerateField = viewModel.feerateField, - sendEverything = viewModel.sendEverything, - spendable = viewModel.spendable(), - cap = GroupWalletRollout.memberCapFor(chain), - preview = preview, - amountProblem = preview?.takeIf { viewModel.isAboutTheAmount(it) }, - coinsKnown = state.walletState != null, - chain = chain, - ownWallet = true, - ) - - Text( - text = stringResource(Res.string.signed_by_you_alone_and_sent_at_once), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - - Button( - enabled = preview is GroupSpendBuilder.Result.Built && !viewModel.isActionPending.value, - onClick = { viewModel.send(onSent = { notify(sent); onNavigateBack() }, onFailure = { notify(couldNotSend) }) }, - ) { - Icon(Icons.Default.Send, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.sign_and_send)) - } - } - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberWalletItems.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberWalletItems.kt deleted file mode 100644 index 94045841..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberWalletItems.kt +++ /dev/null @@ -1,112 +0,0 @@ -package mobi.giza.compose.ui.composable - -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.lazy.LazyListScope -import androidx.compose.foundation.lazy.items -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.AccountBalanceWallet -import androidx.compose.material.icons.filled.Add -import androidx.compose.material3.Icon -import androidx.compose.material3.ListItem -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.minimumInteractiveComponentSize -import androidx.compose.runtime.Composable -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextOverflow -import mobi.giza.compose.resources.Res -import mobi.giza.compose.resources.a_group -import mobi.giza.compose.resources.balance_not_known_yet -import mobi.giza.compose.resources.guarded_wallets -import mobi.giza.compose.resources.key_on_another_device -import mobi.giza.compose.resources.new_guarded_wallet -import mobi.giza.compose.resources.s_did_not_sign -import mobi.giza.compose.resources.s_dot_s -import mobi.giza.compose.resources.s_is_signing -import mobi.giza.compose.resources.s_sats -import mobi.giza.compose.resources.waiting_for_someone_in_s_to_put_it_to_the_group -import mobi.giza.compose.resources.you_have_no_guarded_wallets -import mobi.giza.compose.resources.you_re_no_longer_in_s -import mobi.giza.compose.managers.MemberWalletManager -import mobi.giza.compose.text.grouped -import mobi.giza.compose.ui.composable.widgets.Decorative -import mobi.giza.compose.ui.composable.widgets.EmptyState -import mobi.giza.compose.ui.theme.spacing -import mobi.giza.compose.ui.view.model.MemberWalletsViewModel -import org.jetbrains.compose.resources.stringResource - -/** - * A member's guarded wallets, on their own profile: one row per wallet, named - * for the group that guards it, and the way to ask for another. - * `docs/member-guarded-wallets.md`, Phase 8. - * - * Never published. A profile's kind 0 is public, and a member wallet's xpub - * never leaves an encryption. - */ -fun LazyListScope.memberWalletItems( - rows: List?, - onOpen: (walletId: String) -> Unit, - onNew: (() -> Unit)?, -) { - item { - Text( - modifier = Modifier.fillMaxWidth(), - text = stringResource(Res.string.guarded_wallets), - style = MaterialTheme.typography.titleMedium, - ) - } - - when { - rows == null -> Unit - rows.isEmpty() -> item { EmptyState(message = stringResource(Res.string.you_have_no_guarded_wallets), icon = Icons.Default.AccountBalanceWallet) } - else -> items(rows, key = { "member-wallet-" + it.wallet.walletId }) { row -> - ListItem( - modifier = Modifier.clickable { onOpen(row.wallet.walletId) }.minimumInteractiveComponentSize(), - leadingContent = { Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) }, - headlineContent = { - val group = groupNameOf(row.wallet) - Text( - text = row.wallet.label?.let { stringResource(Res.string.s_dot_s, group, it) } ?: group, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - }, - supportingContent = { Text(supportingLine(row)) }, - ) - } - } - - onNew?.let { new -> - item { - TextButton(onClick = new) { - Icon(Icons.Default.Add, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.new_guarded_wallet)) - } - } - } -} - -/** The guarding group as the member's rows name it: the room's name here, or a generic one. */ -@Composable -internal fun groupNameOf(wallet: MemberWalletManager.MemberWalletRow): String = - wallet.groupRoom?.chatRoom?.subject?.takeIf { it.isNotBlank() } ?: stringResource(Res.string.a_group) - -@Composable -private fun supportingLine(row: MemberWalletsViewModel.Row): String { - val group = groupNameOf(row.wallet) - if (!row.wallet.isMember) return stringResource(Res.string.you_re_no_longer_in_s, group) - val balance = row.walletState?.let { stringResource(Res.string.s_sats, it.confirmedBalance.grouped()) } - ?: stringResource(Res.string.balance_not_known_yet) - return when (row.wallet.state) { - MemberWalletManager.WalletState.ASKED -> stringResource(Res.string.waiting_for_someone_in_s_to_put_it_to_the_group, group) - MemberWalletManager.WalletState.SIGNING -> stringResource(Res.string.s_is_signing, group) - MemberWalletManager.WalletState.NOT_SIGNED -> stringResource(Res.string.s_did_not_sign, group) - MemberWalletManager.WalletState.OPEN -> balance - MemberWalletManager.WalletState.WATCH_ONLY -> stringResource(Res.string.s_dot_s, balance, stringResource(Res.string.key_on_another_device)) - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberWalletPolicyScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberWalletPolicyScreen.kt deleted file mode 100644 index 1a12c42a..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberWalletPolicyScreen.kt +++ /dev/null @@ -1,229 +0,0 @@ -package mobi.giza.compose.ui.composable - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.AlertDialog -import androidx.compose.material3.Button -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedButton -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.setValue -import androidx.compose.ui.Modifier -import androidx.lifecycle.viewmodel.compose.viewModel -import mobi.giza.compose.resources.Res -import mobi.giza.compose.resources.a_coin_the_member_moves_starts_waiting_again -import mobi.giza.compose.resources.after_s -import mobi.giza.compose.resources.ask_the_group -import mobi.giza.compose.resources.cancel -import mobi.giza.compose.resources.couldn_t_ask_the_group -import mobi.giza.compose.resources.doesn_t_guard_members_wallets -import mobi.giza.compose.resources.guards_members_wallets -import mobi.giza.compose.resources.how_long_before_this_group_can_take_a_member_s_coin -import mobi.giza.compose.resources.members_guarded_wallets -import mobi.giza.compose.resources.members_on_older_apps_can_only_be_guarded_at_12 -import mobi.giza.compose.resources.stop -import mobi.giza.compose.resources.stop_guarding_new_members_wallets_question -import mobi.giza.compose.resources.stop_guarding_new_wallets -import mobi.giza.compose.resources.stopped_guarding_new_members_wallets -import mobi.giza.compose.resources.wallets_already_guarded_keep_their_delay -import mobi.giza.compose.resources.wallets_already_guarded_stay_guarded -import mobi.giza.compose.nostr.wallet.MemberWalletPolicyEvent -import mobi.giza.compose.repository.ChatRepository -import mobi.giza.compose.repository.FrostSigningRepository -import mobi.giza.compose.repository.MemberWalletRepository -import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute -import mobi.giza.compose.ui.composable.navigation.routes.Route -import mobi.giza.compose.ui.composable.widgets.ErrorState -import mobi.giza.compose.ui.composable.widgets.GuardianDelayChooser -import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator -import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState -import mobi.giza.compose.ui.composable.widgets.NavigateBackButton -import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition -import mobi.giza.compose.ui.composable.widgets.delayText -import mobi.giza.compose.ui.composable.widgets.rememberNotifier -import mobi.giza.compose.ui.theme.readableContent -import mobi.giza.compose.ui.theme.spacing -import mobi.giza.compose.ui.view.model.MemberWalletPolicyViewModel -import mobi.giza.compose.ui.view.state.MemberWalletPolicyUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import org.jetbrains.compose.resources.stringResource - -/** - * Whether the group guards its members' wallets, at what delay, and closing it - * again -- `docs/member-wallet-delay.md`, Phase 6. - * - * What a change reaches is said before the button: only wallets asked for from - * now on, never one already guarded, and closing releases nothing. A device - * that cannot sign sees where the group stands and nothing to press. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun MemberWalletPolicyScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - initialUIState: MemberWalletPolicyUIState = MemberWalletPolicyUIState.Loading, - chatRepository: ChatRepository, - memberWalletRepository: MemberWalletRepository, - frostSigningRepository: FrostSigningRepository, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val viewModel: MemberWalletPolicyViewModel = viewModel( - factory = MemberWalletPolicyViewModel.factory( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - initialUIState = initialUIState, - chatRepository = chatRepository, - memberWalletRepository = memberWalletRepository, - frostSigningRepository = frostSigningRepository, - ) - ) - - LaunchedEffect(chatRoomId) { - if (initialUIState == MemberWalletPolicyUIState.Loading) viewModel.initiate() - } - - // Read above the handlers, which are not composable; the caller's scope, so - // the message outlives the screen moving onto the signing session. - val notify = rememberNotifier(rememberCoroutineScope()) - val couldNotAsk = stringResource(Res.string.couldn_t_ask_the_group) - val toSession = { sessionId: String -> - onNavigateToRoute(FrostSigningRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, sessionId = sessionId)) - } - var confirmingClose by remember { mutableStateOf(false) } - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { Text(stringResource(Res.string.members_guarded_wallets)) }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - } - ) { padding -> - ScreenStateTransition(viewModel.uiState) { uiState -> - when (val state = uiState) { - MemberWalletPolicyUIState.Loading -> LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding)) - - is MemberWalletPolicyUIState.Error -> ErrorState( - modifier = Modifier.padding(padding), - message = state.message, - // Reloading reads the group again, which is what failed. - onRetry = viewModel::initiate, - ) - - is MemberWalletPolicyUIState.Loaded -> Column( - modifier = Modifier.padding(padding).readableContent().fillMaxSize() - .verticalScroll(rememberScrollState()) - .padding(MaterialTheme.spacing.screenMargin), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - ) { - MemberWalletPolicyState(state.policy) - - if (state.canSign) { - GuardianDelayChooser( - title = stringResource(Res.string.how_long_before_this_group_can_take_a_member_s_coin), - consequence = stringResource(Res.string.a_coin_the_member_moves_starts_waiting_again), - input = viewModel.delay.input.value, - delay = viewModel.delay.delay(), - isCustom = viewModel.delay.isCustom.value, - problem = viewModel.delay.problem(), - onPreset = viewModel.delay::pick, - onCustom = viewModel.delay::useCustom, - onInput = viewModel.delay::type, - ) - Text( - text = stringResource(Res.string.wallets_already_guarded_keep_their_delay), - style = MaterialTheme.typography.bodyMedium, - ) - Text( - text = stringResource(Res.string.members_on_older_apps_can_only_be_guarded_at_12), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - - // Disabled, with the reason, while there is nothing to ask: - // a delay out of range, or the one the group already has. - val problem = viewModel.openProblem() - Button( - onClick = { viewModel.proposeOpen(onSuccess = toSession, onFailure = { notify(couldNotAsk) }) }, - enabled = problem == null && !viewModel.isActionPending.value, - ) { Text(stringResource(Res.string.ask_the_group)) } - if (problem != null && viewModel.delay.problem() == null) { - Text(text = problem, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - } - - if (viewModel.canClose()) { - OutlinedButton( - onClick = { confirmingClose = true }, - enabled = !viewModel.isActionPending.value, - ) { Text(stringResource(Res.string.stop_guarding_new_wallets)) } - } - } - } - } - } - } - - if (confirmingClose) { - AlertDialog( - onDismissRequest = { confirmingClose = false }, - title = { Text(stringResource(Res.string.stop_guarding_new_members_wallets_question)) }, - // What closing leaves alone, said where it is decided: the group's leaf - // is in every address of every wallet it already guards. - text = { Text(stringResource(Res.string.wallets_already_guarded_stay_guarded)) }, - confirmButton = { - TextButton(onClick = { - confirmingClose = false - viewModel.proposeClose(onSuccess = toSession, onFailure = { notify(couldNotAsk) }) - }) { Text(stringResource(Res.string.stop)) } - }, - dismissButton = { - TextButton(onClick = { confirmingClose = false }) { Text(stringResource(Res.string.cancel)) } - }, - ) - } -} - -/** - * Where the group stands on its members' wallets: guarding them after a delay, - * never having said so, or having stopped. Shared with the group's page. - */ -@Composable -internal fun MemberWalletPolicyState(policy: MemberWalletPolicyEvent.Policy?) { - Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { - Text( - text = stringResource( - when (policy) { - is MemberWalletPolicyEvent.Policy.Open -> Res.string.guards_members_wallets - is MemberWalletPolicyEvent.Policy.Closed -> Res.string.stopped_guarding_new_members_wallets - null -> Res.string.doesn_t_guard_members_wallets - } - ), - style = MaterialTheme.typography.titleMedium, - ) - if (policy is MemberWalletPolicyEvent.Policy.Open) { - Text( - text = stringResource(Res.string.after_s, delayText(policy.delay)), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberWalletScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberWalletScreen.kt deleted file mode 100644 index 41ae51d5..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberWalletScreen.kt +++ /dev/null @@ -1,420 +0,0 @@ -package mobi.giza.compose.ui.composable - -import mobi.giza.compose.managers.MemberWalletManager -import mobi.giza.compose.resources.s_has_stopped_guarding_members_wallets_discard -import mobi.giza.compose.resources.s_has_changed_its_delay_since_you_asked -import mobi.giza.compose.resources.s_would_refuse_this_request_asked_before -import mobi.giza.compose.resources.s_would_refuse_this_request -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.text.selection.SelectionContainer -import androidx.compose.foundation.verticalScroll -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.ContentCopy -import androidx.compose.material.icons.filled.Key -import androidx.compose.material.icons.filled.Send -import androidx.compose.material3.Button -import androidx.compose.material3.AlertDialog -import androidx.compose.material3.Card -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Icon -import androidx.compose.material3.ListItem -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedButton -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.setValue -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalClipboardManager -import androidx.compose.ui.text.buildAnnotatedString -import androidx.compose.ui.text.style.TextOverflow -import androidx.lifecycle.viewmodel.compose.viewModel -import mobi.giza.compose.resources.Res -import mobi.giza.compose.resources.a_group -import mobi.giza.compose.resources.address_copied -import mobi.giza.compose.resources.ask_again -import mobi.giza.compose.resources.cancel -import mobi.giza.compose.resources.change_descriptor -import mobi.giza.compose.resources.close -import mobi.giza.compose.resources.coins -import mobi.giza.compose.resources.copied -import mobi.giza.compose.resources.copy_address -import mobi.giza.compose.resources.couldn_t_ask_again -import mobi.giza.compose.resources.couldn_t_discard_the_wallet -import mobi.giza.compose.resources.discard -import mobi.giza.compose.resources.discard_this_wallet_question -import mobi.giza.compose.resources.discarding_forgets_its_key -import mobi.giza.compose.resources.export_key -import mobi.giza.compose.resources.export_this_wallet_s_key_question -import mobi.giza.compose.resources.finding_your_coins -import mobi.giza.compose.resources.copy -import mobi.giza.compose.resources.send -import mobi.giza.compose.resources.guarded_by_s -import mobi.giza.compose.resources.guarded_wallet -import mobi.giza.compose.resources.if_you_lose_this_device_those_groups_can_still_move_your_coins -import mobi.giza.compose.resources.nothing_has_been_sent_to_this_wallet_yet -import mobi.giza.compose.resources.receive_address -import mobi.giza.compose.resources.receive_descriptor -import mobi.giza.compose.resources.s_did_not_sign -import mobi.giza.compose.resources.s_is_signing -import mobi.giza.compose.resources.s_took_s_sats_in_s -import mobi.giza.compose.resources.show_key -import mobi.giza.compose.resources.taken_by_guardians -import mobi.giza.compose.resources.the_key_of_this_wallet_is_on_another_device -import mobi.giza.compose.resources.waiting_for_someone_in_s_to_put_it_to_the_group -import mobi.giza.compose.resources.whoever_holds_these_descriptors_holds_the_coins -import mobi.giza.compose.resources.you_re_no_longer_in_s -import mobi.giza.compose.resources.your_spends -import mobi.giza.compose.resources.confirmed -import mobi.giza.compose.resources.in_the_mempool -import mobi.giza.compose.resources.sent_waiting_for_the_network -import mobi.giza.compose.managers.MemberWalletManager.WalletState -import mobi.giza.compose.repository.MemberWalletRepository -import mobi.giza.compose.text.grouped -import mobi.giza.compose.ui.composable.widgets.Decorative -import mobi.giza.compose.ui.composable.widgets.EmptyState -import mobi.giza.compose.ui.composable.widgets.ErrorState -import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator -import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState -import mobi.giza.compose.ui.composable.widgets.NavigateBackButton -import mobi.giza.compose.ui.composable.widgets.QRCodeView -import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition -import mobi.giza.compose.ui.composable.widgets.rememberNotifier -import mobi.giza.compose.ui.theme.readableContent -import mobi.giza.compose.ui.theme.spacing -import mobi.giza.compose.ui.view.model.MemberWalletViewModel -import mobi.giza.compose.ui.view.state.MemberWalletUIState -import mobi.giza.compose.wallet.GroupOnchainWallets -import mobi.giza.compose.wallet.bip21Uri -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import org.jetbrains.compose.resources.stringResource - -/** - * One of the member's guarded wallets. - * - * Before a group has certified it, where the asking has got to and the two - * things the member can do about it: ask again, or discard the key -- which is - * safe exactly then, because no address was ever offered. Once certified, the - * wallet itself: balance, the address to be paid at, the coins, and every coin - * a guardian took, read off the chain. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun MemberWalletScreen( - activeUserPublicKey: HexKey, - walletId: String, - initialUIState: MemberWalletUIState = MemberWalletUIState.Loading, - memberWalletRepository: MemberWalletRepository, - wallets: GroupOnchainWallets, - /** The send form for this wallet, or null where there is none to offer. */ - onSend: ((walletId: String) -> Unit)? = null, - onNavigateBack: () -> Unit, -) { - val viewModel: MemberWalletViewModel = viewModel( - factory = MemberWalletViewModel.factory( - ownerPublicKey = activeUserPublicKey, - walletId = walletId, - initialUIState = initialUIState, - memberWalletRepository = memberWalletRepository, - wallets = wallets, - ) - ) - - LaunchedEffect(true) { - if (initialUIState == MemberWalletUIState.Loading) viewModel.initiate() - } - - val notify = rememberNotifier(rememberCoroutineScope()) - val couldNotAskAgain = stringResource(Res.string.couldn_t_ask_again) - val couldNotDiscard = stringResource(Res.string.couldn_t_discard_the_wallet) - val addressCopied = stringResource(Res.string.address_copied) - val copied = stringResource(Res.string.copied) - val clipboardManager = LocalClipboardManager.current - - var confirmingDiscard by remember { mutableStateOf(false) } - var confirmingExport by remember { mutableStateOf(false) } - - val title = (viewModel.uiState as? MemberWalletUIState.Loaded)?.wallet?.label ?: stringResource(Res.string.guarded_wallet) - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { Text(title, maxLines = 1, overflow = TextOverflow.Ellipsis) }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - } - ) { padding -> - ScreenStateTransition(viewModel.uiState) { uiState -> - when (val state = uiState) { - MemberWalletUIState.Loading -> LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding)) - - // Nothing to retry: the wallet came from a navigation argument. - is MemberWalletUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = state.message, onRetry = null) - - is MemberWalletUIState.Loaded -> { - val wallet = state.wallet - val group = wallet.groupRoom?.chatRoom?.subject?.takeIf { it.isNotBlank() } ?: stringResource(Res.string.a_group) - val walletState = state.walletState - - LazyColumn( - modifier = Modifier.padding(padding).readableContent().fillMaxSize() - .padding(MaterialTheme.spacing.screenMargin), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - ) { - item { Text(stringResource(Res.string.guarded_by_s, group), style = MaterialTheme.typography.titleMedium) } - item { - Text( - reachText(group, state.delays, wallet.account.chain), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - if (!wallet.isMember) item { Text(stringResource(Res.string.you_re_no_longer_in_s, group)) } - - when (wallet.state) { - WalletState.ASKED, WalletState.SIGNING, WalletState.NOT_SIGNED -> { - item { - Text( - stringResource( - when (wallet.state) { - WalletState.SIGNING -> Res.string.s_is_signing - WalletState.NOT_SIGNED -> Res.string.s_did_not_sign - else -> Res.string.waiting_for_someone_in_s_to_put_it_to_the_group - }, - group, - ) - ) - } - // Why the group would refuse the request as it stands, said - // before the button that fixes it. docs/member-wallet-delay.md. - wallet.refusedBecause?.let { why -> - item { - Text( - stringResource( - when (why) { - MemberWalletManager.Why.NO_POLICY -> Res.string.s_would_refuse_this_request_asked_before - MemberWalletManager.Why.DELAY_CHANGED -> Res.string.s_has_changed_its_delay_since_you_asked - MemberWalletManager.Why.CLOSED -> Res.string.s_has_stopped_guarding_members_wallets_discard - MemberWalletManager.Why.NOT_THE_GROUPS -> Res.string.s_would_refuse_this_request - }, - group, - ), - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - // A closed group takes no new request, so asking again - // could only fail; discarding is what is left. - if (wallet.state != WalletState.SIGNING && wallet.refusedBecause != MemberWalletManager.Why.CLOSED) { - item { - OutlinedButton( - onClick = { viewModel.askAgain(onAsked = {}, onFailure = { notify(couldNotAskAgain) }) }, - enabled = !viewModel.isActionPending.value, - ) { Text(stringResource(Res.string.ask_again)) } - } - } - if (wallet.state != WalletState.SIGNING) { - item { - TextButton(onClick = { confirmingDiscard = true }, enabled = !viewModel.isActionPending.value) { - Text(stringResource(Res.string.discard)) - } - } - } - } - - WalletState.OPEN, WalletState.WATCH_ONLY -> { - item { BalanceCard(walletState) } - - if (wallet.state == WalletState.WATCH_ONLY) { - item { - Text( - stringResource(Res.string.the_key_of_this_wallet_is_on_another_device), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - - onSend?.takeIf { wallet.state == WalletState.OPEN }?.let { send -> - item { SendButton(onClick = { send(wallet.walletId) }) } - } - - when { - walletState?.receiveAddress == null -> item { - LoadingDataIndicator(fillScreen = false, text = stringResource(Res.string.finding_your_coins)) - } - - else -> { - val address = walletState.receiveAddress!! - item { - Card(modifier = Modifier.fillMaxWidth()) { - Column( - modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - ) { - Text(stringResource(Res.string.receive_address), style = MaterialTheme.typography.titleMedium) - QRCodeView(bip21Uri(address)) - SelectionContainer { Text(text = address, style = MaterialTheme.typography.bodyMedium) } - TextButton(onClick = { - clipboardManager.setText(buildAnnotatedString { append(address) }) - notify(addressCopied) - }) { - Icon(Icons.Default.ContentCopy, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.copy_address)) - } - } - } - } - - item { Text(stringResource(Res.string.coins), style = MaterialTheme.typography.titleMedium) } - if (walletState.utxos.isEmpty()) { - item { EmptyState(message = stringResource(Res.string.nothing_has_been_sent_to_this_wallet_yet)) } - } else { - items(walletState.utxos, key = { it.utxo.outPoint.toString() }) { utxo -> - CoinRow(utxo = utxo, confirmations = walletState.confirmations(utxo)) - } - } - } - } - - if (state.spends.isNotEmpty()) { - item { Text(stringResource(Res.string.your_spends), style = MaterialTheme.typography.titleMedium) } - items(state.spends, key = { "spend-" + it.txid }) { spend -> - ListItem( - headlineContent = { Text(spend.txid, maxLines = 1, overflow = TextOverflow.Ellipsis) }, - supportingContent = { - Text( - stringResource( - when { - spend.confirmedAt != null -> Res.string.confirmed - spend.seenAt != null -> Res.string.in_the_mempool - else -> Res.string.sent_waiting_for_the_network - } - ) - ) - }, - ) - } - } - - if (state.taken.isNotEmpty()) { - item { Text(stringResource(Res.string.taken_by_guardians), style = MaterialTheme.typography.titleMedium) } - items(state.taken, key = { "taken-" + it.txid + it.guardianName }) { line -> - ListItem( - headlineContent = { - Text(stringResource(Res.string.s_took_s_sats_in_s, line.guardianName ?: stringResource(Res.string.a_group), line.amount.grouped(), line.txid)) - } - ) - } - } - - if (wallet.state == WalletState.OPEN) { - item { - TextButton(onClick = { confirmingExport = true }) { - Icon(Icons.Default.Key, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.export_key)) - } - } - } - } - } - - item { - Text( - stringResource(Res.string.if_you_lose_this_device_those_groups_can_still_move_your_coins), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - } - } - } - } - - if (confirmingDiscard) { - AlertDialog( - onDismissRequest = { confirmingDiscard = false }, - title = { Text(stringResource(Res.string.discard_this_wallet_question)) }, - text = { Text(stringResource(Res.string.discarding_forgets_its_key)) }, - confirmButton = { - TextButton(onClick = { - confirmingDiscard = false - viewModel.discard(onDiscarded = onNavigateBack, onFailure = { notify(couldNotDiscard) }) - }) { Text(stringResource(Res.string.discard)) } - }, - dismissButton = { TextButton(onClick = { confirmingDiscard = false }) { Text(stringResource(Res.string.cancel)) } }, - ) - } - - if (confirmingExport) { - AlertDialog( - onDismissRequest = { confirmingExport = false }, - title = { Text(stringResource(Res.string.export_this_wallet_s_key_question)) }, - text = { Text(stringResource(Res.string.whoever_holds_these_descriptors_holds_the_coins)) }, - confirmButton = { - TextButton(onClick = { - confirmingExport = false - viewModel.exportKey() - }) { Text(stringResource(Res.string.show_key)) } - }, - dismissButton = { TextButton(onClick = { confirmingExport = false }) { Text(stringResource(Res.string.cancel)) } }, - ) - } - - viewModel.exported?.let { (receive, change) -> - AlertDialog( - onDismissRequest = viewModel::hideKey, - title = { Text(stringResource(Res.string.export_key)) }, - text = { - Column( - modifier = Modifier.verticalScroll(rememberScrollState()), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - ) { - listOf(Res.string.receive_descriptor to receive, Res.string.change_descriptor to change).forEach { (name, descriptor) -> - Text(stringResource(name), style = MaterialTheme.typography.titleSmall) - SelectionContainer { Text(descriptor, style = MaterialTheme.typography.bodySmall) } - TextButton(onClick = { - clipboardManager.setText(buildAnnotatedString { append(descriptor) }) - notify(copied) - }) { - Icon(Icons.Default.ContentCopy, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.copy)) - } - } - } - }, - confirmButton = { TextButton(onClick = viewModel::hideKey) { Text(stringResource(Res.string.close)) } }, - ) - } -} - -@Composable -private fun SendButton(onClick: () -> Unit) { - Button(onClick = onClick) { - Icon(Icons.Default.Send, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.send)) - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/NewMemberWalletScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/NewMemberWalletScreen.kt deleted file mode 100644 index b9941f72..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/NewMemberWalletScreen.kt +++ /dev/null @@ -1,248 +0,0 @@ -package mobi.giza.compose.ui.composable - -import mobi.giza.compose.resources.this_group_has_stopped_guarding_members_wallets -import mobi.giza.compose.resources.this_group_doesn_t_guard_members_wallets -import mobi.giza.compose.ui.composable.widgets.delayText -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.AccountBalanceWallet -import androidx.compose.material.icons.filled.Groups -import androidx.compose.material3.Button -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Icon -import androidx.compose.material3.ListItem -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar -import androidx.compose.material3.minimumInteractiveComponentSize -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextOverflow -import androidx.lifecycle.viewmodel.compose.viewModel -import mobi.giza.compose.resources.Res -import mobi.giza.compose.resources.a_group -import mobi.giza.compose.resources.a_wallet_only_you_can_spend_from_guarded_by_s -import mobi.giza.compose.resources.ask_s -import mobi.giza.compose.resources.ask_the_group_for_its_key -import mobi.giza.compose.resources.asked_for_the_group_s_key -import mobi.giza.compose.resources.asked_s_to_guard_a_wallet -import mobi.giza.compose.resources.choose_a_group_to_guard_it -import mobi.giza.compose.resources.couldn_t_ask_the_group_to_guard_a_wallet -import mobi.giza.compose.resources.if_you_lose_this_device_those_groups_can_still_move_your_coins -import mobi.giza.compose.resources.label_optional -import mobi.giza.compose.resources.member_wallets_are_not_offered_on_this_network -import mobi.giza.compose.resources.members_of_those_groups_will_see_this_wallet -import mobi.giza.compose.resources.new_guarded_wallet -import mobi.giza.compose.resources.only_a_group_can_guard_a_wallet -import mobi.giza.compose.resources.s_and_the_d_groups_above_it_can_take_any_coin_without_asking_you -import mobi.giza.compose.resources.s_and_the_group_above_it_can_take_any_coin_without_asking_you -import mobi.giza.compose.resources.s_can_take_any_coin_without_asking_you -import mobi.giza.compose.resources.this_device_does_not_know_what_this_group_signs_with -import mobi.giza.compose.resources.this_group_s_guardian_keys_can_t_be_read_to_guard_a_wallet -import mobi.giza.compose.resources.this_profile_cannot_sign_a_request -import mobi.giza.compose.resources.none_of_your_groups_guards_members_wallets_yet -import mobi.giza.compose.managers.MemberWalletManager -import mobi.giza.compose.repository.MemberWalletRepository -import mobi.giza.compose.ui.composable.widgets.Decorative -import mobi.giza.compose.ui.composable.widgets.EmptyState -import mobi.giza.compose.ui.composable.widgets.ErrorState -import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator -import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState -import mobi.giza.compose.ui.composable.widgets.NavigateBackButton -import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition -import mobi.giza.compose.ui.composable.widgets.rememberNotifier -import mobi.giza.compose.ui.theme.readableContent -import mobi.giza.compose.ui.theme.spacing -import mobi.giza.compose.ui.view.model.NewMemberWalletViewModel -import mobi.giza.compose.ui.view.state.NewMemberWalletUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.Chain -import org.jetbrains.compose.resources.stringResource - -/** - * Asking a group to guard a wallet only this member can spend from. - * - * A consent screen first and a form second: what the member gives up -- the - * groups that can take their coins, and see them -- is said before the one - * button, in the words `docs/member-guarded-wallets.md` uses. Nothing leaves the - * device until that button: the key is made, the leaves worked out and the key - * stored, and only then is the group asked. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun NewMemberWalletScreen( - activeUserPublicKey: HexKey, - chatRoomId: String?, - chain: Chain, - initialUIState: NewMemberWalletUIState = NewMemberWalletUIState.Loading, - memberWalletRepository: MemberWalletRepository, - onNavigateBack: () -> Unit, -) { - val viewModel: NewMemberWalletViewModel = viewModel( - factory = NewMemberWalletViewModel.factory( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - chain = chain, - initialUIState = initialUIState, - memberWalletRepository = memberWalletRepository, - ) - ) - - LaunchedEffect(true) { - if (initialUIState == NewMemberWalletUIState.Loading) viewModel.initiate() - } - - // Read above the handlers: the notifier and the strings are composable and - // an onClick is not. The caller's scope, so "asked" outlives the screen - // navigating away. - val notify = rememberNotifier(rememberCoroutineScope()) - val couldNotAsk = stringResource(Res.string.couldn_t_ask_the_group_to_guard_a_wallet) - val fallbackName = stringResource(Res.string.a_group) - val chosenName = (viewModel.uiState as? NewMemberWalletUIState.Chosen)?.room?.chatRoom?.subject?.takeIf { it.isNotBlank() } ?: fallbackName - val asked = stringResource(Res.string.asked_s_to_guard_a_wallet, chosenName) - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { Text(stringResource(Res.string.new_guarded_wallet)) }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - } - ) { padding -> - ScreenStateTransition(viewModel.uiState) { uiState -> - when (val state = uiState) { - NewMemberWalletUIState.Loading -> LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding)) - - // Nothing to retry: the group came from a navigation argument. - is NewMemberWalletUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = state.message, onRetry = null) - - is NewMemberWalletUIState.Picking -> if (state.groups.isEmpty()) { - EmptyState( - modifier = Modifier.padding(padding).readableContent(), - message = stringResource(Res.string.none_of_your_groups_guards_members_wallets_yet), - icon = Icons.Default.Groups, - ) - } else { - LazyColumn( - modifier = Modifier.padding(padding).readableContent().fillMaxSize() - .padding(MaterialTheme.spacing.screenMargin), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap), - ) { - item { - Text(stringResource(Res.string.choose_a_group_to_guard_it), style = MaterialTheme.typography.titleMedium) - } - items(state.groups, key = { it.room.chatRoom.id }) { choice -> - ListItem( - modifier = Modifier.clickable { viewModel.pick(choice.room.chatRoom.id) }.minimumInteractiveComponentSize(), - leadingContent = { Icon(Icons.Default.Groups, contentDescription = Decorative) }, - headlineContent = { - Text(choice.room.chatRoom.subject?.takeIf { it.isNotBlank() } ?: fallbackName, maxLines = 1, overflow = TextOverflow.Ellipsis) - }, - supportingContent = choice.refusal?.let { refusal -> { Text(refusalText(refusal)) } }, - ) - } - } - } - - is NewMemberWalletUIState.Chosen -> Column( - modifier = Modifier.padding(padding).readableContent().fillMaxSize() - .verticalScroll(rememberScrollState()) - .padding(MaterialTheme.spacing.screenMargin), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - ) { - Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) - Text( - text = stringResource(Res.string.a_wallet_only_you_can_spend_from_guarded_by_s, chosenName), - style = MaterialTheme.typography.titleLarge, - ) - - state.delays?.let { delays -> Text(reachText(chosenName, delays, chain), style = MaterialTheme.typography.bodyLarge) } - Text(stringResource(Res.string.members_of_those_groups_will_see_this_wallet), style = MaterialTheme.typography.bodyLarge) - Text( - stringResource(Res.string.if_you_lose_this_device_those_groups_can_still_move_your_coins), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - - when (val refusal = state.refusal) { - null -> { - OutlinedTextField( - modifier = Modifier.fillMaxWidth(), - value = viewModel.label.value, - onValueChange = viewModel::setLabel, - label = { Text(stringResource(Res.string.label_optional)) }, - singleLine = true, - ) - Button( - onClick = { viewModel.ask(onAsked = { notify(asked); onNavigateBack() }, onFailure = { notify(couldNotAsk) }) }, - enabled = !viewModel.isActionPending.value, - ) { - Text(stringResource(Res.string.ask_s, chosenName)) - } - } - - MemberWalletManager.Refusal.KEY_UNKNOWN -> { - Text(refusalText(refusal), color = MaterialTheme.colorScheme.onSurfaceVariant) - if (state.askedForKey) { - Text(stringResource(Res.string.asked_for_the_group_s_key), color = MaterialTheme.colorScheme.onSurfaceVariant) - } else { - TextButton(onClick = viewModel::askForGroupKey) { Text(stringResource(Res.string.ask_the_group_for_its_key)) } - } - } - - else -> Text(refusalText(refusal), color = MaterialTheme.colorScheme.onSurfaceVariant) - } - } - } - } - } -} - -/** - * Who can take the member's coins, and after how long: the group alone, the - * group and its parent, or the group and N above it, [delays] nearest first. - * Each guardian's own, since every group above chose its own -- - * `docs/guardian-delay.md`. - */ -@Composable -internal fun reachText(groupName: String, delays: List, chain: Chain?): String = when (delays.size) { - 0 -> "" - 1 -> stringResource(Res.string.s_can_take_any_coin_without_asking_you, groupName, delayText(delays[0], chain)) - 2 -> stringResource( - Res.string.s_and_the_group_above_it_can_take_any_coin_without_asking_you, - groupName, delayText(delays[0], chain), delayText(delays[1], chain), - ) - else -> stringResource( - Res.string.s_and_the_d_groups_above_it_can_take_any_coin_without_asking_you, - groupName, delayText(delays[0], chain), delays.size - 1, delayText(delays.drop(1).min(), chain), - ) -} - -@Composable -private fun refusalText(refusal: MemberWalletManager.Refusal): String = stringResource( - when (refusal) { - MemberWalletManager.Refusal.CANNOT_SIGN -> Res.string.this_profile_cannot_sign_a_request - MemberWalletManager.Refusal.NOT_A_GROUP -> Res.string.only_a_group_can_guard_a_wallet - MemberWalletManager.Refusal.KEY_UNKNOWN -> Res.string.this_device_does_not_know_what_this_group_signs_with - MemberWalletManager.Refusal.GUARDIANS_UNREADABLE -> Res.string.this_group_s_guardian_keys_can_t_be_read_to_guard_a_wallet - MemberWalletManager.Refusal.NOT_ON_THIS_NETWORK -> Res.string.member_wallets_are_not_offered_on_this_network - MemberWalletManager.Refusal.NOT_OFFERED -> Res.string.this_group_doesn_t_guard_members_wallets - MemberWalletManager.Refusal.CLOSED -> Res.string.this_group_has_stopped_guarding_members_wallets - } -) 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 829a47e6..b990a85d 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,8 +1,6 @@ package mobi.giza.compose.ui.composable.navigation import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import mobi.giza.compose.ui.composable.MemberWalletPolicyScreen -import mobi.giza.compose.ui.composable.navigation.routes.MemberWalletPolicyRoute import mobi.giza.compose.ui.composable.GroupSendScreen import mobi.giza.compose.ui.composable.navigation.routes.GroupSendRoute import androidx.compose.foundation.layout.fillMaxSize @@ -142,13 +140,6 @@ import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import mobi.giza.compose.ui.composable.navigation.routes.GroupWalletRoute import mobi.giza.compose.ui.composable.navigation.routes.GroupWalletAddressesRoute -import mobi.giza.compose.ui.composable.navigation.routes.NewMemberWalletRoute -import mobi.giza.compose.ui.composable.navigation.routes.MemberWalletRoute -import mobi.giza.compose.ui.composable.navigation.routes.MemberSendRoute -import mobi.giza.compose.ui.composable.MemberSendScreen -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.GroupTransactionWatcher import fr.acinq.phoenix.managers.NodeParamsManager @@ -216,14 +207,6 @@ fun GizaNavHost( applicationIOScope ) } - - val databaseMemberWalletRepository = remember { - DatabaseMemberWalletRepository( - database = auxDatabaseManager.auxDatabase, - activeIdentity = sovereignWalletViewModel.activeIdentity, - ) - } - val databaseMarmotRepository = remember { DatabaseMarmotRepository( database = auxDatabaseManager.auxDatabase, @@ -1146,68 +1129,6 @@ fun GizaNavHost( } ) } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - val wallets = groupOnchainWallets ?: return@composable - - MemberWalletScreen( - activeUserPublicKey = route.activeUserPublicKey, - walletId = route.walletId, - memberWalletRepository = databaseMemberWalletRepository, - wallets = wallets, - onSend = { walletId -> - navController.navigate(route = MemberSendRoute(activeUserPublicKey = route.activeUserPublicKey, walletId = walletId)) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - val wallets = groupOnchainWallets ?: return@composable - - MemberSendScreen( - activeUserPublicKey = route.activeUserPublicKey, - walletId = route.walletId, - chain = NodeParamsManager.chain, - memberWalletRepository = databaseMemberWalletRepository, - wallets = wallets, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - MemberWalletPolicyScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - chatRepository = databaseChatRepository, - memberWalletRepository = databaseMemberWalletRepository, - frostSigningRepository = databaseFrostSigningRepository, - onNavigateToRoute = { actionRoute -> - navController.navigate(route = actionRoute) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - NewMemberWalletScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - chain = NodeParamsManager.chain, - memberWalletRepository = databaseMemberWalletRepository, - onNavigateBack = { - navController.popBackStack() - } - ) - } composable { backStackEntry -> val route = backStackEntry.toRoute() val wallets = groupOnchainWallets ?: return@composable diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/MemberSendRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/MemberSendRoute.kt deleted file mode 100644 index 87706b8e..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/MemberSendRoute.kt +++ /dev/null @@ -1,10 +0,0 @@ -package mobi.giza.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** The form a member sends from their own guarded wallet with, signing alone. */ -@Serializable -data class MemberSendRoute( - val activeUserPublicKey: String, - val walletId: String, -): Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/MemberWalletPolicyRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/MemberWalletPolicyRoute.kt deleted file mode 100644 index be81d409..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/MemberWalletPolicyRoute.kt +++ /dev/null @@ -1,13 +0,0 @@ -package mobi.giza.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** - * Whether the group [chatRoomId] guards its members' wallets, at what delay, - * and closing it again -- `docs/member-wallet-delay.md`, Phase 6. - */ -@Serializable -data class MemberWalletPolicyRoute( - val activeUserPublicKey: String, - val chatRoomId: String, -): Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/MemberWalletRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/MemberWalletRoute.kt deleted file mode 100644 index f35389f5..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/MemberWalletRoute.kt +++ /dev/null @@ -1,14 +0,0 @@ -package mobi.giza.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** - * One of the active member's guarded wallets: its balance, where to be paid, - * its coins, what its guardians took, and -- while no group has certified it -- - * where the asking has got to. `docs/member-guarded-wallets.md`, Phase 8. - */ -@Serializable -data class MemberWalletRoute( - val activeUserPublicKey: String, - val walletId: String, -): Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/NewMemberWalletRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/NewMemberWalletRoute.kt deleted file mode 100644 index 8cc30942..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/NewMemberWalletRoute.kt +++ /dev/null @@ -1,14 +0,0 @@ -package mobi.giza.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** - * Asking a group to guard a wallet only the active member can spend from -- - * `docs/member-guarded-wallets.md`, Phase 6. With [chatRoomId] the group is - * already chosen; without it the screen offers the groups this profile is in. - */ -@Serializable -data class NewMemberWalletRoute( - val activeUserPublicKey: String, - val chatRoomId: String? = null, -): Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/MemberSendViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/MemberSendViewModel.kt deleted file mode 100644 index 45cf1aec..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/MemberSendViewModel.kt +++ /dev/null @@ -1,185 +0,0 @@ -package mobi.giza.compose.ui.view.model - -import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import co.touchlab.kermit.Logger -import mobi.giza.compose.database.model.MemberWalletSpend -import mobi.giza.compose.managers.MemberWalletManager -import mobi.giza.compose.repository.MemberWalletRepository -import mobi.giza.compose.text.SatsInput -import mobi.giza.compose.text.parseSats -import mobi.giza.compose.ui.view.state.MemberSendUIState -import mobi.giza.compose.wallet.GroupOnchainWallets -import mobi.giza.compose.wallet.GroupSpend -import mobi.giza.compose.wallet.GroupSpendBuilder -import mobi.giza.compose.wallet.GroupWalletRollout -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.OutPoint -import fr.acinq.bitcoin.Satoshi -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.Job -import kotlinx.coroutines.flow.combine -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext -import kotlin.time.Clock - -/** - * A spend from the member's own guarded wallet, built as they type and signed - * alone when they ask. - * - * The group's send form, read the same way -- the preview is the spend, so the - * fee shown is the fee paid -- with one difference that matters: there is no - * quorum after this. Pressing the button signs and broadcasts. - */ -class MemberSendViewModel( - private val ownerPublicKey: HexKey, - val walletId: String, - val chain: Chain, - initialUIState: MemberSendUIState, - private val memberWalletRepository: MemberWalletRepository, - private val wallets: GroupOnchainWallets, -) : ViewModel() { - private val logger = Logger.withTag(TAG) - - var uiState: MemberSendUIState by mutableStateOf(initialUIState) - private set - - val addressField = TextFieldState() - val amountField = TextFieldState() - val feerateField = TextFieldState() - val sendEverything: MutableState = mutableStateOf(false) - - val isActionPending: MutableState = mutableStateOf(false) - - private var watching: Job? = null - - fun initiate() { - viewModelScope.launch(Dispatchers.IO) { - val wallet = memberWalletRepository.walletOf(ownerPublicKey, walletId) - if (wallet == null) { - uiState = MemberSendUIState.Error("Couldn't find this wallet") - return@launch - } - if (wallet.state != MemberWalletManager.WalletState.OPEN) { - uiState = MemberSendUIState.Unavailable - return@launch - } - - val ready = MemberSendUIState.Ready(wallet = wallet, walletState = null) - uiState = ready - - wallets.suggestedFeeratePerVbyte(chain)?.let { suggested -> - withContext(Dispatchers.Main) { - if (feerateField.text.isEmpty()) feerateField.setTextAndPlaceCursorAtEnd(suggested.toString()) - } - } - - watching?.cancel() - watching = viewModelScope.launch(Dispatchers.IO) { - combine(wallets.walletFor(wallet.account).state, memberWalletRepository.observeSpends(walletId)) { state, spends -> - val (reserved, reservedChange) = reservationsOf(spends, ready) - ready.copy(walletState = state, reserved = reserved, reservedChange = reservedChange) - }.collect { uiState = it } - } - } - } - - /** - * What the member's own spends still on their way hold: their coins, and the - * change they pay back to. Electrum stops listing a coin once a spend of it - * is in the mempool, so this matters for the moment between signing and the - * server hearing of it -- a second send then would spend the same coin. - */ - private fun reservationsOf(spends: List, ready: MemberSendUIState.Ready): Pair, Set> { - val open = spends.filter { it.seenAt == null && it.replacedByTxid == null } - .mapNotNull { GroupSpend.decode(it.psbt) } - .mapNotNull { (GroupSpend.check(it, ready.wallet.account) as? GroupSpend.Result.Ok)?.checked } - return open.flatMap { spend -> spend.inputs.map { it.outPoint } }.toSet() to - open.flatMap { spend -> spend.outputs.mapNotNull { it.change?.index } }.toSet() - } - - fun amount(): SatsInput = parseSats(amountField.text) - - fun spendable(): Satoshi? { - val state = uiState as? MemberSendUIState.Ready ?: return null - return state.walletState?.let { GroupSpendBuilder.spendableBalance(it, state.reserved, GroupSpend.Spender.Owner) } - } - - fun isAboutTheAmount(result: GroupSpendBuilder.Result?): Boolean = - !sendEverything.value && ( - result is GroupSpendBuilder.Result.InvalidAmount || - result is GroupSpendBuilder.Result.OverCap || - result == GroupSpendBuilder.Result.NotEnough || - result == GroupSpendBuilder.Result.BelowDust - ) - - /** The spend the form describes, or null while it is incomplete -- the same build the group's form makes. */ - fun preview(): GroupSpendBuilder.Result? { - val state = uiState as? MemberSendUIState.Ready ?: return null - val walletState = state.walletState ?: return null - - val amount = if (sendEverything.value) { - null - } else { - when (val input = amount()) { - SatsInput.Empty -> return null - is SatsInput.Sats -> input.amount - else -> return GroupSpendBuilder.Result.InvalidAmount(input) - } - } - val feerate = feerateField.text.toString().trim().toLongOrNull()?.takeIf { it > 0 } ?: return null - val address = addressField.text.toString().trim().takeIf { it.isNotEmpty() } ?: return null - - val built = if (amount == null) { - GroupSpendBuilder.sendAll(walletState, address, feerate, state.reserved) - } else { - GroupSpendBuilder.send(walletState, address, amount, feerate, state.reserved, state.reservedChange) - } - return GroupSpendBuilder.capped(built, GroupWalletRollout.memberCapFor(chain)) - } - - /** Signs what the form describes and hands it to Electrum. [onSent] when it went, [onFailure] when it did not. */ - fun send(onSent: () -> Unit, onFailure: () -> Unit) { - val built = preview() as? GroupSpendBuilder.Result.Built ?: return - if (isActionPending.value) return - isActionPending.value = true - - viewModelScope.launch(Dispatchers.IO) { - val sent = runCatching { - val signed = memberWalletRepository.signSpend(walletId, built.psbt) - wallets.broadcast(signed, chain) - memberWalletRepository.recordChain(signed.txid.toString(), confirmations = null, broadcastAt = Clock.System.now()) - }.onFailure { logger.e("Couldn't send from wallet $walletId", it) }.isSuccess - - withContext(Dispatchers.Main) { - isActionPending.value = false - if (sent) onSent() else onFailure() - } - } - } - - companion object { - private const val TAG = "MemberSendViewModel" - - fun factory( - ownerPublicKey: HexKey, - walletId: String, - chain: Chain, - initialUIState: MemberSendUIState = MemberSendUIState.Loading, - memberWalletRepository: MemberWalletRepository, - wallets: GroupOnchainWallets, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { MemberSendViewModel(ownerPublicKey, walletId, chain, initialUIState, memberWalletRepository, wallets) } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/MemberWalletPolicyViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/MemberWalletPolicyViewModel.kt deleted file mode 100644 index 8db604a3..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/MemberWalletPolicyViewModel.kt +++ /dev/null @@ -1,142 +0,0 @@ -package mobi.giza.compose.ui.view.model - -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import co.touchlab.kermit.Logger -import mobi.giza.compose.managers.GuardianDerivation -import mobi.giza.compose.nostr.wallet.MemberWalletPolicyEvent -import mobi.giza.compose.repository.ChatRepository -import mobi.giza.compose.repository.FrostSigningRepository -import mobi.giza.compose.repository.MemberWalletRepository -import mobi.giza.compose.ui.view.state.MemberWalletPolicyUIState -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext - -/** - * Whether a group guards its members' wallets, at what delay, and closing it - * again -- `docs/member-wallet-delay.md`, Phase 6. - * - * Proposes a policy the way opening a wallet proposes a statement: a signing - * session in the group's room, which proposing counts as approving. Nothing - * changes until a quorum signs, and every policy reaches only the wallets asked - * for after it -- one already guarded keeps its delay, and closing never - * releases it. - */ -class MemberWalletPolicyViewModel( - private val activeUserPublicKey: HexKey, - private val chatRoomId: String, - initialUIState: MemberWalletPolicyUIState, - private val chatRepository: ChatRepository, - private val memberWalletRepository: MemberWalletRepository, - private val frostSigningRepository: FrostSigningRepository, -) : ViewModel() { - private val logger = Logger.withTag(TAG) - - var uiState: MemberWalletPolicyUIState by mutableStateOf(initialUIState) - private set - - val isActionPending: MutableState = mutableStateOf(false) - - /** The delay being chosen, starting from the group's own or the default. */ - val delay = GuardianDelayInput() - - /** Whether [initiate] has set [delay] from the group's policy, which it does once. */ - private var started = false - - fun initiate() { - viewModelScope.launch(Dispatchers.IO) { - val room = chatRepository.getChatRoomByIdentifier(chatRoomId) - if (room == null) { - uiState = MemberWalletPolicyUIState.Error("Couldn't find the group") - return@launch - } - val policy = memberWalletRepository.policyOf(chatRoomId) - val canSign = room.chatRoom.mlsGroupState != null && chatRepository.canSign(chatRoomId) - if (!started) { - started = true - delay.reset((policy as? MemberWalletPolicyEvent.Policy.Open)?.delay ?: GuardianDerivation.DEFAULT_DELAY) - } - uiState = MemberWalletPolicyUIState.Loaded(room, policy, canSign) - } - } - - /** - * Why opening at the chosen delay cannot be proposed, or null when it can: - * a delay out of range, or the delay the group already has -- a quorum - * asked to restate itself is asked for nothing. - */ - fun openProblem(): String? { - delay.problem()?.let { return it } - val loaded = uiState as? MemberWalletPolicyUIState.Loaded ?: return "Still loading" - if (!loaded.canSign) return "This device can't put a change to the group." - val current = (loaded.policy as? MemberWalletPolicyEvent.Policy.Open)?.delay - if (current == delay.delay()) return "That is already this group's delay." - return null - } - - /** Whether closing can be proposed: only a group that is open. */ - fun canClose(): Boolean = (uiState as? MemberWalletPolicyUIState.Loaded)?.let { it.isOpen && it.canSign } == true - - /** Asks the group to guard members' wallets at the chosen delay. */ - fun proposeOpen(onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) { - if (openProblem() != null) return - propose(MemberWalletPolicyEvent.open(delay.delay() ?: return), onSuccess, onFailure) - } - - /** Asks the group to stop guarding new members' wallets. */ - fun proposeClose(onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) { - if (!canClose()) return - propose(MemberWalletPolicyEvent.closed(), onSuccess, onFailure) - } - - private fun propose(template: EventTemplate<*>, onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) { - val loaded = uiState as? MemberWalletPolicyUIState.Loaded ?: return - if (isActionPending.value) return - isActionPending.value = true - - viewModelScope.launch(Dispatchers.IO) { - val session = runCatching { - frostSigningRepository.proposeSigning( - localChatRoom = loaded.localChatRoom, - userPublicKey = activeUserPublicKey, - kind = template.kind, - tags = template.tags, - content = template.content, - ) - }.onFailure { logger.e("Failed to propose a member-wallet policy for $chatRoomId", it) }.getOrNull() - - withContext(Dispatchers.Main) { - isActionPending.value = false - if (session != null) onSuccess(session.id) else onFailure() - } - } - } - - companion object { - private const val TAG = "MemberWalletPolicyViewModel" - - fun factory( - activeUserPublicKey: HexKey, - chatRoomId: String, - initialUIState: MemberWalletPolicyUIState = MemberWalletPolicyUIState.Loading, - chatRepository: ChatRepository, - memberWalletRepository: MemberWalletRepository, - frostSigningRepository: FrostSigningRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - MemberWalletPolicyViewModel(activeUserPublicKey, chatRoomId, initialUIState, chatRepository, memberWalletRepository, frostSigningRepository) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/MemberWalletViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/MemberWalletViewModel.kt deleted file mode 100644 index 5064e427..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/MemberWalletViewModel.kt +++ /dev/null @@ -1,159 +0,0 @@ -package mobi.giza.compose.ui.view.model - -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import co.touchlab.kermit.Logger -import mobi.giza.compose.repository.MemberWalletRepository -import mobi.giza.compose.ui.view.state.MemberWalletUIState -import mobi.giza.compose.ui.view.state.TakenLine -import mobi.giza.compose.wallet.GroupOnchainWallets -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.Job -import kotlinx.coroutines.flow.combine -import kotlinx.coroutines.flow.distinctUntilChangedBy -import mobi.giza.compose.database.model.MemberWalletSpend -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.Transaction -import kotlin.time.Clock -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext - -/** - * One of the member's guarded wallets: read once for where the asking has got - * to, then -- for a certified wallet on a profile that can watch the chain -- - * watched for its coins, and searched for what its guardians took. - * - * Addresses are offered only once a group has certified the wallet: a wallet - * nobody has agreed to guard should not be handed out to be paid. - */ -class MemberWalletViewModel( - private val ownerPublicKey: HexKey, - walletId: String, - initialUIState: MemberWalletUIState, - private val memberWalletRepository: MemberWalletRepository, - private val wallets: GroupOnchainWallets, -) : ViewModel() { - private val logger = Logger.withTag(TAG) - - /** - * The wallet on screen. Moves when asking again had to make a new request - * under the group's newest policy, with a new key, in place of this one -- - * `docs/member-wallet-delay.md`, Phase 5. - */ - var walletId: String = walletId - private set - - var uiState: MemberWalletUIState by mutableStateOf(initialUIState) - private set - - val isActionPending: MutableState = mutableStateOf(false) - - /** The exported descriptors while they are being shown, and only then. */ - var exported: Pair? by mutableStateOf(null) - private set - - private var watching: Job? = null - - fun initiate() { - viewModelScope.launch(Dispatchers.IO) { - val wallet = memberWalletRepository.walletOf(ownerPublicKey, walletId) - if (wallet == null) { - uiState = MemberWalletUIState.Error("Couldn't find this wallet") - return@launch - } - val loaded = MemberWalletUIState.Loaded(wallet = wallet) - uiState = loaded - - watching?.cancel() - if (!wallet.isCertified) return@launch - watching = viewModelScope.launch(Dispatchers.IO) { - var taken = emptyList() - combine( - wallets.walletFor(wallet.account).state - .distinctUntilChangedBy { state -> state.utxos.map { it.utxo.outPoint } to state.tipHeight }, - memberWalletRepository.observeSpends(walletId), - ) { state, spends -> state to spends } - .collect { (state, spends) -> - uiState = loaded.copy(walletState = state, taken = taken, spends = spends) - follow(spends, wallet.account.chain) - // History, not a watch: a device asleep when a guardian took a - // coin still finds it, since the chain keeps the record. - taken = wallets.guardianSpends(state).map { spend -> - TakenLine(spend.txid.toString(), memberWalletRepository.roomName(spend.guardian.chatRoomId), spend.amount) - } - uiState = loaded.copy(walletState = state, taken = taken, spends = spends) - } - } - } - } - - /** - * Asks the chain where each of the member's unsettled spends has got to, - * and sends again any Electrum has not heard of. There is no session for - * `GroupTransactionWatcher` to follow, so the wallet screen follows its own - * spends while it is open -- the economy the guardian-spend notice makes: a - * device that never opens the screen writes nothing, and the chain keeps the - * record for the next one that does. - */ - private suspend fun follow(spends: List, chain: Chain) { - spends.filter { it.confirmedAt == null && it.replacedByTxid == null }.forEach { spend -> - val tx = runCatching { Transaction.read(spend.signedTransaction) }.getOrNull() ?: return@forEach - val confirmations = wallets.confirmationsOf(tx, chain) - val resent = if (confirmations == null) { - runCatching { wallets.broadcast(tx, chain) }.getOrNull()?.let { Clock.System.now() } - } else null - memberWalletRepository.recordChain(spend.txid, confirmations, broadcastAt = resent) - } - } - - fun askAgain(onAsked: () -> Unit, onFailure: () -> Unit) = act(onAsked, onFailure) { - walletId = memberWalletRepository.askAgain(walletId) - initiate() - } - - fun discard(onDiscarded: () -> Unit, onFailure: () -> Unit) = act(onDiscarded, onFailure) { - memberWalletRepository.discard(walletId) - } - - fun exportKey() { - viewModelScope.launch(Dispatchers.IO) { exported = memberWalletRepository.exportKey(walletId) } - } - - fun hideKey() { - exported = null - } - - private fun act(onDone: () -> Unit, onFailure: () -> Unit, action: suspend () -> Unit) { - if (isActionPending.value) return - isActionPending.value = true - viewModelScope.launch(Dispatchers.IO) { - val done = runCatching { action() }.onFailure { logger.e("Couldn't act on wallet $walletId", it) }.isSuccess - withContext(Dispatchers.Main) { - isActionPending.value = false - if (done) onDone() else onFailure() - } - } - } - - companion object { - private const val TAG = "MemberWalletViewModel" - - fun factory( - ownerPublicKey: HexKey, - walletId: String, - initialUIState: MemberWalletUIState = MemberWalletUIState.Loading, - memberWalletRepository: MemberWalletRepository, - wallets: GroupOnchainWallets, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { MemberWalletViewModel(ownerPublicKey, walletId, initialUIState, memberWalletRepository, wallets) } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/MemberWalletsViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/MemberWalletsViewModel.kt deleted file mode 100644 index f8800791..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/MemberWalletsViewModel.kt +++ /dev/null @@ -1,70 +0,0 @@ -package mobi.giza.compose.ui.view.model - -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import mobi.giza.compose.managers.MemberWalletManager -import mobi.giza.compose.repository.MemberWalletRepository -import mobi.giza.compose.wallet.GroupOnchainWallets -import mobi.giza.compose.wallet.GroupWalletState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.Job -import kotlinx.coroutines.flow.combine -import kotlinx.coroutines.flow.flowOf -import kotlinx.coroutines.launch - -/** - * A member's guarded wallets, as their profile lists them: each one's state, - * and -- for the ones a group has certified -- its balance. [wallets] is null - * only where the profile is composed without an identity: previews and tests. - */ -class MemberWalletsViewModel( - private val ownerPublicKey: HexKey, - private val memberWalletRepository: MemberWalletRepository, - private val wallets: GroupOnchainWallets?, -) : ViewModel() { - /** One wallet and, once the chain has answered, its coins. */ - data class Row(val wallet: MemberWalletManager.MemberWalletRow, val walletState: GroupWalletState?) - - /** Null until the first read. */ - var rows: List? by mutableStateOf(null) - private set - - private var watching: Job? = null - - /** Reads the list again: called each time the profile is shown, since a certificate can arrive while it is not. */ - fun refresh() { - viewModelScope.launch(Dispatchers.IO) { - val found = memberWalletRepository.walletsOf(ownerPublicKey) - rows = found.map { Row(it, walletState = null) } - - watching?.cancel() - val watched = found.filter { it.isCertified } - if (wallets == null || watched.isEmpty()) return@launch - watching = viewModelScope.launch(Dispatchers.IO) { - val states = found.map { wallet -> - if (wallet.isCertified) wallets.walletFor(wallet.account).state else flowOf(null) - } - combine(states) { it.toList() }.collect { current -> - rows = found.zip(current) { wallet, state -> Row(wallet, state) } - } - } - } - } - - companion object { - fun factory( - ownerPublicKey: HexKey, - memberWalletRepository: MemberWalletRepository, - wallets: GroupOnchainWallets?, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { MemberWalletsViewModel(ownerPublicKey, memberWalletRepository, wallets) } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/NewMemberWalletViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/NewMemberWalletViewModel.kt deleted file mode 100644 index 53bdda86..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/NewMemberWalletViewModel.kt +++ /dev/null @@ -1,133 +0,0 @@ -package mobi.giza.compose.ui.view.model - -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import co.touchlab.kermit.Logger -import mobi.giza.compose.managers.MemberWalletManager -import mobi.giza.compose.repository.MemberWalletRepository -import mobi.giza.compose.ui.view.state.GroupChoice -import mobi.giza.compose.ui.view.state.NewMemberWalletUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.Chain -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext - -/** - * Asking a group to guard a wallet only this member can spend from. - * - * The screen offers nothing that would be refused. Every refusal is read before - * the button is drawn and again inside `MemberWalletManager.request`, the way - * the subgroup picker refuses: the screen keeps a member out of a dead end, the - * manager keeps a bug out of the room. - */ -class NewMemberWalletViewModel( - val activeUserPublicKey: HexKey, - private val chatRoomId: String?, - private val chain: Chain, - initialUIState: NewMemberWalletUIState, - private val memberWalletRepository: MemberWalletRepository, -) : ViewModel() { - private val logger = Logger.withTag(TAG) - - var uiState: NewMemberWalletUIState by mutableStateOf(initialUIState) - private set - - val label: MutableState = mutableStateOf("") - - val isActionPending: MutableState = mutableStateOf(false) - - fun initiate() { - viewModelScope.launch(Dispatchers.IO) { - uiState = when (val chosen = chatRoomId) { - null -> NewMemberWalletUIState.Picking( - memberWalletRepository.groupsOf(activeUserPublicKey) - .map { GroupChoice(it, refusal(it.chatRoom.id)) } - // A group that has never opened to its members' wallets, or - // has closed, is not a choice, so it is not on the list. A - // group whose key -- and so whose policy -- this device has - // not been told yet stays, with the button that asks: it may - // well be open. docs/member-wallet-delay.md. - .filter { it.refusal !in NOT_A_CHOICE } - ) - else -> choose(chosen) ?: NewMemberWalletUIState.Error("Couldn't find the group") - } - } - } - - fun pick(chatRoomId: String) { - viewModelScope.launch(Dispatchers.IO) { - uiState = choose(chatRoomId) ?: NewMemberWalletUIState.Error("Couldn't find the group") - } - } - - private suspend fun choose(chatRoomId: String): NewMemberWalletUIState.Chosen? { - val room = memberWalletRepository.groupsOf(activeUserPublicKey).firstOrNull { it.chatRoom.id == chatRoomId } ?: return null - return NewMemberWalletUIState.Chosen( - room = room, - refusal = refusal(chatRoomId), - reach = memberWalletRepository.reachOf(chatRoomId), - delays = memberWalletRepository.delaysOf(chatRoomId), - ) - } - - private suspend fun refusal(chatRoomId: String): MemberWalletManager.Refusal? = - memberWalletRepository.refusal(chatRoomId, chain) - - fun askForGroupKey() { - val chosen = uiState as? NewMemberWalletUIState.Chosen ?: return - viewModelScope.launch(Dispatchers.IO) { - memberWalletRepository.askForGroupKey(chosen.room.chatRoom.id) - uiState = chosen.copy(askedForKey = true) - } - } - - fun setLabel(value: String) { - label.value = value.take(LABEL_LENGTH) - } - - /** Asks the chosen group; [onAsked] gets the group's name, [onFailure] runs when it could not. */ - fun ask(onAsked: () -> Unit, onFailure: () -> Unit) { - val chosen = uiState as? NewMemberWalletUIState.Chosen ?: return - if (chosen.refusal != null || isActionPending.value) return - isActionPending.value = true - viewModelScope.launch(Dispatchers.IO) { - val asked = runCatching { - memberWalletRepository.request(chosen.room.chatRoom.id, chain, label.value.takeIf { it.isNotBlank() }) - }.onFailure { logger.e("Couldn't ask ${chosen.room.chatRoom.id} to guard a wallet", it) }.isSuccess - withContext(Dispatchers.Main) { - isActionPending.value = false - if (asked) onAsked() else onFailure() - } - } - } - - companion object { - /** Refusals that say a group is not guarding members' wallets, rather than that this device cannot ask yet. */ - private val NOT_A_CHOICE = setOf(MemberWalletManager.Refusal.NOT_OFFERED, MemberWalletManager.Refusal.CLOSED) - - private const val TAG = "NewMemberWalletViewModel" - - /** The longest label a request carries -- `MemberWalletRequestEvent.MAX_LABEL_LENGTH`. */ - const val LABEL_LENGTH = 64 - - fun factory( - activeUserPublicKey: HexKey, - chatRoomId: String?, - chain: Chain, - initialUIState: NewMemberWalletUIState = NewMemberWalletUIState.Loading, - memberWalletRepository: MemberWalletRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - NewMemberWalletViewModel(activeUserPublicKey, chatRoomId, chain, initialUIState, memberWalletRepository) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/PersonGuardedWalletsViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/PersonGuardedWalletsViewModel.kt deleted file mode 100644 index 41928c3d..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/PersonGuardedWalletsViewModel.kt +++ /dev/null @@ -1,41 +0,0 @@ -package mobi.giza.compose.ui.view.model - -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.ViewModelProvider -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import mobi.giza.compose.managers.MemberWalletManager -import mobi.giza.compose.repository.MemberWalletRepository -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch - -/** - * A person's guarded wallets as the groups this profile is in guard them -- - * the person's page's *Wallets your groups guard*, one entry per wallet and - * each with the groups that hold a leaf in it. Where a group's page lists a - * member's wallet, its row leads here, since a person is someone to look at, - * not a room to go into. - */ -class PersonGuardedWalletsViewModel( - private val ownerPublicKey: HexKey, - private val memberWalletRepository: MemberWalletRepository, -) : ViewModel() { - /** One per wallet, each with the groups here holding a leaf in it. */ - var rows: List by mutableStateOf(emptyList()) - private set - - fun initiate() { - viewModelScope.launch(Dispatchers.IO) { rows = MemberWalletManager.byWallet(memberWalletRepository.guardedByGroupsHere(ownerPublicKey)) } - } - - companion object { - fun factory(ownerPublicKey: HexKey, memberWalletRepository: MemberWalletRepository): ViewModelProvider.Factory = viewModelFactory { - initializer { PersonGuardedWalletsViewModel(ownerPublicKey, memberWalletRepository) } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/MemberSendUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/MemberSendUIState.kt deleted file mode 100644 index 40936eae..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/MemberSendUIState.kt +++ /dev/null @@ -1,24 +0,0 @@ -package mobi.giza.compose.ui.view.state - -import mobi.giza.compose.managers.MemberWalletManager -import mobi.giza.compose.wallet.GroupWalletState -import fr.acinq.bitcoin.OutPoint - -sealed interface MemberSendUIState { - data object Loading : MemberSendUIState - - data class Error(val message: String) : MemberSendUIState - - /** A wallet this device can spend from: certified, its key here, and a node to see the coins with. */ - data object Unavailable : MemberSendUIState - - data class Ready( - val wallet: MemberWalletManager.MemberWalletRow, - /** Null until Electrum answers. */ - val walletState: GroupWalletState?, - /** The coins the member's own unsettled spends hold, which a new one leaves alone. */ - val reserved: Set = emptySet(), - /** The change indices those spends pay back to, which a new one pays past. */ - val reservedChange: Set = emptySet(), - ) : MemberSendUIState -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/MemberWalletPolicyUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/MemberWalletPolicyUIState.kt deleted file mode 100644 index 0c13a570..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/MemberWalletPolicyUIState.kt +++ /dev/null @@ -1,23 +0,0 @@ -package mobi.giza.compose.ui.view.state - -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.nostr.wallet.MemberWalletPolicyEvent - -sealed interface MemberWalletPolicyUIState { - data object Loading : MemberWalletPolicyUIState - - data class Error(val message: String) : MemberWalletPolicyUIState - - /** - * The group, and what it says about its members' wallets now: [policy] is - * its newest, open or closed, or null for one it never signed. [canSign] is - * whether this device can put a change to the group. - */ - data class Loaded( - val localChatRoom: LocalChatRoom, - val policy: MemberWalletPolicyEvent.Policy?, - val canSign: Boolean, - ) : MemberWalletPolicyUIState { - val isOpen: Boolean get() = policy is MemberWalletPolicyEvent.Policy.Open - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/MemberWalletUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/MemberWalletUIState.kt deleted file mode 100644 index a940920b..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/MemberWalletUIState.kt +++ /dev/null @@ -1,34 +0,0 @@ -package mobi.giza.compose.ui.view.state - -import mobi.giza.compose.database.model.MemberWalletSpend -import mobi.giza.compose.managers.MemberWalletManager -import mobi.giza.compose.wallet.GroupWalletState -import fr.acinq.bitcoin.Satoshi - -sealed interface MemberWalletUIState { - data object Loading : MemberWalletUIState - - data class Error(val message: String) : MemberWalletUIState - - data class Loaded( - val wallet: MemberWalletManager.MemberWalletRow, - /** Null before Electrum's first answer, and for a wallet no group has certified. */ - val walletState: GroupWalletState? = null, - /** What the wallet's guardians took from it, read off the chain: never stored, found again on each look. */ - val taken: List = emptyList(), - /** The spends the member signed from it, newest first. */ - val spends: List = emptyList(), - /** How many groups guard it, for the line under the title. */ - val reach: Int = wallet.account.guardians.size, - /** Each guardian's delay, nearest first: the leaves the wallet's addresses carry. */ - val delays: List = wallet.account.guardians.map { it.delay }, - ) : MemberWalletUIState -} - -/** One guardian spend from a member's wallet, named for the group that made it. */ -data class TakenLine( - val txid: String, - /** The guardian's room name on this device, or null when this device is not in it. */ - val guardianName: String?, - val amount: Satoshi, -) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/NewMemberWalletUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/NewMemberWalletUIState.kt deleted file mode 100644 index 37601575..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/NewMemberWalletUIState.kt +++ /dev/null @@ -1,37 +0,0 @@ -package mobi.giza.compose.ui.view.state - -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.managers.MemberWalletManager - -sealed interface NewMemberWalletUIState { - data object Loading : NewMemberWalletUIState - - data class Error(val message: String) : NewMemberWalletUIState - - /** - * No group chosen yet: every group this profile is in that guards members' - * wallets, or may -- one whose key this device does not know yet -- each - * with why it cannot guard a wallet now, if it cannot. - */ - data class Picking(val groups: List) : NewMemberWalletUIState - - /** - * A group chosen. [refusal] null means it can be asked, and [reach] is how - * many groups the wallet would be guarded by -- the group and every group - * above it whose key it passes down. - */ - data class Chosen( - val room: LocalChatRoom, - val refusal: MemberWalletManager.Refusal?, - val reach: Int?, - /** Each guardian's delay, nearest first, as [reach] counts them; null while the group's key is unknown. */ - val delays: List? = null, - /** The member already asked the group for its key, and is waiting on an answer. */ - val askedForKey: Boolean = false, - ) : NewMemberWalletUIState -} - -data class GroupChoice( - val room: LocalChatRoom, - val refusal: MemberWalletManager.Refusal?, -) diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ForkCompatibilityTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ForkCompatibilityTest.kt index c89fcf50..f6cc3aa7 100644 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ForkCompatibilityTest.kt +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ForkCompatibilityTest.kt @@ -10,7 +10,6 @@ import fr.acinq.phoenix.data.WalletId import fr.acinq.phoenix.managers.NodeParamsManager import fr.acinq.bitcoin.MnemonicCode import fr.acinq.bitcoin.byteVector -import mobi.giza.compose.nostr.wallet.MemberWalletRequestEvent import kotlin.test.Test import kotlin.test.assertEquals @@ -52,17 +51,6 @@ class ForkCompatibilityTest { assertEquals(PINNED_SHARED_KEY, SharedKeyDerivation.derive(threshold).hex) } - // bennu/member-wallet/id/v1 and bennu/member-wallet/possession/v1 - @Test - fun `member wallet id and possession message`() { - val walletKey = key(0x3a11e7).publicKey() - assertEquals(PINNED_MEMBER_WALLET_ID, MemberWalletDerivation.walletId(walletKey)) - assertEquals( - PINNED_POSSESSION_MESSAGE, - MemberWalletRequestEvent.possessionMessage(key(0xa11ce).publicKey().xOnly().value.toHex(), room, walletKey, Chain.Mainnet).toHex(), - ) - } - // bennu/group-wallet/account/v1, bennu/group-wallet/guardian/v1 and …/guardian/child/v1 @Test fun `group wallet account and guardian root`() { @@ -102,8 +90,6 @@ class ForkCompatibilityTest { const val PINNED_PHRASE_HOST_KEY = "03b93ca2ea2bac313457180953bbede99450d59ce01916e98d42df09fdabbbe83f" const val PINNED_HOST_KEY = "028871ab105eac8812fa7aab4b9110ad20b5dcfba9f65271431dcb417258da08af" const val PINNED_SHARED_KEY = "5eb33e9c2a5a90ae4d273b687eb1265f8b79c2bcee28f9ae9dc44dba6e788444" - const val PINNED_MEMBER_WALLET_ID = "2282987a87614b622a25500102158d65ed01165919f98bc372aa3d39c828d5db" - const val PINNED_POSSESSION_MESSAGE = "43a8cc800f2205edb6384d2758e53b40692859524255449521036f11cdca3396" const val PINNED_GROUP_ADDRESS = "bc1paul0w26tuf9sm75htghayux7xf6vep4zsqrrm0sysawghqjkdm9smddcqp" const val PINNED_GUARDIAN_ROOT = "03be02bea3b2feeb8d104c537db973f062211c89a2b82a0d2f9789184c260cbab4" const val PINNED_GUARDIAN_CHILD_INDEX = 1976210374L diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/GuardedWalletLineageTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/GuardedWalletLineageTest.kt deleted file mode 100644 index 3fe24638..00000000 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/GuardedWalletLineageTest.kt +++ /dev/null @@ -1,59 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.managers.LineageExample.heldBy -import mobi.giza.compose.managers.LineageExample.m -import mobi.giza.compose.managers.LineageExample.n -import mobi.giza.compose.managers.LineageExample.p -import mobi.giza.compose.managers.LineageExample.r -import mobi.giza.compose.managers.LineageExample.rent -import mobi.giza.compose.managers.LineageExample.rentGuardians -import mobi.giza.compose.managers.LineageExample.savings -import mobi.giza.compose.managers.LineageExample.savingsGuardians -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertNull -import kotlin.test.assertTrue - -/** - * Which group directly guards a member's wallet, and which branch of an - * ancestor's tree it sits under -- read off the guardians and the line of - * descent a verified certificate already gives. `docs/member-wallet-guarding-group.md`, Phase 1. - */ -class GuardedWalletLineageTest { - @Test - fun `the root sees Savings guarded by M, two generations down through P`() { - val wallet = heldBy(r, savings, savingsGuardians) - - assertEquals(m, wallet.directGuardianChatRoomId) - assertEquals(p, wallet.branchChatRoomId) - assertEquals(2, wallet.position) - assertFalse(wallet.isGuardedHere) - } - - @Test - fun `the root sees Rent guarded by its own child N, which is also the branch`() { - val wallet = heldBy(r, rent, rentGuardians) - - assertEquals(n, wallet.directGuardianChatRoomId) - assertEquals(n, wallet.branchChatRoomId) - assertEquals(1, wallet.position) - } - - @Test - fun `the middle group sees the same guardian, with M as its branch`() { - val wallet = heldBy(p, savings, savingsGuardians) - - assertEquals(m, wallet.directGuardianChatRoomId) - assertEquals(m, wallet.branchChatRoomId) - } - - @Test - fun `the group that signed the certificate guards it here, and has no branch`() { - val wallet = heldBy(m, savings, savingsGuardians) - - assertEquals(m, wallet.directGuardianChatRoomId) - assertTrue(wallet.isGuardedHere) - assertNull(wallet.branchChatRoomId) - } -} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/LineageExample.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/LineageExample.kt deleted file mode 100644 index 35a8096f..00000000 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/LineageExample.kt +++ /dev/null @@ -1,87 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.nostr.wallet.MemberWalletCertificateEvent -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.secp256k1.Hex - -/** - * The tree `docs/member-wallet-guarding-group.md` uses throughout, with Alice's - * two wallets in it: - * - * ``` - * R root - * ├── P R's guarded subgroup - * │ └── M P's guarded subgroup — guards Alice's "Savings" - * └── N R's guarded subgroup — guards Alice's "Rent" - * ``` - * - * The guardians are real grants, so `position` and `lineage` are what a - * verified certificate would give; the events are stand-ins, since nothing here - * checks a signature. - */ -object LineageExample { - private fun key(seed: Int): String = - PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))).publicKey().toString() - - val rKey = key(0x600d) - val pKey = key(0xbeef) - val mKey = key(0xcafe) - val nKey = key(0xf00d) - - val r = SharedKeyDerivation.marmotGroupId(rKey) - val p = SharedKeyDerivation.marmotGroupId(pKey) - val m = SharedKeyDerivation.marmotGroupId(mKey) - val n = SharedKeyDerivation.marmotGroupId(nKey) - - val alice = key(0xa11ce) - val savings = "5".repeat(64) - val rent = "7".repeat(64) - - private val pGrant = GuardianDerivation.grant(rKey, r, emptyList(), p) - private val mGrant = GuardianDerivation.grant(pKey, p, pGrant, m) - private val nGrant = GuardianDerivation.grant(rKey, r, emptyList(), n) - - /** Savings' guardians, `[M, P, R]`. */ - val savingsGuardians = GuardianDerivation.grant(mKey, m, mGrant, savings) - - /** Rent's guardians, `[N, R]`. */ - val rentGuardians = GuardianDerivation.grant(nKey, n, nGrant, rent) - - /** - * Alice's wallet [walletId] under [guardians], as [ancestor] holds it. - * [label] and the names are what `GuardianManager.named` would fill. - */ - fun heldBy( - ancestor: String, - walletId: String, - guardians: List, - label: String? = null, - ownerPublicKey: String = alice, - ownerName: String? = "alice", - guardianName: String? = null, - branchName: String? = null, - walletKey: Int = 0xdecaf, - ): GuardianManager.GuardedWallet { - val account = GroupWalletDerivation.account(key(walletKey), Chain.Regtest, guardians = guardians) - val certificate = Event(walletId.take(63) + "c", guardians.first().chatRoomId, 1_700_000_000, MemberWalletCertificateEvent.KIND, emptyArray(), walletId, "") - return GuardianManager.GuardedWallet( - ancestorChatRoomId = ancestor, - descendantChatRoomId = walletId, - statement = certificate, - account = account, - certificate = certificate, - lineage = requireNotNull(GuardianDerivation.lineage(guardians, walletId, ancestor)) { "$ancestor does not guard $walletId" }, - subject = GuardianManager.GuardedSubject.Member( - id = walletId, - ownerPublicKey = ownerPublicKey, - label = label, - ownerName = ownerName, - guardianName = guardianName, - branchName = branchName, - ), - ) - } -} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/MemberWalletDerivationTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/MemberWalletDerivationTest.kt deleted file mode 100644 index 5610bd0d..00000000 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/MemberWalletDerivationTest.kt +++ /dev/null @@ -1,168 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.wallet.GroupSpend -import mobi.giza.compose.wallet.GroupSpendBuilder -import mobi.giza.compose.wallet.GroupWalletState -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.Descriptor -import fr.acinq.bitcoin.OutPoint -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.Satoshi -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 fr.acinq.secp256k1.Hex -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFails -import kotlin.test.assertIs -import kotlin.test.assertNotEquals -import kotlin.test.assertTrue - -/** - * A member's guarded wallet, from the member's side: the private key reaches - * every address the public derivation does, and a spend signed with it is one - * the script interpreter accepts. The guardians' side -- that an ancestor signs - * every leaf of a member's wallet -- is the last test. - */ -class MemberWalletDerivationTest { - private val chain = Chain.Regtest - - private fun privateKey(seed: Long): PrivateKey = PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))) - - private val walletPrivateKey = privateKey(0xa11ce) - private val walletKey = walletPrivateKey.publicKey() - private val walletId = MemberWalletDerivation.walletId(walletKey) - - private val groupKey = privateKey(0x6a0b).publicKey().toString() - private val groupRoom = SharedKeyDerivation.marmotGroupId(groupKey) - private val parentKey = privateKey(0x9a9e).publicKey().toString() - private val parentRoom = SharedKeyDerivation.marmotGroupId(parentKey) - - /** The group's own grant from its parent, then the group's grant to the member's wallet: two guardians. */ - private val grant: List = run { - val groupsOwn = GuardianDerivation.grant(parentKey, parentRoom, emptyList(), groupRoom) - GuardianDerivation.grant(groupKey, groupRoom, groupsOwn, walletId) - } - - private val account = MemberWalletDerivation.account(walletKey, chain, grant) - - @Test - fun `the wallet id is a hash of the key and not the key`() { - assertEquals(64, walletId.length) - assertNotEquals(walletKey.xOnly().value.toHex(), walletId) - assertEquals(walletId, MemberWalletDerivation.walletId(walletKey.toString())) - assertNotEquals(walletId, MemberWalletDerivation.walletId(privateKey(0xb0b).publicKey())) - // A wallet id is a valid child index, as a room id is. - GuardianDerivation.childIndex(walletId) - } - - @Test - fun `the private key reaches every address the public derivation does`() { - for (change in listOf(GroupWalletDerivation.RECEIVE, GroupWalletDerivation.CHANGE)) { - for (index in listOf(0L, 1L, 2L, 7L, 1_000L)) { - val derived = GroupWalletDerivation.derive(account, change, index) - val privateKey = MemberWalletDerivation.privateKeyAt(walletPrivateKey, chain, change, index) - assertEquals(derived.internalKey, privateKey.xOnlyPublicKey(), "at $change/$index") - } - } - } - - @Test - fun `the account private key extends to the account xpub`() { - val extended = MemberWalletDerivation.accountPrivateKey(walletPrivateKey, chain) - assertEquals(account.extendedPublicKey, extended.extendedPublicKey) - assertNotEquals(walletKey, extended.publicKey, "the wallet key itself is never the account key") - } - - @Test - fun `the descriptors carry the tree and check out`() { - assertTrue(account.isGuarded) - val descriptor = account.receiveDescriptor - val (body, checksum) = descriptor.split('#') - assertEquals(Descriptor.checksum(body), checksum) - assertTrue(body.contains("and_v(v:pk("), "a leaf per guardian") - assertEquals(2, Regex("older\\(12\\)").findAll(body).count()) - } - - private fun coin(index: Int, sats: Long): Pair { - val derived = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, index.toLong()) - val tx = Transaction( - 2, - listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { (index + 1).toByte() })), 0), ByteVector.empty, 0xffffffffL)), - listOf(TxOut(Satoshi(sats), derived.pubkeyScript)), - 0, - ) - val meta = WalletState.AddressMeta.Derived(index) - return derived.address(chain) to WalletState.AddressState(meta, alreadyUsed = true, utxos = listOf(WalletState.Utxo(tx.txid, 0, 100, tx, meta))) - } - - private fun state(vararg coins: Pair): GroupWalletState { - val change = WalletState( - mapOf( - GroupWalletDerivation.derive(account, GroupWalletDerivation.CHANGE, 0).address(chain) to - WalletState.AddressState(WalletState.AddressMeta.Derived(0), false, emptyList()) - ) - ) - return GroupWalletState(account, WalletState(coins.toMap()), change, tipHeight = 110) - } - - private fun checked(result: GroupSpendBuilder.Result): GroupSpend.Checked { - val built = assertIs(result) - return assertIs(GroupSpend.check(built.psbt, account)).checked - } - - @Test - fun `a spend the member signs alone is one the network accepts`() { - val spend = checked( - GroupSpendBuilder.sendAll(state(coin(0, 60_000), coin(3, 40_000)), "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080", 5L, emptySet()) - ) - val signatures = spend.inputs.map { MemberWalletDerivation.sign(walletPrivateKey, chain, it) } - val signed = spend.witnessed(signatures) - - assertEquals(2, signed.txIn.size) - signed.txIn.forEach { assertEquals(1, it.witness.stack.size, "a key-path spend reveals no tree") } - signed.correctlySpends(spend.inputs.associate { it.outPoint to it.txOut }, ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) - } - - @Test - fun `another key does not sign the member's coins`() { - val spend = checked( - GroupSpendBuilder.sendAll(state(coin(0, 60_000)), "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080", 5L, emptySet()) - ) - assertFails { MemberWalletDerivation.sign(privateKey(0xb0b), chain, spend.inputs.single()) } - } - - @Test - fun `every guardian reaches its leaf in the member's wallet`() { - // The group itself, then its parent two generations up: the walk each - // signs a leaf with ends at the wallet id, as it would end at a room. - val groupLineage = GuardianDerivation.lineage(grant, walletId, groupRoom)!! - assertEquals(listOf(walletId), groupLineage) - val parentLineage = GuardianDerivation.lineage(grant, walletId, parentRoom)!! - assertEquals(listOf(groupRoom, walletId), parentLineage) - - listOf(groupKey to groupLineage, parentKey to parentLineage).forEachIndexed { position, (key, lineage) -> - val signing = GuardianDerivation.signingCache(key, lineage, chain, MemberWalletDerivation.ACCOUNT, 0, 4) - assertEquals(GuardianDerivation.leafKey(grant[position], chain, MemberWalletDerivation.ACCOUNT, 0, 4), signing.leafKey) - } - } - - @Test - fun `the exported descriptors carry the private key and nothing else changes`() { - val (receive, change) = MemberWalletDerivation.privateDescriptors(walletPrivateKey, account) - for ((exported, public) in listOf(receive to account.receiveDescriptor, change to account.changeDescriptor)) { - val (body, checksum) = exported.split('#') - assertEquals(Descriptor.checksum(body), checksum) - assertTrue(body.contains("tprv"), "a test network's private key") - assertTrue(!body.contains(account.xpub), "the account xpub is gone") - assertEquals(public.substringBefore('#').replace(account.xpub, ""), body.replace(Regex("tprv[1-9A-HJ-NP-Za-km-z]+"), "")) - } - assertFails { MemberWalletDerivation.privateDescriptors(privateKey(0xb0b), account) } - } -} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/wallet/MemberWalletPolicyEventTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/wallet/MemberWalletPolicyEventTest.kt deleted file mode 100644 index e91fb6ea..00000000 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/wallet/MemberWalletPolicyEventTest.kt +++ /dev/null @@ -1,92 +0,0 @@ -package mobi.giza.compose.nostr.wallet - -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Crypto -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.secp256k1.Hex -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertIs -import kotlin.test.assertNull - -/** - * A group's policy on its members' wallets -- `docs/member-wallet-delay.md`, - * Phase 1. The room is a key whose secret the test holds: `isSignedByRoom` asks - * only that the room's id signed it. - */ -class MemberWalletPolicyEventTest { - private val roomKey = PrivateKey(ByteVector32(Hex.decode("07".repeat(32)))) - private val roomId = roomKey.publicKey().xOnly().value.toString() - private val strangerKey = PrivateKey(ByteVector32(Hex.decode("09".repeat(32)))) - - private fun signed( - tags: Array>, - createdAt: Long = 1_700_000_000, - by: PrivateKey = roomKey, - kind: Int = MemberWalletPolicyEvent.KIND, - ): Event { - val pubKey = by.publicKey().xOnly().value.toString() - val id = EventHasher.hashId(pubKey, createdAt, kind, tags, "") - return Event(id, pubKey, createdAt, kind, tags, "", Crypto.signSchnorr(ByteVector32(id), by, null).toString()) - } - - private fun open(delay: Long, createdAt: Long = 1_700_000_000) = signed(MemberWalletPolicyEvent.open(delay, createdAt).tags, createdAt) - private fun closed(createdAt: Long = 1_700_000_000) = signed(MemberWalletPolicyEvent.closed(createdAt).tags, createdAt) - - @Test - fun `an open policy and a closed one each read back`() { - val opened = assertIs(MemberWalletPolicyEvent.verify(open(144), roomId)) - assertEquals(144L, opened.delay) - assertIs(MemberWalletPolicyEvent.verify(closed(), roomId)) - } - - @Test - fun `a policy that does not say one thing a device can act on does not read`() { - val d = arrayOf("d", MemberWalletPolicyEvent.IDENTIFIER) - val cases = mapOf( - "another kind" to signed(arrayOf(d, arrayOf("guardian_delay", "144")), kind = 30336), - "no d tag" to signed(arrayOf(arrayOf("guardian_delay", "144"))), - "another d tag" to signed(arrayOf(arrayOf("d", "subgroups"), arrayOf("guardian_delay", "144"))), - "two delays" to signed(arrayOf(d, arrayOf("guardian_delay", "144"), arrayOf("guardian_delay", "12"))), - "five blocks" to signed(arrayOf(d, arrayOf("guardian_delay", "5"))), - "65,536 blocks" to signed(arrayOf(d, arrayOf("guardian_delay", "65536"))), - "a word" to signed(arrayOf(d, arrayOf("guardian_delay", "twelve"))), - "both a delay and closed" to signed(arrayOf(d, arrayOf("guardian_delay", "144"), arrayOf("closed"))), - "neither" to signed(arrayOf(d)), - "another room's signature" to signed(MemberWalletPolicyEvent.open(144).tags, by = strangerKey), - ) - cases.forEach { (name, event) -> assertNull(MemberWalletPolicyEvent.verify(event, roomId), "a policy with $name read") } - } - - @Test - fun `the newest decides, open or closed, in any order`() { - val first = open(12, createdAt = 1_700_000_000) - val shut = closed(createdAt = 1_700_000_100) - val reopened = open(1_008, createdAt = 1_700_000_200) - - listOf(listOf(first, shut, reopened), listOf(reopened, first, shut), listOf(shut, reopened, first)).forEach { events -> - assertEquals(1_008L, assertIs(MemberWalletPolicyEvent.newestAmong(events, roomId)).delay) - } - assertIs(MemberWalletPolicyEvent.newestAmong(listOf(shut, first), roomId)) - assertNull(MemberWalletPolicyEvent.newestAmong(emptyList(), roomId)) - } - - @Test - fun `a tie on the timestamp goes to the larger id, on every device`() { - val a = open(144, createdAt = 1_700_000_000) - val b = open(1_008, createdAt = 1_700_000_000) - val larger = listOf(a, b).maxBy { it.id } - - assertEquals(larger.id, MemberWalletPolicyEvent.newestAmong(listOf(a, b), roomId)?.event?.id) - assertEquals(larger.id, MemberWalletPolicyEvent.newestAmong(listOf(b, a), roomId)?.event?.id) - } - - @Test - fun `an open policy outside the range cannot be built`() { - assertFailsWith { MemberWalletPolicyEvent.open(5) } - assertFailsWith { MemberWalletPolicyEvent.open(65_536) } - } -} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/wallet/MemberWalletRequestEventTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/wallet/MemberWalletRequestEventTest.kt deleted file mode 100644 index 966eaa7f..00000000 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/wallet/MemberWalletRequestEventTest.kt +++ /dev/null @@ -1,127 +0,0 @@ -package mobi.giza.compose.nostr.wallet - -import mobi.giza.compose.managers.GuardianDerivation -import mobi.giza.compose.managers.MemberWalletDerivation -import mobi.giza.compose.managers.SharedKeyDerivation -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.Crypto -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.secp256k1.Hex -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertNotNull -import kotlin.test.assertNull - -/** - * A member's request, read and believed on everything that can be checked - * without the group's key -- one mutation per check, each of which has to be - * enough on its own to refuse it. - */ -class MemberWalletRequestEventTest { - private val chain = Chain.Regtest - - private fun privateKey(seed: Long): PrivateKey = PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))) - - private val member = privateKey(0x3e3be7) - private val walletPrivateKey = privateKey(0xa11ce) - private val walletKey = walletPrivateKey.publicKey() - private val walletId = MemberWalletDerivation.walletId(walletKey) - - private val groupKey = privateKey(0x6a0b).publicKey().toString() - private val groupRoom = SharedKeyDerivation.marmotGroupId(groupKey) - private val parentKey = privateKey(0x9a9e).publicKey().toString() - private val parentRoom = SharedKeyDerivation.marmotGroupId(parentKey) - - private val grant = GuardianDerivation.grant( - groupKey, groupRoom, GuardianDerivation.grant(parentKey, parentRoom, emptyList(), groupRoom), walletId, - ) - private val account = MemberWalletDerivation.account(walletKey, chain, grant) - - private fun request(label: String? = "Savings", group: String = groupRoom) = - MemberWalletRequestEvent.build(member, group, walletPrivateKey, account, label, createdAt = 1_700_000_000) - - /** [event] with [tags], re-signed by the member, so only the tags are wrong. */ - private fun resigned(event: Event, tags: Array> = event.tags, content: String = event.content): Event { - val id = EventHasher.hashId(event.pubKey, event.createdAt, event.kind, tags, content) - val sig = Crypto.signSchnorr(ByteVector32(id), member, null).toHex() - return Event(id, event.pubKey, event.createdAt, event.kind, tags, content, sig) - } - - private fun Event.replacing(name: String, vararg value: String): Array> = - tags.map { if (it[0] == name) arrayOf(name, *value) else it }.toTypedArray() - - @Test - fun `a request reads and is believed`() { - val verified = assertNotNull(MemberWalletRequestEvent.verified(request())) - assertEquals(member.xOnlyPublicKey().value.toHex(), verified.reading.memberPublicKey) - assertEquals(groupRoom, verified.reading.groupChatRoomId) - assertEquals(walletId, verified.reading.walletId) - assertEquals(grant, verified.reading.guardians) - assertEquals("Savings", verified.reading.label) - assertEquals(account, verified.account) - } - - @Test - fun `a request with no label reads`() { - assertNull(assertNotNull(MemberWalletRequestEvent.verified(request(label = null))).reading.label) - assertNull(MemberWalletRequestEvent.verified(request(label = " ")).let { it?.reading?.label }) - } - - @Test - fun `a request somebody else signed is refused`() { - val signedByAnother = request().let { Event(it.id, it.pubKey, it.createdAt, it.kind, it.tags, it.content, "0".repeat(128)) } - assertNull(MemberWalletRequestEvent.verified(signedByAnother)) - } - - @Test - fun `a wallet id that is not the key's is refused`() { - val event = request() - assertNull(MemberWalletRequestEvent.verified(resigned(event, event.replacing("wallet", "f".repeat(64))))) - } - - @Test - fun `a possession signature by another key is refused`() { - val event = request() - val other = Crypto.signSchnorr(ByteVector32("ab".repeat(32)), privateKey(0xb0b), null).toHex() - assertNull(MemberWalletRequestEvent.verified(resigned(event, event.replacing("possession", other)))) - } - - @Test - fun `a request that leaves out the group it asks is refused`() { - // Signed for the group, but asking a stranger: the nearest guardian is not the group asked. - val event = request() - val stranger = SharedKeyDerivation.marmotGroupId(privateKey(0x57a9).publicKey().toString()) - assertNull(MemberWalletRequestEvent.verified(resigned(event, event.replacing("h", stranger)))) - } - - @Test - fun `a descriptor that does not rederive is refused`() { - val event = request() - val plain = MemberWalletDerivation.account(walletKey, chain, emptyList()) - val tags = event.tags.map { if (it[0] == "descriptor" && it[2] == "receive") arrayOf("descriptor", plain.receiveDescriptor, "receive") else it } - assertNull(MemberWalletRequestEvent.verified(resigned(event, tags.toTypedArray()))) - // The xpub does not depend on the guardians, so it is another key's that does not rederive. - val another = MemberWalletDerivation.account(privateKey(0xb0b).publicKey(), chain, grant) - assertNull(MemberWalletRequestEvent.verified(resigned(event, content = another.xpub))) - } - - @Test - fun `two wallet tags, or none, do not read`() { - val event = request() - assertNull(MemberWalletRequestEvent.read(resigned(event, event.tags + arrayOf(arrayOf("wallet", walletId))))) - assertNull(MemberWalletRequestEvent.read(resigned(event, event.tags.filterNot { it[0] == "wallet" }.toTypedArray()))) - } - - @Test - fun `a request travels whole, sent only by the member who signed it`() { - val signed = request() - fun inner(sender: String) = Event("1".repeat(64), sender, signed.createdAt, MemberWalletRequestEvent.KIND, emptyArray(), signed.toJson(), "") - - assertEquals(signed.id, MemberWalletRequestEvent.carried(inner(signed.pubKey))?.id) - assertNotNull(MemberWalletRequestEvent.verified(MemberWalletRequestEvent.carried(inner(signed.pubKey))!!), "the signature survives the trip") - assertNull(MemberWalletRequestEvent.carried(inner("2".repeat(64))), "nobody passes a request on") - } -} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/ui/view/state/GuardedWalletRowTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/ui/view/state/GuardedWalletRowTest.kt deleted file mode 100644 index 2988c406..00000000 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/ui/view/state/GuardedWalletRowTest.kt +++ /dev/null @@ -1,123 +0,0 @@ -package mobi.giza.compose.ui.view.state - -import mobi.giza.compose.managers.GroupWalletDerivation -import mobi.giza.compose.managers.GuardianDerivation -import mobi.giza.compose.managers.GuardianManager -import mobi.giza.compose.managers.LineageExample -import mobi.giza.compose.managers.LineageExample.heldBy -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import mobi.giza.compose.wallet.GroupWalletState -import com.vitorpamplona.quartz.nip01Core.core.Event -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.Transaction -import fr.acinq.bitcoin.TxId -import fr.acinq.bitcoin.TxIn -import fr.acinq.bitcoin.TxOut -import fr.acinq.lightning.blockchain.electrum.WalletState -import fr.acinq.secp256k1.Hex -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertNull - -/** - * What an ancestor's wallet screen says about a descendant's guarded wallet: a - * funding is *arriving* until the leaf's lock lets it go, and then *within - * reach* -- never neither, which would make the money look gone. - */ -class GuardedWalletRowTest { - private val descendantRoomId = "c".repeat(64) - /** Guarded by the ancestor below, at the default delay, as a verified statement would be. */ - private val account = GroupWalletDerivation.account( - PrivateKey(ByteVector32(Hex.decode("decaf".padStart(64, '0')))).publicKey().toString(), Chain.Regtest, - guardians = GuardianDerivation.grant(PrivateKey(ByteVector32(Hex.decode("a11ce".padStart(64, '0')))).publicKey().toString(), "d".repeat(64), emptyList(), descendantRoomId), - ) - private val wallet = GuardianManager.GuardedWallet( - ancestorChatRoomId = "d".repeat(64), - descendantChatRoomId = descendantRoomId, - statement = Event("1".repeat(64), descendantRoomId, 1_700_000_000, GroupWalletStatementEvent.KIND, emptyArray(), "", ""), - account = account, - certificate = Event("2".repeat(64), "d".repeat(64), 1_700_000_000, 0, emptyArray(), "", ""), - lineage = listOf(descendantRoomId), - ) - - /** One coin of 50,000 sats at the first receive address, confirmed at [height] (0 in the mempool), with the tip at [tip]. */ - private fun holding(height: Long, tip: Int): GroupWalletState { - val derived = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, 0) - val tx = Transaction(2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 7 })), 0), ByteVector.empty, 0xffffffffL)), listOf(TxOut(Satoshi(50_000), derived.pubkeyScript)), 0) - val meta = WalletState.AddressMeta.Derived(0) - return GroupWalletState( - account, - WalletState(mapOf(derived.address(Chain.Regtest) to WalletState.AddressState(meta, true, listOf(WalletState.Utxo(tx.txid, 0, height, tx, meta))))), - WalletState.empty, - tipHeight = tip, - ) - } - - @Test - fun `a coin is arriving until the lock lets it go, then within reach`() { - val lock = GuardianDerivation.DEFAULT_DELAY.toInt() - - val mempool = GuardedWalletRow(wallet, holding(height = 0, tip = 100)) - assertEquals(Satoshi(50_000), mempool.arriving) - assertEquals(Satoshi(0), mempool.withinReach) - - val young = GuardedWalletRow(wallet, holding(height = 100, tip = 100 + lock - 2)) - assertEquals(Satoshi(50_000), young.arriving, "${lock - 1} confirmations") - assertEquals(Satoshi(0), young.withinReach) - - val old = GuardedWalletRow(wallet, holding(height = 100, tip = 100 + lock - 1)) - assertEquals(Satoshi(0), old.arriving, "$lock confirmations") - assertEquals(Satoshi(50_000), old.withinReach) - } - - @Test - fun `nothing is said before the chain is known`() { - val row = GuardedWalletRow(wallet, walletState = null) - assertNull(row.arriving) - assertNull(row.withinReach) - } - - // ---- By person: docs/member-wallet-guarding-group.md, Phase 4 --------- - - private val r = LineageExample.r - private val savingsAtR = GuardedWalletRow(heldBy(r, LineageExample.savings, LineageExample.savingsGuardians, label = "Savings", guardianName = "#M"), walletState = null) - private val rentAtR = GuardedWalletRow(heldBy(r, LineageExample.rent, LineageExample.rentGuardians, label = "Rent", guardianName = "#N"), walletState = null) - - @Test - fun `a member's two wallets under two groups are one person, the nearer first`() { - val people = listOf(savingsAtR, rentAtR).byPerson() - - val alice = people.single() - assertEquals(LineageExample.alice, alice.ownerPublicKey) - assertEquals("alice", alice.ownerName) - assertEquals(2, alice.guardianCount) - assertEquals(listOf("Rent", "Savings"), alice.rows.map { (it.wallet.subject as GuardianManager.GuardedSubject.Member).label }) - } - - @Test - fun `two wallets under one group count one guardian`() { - // A second wallet N guards for her: the guardians name the same rooms. - val holiday = GuardedWalletRow(heldBy(r, "9".repeat(64), LineageExample.rentGuardians, label = "Holiday"), walletState = null) - val alice = listOf(rentAtR, holiday).byPerson().single() - assertEquals(1, alice.guardianCount) - } - - @Test - fun `a subgroup's wallet is not a person`() { - assertEquals(emptyList(), listOf(GuardedWalletRow(wallet, walletState = null)).byPerson()) - } - - @Test - fun `people sort by name, and by key where there is none`() { - val bob = GuardedWalletRow(heldBy(r, "8".repeat(64), LineageExample.rentGuardians, ownerPublicKey = "b".repeat(64), ownerName = "bob"), walletState = null) - val nameless = GuardedWalletRow(heldBy(r, "6".repeat(64), LineageExample.rentGuardians, ownerPublicKey = "0".repeat(64), ownerName = null), walletState = null) - - val people = listOf(bob, nameless, savingsAtR).byPerson() - assertEquals(listOf("0".repeat(64), LineageExample.alice, "b".repeat(64)), people.map { it.ownerPublicKey }) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/dao/MemberWalletDaoJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/dao/MemberWalletDaoJvmTest.kt deleted file mode 100644 index 79ea0d35..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/dao/MemberWalletDaoJvmTest.kt +++ /dev/null @@ -1,76 +0,0 @@ -package mobi.giza.compose.database.dao - -import androidx.room3.Room -import mobi.giza.compose.database.GizaDatabase -import mobi.giza.compose.database.builder.getRoomDatabase -import mobi.giza.compose.database.model.MemberWallet -import mobi.giza.compose.database.model.MemberWalletSpend -import mobi.giza.compose.managers.GroupFixtures -import kotlinx.coroutines.runBlocking -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.time.Instant - -/** - * Schema 30's two tables round-trip, are scoped by profile, and -- the property - * that matters most -- outlive the room of the group that guards them. - */ -class MemberWalletDaoJvmTest { - private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) - - @AfterTest - fun closeDb() = db.close() - - private val group = "6a".repeat(32) - private val alice = "a1".repeat(32) - private val bob = "b0".repeat(32) - - private fun wallet(id: String, owner: String = alice) = MemberWallet( - walletId = id, - ownerPublicKey = owner, - guardingChatRoomId = group, - chain = "regtest", - walletPrivateKey = "11".repeat(32), - label = "Savings", - requestJson = "{}", - createdAt = Instant.fromEpochSeconds(1_700_000_000), - ) - - @Test - fun `a wallet round-trips and is listed for its owner only`(): Unit = runBlocking { - val dao = db.memberWalletDao() - dao.upsert(wallet("01".repeat(32))) - dao.upsert(wallet("02".repeat(32), owner = bob)) - - assertEquals(wallet("01".repeat(32)), dao.getById("01".repeat(32))) - assertEquals(listOf("01".repeat(32)), dao.getByOwner(alice).map { it.walletId }) - assertEquals(2, dao.getByGuardingChatRoomId(group).size) - assertFalse(wallet("01".repeat(32)).toString().contains("11".repeat(32)), "the key is never in a log line") - } - - @Test - fun `deleting the group's room leaves the key`(): Unit = runBlocking { - GroupFixtures.seedRoom(db, group) - db.memberWalletDao().upsert(wallet("01".repeat(32))) - - db.chatRoomDao().delete(assertNotNull(db.chatRoomDao().findChatRoomById(group)).chatRoom) - - assertNull(db.chatRoomDao().findChatRoomById(group)) - assertNotNull(db.memberWalletDao().getById("01".repeat(32))) - } - - @Test - fun `a spend round-trips and is filled in`(): Unit = runBlocking { - val dao = db.memberWalletDao() - val spend = MemberWalletSpend(txid = "aa".repeat(32), walletId = "01".repeat(32), psbt = "cHNidP8=", signedTransaction = "00") - dao.upsertSpend(spend) - dao.upsertSpend(spend.copy(seenAt = Instant.fromEpochSeconds(1_700_000_100))) - - assertEquals(Instant.fromEpochSeconds(1_700_000_100), dao.getSpend("aa".repeat(32))?.seenAt) - assertEquals(1, dao.getSpends("01".repeat(32)).size) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupFixtures.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupFixtures.kt index 5b1f4c3d..c16cdb19 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupFixtures.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupFixtures.kt @@ -1,7 +1,5 @@ package mobi.giza.compose.managers -import mobi.giza.compose.database.model.GroupSignedEvent -import mobi.giza.compose.nostr.wallet.MemberWalletPolicyEvent import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.model.ChatRoom import mobi.giza.compose.database.model.DkgParticipantMessage @@ -67,32 +65,6 @@ internal object GroupFixtures { return Event(id = id, pubKey = pubKey, createdAt = createdAt, kind = kind, tags = tags, content = content, sig = signature(material, id)) } - /** - * [group]'s policy on its members' wallets, signed by its room: open at - * [delay], or closed when [delay] is null. `docs/member-wallet-delay.md`. - */ - fun memberWalletPolicy(group: KeyMaterial, delay: Long?, createdAt: Long = 1_700_000_000): Event { - val template = delay?.let { MemberWalletPolicyEvent.open(it, createdAt) } ?: MemberWalletPolicyEvent.closed(createdAt) - return signedAsRoom(group, template.kind, template.tags, template.content, createdAt) - } - - /** - * [group] opened to its members' wallets at [delay]: the policy every member - * wallet test needs before a member can ask, since a group with none does - * not guard members' wallets. `docs/member-wallet-delay.md`, D8. - */ - suspend fun openToMembers(db: GizaDatabase, group: KeyMaterial, delay: Long = GuardianDerivation.DEFAULT_DELAY, createdAt: Long = 1_600_000_000) { - if (db.chatRoomDao().findChatRoomById(roomOf(group)) == null) seedRoom(db, roomOf(group)) - filePolicy(db, group, memberWalletPolicy(group, delay, createdAt)) - } - - /** [policy] filed as [group]'s room files a signed event: a `GroupSignedEvent` row. */ - suspend fun filePolicy(db: GizaDatabase, group: KeyMaterial, policy: Event) { - db.groupSignedEventDao().upsert( - GroupSignedEvent.fromEvent(policy, chatRoomId = roomOf(group), derivationPath = SharedKeyDerivation.formatPath(path), frostSigningSessionId = null) - ) - } - /** * [parent]'s certificate for [child], granting [guardians] under [policy] -- * the grant is the caller's, so a test can hand over a wrong one. diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupKeyNoticeJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupKeyNoticeJvmTest.kt deleted file mode 100644 index 18cebed5..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupKeyNoticeJvmTest.kt +++ /dev/null @@ -1,176 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.nostr.wallet.MemberWalletPolicyEvent -import androidx.room3.Room -import mobi.giza.compose.database.GizaDatabase -import mobi.giza.compose.database.builder.getRoomDatabase -import mobi.giza.compose.database.model.MarmotInnerEvent -import mobi.giza.compose.managers.GroupFixtures.fileKeyState -import mobi.giza.compose.managers.GroupFixtures.guardedCertificate -import mobi.giza.compose.managers.GroupFixtures.keyMaterial -import mobi.giza.compose.managers.GroupFixtures.roomOf -import mobi.giza.compose.managers.GroupFixtures.thresholdKeyOf -import mobi.giza.compose.managers.MemberWalletManager.asEvent -import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent -import mobi.giza.compose.nostr.wallet.GroupKeyNoticeEvent -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.toHexKey -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair -import kotlinx.coroutines.runBlocking -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.Instant - -/** - * A member who holds no key state asking what the group signs with, and a member - * who holds one answering -- two devices, two databases, the inner-event rows - * carried from one to the other as the MLS room would carry them. - * - * The negative cases carry the weight: an answer is believed only for what it - * can prove about itself, and never filed as the room's key state. - */ -class GroupKeyNoticeJvmTest { - private val asking: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) - private val answering: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) - - @AfterTest - fun closeDbs() { - asking.close() - answering.close() - } - - private val parent = keyMaterial("9a9e") - private val group = keyMaterial("6a0b") - private val stranger = keyMaterial("57a9") - private val groupRoom = roomOf(group) - private val certificate = guardedCertificate(parent, group) - - private val member = KeyPair().pubKey.toHexKey() - private val signer = KeyPair().pubKey.toHexKey() - - /** Carries every row of [kind] in the group's room from [from] to [to], as the room would. */ - private suspend fun deliver(from: GizaDatabase, to: GizaDatabase) = - from.marmotInnerEventDao().getByChatRoomAndKinds(groupRoom, listOf(GroupKeyNoticeEvent.KIND)).forEach { to.marmotInnerEventDao().upsert(it) } - - @Test - fun `a member with no key state asks, is answered, and learns the key and the certificate`(): Unit = runBlocking { - fileKeyState(answering, group, certificate) - - assertNull(MemberWalletManager.groupKeyFor(asking, groupRoom)) - assertTrue(MemberWalletManager.askForGroupKey(asking, groupRoom, member)) - assertFalse(MemberWalletManager.askForGroupKey(asking, groupRoom, member), "asked and not yet answered") - - deliver(asking, answering) - val request = answering.marmotInnerEventDao().getByChatRoomAndKinds(groupRoom, listOf(GroupKeyNoticeEvent.KIND)).single().asEvent() - assertTrue(MemberWalletManager.answerKeyRequest(answering, groupRoom, request, signer)) - assertFalse(MemberWalletManager.answerKeyRequest(answering, groupRoom, request, signer), "answered once") - - deliver(answering, asking) - val groupKey = assertNotNull(MemberWalletManager.groupKeyFor(asking, groupRoom)) - assertEquals(thresholdKeyOf(group), groupKey.thresholdPublicKey) - assertEquals(certificate.id, groupKey.certificate?.id) - assertEquals(SubgroupBirthCertificateEvent.parseGuardians(certificate.tags), groupKey.guardians) - assertNull(groupKey.policy, "the answering device held no member-wallet policy, and says nothing about one") - - assertNull(asking.groupKeyStateDao().getByChatRoomId(groupRoom), "an answer is never filed as key state") - assertFalse(MemberWalletManager.askForGroupKey(asking, groupRoom, member), "nothing left to ask") - } - - /** docs/member-wallet-delay.md, Phase 3: the late member's only way to the group's policy. */ - private suspend fun askedAndAnswered(policy: Event) { - fileKeyState(answering, group, certificate) - GroupFixtures.filePolicy(answering, group, policy) - MemberWalletManager.askForGroupKey(asking, groupRoom, member) - deliver(asking, answering) - val request = answering.marmotInnerEventDao().getByChatRoomAndKinds(groupRoom, listOf(GroupKeyNoticeEvent.KIND)).single().asEvent() - assertTrue(MemberWalletManager.answerKeyRequest(answering, groupRoom, request, signer)) - deliver(answering, asking) - } - - @Test - fun `an answer carries the group's open policy to a member who joined after it`(): Unit = runBlocking { - askedAndAnswered(GroupFixtures.memberWalletPolicy(group, 144)) - - val policy = MemberWalletManager.policyFor(asking, groupRoom) - assertEquals(144L, (policy as MemberWalletPolicyEvent.Policy.Open).delay) - } - - @Test - fun `an answer carries a closed policy as well`(): Unit = runBlocking { - askedAndAnswered(GroupFixtures.memberWalletPolicy(group, null)) - - assertTrue(MemberWalletManager.policyFor(asking, groupRoom) is MemberWalletPolicyEvent.Policy.Closed) - } - - @Test - fun `an answer carrying a policy another room signed does not read at all`() { - val forged = GroupFixtures.memberWalletPolicy(stranger, 6) - val tags = GroupKeyNoticeEvent.answeringTags("e".repeat(64), GroupKeyNoticeEvent.GroupKey(groupRoom, thresholdKeyOf(group), certificate), GroupFixtures.path) + - arrayOf(arrayOf("member_wallet_policy", forged.toJson())) - - assertNull(GroupKeyNoticeEvent.read(answer(thresholdKeyOf(group), tags), groupRoom), "present and unreadable is not \"no policy\"") - } - - @Test - fun `a device that holds no key state answers nothing`(): Unit = runBlocking { - MemberWalletManager.askForGroupKey(asking, groupRoom, member) - deliver(asking, answering) - val request = answering.marmotInnerEventDao().getByChatRoomAndKinds(groupRoom, listOf(GroupKeyNoticeEvent.KIND)).single().asEvent() - - assertFalse(MemberWalletManager.answerKeyRequest(answering, groupRoom, request, signer)) - } - - private fun answer(content: String, tags: Array>): Event { - val pubKey = signer - val id = EventHasher.hashId(pubKey, 1_700_000_000, GroupKeyNoticeEvent.KIND, tags, content) - return Event(id, pubKey, 1_700_000_000, GroupKeyNoticeEvent.KIND, tags, content, "") - } - - private fun answerFor(groupKey: GroupKeyNoticeEvent.GroupKey): Event = - answer(groupKey.thresholdPublicKey, GroupKeyNoticeEvent.answeringTags("e".repeat(64), groupKey, GroupFixtures.path)) - - @Test - fun `an answer is believed only for what it proves`() { - val honest = GroupKeyNoticeEvent.GroupKey(groupRoom, thresholdKeyOf(group), certificate) - assertNotNull(GroupKeyNoticeEvent.read(answerFor(honest), groupRoom)) - - // Another group's key does not derive this room. - assertNull(GroupKeyNoticeEvent.read(answerFor(honest.copy(thresholdPublicKey = thresholdKeyOf(stranger))), groupRoom)) - // An answer about another room is not one about this room. - assertNull(GroupKeyNoticeEvent.read(answerFor(honest), roomOf(stranger))) - // A certificate for another child does not certify this one. - val elsewhere = guardedCertificate(parent, stranger) - assertNull(GroupKeyNoticeEvent.read(answerFor(honest.copy(certificate = elsewhere)), groupRoom)) - // A certificate whose signature is not the parent's. - val forged = Event(certificate.id, certificate.pubKey, certificate.createdAt, certificate.kind, certificate.tags, certificate.content, "0".repeat(128)) - assertNull(GroupKeyNoticeEvent.read(answerFor(honest.copy(certificate = forged)), groupRoom)) - // The asking shape is not an answer. - assertNull(GroupKeyNoticeEvent.read(answer("", GroupKeyNoticeEvent.askingTags(groupRoom)), groupRoom)) - // A root group's answer, with no certificate, reads with no guardians. - val root = GroupKeyNoticeEvent.read(answerFor(GroupKeyNoticeEvent.GroupKey(roomOf(parent), thresholdKeyOf(parent), null)), roomOf(parent)) - assertEquals(emptyList(), assertNotNull(root).guardians) - } - - @Test - fun `an answer that does not check out leaves the member asking`(): Unit = runBlocking { - val forged = answerFor(GroupKeyNoticeEvent.GroupKey(groupRoom, thresholdKeyOf(stranger), null)) - asking.marmotInnerEventDao().upsert( - MarmotInnerEvent( - id = forged.id, - publicKey = forged.pubKey, - kind = forged.kind, - createdAt = Instant.fromEpochSeconds(forged.createdAt), - tags = forged.tags, - content = forged.content, - chatRoomId = groupRoom, - ) - ) - assertNull(MemberWalletManager.groupKeyFor(asking, groupRoom)) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GuardedWalletForwardingRulesJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GuardedWalletForwardingRulesJvmTest.kt deleted file mode 100644 index e7ad5b3d..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GuardedWalletForwardingRulesJvmTest.kt +++ /dev/null @@ -1,116 +0,0 @@ -package mobi.giza.compose.managers - -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.thresholdKeyOf -import mobi.giza.compose.managers.GuardianManager.GuardedSubject -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -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.secp256k1.Hex -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertIs -import kotlin.test.assertNotNull -import kotlin.test.assertNull - -/** - * The rules forwarding is built on, with no database: which groups a statement - * is told to from a room -- upward only -- who sends at once, and what a - * forwarder believes before it passes anything on. - * `docs/guarded-wallet-forwarding.md`, Phase 1. - */ -class GuardedWalletForwardingRulesJvmTest { - 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) - - /** A grandchild's guardians as its certificate lists them: its parent, then the root one step further. */ - private val grandchildRoom = roomOf(keyMaterial("c1d0")) - private val grandchildGuardians = GuardianDerivation.grant( - thresholdKeyOf(middle), middleRoom, - GuardianDerivation.grant(thresholdKeyOf(root), rootRoom, emptyList(), middleRoom), - grandchildRoom, - ) - - @Test - fun `a grandchild's statement goes up from where it is, and never back down`() { - assertEquals(listOf(middleRoom, rootRoom), GuardianManager.upwardOf(grandchildGuardians, grandchildRoom), "from its own room, every guardian") - assertEquals(listOf(rootRoom), GuardianManager.upwardOf(grandchildGuardians, middleRoom), "from the middle group, the root alone") - assertEquals(emptyList(), GuardianManager.upwardOf(grandchildGuardians, rootRoom), "from the root, nothing: the middle group told it") - } - - private val member = privateKey(0x3e3be7) - private val walletPrivateKey = privateKey(0xa11ce) - private val walletId = MemberWalletDerivation.walletId(walletPrivateKey.publicKey()) - - /** A member's wallet under `group`, two levels below the root. */ - private val memberGuardians = GuardianDerivation.grant( - thresholdKeyOf(group), groupRoom, - GuardianDerivation.grant( - thresholdKeyOf(middle), middleRoom, - GuardianDerivation.grant(thresholdKeyOf(root), rootRoom, emptyList(), middleRoom), - groupRoom, - ), - walletId, - ) - - private fun certificate(signer: fr.acinq.bitcoin.crypto.frost.KeyMaterial = group): Event { - val request = MemberWalletRequestEvent.build( - memberPrivateKey = member, - groupChatRoomId = groupRoom, - walletPrivateKey = walletPrivateKey, - account = MemberWalletDerivation.account(walletPrivateKey.publicKey(), chain, memberGuardians), - label = null, - createdAt = 1_700_000_000, - ) - val template = MemberWalletCertificateEvent.template(request) - return signedAsRoom(signer, template.kind, template.tags, template.content, template.createdAt) - } - - @Test - fun `a member's wallet goes up from the group that signed it`() { - assertEquals(listOf(middleRoom, rootRoom), GuardianManager.upwardOf(memberGuardians, groupRoom)) - assertEquals(listOf(rootRoom), GuardianManager.upwardOf(memberGuardians, middleRoom)) - } - - @Test - fun `the lowest key sends at once`() { - assertEquals("0a".repeat(32), GuardianManager.electedSender(setOf("ff".repeat(32), "0A".repeat(32), "7c".repeat(32)))) - assertNull(GuardianManager.electedSender(emptySet())) - } - - @Test - fun `a forwarder believes a member's certificate the group signed`() { - val believed = assertNotNull(GuardianManager.believable(certificate())) - assertEquals(walletId, believed.descendantId) - assertEquals(memberGuardians, believed.guardians) - assertIs(believed.subject) - } - - @Test - fun `a forwarder believes nothing it could not check`() { - // Signed by a group that was not the one asked. - assertNull(GuardianManager.believable(certificate(signer = middle))) - // A signature that is not one. - val certificate = certificate() - assertNull(GuardianManager.believable(Event(certificate.id, certificate.pubKey, certificate.createdAt, certificate.kind, certificate.tags, certificate.content, "0".repeat(128)))) - // A plain wallet statement names no guardians. - val plain = GroupWalletStatementEvent.template(GroupWalletDerivation.account(thresholdKeyOf(group), chain)) - assertNull(GuardianManager.believable(signedAsRoom(group, plain.kind, plain.tags, plain.content, plain.createdAt))) - // Something else altogether. - assertNull(GuardianManager.believable(signedAsRoom(group, 1, emptyArray(), "hello"))) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GuardingGroupNameJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GuardingGroupNameJvmTest.kt deleted file mode 100644 index 817f1614..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GuardingGroupNameJvmTest.kt +++ /dev/null @@ -1,269 +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.database.model.MarmotInnerEvent -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.managers.GuardianManager.GuardedSubject -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.assertIs -import kotlin.test.assertNull -import kotlin.time.Instant - -/** - * The names a member's wallet is shown under in a group above it: the group - * that directly guards it, and the branch of the holder's tree it sits under -- - * each from a birth certificate this device can check, whoever handed it over, - * and never from one it cannot. `docs/member-wallet-guarding-group.md`, Phase 2. - * - * The tree is R ⊃ P ⊃ M, and M guards Alice's Savings. - */ -class GuardingGroupNameJvmTest { - 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 r = keyMaterial("7007") - private val p = keyMaterial("9a9e") - private val m = keyMaterial("6a0b") - private val stranger = keyMaterial("57a9") - private val rRoom = roomOf(r) - private val pRoom = roomOf(p) - private val mRoom = roomOf(m) - - 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 pGrant = GuardianDerivation.grant(thresholdKeyOf(r), rRoom, emptyList(), pRoom) - private val mGrant = GuardianDerivation.grant(thresholdKeyOf(p), pRoom, pGrant, mRoom) - private val savingsGrant = GuardianDerivation.grant(thresholdKeyOf(m), mRoom, mGrant, walletId) - - /** R's certificate for P, and P's for M, as their founding named them. */ - private val pCertificate = birthCertificate(r, p, pGrant, name = "#P") - private val mCertificate = birthCertificate(p, m, mGrant, name = "#M") - - /** M's certificate for Alice's Savings, guarded by `[M, P, R]`. */ - private val savings: Event = run { - val request = MemberWalletRequestEvent.build( - memberPrivateKey = member, - groupChatRoomId = mRoom, - walletPrivateKey = walletPrivateKey, - account = MemberWalletDerivation.account(walletPrivateKey.publicKey(), chain, savingsGrant), - label = "Savings", - createdAt = 1_700_000_000, - ) - val template = MemberWalletCertificateEvent.template(request) - signedAsRoom(m, template.kind, template.tags, template.content, template.createdAt) - } - - /** This device in [material]'s room, holding its key state. */ - private suspend fun inRoom(material: KeyMaterial, certificate: Event? = null, subject: String = "#" + roomOf(material).take(4)) { - signingRoom(db, material, members = listOf(memberPublicKey), subject = subject) - fileKeyState(db, material, certificate) - } - - /** [certificate] as one of [signer]'s own signed events here. */ - private suspend fun fileSigned(certificate: Event, signer: String) = - db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(certificate, chatRoomId = signer, derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path), frostSigningSessionId = null)) - - /** A notice of [statement] told to [room], carrying [certificate] as today's build does, or not as an older one did. */ - private suspend fun noticeIn(room: String, statement: Event, certificate: Event? = null) = - db.marmotInnerEventDao().upsert( - MarmotInnerEvent( - id = statement.id.take(60) + if (certificate == null) "0000" else "0001", - publicKey = memberPublicKey, - kind = GuardedWalletNoticeEvent.KIND, - createdAt = Instant.fromEpochSeconds(1_700_000_100), - tags = listOfNotNull(arrayOf("h", room), certificate?.let(GuardedWalletNoticeEvent::certificateTag)).toTypedArray(), - content = statement.toJson(), - chatRoomId = room, - ) - ) - - private suspend fun heldByR(): GuardedSubject.Member { - val listed = GuardianManager.guardedWalletsOf(db, rRoom).single() - assertEquals(mRoom, listed.directGuardianChatRoomId) - return assertIs(listed.subject) - } - - @Test - fun `a device in R and P names M from the certificate P signed`(): Unit = runBlocking { - inRoom(r) - inRoom(p, pCertificate) - fileSigned(pCertificate, signer = rRoom) - fileSigned(mCertificate, signer = pRoom) - noticeIn(rRoom, savings) - - val subject = heldByR() - assertEquals("#M", subject.guardianName) - assertEquals("#P", subject.branchName) - } - - @Test - fun `a device in R only knows its own branch, and not the group below it`(): Unit = runBlocking { - inRoom(r) - fileSigned(pCertificate, signer = rRoom) - noticeIn(rRoom, savings) - - val subject = heldByR() - assertNull(subject.guardianName) - assertEquals("#P", subject.branchName) - } - - @Test - fun `a certificate for M that P did not sign names nothing`(): Unit = runBlocking { - inRoom(r) - inRoom(p, pCertificate) - fileSigned(pCertificate, signer = rRoom) - // Filed under P, signed by a stranger: it does not certify M as P's child. - fileSigned(birthCertificate(stranger, m, mGrant, name = "#Impostor"), signer = pRoom) - noticeIn(rRoom, savings) - - assertNull(heldByR().guardianName) - } - - @Test - fun `a renamed M is still shown by its founding name`(): Unit = runBlocking { - inRoom(r) - inRoom(m, mCertificate, subject = "#Renamed") - fileSigned(pCertificate, signer = rRoom) - noticeIn(rRoom, savings) - - assertEquals("#M", heldByR().guardianName) - } - - @Test - fun `with no certificate to check, the room's name here is used`(): Unit = runBlocking { - inRoom(r) - inRoom(m, subject = "#Here") - noticeIn(rRoom, savings) - - assertEquals("#Here", heldByR().guardianName) - } - - // ---- Phase 3: the notice carries the guardian's certificate ---------- - - @Test - fun `a notice carrying M's certificate lets a device in R only name M`(): Unit = runBlocking { - inRoom(r) - noticeIn(rRoom, savings, certificate = mCertificate) - - val listed = GuardianManager.guardedWalletsOf(db, rRoom).single() - assertEquals("#M", assertIs(listed.subject).guardianName) - assertEquals(mCertificate.id, listed.guardianCertificate?.id) - } - - @Test - fun `a carried certificate that does not certify M is ignored, and the wallet is still listed`(): Unit = runBlocking { - inRoom(r) - // P's own certificate, naming P rather than M; and one for M a stranger signed. - noticeIn(rRoom, savings, certificate = pCertificate) - db.marmotInnerEventDao().upsert( - MarmotInnerEvent( - id = "ab".repeat(32), - publicKey = memberPublicKey, - kind = GuardedWalletNoticeEvent.KIND, - createdAt = Instant.fromEpochSeconds(1_700_000_200), - tags = arrayOf(arrayOf("h", rRoom), GuardedWalletNoticeEvent.certificateTag(birthCertificate(stranger, m, mGrant, name = "#Impostor"))), - content = savings.toJson(), - chatRoomId = rRoom, - ) - ) - - val listed = GuardianManager.guardedWalletsOf(db, rRoom).single() - assertNull(assertIs(listed.subject).guardianName) - assertNull(listed.guardianCertificate) - } - - @Test - fun `a room told before notices carried the certificate is offered again, once`(): Unit = runBlocking { - inRoom(m, mCertificate) - inRoom(p) - fileSigned(savings, signer = mRoom) - noticeIn(pRoom, savings) - - val again = GuardianManager.shareableFrom(db, mRoom, chain).single() - assertEquals(listOf(pRoom), again.rooms.map { it.chatRoom.id }) - assertEquals(mCertificate.id, again.certificate?.id) - - GuardianManager.share(db, again.statement, again.rooms, memberPublicKey, certificate = again.certificate) - assertEquals(emptyList(), GuardianManager.shareableFrom(db, mRoom, chain)) - } - - @Test - fun `with no certificate to add, a room already told is not offered again`(): Unit = runBlocking { - inRoom(m) - inRoom(p) - fileSigned(savings, signer = mRoom) - noticeIn(pRoom, savings) - - assertEquals(emptyList(), GuardianManager.shareableFrom(db, mRoom, chain)) - } - - @Test - fun `forwarding from M to P and on to R carries the certificate at both hops`(): Unit = runBlocking { - inRoom(m, mCertificate) - inRoom(p) - fileSigned(savings, signer = mRoom) - - val first = GuardianManager.shareableFrom(db, mRoom, chain).single() - GuardianManager.share(db, first.statement, first.rooms, memberPublicKey, certificate = first.certificate) - - // R joins this device later, so the second hop is P's to make. - inRoom(r) - val second = GuardianManager.shareableFrom(db, pRoom, chain).single() - assertEquals(listOf(rRoom), second.rooms.map { it.chatRoom.id }) - GuardianManager.share(db, second.statement, second.rooms, memberPublicKey, certificate = second.certificate) - - listOf(pRoom, rRoom).forEach { room -> - val notice = db.marmotInnerEventDao().getByChatRoomAndKinds(room, listOf(GuardedWalletNoticeEvent.KIND)).single() - assertEquals(mCertificate.id, GuardedWalletNoticeEvent.certificateIn(notice.tags)?.id, "the notice in $room") - } - } - - @Test - fun `forwarding on its own carries the certificate too, and tells a room told without it once more`(): Unit = runBlocking { - inRoom(m, mCertificate) - inRoom(p) - inRoom(r) - fileSigned(savings, signer = mRoom) - // R was told before notices carried the certificate. - noticeIn(rRoom, savings) - - val told = GuardianManager.forward(db, savings, mRoom, whenElected = false) - assertEquals(setOf(pRoom, rRoom), told.map { it.chatRoom.id }.toSet()) - listOf(pRoom, rRoom).forEach { room -> - val carried = db.marmotInnerEventDao().getByChatRoomAndKinds(room, listOf(GuardedWalletNoticeEvent.KIND)) - .mapNotNull { GuardedWalletNoticeEvent.certificateIn(it.tags) } - assertEquals(listOf(mCertificate.id), carried.map { it.id }, "the notice in $room") - } - assertEquals(emptyList(), GuardianManager.forward(db, savings, mRoom, whenElected = false), "told once with it") - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MemberWalletGuardianJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MemberWalletGuardianJvmTest.kt deleted file mode 100644 index 07a6d6c0..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MemberWalletGuardianJvmTest.kt +++ /dev/null @@ -1,242 +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.database.model.MarmotInnerEvent -import mobi.giza.compose.managers.GroupFixtures.fileKeyState -import mobi.giza.compose.managers.GroupFixtures.guardedCertificate -import mobi.giza.compose.managers.GroupFixtures.keyMaterial -import mobi.giza.compose.managers.GroupFixtures.roomOf -import mobi.giza.compose.managers.GroupFixtures.signWith -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.managers.GuardianManager.GuardedSubject -import mobi.giza.compose.nostr.wallet.GuardedWalletNoticeEvent -import mobi.giza.compose.nostr.wallet.MemberWalletCertificateEvent -import mobi.giza.compose.nostr.wallet.MemberWalletRequestEvent -import mobi.giza.compose.wallet.GroupSpend -import mobi.giza.compose.wallet.GroupSpendBuilder -import mobi.giza.compose.wallet.GroupWalletState -import com.vitorpamplona.quartz.nip01Core.core.Event -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.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 fr.acinq.secp256k1.Hex -import kotlinx.coroutines.runBlocking -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFails -import kotlin.test.assertIs -import kotlin.test.assertNotNull -import kotlin.test.assertNull -import kotlin.test.assertTrue -import kotlin.time.Instant - -/** - * The guardians' side of a member's wallet: the group that signed its - * certificate lists it, a group above learns of it from a notice and lists it - * too, each finds its own leaf in the wallet's addresses, and a spend through - * that leaf is one the script interpreter takes once the coin is 12 blocks old. - */ -class MemberWalletGuardianJvmTest { - 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 parent = keyMaterial("9a9e") - private val group = keyMaterial("6a0b") - private val stranger = keyMaterial("57a9") - private val groupRoom = roomOf(group) - private val parentRoom = roomOf(parent) - - 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 grant = GuardianDerivation.grant( - thresholdKeyOf(group), groupRoom, - GuardianDerivation.grant(thresholdKeyOf(parent), parentRoom, emptyList(), groupRoom), - walletId, - ) - - private fun certificate(guardians: List = grant): Event { - val request = MemberWalletRequestEvent.build( - memberPrivateKey = member, - groupChatRoomId = groupRoom, - walletPrivateKey = walletPrivateKey, - account = MemberWalletDerivation.account(walletPrivateKey.publicKey(), chain, guardians), - label = "Savings", - createdAt = 1_700_000_000, - ) - val template = MemberWalletCertificateEvent.template(request) - return signedAsRoom(group, template.kind, template.tags, template.content, template.createdAt) - } - - /** This device in [material]'s room, holding its verified key state. */ - private suspend fun inRoom(material: fr.acinq.bitcoin.crypto.frost.KeyMaterial, certificate: Event? = null) { - signingRoom(db, material, members = listOf(memberPublicKey), subject = "#" + roomOf(material).take(4)) - fileKeyState(db, material, certificate) - GroupFixtures.openToMembers(db, material) - } - - private suspend fun fileSigned(certificate: Event) = - db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(certificate, chatRoomId = groupRoom, derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path), frostSigningSessionId = null)) - - private suspend fun noticeIn(room: String, statement: Event) = - db.marmotInnerEventDao().upsert( - MarmotInnerEvent( - id = statement.id.take(60) + "0000", - publicKey = memberPublicKey, - kind = GuardedWalletNoticeEvent.KIND, - createdAt = Instant.fromEpochSeconds(1_700_000_100), - tags = arrayOf(arrayOf("h", room)), - content = statement.toJson(), - chatRoomId = room, - ) - ) - - @Test - fun `the group that signed it lists its member's wallet as theirs`(): Unit = runBlocking { - GroupFixtures.seedProfile(db, memberPublicKey, name = "alice") - inRoom(group, guardedCertificate(parent, group)) - fileSigned(certificate()) - - val listed = GuardianManager.guardedWalletsOf(db, groupRoom).single() - val subject = assertIs(listed.subject) - assertEquals(walletId, subject.id) - assertEquals(memberPublicKey, subject.ownerPublicKey) - assertEquals("alice", subject.ownerName) - assertEquals("Savings", subject.label) - assertEquals(walletId, listed.descendantChatRoomId) - assertEquals(listOf(walletId), listed.lineage) - assertEquals(0, listed.position) - assertNull(listed.name, "a member's wallet has no founding name") - assertEquals("@alice", listed.spender().name) - } - - @Test - fun `a group above learns of it from a notice, and walks down to its own leaf`(): Unit = runBlocking { - inRoom(parent) - noticeIn(parentRoom, certificate()) - - val listed = GuardianManager.guardedWalletsOf(db, parentRoom).single() - assertEquals(listOf(groupRoom, walletId), listed.lineage) - assertEquals(1, listed.position) - // The notice as it was filed: a second of the same certificate would be silent. - val filed = db.marmotInnerEventDao().getByChatRoomAndKinds(parentRoom, listOf(GuardedWalletNoticeEvent.KIND)).single() - assertTrue(GuardianManager.describeNotice(db, parentRoom, Event(filed.id, filed.publicKey, filed.createdAt.epochSeconds, filed.kind, filed.tags, filed.content, ""))!!.startsWith("Shared @")) - } - - @Test - fun `a notice whose entry for this group is not the key it reaches is ignored`(): Unit = runBlocking { - inRoom(parent) - // The group signed a certificate naming the stranger's key under the parent's room. - val forged = listOf(grant[0], GuardianDerivation.grant(thresholdKeyOf(stranger), parentRoom, emptyList(), groupRoom).single().grantedTo(walletId)) - noticeIn(parentRoom, certificate(forged)) - assertTrue(GuardianManager.guardedWalletsOf(db, parentRoom).isEmpty()) - } - - @Test - fun `a member of both groups can carry it upward`(): Unit = runBlocking { - inRoom(group, guardedCertificate(parent, group)) - inRoom(parent) - fileSigned(certificate()) - - val shareable = GuardianManager.shareableFrom(db, groupRoom, chain).single() - assertEquals(memberPublicKey, shareable.ownerPublicKey) - assertEquals(listOf(parentRoom), shareable.rooms.map { it.chatRoom.id }) - - GuardianManager.share(db, shareable.statement, shareable.rooms, memberPublicKey, certificate = shareable.certificate) - assertEquals(walletId, GuardianManager.guardedWalletsOf(db, parentRoom).single().descendantChatRoomId) - assertTrue(GuardianManager.shareableFrom(db, groupRoom, chain).isEmpty(), "told once") - } - - @Test - fun `a guardian's spend through its leaf of a member's wallet`(): Unit = runBlocking { - inRoom(parent) - noticeIn(parentRoom, certificate()) - val wallet = GuardianManager.guardedWalletsOf(db, parentRoom).single() - - // One coin at receive address 2, confirmed long enough ago. - val derived = GroupWalletDerivation.derive(wallet.account, GroupWalletDerivation.RECEIVE, 2) - val funding = Transaction(2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 3 })), 0), ByteVector.empty, 0xffffffffL)), listOf(TxOut(Satoshi(60_000), derived.pubkeyScript)), 0) - val meta = WalletState.AddressMeta.Derived(2) - val receive = WalletState(mapOf(derived.address(chain) to WalletState.AddressState(meta, true, listOf(WalletState.Utxo(funding.txid, 0, 100, funding, meta))))) - val change = WalletState(mapOf(GroupWalletDerivation.derive(wallet.account, GroupWalletDerivation.CHANGE, 0).address(chain) to WalletState.AddressState(WalletState.AddressMeta.Derived(0), false, emptyList()))) - val state = GroupWalletState(wallet.account, receive, change, tipHeight = 200) - - val spender = wallet.spender(thresholdKeyOf(parent)) - val built = assertIs(GroupSpendBuilder.sendAll(state, "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080", 3L, emptySet(), spender)) - val checked = assertIs(GroupSpend.check(built.psbt, wallet.account, spender)).checked - - val signatures = checked.inputs.map { signWith(parent, it.cache, it.sighash) } - val signed = checked.witnessed(signatures) - signed.correctlySpends(checked.inputs.associate { it.outPoint to it.txOut }, ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) - assertEquals(3, signed.txIn.single().witness.stack.size, "signature, leaf, control block") - - // The member's own device names who took it. - val taken = GuardianManager.takenIn(signed, wallet.account, mapOf(funding.let { OutPoint(it, 0) } to (funding.txOut[0] to derived))) - assertEquals(parentRoom, taken.single().guardian.chatRoomId) - - // Eleven blocks is too soon: the same spend at sequence 11, signed properly - // for that sequence, so the only thing wrong with it is the lock. - val input = checked.inputs.single() - val unsigned = checked.tx.let { tx -> Transaction(tx.version, tx.txIn.map { it.copy(sequence = 11, witness = fr.acinq.bitcoin.ScriptWitness.empty) }, tx.txOut, tx.lockTime) } - val sighash = unsigned.hashForSigningTaprootScriptPath(0, checked.spentOutputs, fr.acinq.bitcoin.SigHash.SIGHASH_DEFAULT, input.leaf!!.hash()) - val early = unsigned.updateWitness(0, input.witness(signWith(parent, input.cache, sighash))) - assertFails { early.correctlySpends(checked.inputs.associate { it.outPoint to it.txOut }, ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) } - } - - @Test - fun `a group funds its member's wallet, and its signers read where the money goes`(): Unit = runBlocking { - GroupFixtures.seedProfile(db, memberPublicKey, name = "alice") - inRoom(group, guardedCertificate(parent, group)) - fileSigned(certificate()) - val wallet = GuardianManager.guardedWalletsOf(db, groupRoom).single() - - // The group's own wallet, with one coin to fund from. - val own = GroupWalletDerivation.account(thresholdKeyOf(group), chain) - val coin = GroupWalletDerivation.derive(own, GroupWalletDerivation.RECEIVE, 0) - val funding = Transaction(2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 5 })), 0), ByteVector.empty, 0xffffffffL)), listOf(TxOut(Satoshi(90_000), coin.pubkeyScript)), 0) - val meta = WalletState.AddressMeta.Derived(0) - val ownState = GroupWalletState( - own, - WalletState(mapOf(coin.address(chain) to WalletState.AddressState(meta, true, listOf(WalletState.Utxo(funding.txid, 0, 100, funding, meta))))), - WalletState(mapOf(GroupWalletDerivation.derive(own, GroupWalletDerivation.CHANGE, 0).address(chain) to WalletState.AddressState(WalletState.AddressMeta.Derived(0), false, emptyList()))), - tipHeight = 110, - ) - - // The member's address two past their current one. - val target = GroupWalletDerivation.derive(wallet.account, GroupWalletDerivation.RECEIVE, 2) - val built = assertIs( - GroupSpendBuilder.send(ownState, GroupSpendBuilder.Destination.Funding(wallet.account, target), Satoshi(20_000), 3L, emptySet()) - ) - val checked = assertIs(GroupSpend.check(built.psbt, own)).checked - val reading = assertIs(GroupSpend.fundingsOf(checked, listOf(wallet))) - - val funded = reading.fundings.single() - assertEquals(walletId, funded.wallet.descendantChatRoomId) - assertEquals(target.pubkeyScript, checked.tx.txOut[funded.outputIndex].publicKeyScript) - val summary = mobi.giza.compose.text.ProposedSpend.summarize(checked.copy(fundings = reading.fundings), chain) - assertEquals("Fund @alice's guarded wallet “Savings”", summary.label) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MemberWalletPagesJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MemberWalletPagesJvmTest.kt deleted file mode 100644 index 7d03d9e7..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MemberWalletPagesJvmTest.kt +++ /dev/null @@ -1,155 +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.database.model.MarmotInnerEvent -import mobi.giza.compose.managers.GroupFixtures.fileKeyState -import mobi.giza.compose.managers.GroupFixtures.guardedCertificate -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.nostr.wallet.GuardedWalletNoticeEvent -import mobi.giza.compose.nostr.wallet.MemberWalletCertificateEvent -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.secp256k1.Hex -import kotlinx.coroutines.runBlocking -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertNull -import kotlin.test.assertTrue -import kotlin.time.Instant - -/** - * What the group's page and the person's page say about member wallets: the - * group lists its members' wallets apart from its subgroups, with the requests - * still waiting for a signer, and the person's page lists every group here that - * guards them. - */ -class MemberWalletPagesJvmTest { - 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 parent = keyMaterial("9a9e") - private val group = keyMaterial("6a0b") - private val groupRoom = roomOf(group) - private val parentRoom = roomOf(parent) - - private val alice = privateKey(0xa11ce5) - private val alicePublicKey = alice.xOnlyPublicKey().value.toHex() - private val bob = privateKey(0xb0b5) - private val bobPublicKey = bob.xOnlyPublicKey().value.toHex() - - private suspend fun certify(requestJson: String): Event { - val template = MemberWalletCertificateEvent.template(Event.fromJson(requestJson)) - val signed = signedAsRoom(group, template.kind, template.tags, template.content, template.createdAt) - db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(signed, chatRoomId = groupRoom, derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path), frostSigningSessionId = null)) - return signed - } - - @Test - fun `the group lists its members' wallets, certified and waiting, and never as subgroups`(): Unit = runBlocking { - GroupFixtures.seedProfile(db, alicePublicKey, name = "alice") - signingRoom(db, group, members = listOf(alicePublicKey, bobPublicKey), holdsShare = false) - fileKeyState(db, group, guardedCertificate(parent, group)) - GroupFixtures.openToMembers(db, group) - - val certified = MemberWalletManager.request(db, groupRoom, alice, chain, label = "Savings") - certify(certified.requestJson) - val waiting = MemberWalletManager.request(db, groupRoom, bob, chain, label = null) - - val listed = MemberWalletManager.memberWalletsOf(db, groupRoom) - assertEquals(listOf(certified.walletId to true, waiting.walletId to false), listed.map { it.walletId to it.isCertified }) - assertEquals("alice", listed.first().ownerName) - assertEquals("Savings", listed.first().label) - assertEquals(bobPublicKey, listed.last().ownerPublicKey) - assertTrue(SubgroupManager.subgroupsOf(db, groupRoom).isEmpty()) - } - - @Test - fun `the person's page lists every group here that guards them`(): Unit = runBlocking { - signingRoom(db, group, members = listOf(alicePublicKey)) - fileKeyState(db, group, guardedCertificate(parent, group)) - GroupFixtures.openToMembers(db, group) - signingRoom(db, parent, members = listOf(alicePublicKey), holdsShare = false, subject = "#Root") - fileKeyState(db, parent) - GroupFixtures.openToMembers(db, parent) - - val wallet = MemberWalletManager.request(db, groupRoom, alice, chain, label = null) - val certificate = certify(wallet.requestJson) - db.marmotInnerEventDao().upsert( - MarmotInnerEvent( - id = "9".repeat(64), publicKey = alicePublicKey, kind = GuardedWalletNoticeEvent.KIND, - createdAt = Instant.fromEpochSeconds(1_700_000_100), tags = arrayOf(arrayOf("h", parentRoom)), - content = certificate.toJson(), chatRoomId = parentRoom, - ) - ) - - val here = MemberWalletManager.guardedByGroupsHere(db, GroupFixtures.owner, alicePublicKey) - assertEquals(setOf(groupRoom, parentRoom), here.map { it.wallet.ancestorChatRoomId }.toSet()) - assertEquals(true, here.single { it.wallet.ancestorChatRoomId == groupRoom }.canSpend, "a share of the group's key") - assertEquals(false, here.single { it.wallet.ancestorChatRoomId == parentRoom }.canSpend, "none of the root's") - assertEquals("#Root", here.single { it.wallet.ancestorChatRoomId == parentRoom }.holderName) - assertTrue(MemberWalletManager.guardedByGroupsHere(db, GroupFixtures.owner, bobPublicKey).isEmpty()) - } - - // ---- One entry per wallet: docs/member-wallet-guarding-group.md, Phase 6 - - @Test - fun `a wallet held by a group and its parent is one entry, guarded by the group, with both holders`(): Unit = runBlocking { - signingRoom(db, group, members = listOf(alicePublicKey)) - fileKeyState(db, group, guardedCertificate(parent, group)) - GroupFixtures.openToMembers(db, group) - signingRoom(db, parent, members = listOf(alicePublicKey), holdsShare = false, subject = "#Root") - fileKeyState(db, parent) - GroupFixtures.openToMembers(db, parent) - - val wallet = MemberWalletManager.request(db, groupRoom, alice, chain, label = "Savings") - val certificate = certify(wallet.requestJson) - db.marmotInnerEventDao().upsert( - MarmotInnerEvent( - id = "9".repeat(64), publicKey = alicePublicKey, kind = GuardedWalletNoticeEvent.KIND, - createdAt = Instant.fromEpochSeconds(1_700_000_100), tags = arrayOf(arrayOf("h", parentRoom)), - content = certificate.toJson(), chatRoomId = parentRoom, - ) - ) - - val entry = MemberWalletManager.byWallet(MemberWalletManager.guardedByGroupsHere(db, GroupFixtures.owner, alicePublicKey)).single() - assertEquals(wallet.walletId, entry.walletId) - assertEquals("Savings", entry.label) - assertEquals("#Child", entry.guardianName, "the founding name the parent certified") - assertEquals(listOf(groupRoom, parentRoom), entry.holders.map { it.wallet.ancestorChatRoomId }) - assertEquals(listOf(true, false), entry.holders.map { it.canSpend }, "a share of the group's key, none of the root's") - } - - @Test - fun `Savings held by P and R, and Rent held by R, are two entries`() { - val savingsAtP = MemberWalletManager.GuardedHere(LineageExample.heldBy(LineageExample.p, LineageExample.savings, LineageExample.savingsGuardians, label = "Savings", guardianName = "#M"), holderName = "#P", canSpend = true) - val savingsAtR = MemberWalletManager.GuardedHere(LineageExample.heldBy(LineageExample.r, LineageExample.savings, LineageExample.savingsGuardians, label = "Savings", guardianName = null, branchName = "#P"), holderName = "#R", canSpend = true) - val rentAtR = MemberWalletManager.GuardedHere(LineageExample.heldBy(LineageExample.r, LineageExample.rent, LineageExample.rentGuardians), holderName = "#R", canSpend = false) - - val entries = MemberWalletManager.byWallet(listOf(savingsAtR, rentAtR, savingsAtP)) - assertEquals(listOf(LineageExample.savings, LineageExample.rent), entries.map { it.walletId }) - - val savings = entries.first() - assertEquals("#M", savings.guardianName, "named by whichever holder can") - assertEquals(listOf("#P", "#R"), savings.holders.map { it.holderName }, "nearest first") - - val rent = entries.last() - assertNull(rent.guardianName) - assertEquals("#R", rent.below, "N is unnamed here, but it is below R") - assertEquals(listOf(false), rent.holders.map { it.canSpend }) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MemberWalletPolicyJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MemberWalletPolicyJvmTest.kt deleted file mode 100644 index ce186f3e..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MemberWalletPolicyJvmTest.kt +++ /dev/null @@ -1,251 +0,0 @@ -package mobi.giza.compose.managers - -import kotlin.test.assertFalse -import mobi.giza.compose.nostr.wallet.MemberWalletCertificateEvent -import kotlin.test.assertTrue -import kotlin.test.assertNotNull -import kotlin.test.assertFailsWith -import mobi.giza.compose.managers.GroupFixtures.thresholdKeyOf -import mobi.giza.compose.nostr.wallet.MemberWalletRequestEvent -import com.vitorpamplona.quartz.nip01Core.core.Event -import fr.acinq.secp256k1.Hex -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Chain -import androidx.room3.Room -import mobi.giza.compose.database.GizaDatabase -import mobi.giza.compose.database.builder.getRoomDatabase -import mobi.giza.compose.managers.GroupFixtures.filePolicy -import mobi.giza.compose.managers.GroupFixtures.keyMaterial -import mobi.giza.compose.managers.GroupFixtures.memberWalletPolicy -import mobi.giza.compose.managers.GroupFixtures.roomOf -import mobi.giza.compose.nostr.wallet.MemberWalletPolicyEvent -import mobi.giza.compose.text.ProposedEvent -import kotlinx.coroutines.runBlocking -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertIs -import kotlin.test.assertNull - -/** - * A group's policy on its members' wallets, as the group's own devices read it - * -- `docs/member-wallet-delay.md`. - */ -class MemberWalletPolicyJvmTest { - private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) - - @AfterTest - fun closeDb() = db.close() - - private val group = keyMaterial("6a0b") - private val stranger = keyMaterial("5e7a") - private val groupRoom = roomOf(group) - - // ---- Phase 2: the group files it --------------------------------------- - - @Test - fun `a group that never signed a policy has none`(): Unit = runBlocking { - assertNull(MemberWalletManager.policyFor(db, groupRoom)) - } - - @Test - fun `the newest stored policy decides, open or closed, either way round`(): Unit = runBlocking { - GroupFixtures.seedRoom(db, groupRoom) - filePolicy(db, group, memberWalletPolicy(group, 144, createdAt = 1_700_000_000)) - filePolicy(db, group, memberWalletPolicy(group, null, createdAt = 1_700_000_100)) - assertIs(MemberWalletManager.policyFor(db, groupRoom)) - - filePolicy(db, group, memberWalletPolicy(group, 1_008, createdAt = 1_700_000_200)) - assertEquals(1_008L, assertIs(MemberWalletManager.policyFor(db, groupRoom)).delay) - } - - @Test - fun `a policy another room signed is not this group's`(): Unit = runBlocking { - GroupFixtures.seedRoom(db, groupRoom) - // Filed under this room, signed by another: nothing a device can act on. - val forged = memberWalletPolicy(stranger, 6) - db.groupSignedEventDao().upsert( - mobi.giza.compose.database.model.GroupSignedEvent.fromEvent(forged, chatRoomId = groupRoom, derivationPath = null, frostSigningSessionId = null) - ) - assertNull(MemberWalletManager.policyFor(db, groupRoom)) - } - - @Test - fun `a signer reads what a policy decides, and what closing leaves alone`() { - val opened = memberWalletPolicy(group, 144) - assertEquals("Members' guarded wallets", ProposedEvent.summarize(opened).label) - assertEquals("this group after 144 blocks, about 1 day · for wallets asked for from now on", ProposedEvent.summarize(opened).detail) - - val closed = memberWalletPolicy(group, null) - assertEquals("no new ones · wallets already guarded stay guarded", ProposedEvent.summarize(closed).detail) - } - - // ---- Phase 4: the member builds under it ------------------------------- - - private val parent = keyMaterial("9a9e") - private val chain = Chain.Regtest - private val member = PrivateKey(ByteVector32(Hex.decode("3e3be7".padStart(64, '0')))) - private val memberPublicKey = member.xOnlyPublicKey().value.toHex() - - private suspend fun asMember() { - GroupFixtures.signingRoom(db, group, members = listOf(memberPublicKey), holdsShare = false) - GroupFixtures.fileKeyState(db, group, GroupFixtures.guardedCertificate(parent, group)) - } - - @Test - fun `a member asks only a group that has opened`(): Unit = runBlocking { - asMember() - assertEquals(MemberWalletManager.Refusal.NOT_OFFERED, MemberWalletManager.refusal(db, groupRoom, canSign = true, chain)) - assertFailsWith { MemberWalletManager.request(db, groupRoom, member, chain, label = null) } - assertNull(MemberWalletManager.delaysOf(db, groupRoom)) - - filePolicy(db, group, memberWalletPolicy(group, null)) - assertEquals(MemberWalletManager.Refusal.CLOSED, MemberWalletManager.refusal(db, groupRoom, canSign = true, chain)) - assertFailsWith { MemberWalletManager.request(db, groupRoom, member, chain, label = null) } - assertTrue(db.memberWalletDao().getByOwner(memberPublicKey).isEmpty(), "a refused request makes no key") - } - - @Test - fun `a request is built at the group's delay and carries the policy it was built under`(): Unit = runBlocking { - asMember() - val policy = memberWalletPolicy(group, 4_320) - filePolicy(db, group, policy) - - assertNull(MemberWalletManager.refusal(db, groupRoom, canSign = true, chain)) - assertEquals(listOf(4_320L, GuardianDerivation.DEFAULT_DELAY), MemberWalletManager.delaysOf(db, groupRoom), "the parent's keeps its own") - - val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = null) - val verified = assertNotNull(MemberWalletRequestEvent.verified(Event.fromJson(wallet.requestJson))) - assertEquals(4_320L, verified.reading.guardians.first().delay) - assertEquals(policy.id, verified.policy?.event?.id) - } - - @Test - fun `a request whose leaf disagrees with the policy it carries does not check out`(): Unit = runBlocking { - asMember() - val walletKey = MemberWalletDerivation.generate() - val walletId = MemberWalletDerivation.walletId(walletKey.publicKey()) - val atDefault = GuardianDerivation.grant(thresholdKeyOf(group), groupRoom, emptyList(), walletId) - val account = MemberWalletDerivation.account(walletKey.publicKey(), chain, atDefault) - fun build(policy: Event?) = MemberWalletRequestEvent.build(member, groupRoom, walletKey, account, label = null, policy = policy) - - assertNull(MemberWalletRequestEvent.verified(build(memberWalletPolicy(group, 4_320))), "built at 12 under a policy of 4,320") - assertNull(MemberWalletRequestEvent.verified(build(memberWalletPolicy(group, null))), "built under a closed policy") - assertNull(MemberWalletRequestEvent.verified(build(memberWalletPolicy(stranger, 12))), "under another group's policy") - assertNotNull(MemberWalletRequestEvent.verified(build(memberWalletPolicy(group, 12)))) - // A request from before policies still reads: old certificates embed one. - assertNotNull(MemberWalletRequestEvent.verified(build(null))) - } - - // ---- Phase 5: every signer checks it ----------------------------------- - - /** This device as a signer of the group, which the member is in. */ - private suspend fun asSigner() { - GroupFixtures.signingRoom(db, group, members = listOf(memberPublicKey)) - GroupFixtures.fileKeyState(db, group, GroupFixtures.guardedCertificate(parent, group)) - } - - /** What the signer is asked to sign: the certificate for a request built at [delay] under [carried]. */ - private fun proposedUnder(carried: Event?, delay: Long): Event { - val walletKey = MemberWalletDerivation.generate() - val walletId = MemberWalletDerivation.walletId(walletKey.publicKey()) - val parentsGrant = GuardianDerivation.grant(thresholdKeyOf(parent), roomOf(parent), emptyList(), groupRoom) - val guardians = GuardianDerivation.grant(thresholdKeyOf(group), groupRoom, parentsGrant, walletId, delay) - val account = MemberWalletDerivation.account(walletKey.publicKey(), chain, guardians) - val request = MemberWalletRequestEvent.build(member, groupRoom, walletKey, account, label = null, createdAt = 1_700_000_500, policy = carried) - val template = MemberWalletCertificateEvent.template(request) - return Event(MemberWalletManager.certificateIdFor(groupRoom, request), groupRoom, template.createdAt, template.kind, template.tags, template.content, "") - } - - private suspend fun refusal(certificate: Event) = - MemberWalletManager.refuseCertificate(db, groupRoom, thresholdKeyOf(group), certificate) - - @Test - fun `a signer judges a request by the policy it carries, unless it holds a newer one`(): Unit = runBlocking { - asSigner() - val older = 1_700_000_000L - val carried = memberWalletPolicy(group, 4_320, createdAt = older + 100) - - // Held none: a signer that missed the opening is told what it missed. - assertNull(refusal(proposedUnder(carried, 4_320))) - // The leaf has to have the carried delay, as every reader checks. - assertEquals("is not a certificate this group could have been asked for", refusal(proposedUnder(carried, 12))) - - // An older closing the group has since reversed is no reason to refuse. - filePolicy(db, group, memberWalletPolicy(group, null, createdAt = older)) - assertNull(refusal(proposedUnder(carried, 4_320))) - - // A newer delay held: the request is stale. - filePolicy(db, group, memberWalletPolicy(group, 144, createdAt = older + 200)) - assertEquals("was asked under a delay the group has since changed", refusal(proposedUnder(carried, 4_320))) - - // A newer closing held: the group has stopped. - filePolicy(db, group, memberWalletPolicy(group, null, createdAt = older + 300)) - assertEquals("was asked of a group that has since stopped guarding members' wallets", refusal(proposedUnder(carried, 4_320))) - } - - @Test - fun `a request built under no policy, or under a closed one, is refused`(): Unit = runBlocking { - asSigner() - filePolicy(db, group, memberWalletPolicy(group, 12)) - - assertEquals("does not say the group guards members' wallets", refusal(proposedUnder(null, 12))) - assertNotNull(refusal(proposedUnder(memberWalletPolicy(group, null), 12)), "a closed policy opens nothing") - assertNotNull(refusal(proposedUnder(memberWalletPolicy(stranger, 12), 12)), "nor does another group's") - } - - @Test - fun `a stale request says why, and asking again makes a new one at the new delay`(): Unit = runBlocking { - asMember() - filePolicy(db, group, memberWalletPolicy(group, 12, createdAt = 1_700_000_000)) - val asked = MemberWalletManager.request(db, groupRoom, member, chain, label = "Savings") - assertNull(MemberWalletManager.walletsOf(db, memberPublicKey).single().refusedBecause) - - filePolicy(db, group, memberWalletPolicy(group, 144, createdAt = 1_700_000_100)) - assertEquals(MemberWalletManager.Why.DELAY_CHANGED, MemberWalletManager.walletsOf(db, memberPublicKey).single().refusedBecause) - - val replacement = MemberWalletManager.askAgain(db, db.memberWalletDao().getById(asked.walletId)!!, member) - assertTrue(replacement.walletId != asked.walletId, "a new key") - assertNull(db.memberWalletDao().getById(asked.walletId), "the old key, never offered, is gone") - assertEquals("Savings", replacement.label) - val rebuilt = assertNotNull(MemberWalletRequestEvent.verified(Event.fromJson(replacement.requestJson))) - assertEquals(144L, rebuilt.reading.guardians.first().delay) - assertNull(MemberWalletManager.walletsOf(db, memberPublicKey).single().refusedBecause) - } - - @Test - fun `a request to a group that has since closed can only be discarded`(): Unit = runBlocking { - asMember() - filePolicy(db, group, memberWalletPolicy(group, 12, createdAt = 1_700_000_000)) - val asked = MemberWalletManager.request(db, groupRoom, member, chain, label = null) - filePolicy(db, group, memberWalletPolicy(group, null, createdAt = 1_700_000_100)) - - assertEquals(MemberWalletManager.Why.CLOSED, MemberWalletManager.walletsOf(db, memberPublicKey).single().refusedBecause) - assertFailsWith { MemberWalletManager.askAgain(db, db.memberWalletDao().getById(asked.walletId)!!, member) } - assertNotNull(db.memberWalletDao().getById(asked.walletId), "a refused ask leaves the old key for the member to discard") - } - - // ---- the picker leaves out direct chats ------------------------------- - - @Test - fun `a direct chat is not a group that can guard a wallet, a two-member group with a known key is`(): Unit = runBlocking { - val peer = "b".repeat(64) - val direct = keyMaterial("d1ec7") - val shrunk = keyMaterial("5412c") - val waiting = keyMaterial("3a17") - - // A direct chat: two people, and no key anywhere. - GroupFixtures.signingRoom(db, direct, members = listOf(peer), holdsShare = false) - // A group down to two members after its ceremony, whose key this device holds. - GroupFixtures.signingRoom(db, shrunk, members = listOf(peer), holdsShare = false) - GroupFixtures.fileKeyState(db, shrunk) - // A group of three whose key this device has not been told yet: it may be open. - GroupFixtures.signingRoom(db, waiting, members = listOf(peer, "c".repeat(64)), holdsShare = false) - - val listed = MemberWalletManager.groupsOf(db, GroupFixtures.owner).map { it.chatRoom.id }.toSet() - assertEquals(setOf(roomOf(shrunk), roomOf(waiting)), listed) - // And a direct chat's own page offers nothing about members' wallets. - assertFalse(MemberWalletManager.couldGuard(db, db.chatRoomDao().findChatRoomById(roomOf(direct))!!)) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MemberWalletRequestJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MemberWalletRequestJvmTest.kt deleted file mode 100644 index b5525443..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MemberWalletRequestJvmTest.kt +++ /dev/null @@ -1,172 +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.database.model.MarmotInnerEvent -import mobi.giza.compose.managers.GroupFixtures.fileKeyState -import mobi.giza.compose.managers.GroupFixtures.guardedCertificate -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.managers.MemberWalletManager.Refusal -import mobi.giza.compose.managers.MemberWalletManager.asEvent -import mobi.giza.compose.nostr.wallet.GroupKeyNoticeEvent -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.secp256k1.Hex -import kotlinx.coroutines.runBlocking -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertNotNull -import kotlin.test.assertNull -import kotlin.test.assertTrue -import kotlin.time.Instant - -/** - * A member asking a group to guard a wallet: the key stored before anything - * leaves the device, the request one every signer will accept, and each reason - * the screen gives for not asking. - */ -class MemberWalletRequestJvmTest { - 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 parent = keyMaterial("9a9e") - private val group = keyMaterial("6a0b") - private val groupRoom = roomOf(group) - - private val member = privateKey(0x3e3be7) - private val memberPublicKey = member.xOnlyPublicKey().value.toHex() - - /** The group as a member who holds no share sees it: a Marmot room, and nothing to sign with. */ - private suspend fun asMember(knowsKey: Boolean = true) { - signingRoom(db, group, members = listOf(memberPublicKey), holdsShare = false) - if (knowsKey) fileKeyState(db, group, guardedCertificate(parent, group)) - GroupFixtures.openToMembers(db, group) - } - - private suspend fun requestsSent(): List = - db.marmotInnerEventDao().getByChatRoomAndKinds(groupRoom, listOf(MemberWalletRequestEvent.KIND)) - .mapNotNull { MemberWalletRequestEvent.carried(it.asEvent()) } - - @Test - fun `the key is stored and the request one every signer will accept`(): Unit = runBlocking { - asMember() - val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = "Savings") - - assertEquals(wallet, db.memberWalletDao().getById(wallet.walletId)) - assertEquals(memberPublicKey, wallet.ownerPublicKey) - assertEquals(groupRoom, wallet.guardingChatRoomId) - assertEquals("Savings", wallet.label) - assertEquals(wallet.walletId, MemberWalletDerivation.walletId(PrivateKey.fromHex(wallet.walletPrivateKey).publicKey())) - - val sent = requestsSent().single() - val verified = assertNotNull(MemberWalletRequestEvent.verified(sent)) - assertEquals(wallet.walletId, verified.reading.walletId) - assertEquals(SubgroupManager.grantFor(db, groupRoom, thresholdKeyOf(group), wallet.walletId), verified.reading.guardians) - assertEquals(2, verified.reading.guardians.size, "the group, and its parent one step further") - - // Exactly what a signer's device will be shown, and it is signable. - val template = MemberWalletCertificateEvent.template(sent) - val proposed = Event(MemberWalletManager.certificateIdFor(groupRoom, sent), groupRoom, template.createdAt, template.kind, template.tags, template.content, "") - assertNull(MemberWalletManager.refuseCertificate(db, groupRoom, thresholdKeyOf(group), proposed)) - - assertTrue(db.frostSigningSessionDao().getSessionsForChatRoom(groupRoom).isEmpty(), "a member without a share waits for a signer") - assertEquals(listOf(wallet.walletId), MemberWalletManager.awaitingSponsor(db, groupRoom).map { it.reading.walletId }) - } - - @Test - fun `two requests are two keys`(): Unit = runBlocking { - asMember() - val first = MemberWalletManager.request(db, groupRoom, member, chain, label = null) - val second = MemberWalletManager.request(db, groupRoom, member, chain, label = null) - assertTrue(first.walletId != second.walletId) - assertTrue(first.walletPrivateKey != second.walletPrivateKey) - } - - @Test - fun `a member who holds a share puts it to the group at once`(): Unit = runBlocking { - // A share-holding member: one of the ceremony's participants on this device. - signingRoom(db, group, members = listOf(memberPublicKey)) - fileKeyState(db, group, guardedCertificate(parent, group)) - GroupFixtures.openToMembers(db, group) - - val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = null) - - val session = assertNotNull(MemberWalletManager.openSessionFor(db, groupRoom, Event.fromJson(wallet.requestJson))) - assertNotNull(session.signApprovedAt, "proposing is approving") - assertTrue(MemberWalletManager.awaitingSponsor(db, groupRoom).isEmpty()) - } - - @Test - fun `each refusal holds`(): Unit = runBlocking { - assertEquals(Refusal.CANNOT_SIGN, MemberWalletManager.refusal(db, groupRoom, canSign = false, chain)) - assertEquals(Refusal.NOT_A_GROUP, MemberWalletManager.refusal(db, groupRoom, canSign = true, chain)) - - GroupFixtures.seedRoom(db, groupRoom) - assertEquals(Refusal.NOT_A_GROUP, MemberWalletManager.refusal(db, groupRoom, canSign = true, chain), "a room with no MLS state") - - db.chatRoomDao().delete(db.chatRoomDao().findChatRoomById(groupRoom)!!.chatRoom) - asMember(knowsKey = false) - assertEquals(Refusal.KEY_UNKNOWN, MemberWalletManager.refusal(db, groupRoom, canSign = true, chain)) - assertFailsWith { MemberWalletManager.request(db, groupRoom, member, chain, label = null) } - assertTrue(db.memberWalletDao().getByOwner(memberPublicKey).isEmpty(), "a refused request makes no key") - - // Offered on mainnet since the gate lifted -- the refusal is the room's, not - // the network's -- and a member's own spend there still held to the cap. - assertTrue(mobi.giza.compose.wallet.GroupWalletRollout.offersMemberWalletsOn(Chain.Mainnet)) - assertEquals(mobi.giza.compose.wallet.GroupWalletRollout.MAINNET_CAP, mobi.giza.compose.wallet.GroupWalletRollout.memberCapFor(Chain.Mainnet)) - assertNull(mobi.giza.compose.wallet.GroupWalletRollout.memberCapFor(Chain.Signet)) - assertEquals(Refusal.KEY_UNKNOWN, MemberWalletManager.refusal(db, groupRoom, canSign = true, Chain.Mainnet)) - } - - @Test - fun `a member with no key state can ask once an answer is in the room`(): Unit = runBlocking { - asMember(knowsKey = false) - val answer = GroupKeyNoticeEvent.GroupKey(groupRoom, thresholdKeyOf(group), guardedCertificate(parent, group)) - val tags = GroupKeyNoticeEvent.answeringTags("e".repeat(64), answer, GroupFixtures.path) - db.marmotInnerEventDao().upsert( - MarmotInnerEvent(id = "f".repeat(64), publicKey = "5".repeat(64), kind = GroupKeyNoticeEvent.KIND, createdAt = Instant.fromEpochSeconds(1_700_000_000), tags = tags, content = answer.thresholdPublicKey, chatRoomId = groupRoom) - ) - - assertNull(MemberWalletManager.refusal(db, groupRoom, canSign = true, chain)) - assertEquals(2, MemberWalletManager.reachOf(db, groupRoom)) - // The group's own leaf at the default, and the parent's at the delay it - // chose for the group -- the default too, here. docs/guardian-delay.md. - assertEquals(listOf(GuardianDerivation.DEFAULT_DELAY, GuardianDerivation.DEFAULT_DELAY), MemberWalletManager.delaysOf(db, groupRoom)) - val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = null) - assertNotNull(MemberWalletRequestEvent.verified(Event.fromJson(wallet.requestJson))) - } - - @Test - fun `a key is discarded only before a group guards its wallet`(): Unit = runBlocking { - asMember() - val unasked = MemberWalletManager.request(db, groupRoom, member, chain, label = null) - MemberWalletManager.discard(db, unasked.walletId) - assertNull(db.memberWalletDao().getById(unasked.walletId)) - - val guarded = MemberWalletManager.request(db, groupRoom, member, chain, label = null) - val template = MemberWalletCertificateEvent.template(Event.fromJson(guarded.requestJson)) - val signed = signedAsRoom(group, template.kind, template.tags, template.content, template.createdAt) - db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(signed, chatRoomId = groupRoom, derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path), frostSigningSessionId = null)) - - assertFailsWith { MemberWalletManager.discard(db, guarded.walletId) } - assertNotNull(db.memberWalletDao().getById(guarded.walletId)) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MemberWalletSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MemberWalletSigningJvmTest.kt deleted file mode 100644 index af590ebd..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MemberWalletSigningJvmTest.kt +++ /dev/null @@ -1,206 +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.database.model.MarmotInnerEvent -import mobi.giza.compose.managers.GroupFixtures.fileKeyState -import mobi.giza.compose.managers.GroupFixtures.guardedCertificate -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.wallet.MemberWalletCertificateEvent -import mobi.giza.compose.nostr.wallet.MemberWalletRequestEvent -import mobi.giza.compose.text.ProposedEvent -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.secp256k1.Hex -import kotlinx.coroutines.runBlocking -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertNotNull -import kotlin.test.assertNull -import kotlin.test.assertTrue -import kotlin.time.Instant - -/** - * A group's signers checking a member wallet certificate before they are asked - * to approve it, and a signer putting a member's request to the group. - * - * The group is itself a guarded subgroup, so a member's wallet under it carries - * two leaves -- the group's and its parent's, one step further -- and every - * refusal below is one way of getting that list wrong. - */ -class MemberWalletSigningJvmTest { - 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 parent = keyMaterial("9a9e") - private val group = keyMaterial("6a0b") - private val stranger = keyMaterial("57a9") - private val groupRoom = roomOf(group) - - private val member = privateKey(0x3e3be7) - private val memberPublicKey = member.xOnlyPublicKey().value.toHex() - private val outsider = privateKey(0x07575) - private val walletPrivateKey = privateKey(0xa11ce) - private val walletId = MemberWalletDerivation.walletId(walletPrivateKey.publicKey()) - - /** What the group grants the member's wallet: its own key, then its parent's, one step further. */ - private val grant: List = GuardianDerivation.grant( - thresholdKeyOf(group), groupRoom, - GuardianDerivation.grant(thresholdKeyOf(parent), roomOf(parent), emptyList(), groupRoom), - walletId, - ) - - private suspend fun groupRoomHere() = signingRoom(db, group, members = listOf(memberPublicKey)).also { - fileKeyState(db, group, guardedCertificate(parent, group)) - GroupFixtures.openToMembers(db, group) - } - - private fun request(guardians: List = grant, by: PrivateKey = member, asking: String = groupRoom) = - MemberWalletRequestEvent.build( - memberPrivateKey = by, - groupChatRoomId = asking, - walletPrivateKey = walletPrivateKey, - account = MemberWalletDerivation.account(walletPrivateKey.publicKey(), chain, guardians), - label = "Savings", - createdAt = 1_700_000_000, - // Built under the group's open policy, as a member's device builds - // it -- the one groupRoomHere() files. docs/member-wallet-delay.md. - policy = GroupFixtures.memberWalletPolicy(group, GuardianDerivation.DEFAULT_DELAY, createdAt = 1_600_000_000).takeIf { asking == groupRoom }, - ) - - /** The certificate [request] asks for, as a session would carry it -- unsigned, authored by the room. */ - private fun proposed(request: Event, room: String = groupRoom): Event { - val template = MemberWalletCertificateEvent.template(request) - return Event(MemberWalletManager.certificateIdFor(room, request), room, template.createdAt, template.kind, template.tags, template.content, "") - } - - private suspend fun refusal(request: Event): String? = - MemberWalletManager.refuseCertificate(db, groupRoom, thresholdKeyOf(group), proposed(request)) - - @Test - fun `the honest certificate is signable`(): Unit = runBlocking { - groupRoomHere() - assertNull(refusal(request())) - } - - @Test - fun `a certificate that drops the group above is refused`(): Unit = runBlocking { - groupRoomHere() - assertEquals("grants guardian keys this group does not", refusal(request(guardians = grant.take(1)))) - } - - @Test - fun `a certificate whose leaves are reordered is refused`(): Unit = runBlocking { - groupRoomHere() - // Reordered, the group is no longer the nearest guardian, so the request itself is refused. - assertNotNull(refusal(request(guardians = grant.reversed()))) - } - - @Test - fun `a certificate naming another group's key is refused`(): Unit = runBlocking { - groupRoomHere() - val swapped = listOf(grant[0], GuardianDerivation.grant(thresholdKeyOf(stranger), roomOf(stranger), emptyList(), walletId).single()) - assertEquals("grants guardian keys this group does not", refusal(request(guardians = swapped))) - } - - @Test - fun `a certificate asked by somebody who is not a member is refused`(): Unit = runBlocking { - groupRoomHere() - assertEquals("was asked by somebody who is not a member", refusal(request(by = outsider))) - } - - @Test - fun `a request made of another group is refused here`(): Unit = runBlocking { - groupRoomHere() - val elsewhere = request(asking = roomOf(stranger), guardians = GuardianDerivation.grant(thresholdKeyOf(stranger), roomOf(stranger), emptyList(), walletId)) - assertNotNull(MemberWalletManager.refuseCertificate(db, groupRoom, thresholdKeyOf(group), proposed(elsewhere))) - } - - @Test - fun `an unguarded group guards its members with its own key alone`(): Unit = runBlocking { - // A root group: no certificate, so nothing to pass down. - signingRoom(db, group, members = listOf(memberPublicKey)) - fileKeyState(db, group, certificate = null) - GroupFixtures.openToMembers(db, group) - assertNull(refusal(request(guardians = grant.take(1)))) - assertEquals("grants guardian keys this group does not", refusal(request())) - } - - private suspend fun deliverRequest(request: Event) { - db.marmotInnerEventDao().upsert( - MarmotInnerEvent( - id = "1".repeat(63) + "0", - publicKey = request.pubKey, - kind = MemberWalletRequestEvent.KIND, - createdAt = Instant.fromEpochSeconds(request.createdAt), - tags = arrayOf(arrayOf("h", groupRoom)), - content = request.toJson(), - chatRoomId = groupRoom, - ) - ) - } - - @Test - fun `a signer puts a request to the group, and a second sponsor finds the same session`(): Unit = runBlocking { - val room = groupRoomHere() - val request = request() - deliverRequest(request) - assertEquals(listOf(walletId), MemberWalletManager.awaitingSponsor(db, groupRoom).map { it.reading.walletId }) - - val session = MemberWalletManager.putToGroup(db, room, GroupFixtures.owner, request) - val items = db.frostSigningSessionDao().getItems(session.id) - assertEquals(listOf(MemberWalletManager.certificateIdFor(groupRoom, request)), items.map { it.eventId }) - assertTrue(MemberWalletManager.awaitingSponsor(db, groupRoom).isEmpty(), "no longer waiting for a sponsor") - - assertEquals(session.id, MemberWalletManager.putToGroup(db, room, GroupFixtures.owner, request).id) - } - - @Test - fun `a sponsor refuses to put what the group would refuse`(): Unit = runBlocking { - val room = groupRoomHere() - assertFailsWith { - MemberWalletManager.putToGroup(db, room, GroupFixtures.owner, request(guardians = grant.take(1))) - } - assertTrue(db.frostSigningSessionDao().getSessionsForChatRoom(groupRoom).isEmpty()) - } - - @Test - fun `a wallet the group already guards is not put to it again`(): Unit = runBlocking { - val room = groupRoomHere() - val request = request() - val template = MemberWalletCertificateEvent.template(request) - val signed = signedAsRoom(group, template.kind, template.tags, template.content, template.createdAt) - db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(signed, chatRoomId = groupRoom, derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path), frostSigningSessionId = null)) - - assertEquals(listOf(walletId), MemberWalletManager.certificatesOf(db, groupRoom).map { it.walletId }) - assertFailsWith { MemberWalletManager.putToGroup(db, room, GroupFixtures.owner, request) } - } - - @Test - fun `the signers read who it is for and what the group can do`() { - val summary = ProposedEvent.summarize(proposed(request())) { if (it == memberPublicKey) "alice" else null } - assertEquals("Guard a member's wallet", summary.label) - assertTrue(summary.detail.startsWith("For @alice · Savings · on regtest"), summary.detail) - // Each guardian's own delay, nearest first: both are the default here. - assertTrue( - summary.detail.contains("this group can take its coins after 12 blocks, about 2 hours, and the one above it after 12 blocks, about 2 hours"), - summary.detail, - ) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MemberWalletSpendJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MemberWalletSpendJvmTest.kt deleted file mode 100644 index ff9ac5f0..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MemberWalletSpendJvmTest.kt +++ /dev/null @@ -1,140 +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.database.model.MemberWallet -import mobi.giza.compose.managers.GroupFixtures.fileKeyState -import mobi.giza.compose.managers.GroupFixtures.guardedCertificate -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.nostr.wallet.MemberWalletCertificateEvent -import mobi.giza.compose.wallet.GroupSpend -import mobi.giza.compose.wallet.GroupSpendBuilder -import mobi.giza.compose.wallet.GroupWalletState -import com.vitorpamplona.quartz.nip01Core.core.Event -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.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 fr.acinq.secp256k1.Hex -import kotlinx.coroutines.runBlocking -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertIs -import kotlin.test.assertNotNull -import kotlin.test.assertNull -import kotlin.time.Instant - -/** - * A member spending their own guarded wallet alone: the spend checked against - * the account the wallet rederives to, signed with the member's key, accepted - * by the script interpreter, and filed -- and refused for every wallet this - * device cannot sign for. - */ -class MemberWalletSpendJvmTest { - 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 parent = keyMaterial("9a9e") - private val group = keyMaterial("6a0b") - private val groupRoom = roomOf(group) - - private val member = privateKey(0x3e3be7) - private val memberPublicKey = member.xOnlyPublicKey().value.toHex() - - private val destination = "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080" - - private suspend fun certifiedWallet(): MemberWallet { - signingRoom(db, group, members = listOf(memberPublicKey), holdsShare = false) - fileKeyState(db, group, guardedCertificate(parent, group)) - GroupFixtures.openToMembers(db, group) - val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = null) - val template = MemberWalletCertificateEvent.template(Event.fromJson(wallet.requestJson)) - val signed = signedAsRoom(group, template.kind, template.tags, template.content, template.createdAt) - db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(signed, chatRoomId = groupRoom, derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path), frostSigningSessionId = null)) - return wallet - } - - /** [account]'s wallet with one coin of [sats] at receive address [index], and an unused change address. */ - private fun stateWith(account: GroupWalletDerivation.Account, index: Int = 0, sats: Long = 80_000): GroupWalletState { - val derived = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, index.toLong()) - val funding = Transaction(2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 7 })), 0), ByteVector.empty, 0xffffffffL)), listOf(TxOut(Satoshi(sats), derived.pubkeyScript)), 0) - val meta = WalletState.AddressMeta.Derived(index) - val receive = WalletState(mapOf(derived.address(chain) to WalletState.AddressState(meta, true, listOf(WalletState.Utxo(funding.txid, 0, 100, funding, meta))))) - val change = WalletState( - mapOf(GroupWalletDerivation.derive(account, GroupWalletDerivation.CHANGE, 0).address(chain) to WalletState.AddressState(WalletState.AddressMeta.Derived(0), false, emptyList())) - ) - return GroupWalletState(account, receive, change, tipHeight = 110) - } - - @Test - fun `a member signs alone, and the network would take it`(): Unit = runBlocking { - val wallet = certifiedWallet() - val account = assertNotNull(MemberWalletManager.walletOf(db, memberPublicKey, wallet.walletId)).account - val built = assertIs(GroupSpendBuilder.send(stateWith(account), destination, Satoshi(30_000), 3L, emptySet())) - - val signed = MemberWalletManager.signSpend(db, memberPublicKey, wallet.walletId, built.psbt, at = Instant.fromEpochSeconds(1_700_000_000)) - - val checked = assertIs(GroupSpend.check(built.psbt, account)).checked - signed.correctlySpends(checked.inputs.associate { it.outPoint to it.txOut }, ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) - signed.txIn.forEach { assertEquals(1, it.witness.stack.size, "the key path: the tree stays hidden") } - - val spend = assertNotNull(db.memberWalletDao().getSpend(signed.txid.toString())) - assertEquals(wallet.walletId, spend.walletId) - assertNull(spend.seenAt) - - MemberWalletManager.recordChain(db, spend.txid, confirmations = 0, at = Instant.fromEpochSeconds(1_700_000_100)) - assertEquals(Instant.fromEpochSeconds(1_700_000_100), db.memberWalletDao().getSpend(spend.txid)?.seenAt) - assertNull(db.memberWalletDao().getSpend(spend.txid)?.confirmedAt) - MemberWalletManager.recordChain(db, spend.txid, confirmations = 2, at = Instant.fromEpochSeconds(1_700_000_700)) - assertEquals(Instant.fromEpochSeconds(1_700_000_700), db.memberWalletDao().getSpend(spend.txid)?.confirmedAt) - assertEquals(Instant.fromEpochSeconds(1_700_000_100), db.memberWalletDao().getSpend(spend.txid)?.seenAt, "first seen stays first seen") - } - - @Test - fun `a spend of another wallet's coins is refused`(): Unit = runBlocking { - val wallet = certifiedWallet() - val other = MemberWalletDerivation.account(privateKey(0xb0b).publicKey(), chain, emptyList()) - val built = assertIs(GroupSpendBuilder.sendAll(stateWith(other), destination, 3L, emptySet())) - assertFailsWith { MemberWalletManager.signSpend(db, memberPublicKey, wallet.walletId, built.psbt) } - assertEquals(emptyList(), db.memberWalletDao().getSpends(wallet.walletId)) - } - - @Test - fun `nothing is signed before a group certifies the wallet, or without its key`(): Unit = runBlocking { - signingRoom(db, group, members = listOf(memberPublicKey), holdsShare = false) - fileKeyState(db, group, guardedCertificate(parent, group)) - GroupFixtures.openToMembers(db, group) - val asked = MemberWalletManager.request(db, groupRoom, member, chain, label = null) - val account = assertNotNull(MemberWalletManager.walletOf(db, memberPublicKey, asked.walletId)).account - val built = assertIs(GroupSpendBuilder.sendAll(stateWith(account), destination, 3L, emptySet())) - assertFailsWith { MemberWalletManager.signSpend(db, memberPublicKey, asked.walletId, built.psbt) } - - // Certified, and the key on another device. - val template = MemberWalletCertificateEvent.template(Event.fromJson(asked.requestJson)) - val signed = signedAsRoom(group, template.kind, template.tags, template.content, template.createdAt) - db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(signed, chatRoomId = groupRoom, derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path), frostSigningSessionId = null)) - db.memberWalletDao().delete(asked.walletId) - assertFailsWith { MemberWalletManager.signSpend(db, memberPublicKey, asked.walletId, built.psbt) } - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MemberWalletsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MemberWalletsJvmTest.kt deleted file mode 100644 index 399ae641..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MemberWalletsJvmTest.kt +++ /dev/null @@ -1,128 +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.database.model.types.FrostSigningStage -import mobi.giza.compose.managers.GroupFixtures.fileKeyState -import mobi.giza.compose.managers.GroupFixtures.guardedCertificate -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.MemberWalletManager.WalletState -import mobi.giza.compose.nostr.wallet.MemberWalletCertificateEvent -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.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.assertNotNull -import kotlin.test.assertNull -import kotlin.test.assertTrue - -/** - * A member's guarded wallets as their profile lists them: one state per wallet, - * read off the key here, the sessions in the group's room and the group's - * certificates -- and a wallet made on another device, which this one can - * only watch. - */ -class MemberWalletsJvmTest { - 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 parent = keyMaterial("9a9e") - private val group = keyMaterial("6a0b") - private val groupRoom = roomOf(group) - - private val member = privateKey(0x3e3be7) - private val memberPublicKey = member.xOnlyPublicKey().value.toHex() - - private suspend fun setUp(signer: Boolean = false) { - signingRoom(db, group, members = listOf(memberPublicKey), holdsShare = signer) - fileKeyState(db, group, guardedCertificate(parent, group)) - GroupFixtures.openToMembers(db, group) - } - - private suspend fun certify(request: Event) { - val template = MemberWalletCertificateEvent.template(request) - val signed = signedAsRoom(group, template.kind, template.tags, template.content, template.createdAt) - db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(signed, chatRoomId = groupRoom, derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path), frostSigningSessionId = null)) - } - - private suspend fun stateOf(walletId: String): WalletState? = - MemberWalletManager.walletsOf(db, memberPublicKey).firstOrNull { it.walletId == walletId }?.state - - @Test - fun `asked, then certified`(): Unit = runBlocking { - setUp() - val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = "Savings") - assertEquals(WalletState.ASKED, stateOf(wallet.walletId)) - - certify(Event.fromJson(wallet.requestJson)) - val row = assertNotNull(MemberWalletManager.walletOf(db, memberPublicKey, wallet.walletId)) - assertEquals(WalletState.OPEN, row.state) - assertTrue(row.isCertified) - assertTrue(row.isMember) - assertEquals("Savings", row.label) - assertEquals(groupRoom, row.groupRoom?.chatRoom?.id) - assertEquals(2, row.account.guardians.size) - assertNotNull(MemberWalletManager.exportKey(db, memberPublicKey, wallet.walletId)) - } - - @Test - fun `signing, then not signed`(): Unit = runBlocking { - setUp(signer = true) - val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = null) - assertEquals(WalletState.SIGNING, stateOf(wallet.walletId), "a signer puts it to the group at once") - - val session = assertNotNull(MemberWalletManager.openSessionFor(db, groupRoom, Event.fromJson(wallet.requestJson))) - db.frostSigningSessionDao().upsert(session.copy(stage = FrostSigningStage.FAILED)) - assertEquals(WalletState.NOT_SIGNED, stateOf(wallet.walletId)) - } - - @Test - fun `a wallet made on another device is listed to watch`(): Unit = runBlocking { - setUp() - val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = null) - certify(Event.fromJson(wallet.requestJson)) - // As the other device sees it: the certificate, and no key. - db.memberWalletDao().delete(wallet.walletId) - - val row = assertNotNull(MemberWalletManager.walletOf(db, memberPublicKey, wallet.walletId)) - assertEquals(WalletState.WATCH_ONLY, row.state) - assertNull(MemberWalletManager.exportKey(db, memberPublicKey, wallet.walletId), "no key to export here") - } - - @Test - fun `somebody else's wallets are not listed`(): Unit = runBlocking { - setUp() - val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = null) - certify(Event.fromJson(wallet.requestJson)) - assertTrue(MemberWalletManager.walletsOf(db, privateKey(0xb0b).xOnlyPublicKey().value.toHex()).isEmpty()) - } - - @Test - fun `a member who left keeps the wallet, and is told`(): Unit = runBlocking { - setUp() - val wallet = MemberWalletManager.request(db, groupRoom, member, chain, label = null) - certify(Event.fromJson(wallet.requestJson)) - db.participantDao().delete(db.participantDao().findParticipantsByChatRoomId(groupRoom).filter { it.participantPublicKey == memberPublicKey }) - - val row = assertNotNull(MemberWalletManager.walletOf(db, memberPublicKey, wallet.walletId)) - assertFalse(row.isMember) - assertEquals(WalletState.OPEN, row.state) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/nostr/wallet/MemberWalletCertificateEventJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/nostr/wallet/MemberWalletCertificateEventJvmTest.kt deleted file mode 100644 index 83c52f7e..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/nostr/wallet/MemberWalletCertificateEventJvmTest.kt +++ /dev/null @@ -1,134 +0,0 @@ -package mobi.giza.compose.nostr.wallet - -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 -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.thresholdKeyOf -import mobi.giza.compose.managers.GuardianDerivation -import mobi.giza.compose.managers.MemberWalletDerivation -import mobi.giza.compose.managers.SharedKeyDerivation -import mobi.giza.compose.managers.SubgroupManager -import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent -import mobi.giza.compose.nostr.subgroup.tags.GuardianTag -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.assertNotNull -import kotlin.test.assertNull -import kotlin.test.assertTrue - -/** - * A group's certificate that it guards a member's wallet: believed when it is - * exactly the group's signature over the request it carries, and never mistaken - * for a birth certificate by anything that reads those. - */ -class MemberWalletCertificateEventJvmTest { - 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 group = keyMaterial("6a0b") - private val stranger = keyMaterial("57a9") - private val groupRoom = roomOf(group) - - private val member = privateKey(0x3e3be7) - private val walletPrivateKey = privateKey(0xa11ce) - private val walletKey = walletPrivateKey.publicKey() - private val walletId = MemberWalletDerivation.walletId(walletKey) - - private fun request(guardians: List = GuardianDerivation.grant(thresholdKeyOf(group), groupRoom, emptyList(), walletId)) = - MemberWalletRequestEvent.build( - memberPrivateKey = member, - groupChatRoomId = groupRoom, - walletPrivateKey = walletPrivateKey, - account = MemberWalletDerivation.account(walletKey, chain, guardians), - label = "Savings", - createdAt = 1_700_000_000, - ) - - private fun certified(request: Event = request(), signer: KeyMaterial = group): Event { - val template = MemberWalletCertificateEvent.template(request) - return signedAsRoom(signer, MemberWalletCertificateEvent.KIND, template.tags, template.content, createdAt = template.createdAt) - } - - private fun Event.withTags(tags: Array>, signer: KeyMaterial = group): Event = - signedAsRoom(signer, kind, tags, content, createdAt) - - @Test - fun `a certificate the group signed over the request is believed`() { - val verified = assertNotNull(MemberWalletCertificateEvent.verify(certified(), groupRoom)) - assertEquals(member.xOnlyPublicKey().value.toHex(), verified.memberPublicKey) - assertEquals(walletId, verified.walletId) - assertEquals("Savings", verified.label) - assertEquals(groupRoom, verified.groupChatRoomId) - assertTrue(verified.account.isGuarded) - } - - @Test - fun `two sponsors propose one event`() { - assertEquals(certified().id, certified().id) - } - - @Test - fun `a certificate another room signed is refused`() { - assertNull(MemberWalletCertificateEvent.verify(certified(signer = stranger), groupRoom)) - } - - @Test - fun `a certificate over a request to another group is refused`() { - // The stranger signs a request that asked the group: the request is real, the group is not the one asked. - val strangerRoom = roomOf(stranger) - assertNull(MemberWalletCertificateEvent.verify(certified(signer = stranger), strangerRoom)) - } - - @Test - fun `a certificate naming another member is refused`() { - val certificate = certified() - val other = privateKey(0xb0b).xOnlyPublicKey().value.toHex() - val tags = certificate.tags.map { if (it[0] == "p") arrayOf("p", other) else it }.toTypedArray() - assertNull(MemberWalletCertificateEvent.verify(certificate.withTags(tags), groupRoom)) - } - - @Test - fun `a guardian swapped against its request is refused`() { - val certificate = certified() - val swapped = GuardianDerivation.grant(thresholdKeyOf(stranger), groupRoom, emptyList(), walletId).single() - val tags = certificate.tags.map { if (it[0] == "guardian") GuardianTag.assemble(swapped) else it }.toTypedArray() - assertNull(MemberWalletCertificateEvent.verify(certificate.withTags(tags), groupRoom)) - } - - @Test - fun `a member wallet certificate is never a subgroup`(): Unit = runBlocking { - val certificate = certified() - assertFalse(SubgroupBirthCertificateEvent.certifies(certificate, walletId, groupRoom)) - - GroupFixtures.seedRoom(db, groupRoom) - db.groupSignedEventDao().upsert( - GroupSignedEvent.fromEvent( - event = certificate, - chatRoomId = groupRoom, - derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path), - frostSigningSessionId = null, - ) - ) - assertEquals(emptyList(), SubgroupManager.subgroupsOf(db, groupRoom), "a reader of 30329 never sees a 30334") - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GuardedWalletCardJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GuardedWalletCardJvmTest.kt deleted file mode 100644 index 3f01626d..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GuardedWalletCardJvmTest.kt +++ /dev/null @@ -1,234 +0,0 @@ -package mobi.giza.compose.ui.composable - -import mobi.giza.compose.wallet.GroupOnchainWallets -import mobi.giza.compose.wallet.FakeElectrum -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.CoroutineScope -import mobi.giza.compose.managers.GuardianDerivation -import mobi.giza.compose.managers.LineageExample -import mobi.giza.compose.managers.LineageExample.heldBy -import mobi.giza.compose.ui.composable.navigation.routes.ProfilePreviewRoute -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.runtime.CompositionLocalProvider -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalDensity -import androidx.compose.ui.test.ComposeUiTest -import androidx.compose.ui.test.ExperimentalTestApi -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.onNodeWithContentDescription -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import androidx.compose.ui.test.runDesktopComposeUiTest -import androidx.compose.ui.unit.Density -import mobi.giza.compose.database.model.ChatRoom -import mobi.giza.compose.database.model.GroupSignedEvent -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.managers.GroupWalletDerivation -import mobi.giza.compose.managers.GuardianManager -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.FrostSigningRepository -import mobi.giza.compose.ui.composable.navigation.routes.GroupSendRoute -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.GroupWalletUIState -import mobi.giza.compose.ui.view.state.GuardedWalletRow -import mobi.giza.compose.wallet.GroupWalletState -import com.vitorpamplona.quartz.nip01Core.core.Event -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.Transaction -import fr.acinq.bitcoin.TxId -import fr.acinq.bitcoin.TxIn -import fr.acinq.bitcoin.TxOut -import fr.acinq.lightning.blockchain.electrum.WalletState -import fr.acinq.secp256k1.Hex -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.time.Instant - -/** - * A descendant's guarded wallet on an ancestor's wallet screen: a card whose - * actions sit under the name rather than squeezing it, each one telling a - * screen reader which wallet it acts on. `docs/guarded-wallet-funding.md`, Phase 5. - */ -@OptIn(ExperimentalTestApi::class) -class GuardedWalletCardJvmTest { - private val chatRoomId = "d4c3b2a1".repeat(8) - private val descendantRoomId = "c".repeat(64) - - private fun account(seed: String) = GroupWalletDerivation.account( - PrivateKey(ByteVector32(Hex.decode(seed.padStart(64, '0')))).publicKey().toString(), Chain.Regtest, - ) - - /** A descendant's wallet guarded by this room, at the default delay, as a verified statement would be. */ - private fun guardedAccount(seed: String) = GroupWalletDerivation.account( - PrivateKey(ByteVector32(Hex.decode(seed.padStart(64, '0')))).publicKey().toString(), Chain.Regtest, - guardians = GuardianDerivation.grant(PrivateKey(ByteVector32(Hex.decode("a11ce".padStart(64, '0')))).publicKey().toString(), chatRoomId, emptyList(), descendantRoomId), - ) - - private fun holding(account: GroupWalletDerivation.Account, sats: Long, height: Long, tip: Int): GroupWalletState { - val derived = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, 0) - val next = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, 1) - val tx = Transaction(2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 3 })), 0), ByteVector.empty, 0xffffffffL)), listOf(TxOut(Satoshi(sats), derived.pubkeyScript)), 0) - val meta = WalletState.AddressMeta.Derived(0) - return GroupWalletState( - account, - WalletState(mapOf( - derived.address(Chain.Regtest) to WalletState.AddressState(meta, true, listOf(WalletState.Utxo(tx.txid, 0, height, tx, meta))), - next.address(Chain.Regtest) to WalletState.AddressState(WalletState.AddressMeta.Derived(1), false, emptyList()), - )), - WalletState.empty, - tipHeight = tip, - ) - } - - private fun loaded(name: String): GroupWalletUIState.Loaded { - val own = account("1c0ffee") - val descendant = guardedAccount("decaf") - val guarded = GuardianManager.GuardedWallet( - ancestorChatRoomId = chatRoomId, - descendantChatRoomId = descendantRoomId, - statement = Event("1".repeat(64), descendantRoomId, 1_700_000_000, GroupWalletStatementEvent.KIND, emptyArray(), "", ""), - account = descendant, - certificate = Event("2".repeat(64), chatRoomId, 1_700_000_000, 0, arrayOf(arrayOf("name", name)), "", ""), - lineage = listOf(descendantRoomId), - ) - val wallet = GroupWallet( - GroupSignedEvent( - id = "e".repeat(64), chatRoomId = chatRoomId, publicKey = chatRoomId, kind = GroupWalletStatementEvent.KIND, - tags = GroupWalletStatementEvent.template(own).tags, content = own.xpub, signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000), - ), - own, - ) - val room = LocalChatRoom(ChatRoom(id = chatRoomId, userPublicKey = "a".repeat(64), subject = "Treasury", description = null, initialGiftWrapPayloadId = "p", mlsGroupState = "state")) - return GroupWalletUIState.Loaded( - localChatRoom = room, - wallet = wallet, - walletState = holding(own, 100_000, height = 100, tip = 200), - canSign = true, - guardedWallets = listOf(GuardedWalletRow(guarded, holding(descendant, 50_000, height = 0, tip = 200))), - ) - } - - private fun render(state: GroupWalletUIState, fontScale: Float = 1f, width: Int = 400, onRoute: (Route) -> Unit = {}, assertions: ComposeUiTest.() -> Unit) = - runDesktopComposeUiTest(width = width, height = 2400) { - setContent { - GizaTheme { - ProvideSnackbarHost { - CompositionLocalProvider(LocalDensity provides Density(LocalDensity.current.density, fontScale)) { - Box(modifier = Modifier.fillMaxSize()) { - GroupWalletScreen( - activeUserPublicKey = "a".repeat(64), - chatRoomId = chatRoomId, - chain = Chain.Regtest, - initialGroupWalletUIState = state, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - // Never asked: the state is given, so nothing is watched. - wallets = GroupOnchainWallets(FakeElectrum(), CoroutineScope(SupervisorJob())), - onNavigateToRoute = onRoute, - onNavigateBack = {}, - ) - } - } - } - } - } - assertions() - } - - @Test - fun `each guarded wallet offers fund beside spend, each naming its wallet`() = render(loaded("Savings")) { - onNodeWithText("Savings").assertIsDisplayed() - onNodeWithText("0 sats within this group's reach · 50,000 sats arriving").assertIsDisplayed() - onNodeWithContentDescription("Fund Savings's guarded wallet").assertIsDisplayed() - onNodeWithContentDescription("Spend from Savings's guarded wallet").assertIsDisplayed() - } - - @Test - fun `fund opens the send form paying the descendant, from the room's own wallet`() { - var opened: Route? = null - render(loaded("Savings"), onRoute = { opened = it }) { - onNodeWithContentDescription("Fund Savings's guarded wallet").performClick() - } - assertEquals( - GroupSendRoute(activeUserPublicKey = "a".repeat(64), chatRoomId = chatRoomId, relayHint = null, fundChatRoomId = descendantRoomId), - opened, - ) - } - - @Test - fun `a device that cannot sign is offered neither`() = render(loaded("Savings").copy(canSign = false)) { - onNodeWithText("Savings").assertIsDisplayed() - onNodeWithText("Fund").assertDoesNotExist() - onNodeWithText("Spend").assertDoesNotExist() - } - - @Test - fun `at twice the text size the buttons stay whole`() = render(loaded("Savings"), fontScale = 2f) { - onNodeWithContentDescription("Fund Savings's guarded wallet").assertIsDisplayed() - onNodeWithContentDescription("Spend from Savings's guarded wallet").assertIsDisplayed() - } - - // ---- Members' wallets by person: docs/member-wallet-guarding-group.md, Phase 5 - - /** R's wallet screen, guarding Alice's Savings (under M, below P) and Rent (under N). */ - private fun atR(vararg guarded: GuardianManager.GuardedWallet): GroupWalletUIState.Loaded = - loaded("Savings").copy(guardedWallets = guarded.map { GuardedWalletRow(it, walletState = null) }) - - private val savings = heldBy(LineageExample.r, LineageExample.savings, LineageExample.savingsGuardians, label = "Savings", guardianName = "#M", branchName = "#P") - private val rent = heldBy(LineageExample.r, LineageExample.rent, LineageExample.rentGuardians, label = "Rent", guardianName = "#N", branchName = "#N") - - @Test - fun `a member's two wallets under two groups are one header, each card naming its group`() = render(atR(savings, rent)) { - onNodeWithText("Members' wallets").assertIsDisplayed() - onNodeWithText("@alice").assertIsDisplayed() - onNodeWithText("2 wallets, guarded by 2 groups").assertIsDisplayed() - onNodeWithText("Rent").assertIsDisplayed() - onNodeWithText("Guarded by #N").assertIsDisplayed() - onNodeWithText("Savings").assertIsDisplayed() - onNodeWithText("Guarded by #M, below #P").assertIsDisplayed() - } - - @Test - fun `an unlabelled wallet is named by the group that guards it`() = - render(atR(heldBy(LineageExample.r, LineageExample.savings, LineageExample.savingsGuardians, branchName = "#P"))) { - // No name this device can check for M: where it sits instead. - onNodeWithText("Guarded by a group below #P").assertIsDisplayed() - onNodeWithText("1 wallet, guarded by 1 group").assertIsDisplayed() - } - - @Test - fun `each of a member's buttons names its wallet`() = render(atR(savings, rent, heldBy(LineageExample.r, "9".repeat(64), LineageExample.rentGuardians, guardianName = "#N", branchName = "#N"))) { - onNodeWithContentDescription("Fund @alice's guarded wallet “Savings”").assertIsDisplayed() - onNodeWithContentDescription("Spend from @alice's guarded wallet “Savings”").assertIsDisplayed() - onNodeWithContentDescription("Fund @alice's guarded wallet “Rent”").assertIsDisplayed() - onNodeWithContentDescription("Spend from @alice's guarded wallet “Rent”").assertIsDisplayed() - onNodeWithContentDescription("Fund @alice's wallet guarded by #N").assertIsDisplayed() - onNodeWithContentDescription("Spend from @alice's wallet guarded by #N").assertIsDisplayed() - } - - @Test - fun `a wallet this group guards directly says so`() = - render(atR(heldBy(LineageExample.m, LineageExample.savings, LineageExample.savingsGuardians, label = "Savings", guardianName = "#M"))) { - onNodeWithText("Guarded by this group").assertIsDisplayed() - } - - @Test - fun `the header opens the member's profile`() { - var opened: Route? = null - render(atR(savings), onRoute = { opened = it }) { - onNodeWithText("@alice").performClick() - } - assertEquals(ProfilePreviewRoute(activeUserPublicKey = "a".repeat(64), profilePublicKey = LineageExample.alice), opened) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/MemberWalletPolicyViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/MemberWalletPolicyViewModelJvmTest.kt deleted file mode 100644 index 08183ab6..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/MemberWalletPolicyViewModelJvmTest.kt +++ /dev/null @@ -1,141 +0,0 @@ -package mobi.giza.compose.ui.view.model - -import mobi.giza.compose.database.model.ChatRoom -import mobi.giza.compose.database.model.FrostSigningSession -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.managers.GroupFixtures -import mobi.giza.compose.nostr.wallet.MemberWalletPolicyEvent -import mobi.giza.compose.repository.ChatRepository -import mobi.giza.compose.repository.FrostSigningRepository -import mobi.giza.compose.repository.MemberWalletRepository -import mobi.giza.compose.ui.view.state.MemberWalletPolicyUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.Kind -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.delay -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.test.UnconfinedTestDispatcher -import kotlinx.coroutines.test.resetMain -import kotlinx.coroutines.test.setMain -import kotlinx.coroutines.withTimeout -import kotlin.test.AfterTest -import kotlin.test.BeforeTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertIs -import kotlin.test.assertNotNull -import kotlin.test.assertNull -import kotlin.test.assertTrue - -/** - * Opening a group to its members' wallets, changing the delay, and closing it -- - * `docs/member-wallet-delay.md`, Phase 6. The repositories are fakes: what is - * under test is what the screen offers and what it proposes. - */ -@OptIn(ExperimentalCoroutinesApi::class) -class MemberWalletPolicyViewModelJvmTest { - @BeforeTest - fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher()) - - @AfterTest - fun tearDown() = Dispatchers.resetMain() - - private val group = GroupFixtures.keyMaterial("6a0b") - private val chatRoomId = GroupFixtures.roomOf(group) - private val me = "a".repeat(64) - - private val room = LocalChatRoom( - chatRoom = ChatRoom(id = chatRoomId, userPublicKey = me, subject = "#Council", description = null, mlsGroupState = "state") - ) - - private fun chat(canSign: Boolean) = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { - override suspend fun getChatRoomByIdentifier(identifier: String): LocalChatRoom? = room - override suspend fun canSign(chatRoomId: String): Boolean = canSign - } - - private fun members(policy: MemberWalletPolicyEvent.Policy?) = object : MemberWalletRepository by MemberWalletRepository.NO_OP { - override suspend fun policyOf(chatRoomId: String): MemberWalletPolicyEvent.Policy? = policy - } - - private class Proposing : FrostSigningRepository by FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY { - var proposed: Pair>>? = null - override suspend fun proposeSigning( - localChatRoom: LocalChatRoom, - userPublicKey: HexKey, - kind: Kind, - tags: Array>, - content: String, - ): FrostSigningSession? { - proposed = kind to tags - return null - } - } - - private fun open(delay: Long) = MemberWalletPolicyEvent.verify(GroupFixtures.memberWalletPolicy(group, delay), chatRoomId) - private fun closed() = MemberWalletPolicyEvent.verify(GroupFixtures.memberWalletPolicy(group, null), chatRoomId) - - private fun loaded(policy: MemberWalletPolicyEvent.Policy?, canSign: Boolean = true, signing: FrostSigningRepository = Proposing()) = - MemberWalletPolicyViewModel(me, chatRoomId, MemberWalletPolicyUIState.Loading, chat(canSign), members(policy), signing).apply { - initiate() - runBlocking { withTimeout(5_000) { while (uiState !is MemberWalletPolicyUIState.Loaded) delay(10) } } - } - - private fun Proposing.awaitProposed() = runBlocking { withTimeout(5_000) { while (proposed == null) delay(10) } }.let { assertNotNull(proposed) } - - @Test - fun `a group opening for the first time starts at 12, an open one at its own delay`() { - assertEquals(12L, loaded(null).delay.delay()) - assertEquals(12L, loaded(closed()).delay.delay()) - assertEquals(4_320L, loaded(open(4_320)).delay.delay()) - assertTrue(loaded(open(4_320)).delay.isCustom.value.not(), "a preset comes back as its chip") - assertTrue(loaded(open(2_016)).delay.isCustom.value, "anything else in the field") - } - - @Test - fun `opening proposes an open policy at the chosen delay`() { - val signing = Proposing() - val viewModel = loaded(null, signing = signing) - viewModel.delay.pick(1_008) - assertNull(viewModel.openProblem()) - - viewModel.proposeOpen(onSuccess = {}, onFailure = {}) - val (kind, tags) = signing.awaitProposed() - assertEquals(MemberWalletPolicyEvent.KIND, kind) - assertTrue(tags.any { it.toList() == listOf("guardian_delay", "1008") }) - } - - @Test - fun `a delay out of range, or the group's own, is not proposed`() { - val viewModel = loaded(open(144)) - assertEquals("That is already this group's delay.", viewModel.openProblem()) - - viewModel.delay.useCustom() - viewModel.delay.type("5") - assertEquals("A delay is at least 6 blocks.", viewModel.openProblem()) - viewModel.delay.type("65536") - assertEquals("A delay is at most 65,535 blocks.", viewModel.openProblem()) - } - - @Test - fun `closing is offered only to an open group, and proposes a closed policy`() { - assertFalse(loaded(null).canClose()) - assertFalse(loaded(closed()).canClose()) - - val signing = Proposing() - val viewModel = loaded(open(144), signing = signing) - assertTrue(viewModel.canClose()) - viewModel.proposeClose(onSuccess = {}, onFailure = {}) - val (_, tags) = signing.awaitProposed() - assertTrue(tags.any { it.toList() == listOf("closed") }) - } - - @Test - fun `a device that cannot sign is offered nothing to propose`() { - val viewModel = loaded(open(144), canSign = false) - assertIs(viewModel.uiState) - assertNotNull(viewModel.openProblem()) - assertFalse(viewModel.canClose()) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/NewMemberWalletViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/NewMemberWalletViewModelJvmTest.kt deleted file mode 100644 index be626a6b..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/NewMemberWalletViewModelJvmTest.kt +++ /dev/null @@ -1,81 +0,0 @@ -package mobi.giza.compose.ui.view.model - -import mobi.giza.compose.database.model.ChatRoom -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.managers.MemberWalletManager.Refusal -import mobi.giza.compose.repository.MemberWalletRepository -import mobi.giza.compose.ui.view.state.NewMemberWalletUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.Chain -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.delay -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.test.UnconfinedTestDispatcher -import kotlinx.coroutines.test.resetMain -import kotlinx.coroutines.test.setMain -import kotlinx.coroutines.withTimeout -import kotlin.test.AfterTest -import kotlin.test.BeforeTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertIs - -/** - * Which groups the *Choose a group to guard it* list offers -- - * `docs/member-wallet-delay.md`. Only a group that guards members' wallets, or - * may: one whose key this device has not been told is kept, with the button - * that asks, because the answer is how it would learn the group is open. - */ -@OptIn(ExperimentalCoroutinesApi::class) -class NewMemberWalletViewModelJvmTest { - @BeforeTest - fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher()) - - @AfterTest - fun tearDown() = Dispatchers.resetMain() - - private val me = "a".repeat(64) - - private fun room(id: Char) = LocalChatRoom( - chatRoom = ChatRoom(id = id.toString().repeat(64), userPublicKey = me, subject = "#$id", description = null, mlsGroupState = "state") - ) - - /** One group per refusal, and one that can be asked. */ - private val refusals: Map = mapOf( - room('1') to null, - room('2') to Refusal.KEY_UNKNOWN, - room('3') to Refusal.NOT_OFFERED, - room('4') to Refusal.CLOSED, - room('5') to Refusal.GUARDIANS_UNREADABLE, - ) - - private fun repository(groups: Map) = object : MemberWalletRepository by MemberWalletRepository.NO_OP { - override suspend fun groupsOf(ownerPublicKey: HexKey): List = groups.keys.toList() - override suspend fun refusal(chatRoomId: String, chain: Chain): Refusal? = - groups.entries.first { it.key.chatRoom.id == chatRoomId }.value - } - - private fun picking(groups: Map): NewMemberWalletUIState.Picking { - val viewModel = NewMemberWalletViewModel(me, null, Chain.Regtest, NewMemberWalletUIState.Loading, repository(groups)) - viewModel.initiate() - runBlocking { withTimeout(5_000) { while (viewModel.uiState == NewMemberWalletUIState.Loading) delay(10) } } - return assertIs(viewModel.uiState) - } - - @Test - fun `a group that never opened, or has closed, is not on the list`() { - val listed = picking(refusals).groups.associate { it.room.chatRoom.subject to it.refusal } - - assertEquals( - mapOf("#1" to null, "#2" to Refusal.KEY_UNKNOWN, "#5" to Refusal.GUARDIANS_UNREADABLE), - listed, - "an open group, one whose key is not known yet, and one this build cannot read stay, each with its reason", - ) - } - - @Test - fun `a member none of whose groups guards members' wallets sees an empty list`() { - assertEquals(emptyList(), picking(mapOf(room('3') to Refusal.NOT_OFFERED, room('4') to Refusal.CLOSED)).groups) - } -} diff --git a/docs/giza-wallet-removal.md b/docs/giza-wallet-removal.md index 9964e7ce..5ec1ecbc 100644 --- a/docs/giza-wallet-removal.md +++ b/docs/giza-wallet-removal.md @@ -21,7 +21,8 @@ written against `caf1fb18`. |---|---| | 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 | -| 2 | built. 63 files deleted: the Lightning events, managers, Iceberg, `wallet/lightning/`, the repository, five screens with their view models, states and routes, and the regtest network with its build wiring and its section in `CLAUDE.md`. Its four DAOs go; the entities stay for Phase 5. The 147 strings Phases 1 and 2 left unread go. `jvmTest` 1,440 run, 0 failed, 0 skipped; `m3-audit` floors unchanged | Paths below are under +| 2 | built. 63 files deleted: the Lightning events, managers, Iceberg, `wallet/lightning/`, the repository, five screens with their view models, states and routes, and the regtest network with its build wiring and its section in `CLAUDE.md`. Its four DAOs go; the entities stay for Phase 5. The 147 strings Phases 1 and 2 left unread go. `jvmTest` 1,440 run, 0 failed, 0 skipped; `m3-audit` floors unchanged | +| 3 | built, as **member wallets only** (see below). The member-wallet events (30334, 30335, 30336, 30337), `MemberWalletManager`, `MemberWalletDerivation`, the repository and DAO, five screens with their view models, states and routes, and their 74 strings. `GuardianManager` stops reading member certificates. `jvmTest` 1,311 run, 0 failed (one `IdentitySwitchJvmTest` timeout under the full suite's load, which passes three times in three alone and at baseline) | 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. @@ -47,6 +48,7 @@ Where the build chose differently from the phases as written: | FROST's sweep path goes in Phase 4, with the spend | in Phase 2, because it is built on `wallet/lightning/GroupSweep`. A sweep that arrives is filed declined by `declineWalletProposal`, which reads nothing of what it spends -- the path Phase 4 sends every transaction proposal down | | a Lightning kind's line is the retired arm's | and its protocol kinds are no longer *protocol* in `fromGroupEventResult` either: nothing acts on them, so they reach `applyInnerEvent` and its retired arm, which is how a 30355 gets its one line | | existing Lightning and Iceberg lines keep their types as names only | their constants and sets stay in `ChatMessage`, and the transcript draws them as settled lines that open nothing, until Phase 5 deletes the rows | +| Phase 3 removes member wallets, guardians and the subgroup policy; Phase 4 the on-chain wallet | Phase 3 removes **member wallets**, and Phase 4 the on-chain wallet **with** its guardians and the subgroup policy. The guardian derivation, `GuardianManager` and the policy reads are built into `GroupWallet`, `GroupSpend`, `GroupWalletDerivation` and the wallet screens, so they cannot leave before the wallet does and still compile. The lineage fixtures and their three tests went with member wallets, since every wallet they modelled was one | | 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