diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 4b089534..01ca6ae3 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -345,6 +345,7 @@ Key package rotated Subgroups Add subgroup + This subgroup is to keep a guarded wallet. Giza doesn't take part in wallets, so it can't join this ceremony. This group's subgroups must keep guarded wallets. Giza doesn't take part in wallets, so it can't add a subgroup here. No subgroups have been made by this group. Certified, not created yet @@ -461,177 +462,11 @@ Checking whether %1$s can receive messages here. %1$s hasn't set up encrypted messaging yet. Try again later, or ask them to open Giza. - Group onchain wallet - %1$s onchain wallet - Open a group onchain wallet - This group has not opened a wallet. - Opening a wallet asks the group to agree that it keeps coins here. Any quorum of members can then spend them together, and nobody can spend them alone. - Each member's share of the group's key is stored unencrypted on their device. Anyone with an unlocked device, or a copy of its data, holds that member's share. - Couldn't ask the group to open a wallet. - The groups above this one have agreed to guard its wallet. In a guarded wallet each of them can spend any coin that has waited as long as its own delay, without this group agreeing: - Open a guarded wallet - Open without guardians - Guarded wallets - Spend - Spend from %1$s's guarded wallet - Wallets of groups below this one. This group can spend a coin in each once the coin has waited as long as the delay that wallet gives this group. - %1$s sats within this group's reach - Fund - Fund %1$s's guarded wallet - %1$s sats arriving - To - %1$s's guarded wallet - This group can spend these coins again once they have waited %1$s. - Finding an address in %1$s's wallet… - Wait for this group's open payments to %1$s to confirm. - Tell the groups above - Not yet shared with the groups above that you're in - Share - Shared with the groups above - Couldn't share the wallet - Guarded: the groups above this one can spend any coin here that has waited as long as their own delay: - Balance - %1$s sats - %1$s sats on the way - Receive address - Copy address - Address copied - All addresses - Addresses - Each payment should go to a new address. If someone else in the group is already sharing the current one, share one of the ones after it. - Being handed out now - Not used yet - Paid · %1$s sats - Paid · spent since - Copy address %1$s - Address %1$s - Show as a QR code - Address %1$s was just paid - Finding the group's coins… - Nothing has been sent to this wallet yet. - Coins - Change - Received - Waiting for a confirmation - %1$s confirmations - %1$s · %2$s - Not known yet - Export watch-only - Watch-only descriptors copied - Anyone with these can see every address of this wallet and its whole balance. They can't spend from it. - Spend from the group's wallet - This spend could not be checked on this device, so there is nothing to check before signing. Don't sign it. - %1$s sats, back to the group as change - Fee: %1$s sats, at %2$s sats per byte - Spends %1$s of the group's coins - Signed by the group, not by you. Once enough members sign, any member's device can send it to the network. - Send - Send from the group's wallet - Address - Amount in sats - sats - %1$s sats confirmed and free to spend - Send everything - Fee rate in sats per byte - Ask the group to send - Sends %1$s sats, with a fee of %2$s sats. - Sends %1$s sats to %2$s's guarded wallet, with a fee of %3$s sats. - %1$s sats come back to the group as change. - That isn't an address on %1$s. - The group has nothing confirmed to spend yet. - The group doesn't have that much confirmed, after the fee. - That is too little to send: the network won't relay an output that small. - Sats are whole numbers: there is nothing smaller than a sat to send. - That is more sats than there will ever be. - That isn't an amount in sats. - %1$s sats left over are too few to come back as change, and go to the fee. - The group has too many spends with change waiting for signatures. Wait for one to settle, or send everything. - Couldn't ask the group to send. - Sending needs a share of the group's key, and a wallet of your own on this profile to see the group's coins with. - Nothing leaves the wallet until a quorum of members has seen this spend and signed it. - Spends - Waiting for signatures - Signed, sending it to the network - Sent, waiting for a confirmation - Confirmed - Replaced by another spend of the same coins - Send again - Bump the fee - Sent again - Couldn't bump the fee: there isn't enough left over to pay it. - While the wallet is new, a spend on mainnet can send at most %1$s sats. - 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: - The group above this one decided this group's wallet is not guarded. Only this group can spend from it. - %1$s, %2$s - %1$s: after %2$s - 1 hour - 2 hours - 1 day - 1 week - 1 month - 6 months - Longest - Custom - Delay in blocks - A group above this one - This group can spend a coin here after %1$s - Only coins that have waited %1$s can be spent from this guarded wallet. - - %1$s block - %1$s blocks - - - about %1$d minute - about %1$d minutes - - - about %1$d hour - about %1$d hours - - - about %1$d day - about %1$d days - - - about %1$d month - about %1$d months - - - about %1$d year - about %1$d years - - Guarded by %1$s - Guarded by %1$s, below %2$s - this group - a group below %1$s - a group below this one - Members' wallets - %1$s, %2$s - - %1$d wallet - %1$d wallets - - - guarded by %1$d group - guarded by %1$d groups - - Fund %1$s's guarded wallet “%2$s” - 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 - Finding your coins… - %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. - @%1$s - 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 7d37883b..bfceae86 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/GizaDatabase.kt @@ -14,7 +14,6 @@ import mobi.giza.compose.database.model.GroupLightningSeed 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 androidx.room3.ColumnTypeConverters import androidx.room3.AutoMigration import androidx.room3.ConstructedBy @@ -449,7 +448,6 @@ abstract class GizaDatabase: RoomDatabase() { abstract fun groupSignedEventDao(): GroupSignedEventDao - abstract fun groupTransactionDao(): GroupTransactionDao abstract fun connectionDao(): ConnectionDao diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupTransactionDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupTransactionDao.kt deleted file mode 100644 index d1575cb2..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/GroupTransactionDao.kt +++ /dev/null @@ -1,47 +0,0 @@ -package mobi.giza.compose.database.dao - -import androidx.room3.Dao -import androidx.room3.Insert -import androidx.room3.OnConflictStrategy -import androidx.room3.Query -import androidx.room3.Upsert -import mobi.giza.compose.database.model.GroupTransaction -import kotlinx.coroutines.flow.Flow - -@Dao -abstract class GroupTransactionDao { - @Query("SELECT * FROM GroupTransaction WHERE frostSigningSessionId = :sessionId") - abstract suspend fun getBySessionId(sessionId: String): GroupTransaction? - - @Query("SELECT * FROM GroupTransaction WHERE frostSigningSessionId = :sessionId") - abstract fun observeBySessionId(sessionId: String): Flow - - @Query("SELECT * FROM GroupTransaction WHERE chatRoomId = :chatRoomId ORDER BY createdAt DESC") - abstract suspend fun getByChatRoomId(chatRoomId: String): List - - @Query("SELECT * FROM GroupTransaction WHERE chatRoomId = :chatRoomId ORDER BY createdAt DESC") - abstract fun observeByChatRoomId(chatRoomId: String): Flow> - - /** - * Every signed transaction still on its way: not yet seen confirmed, and not - * replaced by another spend of the same coins that was. What the watcher - * broadcasts and looks for. - */ - @Query("SELECT * FROM GroupTransaction WHERE signedTransaction IS NOT NULL AND confirmedAt IS NULL AND replacedByTxid IS NULL") - abstract suspend fun getUnsettled(): List - - @Query("SELECT * FROM GroupTransaction WHERE signedTransaction IS NOT NULL AND confirmedAt IS NULL AND replacedByTxid IS NULL") - abstract fun observeUnsettled(): Flow> - - /** - * The first write, at proposal or acceptance. Ignores a second: the PSBT is - * write-once, and a row for this session already holds the one every item's - * sighash was computed from. - */ - @Insert(onConflict = OnConflictStrategy.IGNORE) - abstract suspend fun insertIfAbsent(transaction: GroupTransaction): Long - - /** Every later write -- signed, broadcast, seen, confirmed -- over the row [insertIfAbsent] made. */ - @Upsert - abstract suspend fun upsert(transaction: GroupTransaction) -} 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 9f2e570b..7ad9c56a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt @@ -2,7 +2,6 @@ package mobi.giza.compose.database.model import mobi.giza.compose.nostr.RetiredKinds -import mobi.giza.compose.text.describe import androidx.room3.Entity import androidx.room3.ForeignKey import androidx.room3.Index @@ -16,8 +15,6 @@ import mobi.giza.compose.database.model.traits.UserViewableEntity import mobi.giza.compose.exceptions.MarmotUnprocessableInnerEventException import mobi.giza.compose.managers.ChronicleManager import mobi.giza.compose.managers.GroupKeyStateManager -import mobi.giza.compose.managers.GroupWalletManager -import mobi.giza.compose.managers.GuardianManager import mobi.giza.compose.managers.SubgroupManager import mobi.giza.compose.extensions.toHex import com.vitorpamplona.quartz.marmot.GroupEventResult @@ -36,9 +33,6 @@ import mobi.giza.compose.nostr.dkg.DkgRitualEvents import mobi.giza.compose.nostr.frost.FrostSigningEvents import mobi.giza.compose.nostr.frost.GroupKeyStateEvent import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent -import mobi.giza.compose.nostr.wallet.GroupWallet -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import mobi.giza.compose.nostr.wallet.GuardedWalletNoticeEvent import mobi.giza.compose.nostr.chronicle.ChronicleEvent import mobi.giza.compose.nostr.chronicle.ChronicleRequestEvent import co.touchlab.kermit.Logger @@ -1398,31 +1392,6 @@ data class ChatMessage( ) } - // 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 - // will send money on. A statement that fails either gets no line; - // it is filed as a `GroupSignedEvent` all the same, and `GroupWallet` - // refuses it there for the same reasons. - GroupWalletStatementEvent.KIND -> { - val signed = GroupSignedEvent.fromEvent(event, chatRoomId = groupId) - val thresholdPublicKey = GroupWalletManager.thresholdKeyFor(database, groupId) - ?: return null - val wallet = GroupWallet.of(signed, thresholdPublicKey) ?: return null - - ChatMessage( - giftWrapPayloadId = null, - messageType = TYPE_GROUP_WALLET_OPENED, - marmotGroupEventId = marmotGroupEventId, - marmotInnerEventId = marmotInnerEventId, - senderPublicKey = senderPublicKey, - isUserMessage = isUserMessage, - chatRoomId = groupId, - createdAt = createdAt, - content = "The group opened a wallet on ${GroupWalletStatementEvent.chainName(wallet.chain)}" - ) - } - // A profile or a relay list -- the group's or a member's own -- // travelling through the room. The app no longer reads either as // the group's, and both are identity plumbing nobody sends into a diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/DkgSession.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/DkgSession.kt index 7251d0fa..c2582220 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/DkgSession.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/DkgSession.kt @@ -8,7 +8,6 @@ import mobi.giza.compose.database.model.traits.LocalStoreEntity import mobi.giza.compose.database.model.traits.TimestampedEntity import mobi.giza.compose.database.model.types.DkgApprovalStep import mobi.giza.compose.database.model.types.DkgRitualStage -import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray import fr.acinq.bitcoin.ByteVector @@ -101,30 +100,14 @@ data class DkgSession( val subject: String? = null, /** - * The wallet policy the coordinator chose for the subgroup this ceremony - * makes, as `SubgroupWalletPolicy.tagValue` -- or null for a ceremony that - * makes no subgroup, or one proposed by a build from before policies. - * `docs/subgroup-wallet-policy.md`. - * - * A claim on a proposal, like [subject], and read for two things only: the - * join screen, which tells an admin what they are agreeing to, and the - * certificate rung, which proposes the certificate under it. What makes it - * binding is the parent's quorum signing it into the certificate, and every - * child signer then refusing a key state whose certificate says otherwise. + * The `wallet` tag a Bennu coordinator put on a subgroup's ceremony, as written, + * or null for none -- which is every ceremony Giza proposes. Read for one thing: + * Giza does not join a ceremony for a guarded subgroup ([isGuardedSubgroup]), + * and its join screen says why. docs/giza-wallet-removal.md, W5. */ val walletPolicy: String? = null, - /** - * The delay, in blocks, the coordinator chose for the parent's own leaf in - * the guarded subgroup this ceremony makes -- or null for an unguarded one, - * one that makes no subgroup, or one from a build before parents chose. - * `docs/guardian-delay.md`. - * - * A claim on a proposal like [walletPolicy], read for the join screen and for - * the certificate rung. A guarded ceremony with none is certified at - * `GuardianDerivation.DEFAULT_DELAY`, which is what its build would have - * written. - */ + /** Read by nothing since the wallets went; the column goes in schema 36. */ val guardianDelay: Long? = null, val stage: DkgRitualStage = DkgRitualStage.COLLECTING_HOST_KEYS, @@ -261,6 +244,9 @@ data class DkgSession( } } -/** [DkgSession.walletPolicy], read; null for none or one this build does not know. */ -val DkgSession.subgroupWalletPolicy: SubgroupWalletPolicy? - get() = walletPolicy?.let(SubgroupWalletPolicy::fromTagValue) +/** + * Whether this is a Bennu subgroup's ceremony whose wallet is to be guarded, which + * Giza does not join (W5, docs/giza-wallet-removal.md). + */ +val DkgSession.isGuardedSubgroup: Boolean + get() = walletPolicy == "guarded" diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index 07410715..15b73579 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -1,12 +1,5 @@ package mobi.giza.compose.database.repository -import mobi.giza.compose.managers.GuardianDerivation -import mobi.giza.compose.nostr.subgroup.WalletPolicyReading -import fr.acinq.bitcoin.Chain -import mobi.giza.compose.managers.GroupWalletManager -import mobi.giza.compose.managers.GuardianManager -import mobi.giza.compose.managers.GroupWalletDerivation -import mobi.giza.compose.nostr.wallet.GroupWallet import mobi.giza.compose.database.GENESIS_AT import mobi.giza.compose.database.GizaDatabase import kotlinx.coroutines.flow.MutableStateFlow @@ -140,81 +133,6 @@ class DatabaseChatRepository( null } - override suspend fun walletPolicyOf(chatRoomId: String): WalletPolicyReading? = try { - SubgroupManager.walletPolicyOf(database, chatRoomId) - } catch (e: Throwable) { - logger.e("Error reading the wallet policy of $chatRoomId", e) - null - } - - // Null on a failure, which reads as keys this build cannot read: the picker - // then refuses a guarded subgroup rather than promising a grant it could not - // check. - override suspend fun guardiansOf(chatRoomId: String): List? = try { - SubgroupManager.guardiansOf(database, chatRoomId) - } catch (e: Throwable) { - logger.e("Error reading the guardians of $chatRoomId", e) - null - } - - override suspend fun groupWallet(chatRoomId: String, chain: Chain): GroupWallet? = try { - GroupWalletManager.walletFor(database, chatRoomId, chain) - } catch (e: Throwable) { - logger.e("Error reading the wallet of $chatRoomId", e) - null - } - - override suspend fun groupWalletAccount(chatRoomId: String, chain: Chain): GroupWalletDerivation.Account? = try { - GroupWalletManager.accountFor(database, chatRoomId, chain) - } catch (e: Throwable) { - logger.e("Error deriving the wallet account of $chatRoomId", e) - null - } - - override suspend fun groupWalletGuardedOpening(chatRoomId: String, chain: Chain): GroupWalletManager.GuardedOpening? = try { - GroupWalletManager.guardedAccountFor(database, chatRoomId, chain) - } catch (e: Throwable) { - logger.e("Error deriving the guarded wallet account of $chatRoomId", e) - null - } - - override suspend fun guardedWallets(chatRoomId: String): List = try { - GuardianManager.guardedWalletsOf(database, chatRoomId) - } catch (e: Throwable) { - logger.e("Error reading the guarded wallets $chatRoomId was told about", e) - emptyList() - } - - override suspend fun shareableGuardedWallets(chatRoomId: String, chain: Chain): List = try { - GuardianManager.shareableFrom(database, chatRoomId, chain) - } catch (e: Throwable) { - logger.e("Error reading what $chatRoomId can tell the groups above it", e) - emptyList() - } - - override suspend fun forwardGuardedWallets(chatRoomId: String): Int = try { - GuardianManager.forwardAll(database, chatRoomId) - } catch (e: Throwable) { - // A room that opens without telling the groups above is wrong and - // survivable, and the button is still there. - logger.e("Error forwarding $chatRoomId's guarded wallets upward", e) - 0 - } - - override suspend fun shareGuardedWallet(shareable: GuardianManager.Shareable, userPublicKey: HexKey): Int = try { - GuardianManager.share(database, shareable.statement, shareable.rooms, userPublicKey, certificate = shareable.certificate) - } catch (e: Throwable) { - logger.e("Error telling the groups above about ${shareable.statement.pubKey}'s guarded wallet", e) - 0 - } - - override suspend fun recordGuardianSpends(chatRoomId: String, taken: List): Int = try { - GuardianManager.recordTaken(database, chatRoomId, taken) - } catch (e: Throwable) { - logger.e("Error recording guardian spends from $chatRoomId's wallet", e) - 0 - } - override suspend fun canSign(chatRoomId: String): Boolean = try { FrostSigningManager.canSign(database, chatRoomId) } catch (e: Throwable) { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseDkgRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseDkgRepository.kt index 5a24575d..c2c54b30 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseDkgRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseDkgRepository.kt @@ -1,6 +1,5 @@ package mobi.giza.compose.database.repository -import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.model.DkgParticipantMessage import mobi.giza.compose.database.model.DkgSession @@ -65,9 +64,7 @@ class DatabaseDkgRepository( threshold: Int, parentChatRoomId: HexKey?, participantPublicKeys: Set?, - subject: String?, - walletPolicy: SubgroupWalletPolicy?, - guardianDelay: Long? + subject: String? ): DkgSession? = try { ChillDkgRitualManager.proposeRitual( database = database, @@ -77,9 +74,7 @@ class DatabaseDkgRepository( threshold = threshold, parentChatRoomId = parentChatRoomId, participantPublicKeys = participantPublicKeys, - subject = subject, - walletPolicy = walletPolicy, - guardianDelay = guardianDelay + subject = subject ) } catch (e: Throwable) { logger.e("Error proposing DKG ritual for ${localChatRoom.chatRoom.id}", e) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseFrostSigningRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseFrostSigningRepository.kt index 8c259551..3c728e24 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseFrostSigningRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseFrostSigningRepository.kt @@ -1,10 +1,5 @@ package mobi.giza.compose.database.repository -import mobi.giza.compose.database.model.GroupTransaction -import mobi.giza.compose.wallet.GroupSpend -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.OutPoint -import fr.acinq.bitcoin.psbt.Psbt import co.touchlab.kermit.Logger import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey @@ -21,7 +16,6 @@ import mobi.giza.compose.database.model.intermdiate.FrostSignerTally import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.database.model.intermdiate.LocalFrostSigningSession import mobi.giza.compose.managers.FrostSigningManager -import mobi.giza.compose.managers.GroupWalletDerivation import mobi.giza.compose.nostr.dkg.DkgRitualEvents import mobi.giza.compose.nostr.frost.FrostSigningEvents import mobi.giza.compose.repository.FrostSigningRepository @@ -133,69 +127,6 @@ class DatabaseFrostSigningRepository( null } - override suspend fun proposeSpend( - localChatRoom: LocalChatRoom, - userPublicKey: HexKey, - psbt: Psbt, - chain: Chain, - ): FrostSigningSession? = proposing(localChatRoom) { - FrostSigningManager.proposeSpend( - database = database, - localChatRoom = localChatRoom, - userPublicKey = userPublicKey, - psbt = psbt, - chain = chain, - ) - } - - override suspend fun proposeGuardianSpend( - localChatRoom: LocalChatRoom, - userPublicKey: HexKey, - psbt: Psbt, - descendantChatRoomId: String, - chain: Chain, - ): FrostSigningSession? = proposing(localChatRoom) { - FrostSigningManager.proposeGuardianSpend( - database = database, - localChatRoom = localChatRoom, - userPublicKey = userPublicKey, - psbt = psbt, - descendantChatRoomId = descendantChatRoomId, - chain = chain, - ) - } - - override suspend fun checkedSpend(sessionId: String): GroupSpend.Checked? = try { - FrostSigningManager.checkedSpend(database, sessionId) - } catch (e: Throwable) { - logger.e("Error checking the spend of $sessionId", e) - null - } - - override suspend fun reservedOutPoints(chatRoomId: String): Set = try { - FrostSigningManager.reservedOutPoints(database, chatRoomId) - } catch (e: Throwable) { - logger.e("Error reading the coins reserved in $chatRoomId", e) - emptySet() - } - - override suspend fun reservedChangeIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set = try { - FrostSigningManager.reservedChangeIndices(database, chatRoomId, account) - } catch (e: Throwable) { - logger.e("Error reading the change addresses reserved in $chatRoomId", e) - emptySet() - } - - override suspend fun reservedFundingIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set = try { - FrostSigningManager.reservedFundingIndices(database, chatRoomId, account) - } catch (e: Throwable) { - logger.e("Error reading the funding addresses reserved in $chatRoomId", e) - emptySet() - } - - override fun observeGroupTransactions(chatRoomId: String): Flow> = - database.groupTransactionDao().observeByChatRoomId(chatRoomId) - override suspend fun resend(localChatRoom: LocalChatRoom, sessionId: String): Boolean = try { FrostSigningManager.resend( database = database, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ChillDkgRitualManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ChillDkgRitualManager.kt index c4ef6610..e4d2b579 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ChillDkgRitualManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ChillDkgRitualManager.kt @@ -1,9 +1,7 @@ package mobi.giza.compose.managers -import mobi.giza.compose.nostr.subgroup.tags.GuardianDelayTag -import mobi.giza.compose.database.model.subgroupWalletPolicy -import mobi.giza.compose.nostr.subgroup.tags.WalletPolicyTag -import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy +import mobi.giza.compose.database.model.isGuardedSubgroup + import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.model.ChatMessage import mobi.giza.compose.database.model.DkgParticipantMessage @@ -187,17 +185,6 @@ object ChillDkgRitualManager { * and is carried to the other admins on the proposal because there is no * longer a room of its own for them to read it off. * - * [walletPolicy] is what the subgroup's wallet is to be, as the coordinator - * chose it on the picker -- carried on the proposal so every admin is told - * before joining, and on the session so whoever proposes the birth - * certificate proposes it under the same one. Only a subgroup's ceremony has - * one. See `docs/subgroup-wallet-policy.md`. - * - * [guardianDelay] is the delay, in blocks, the coordinator chose for the - * parent's own leaf in a guarded subgroup's wallet, carried the same way and - * for the same reasons. Only a guarded ceremony has one, and it is in - * `GuardianDerivation.DELAY_RANGE`. See `docs/guardian-delay.md`. - * * Throws when the group or the threshold cannot support one; the UI checks * both before offering the button, so reaching either is a bug rather than a * user error. @@ -211,23 +198,7 @@ object ChillDkgRitualManager { parentChatRoomId: HexKey? = null, participantPublicKeys: Set? = null, subject: String? = null, - walletPolicy: SubgroupWalletPolicy? = null, - guardianDelay: Long? = null ): DkgSession { - // A policy is for a subgroup's wallet, and a ceremony with no parent makes - // no subgroup. `acceptProposal` drops the same thing on the way in. - // Before the running check, which would otherwise hand back a ceremony - // for a question this one should never have asked. - require(walletPolicy == null || parentChatRoomId != null) { - "Only a subgroup's ceremony carries a wallet policy" - } - // A delay is a guarded wallet's, and within what a leaf can carry. - require(guardianDelay == null || walletPolicy == SubgroupWalletPolicy.GUARDED) { - "Only a guarded subgroup's ceremony carries a guardian delay" - } - require(guardianDelay == null || guardianDelay in GuardianDerivation.DELAY_RANGE) { - "A guardian's delay is ${GuardianDerivation.MIN_DELAY} to ${GuardianDerivation.MAX_DELAY} blocks, not $guardianDelay" - } // Built the way a receiver rebuilds it from the proposal — the p-tags // `broadcast` writes, plus this device — so both sides count the same `n` @@ -326,8 +297,6 @@ object ChillDkgRitualManager { // subgroup's ceremony runs in the parent's room over a subset of it. participantPublicKeys = DkgSession.formatParticipants(members), subject = ceremonySubject, - walletPolicy = walletPolicy?.tagValue, - guardianDelay = guardianDelay, hostPublicKey = deriveHostPublicKey(nostrPrivateKey).value.toHex(), // Fresh per session. Persisted because participantStep1/2 are pure in // it, which is what makes the whole ritual restart-safe. @@ -506,37 +475,6 @@ object ChillDkgRitualManager { return null } - // A policy is only for a subgroup's wallet, and one that does not read is - // not one to join on the assumption it says nothing: an admin would be - // shown no policy and then asked to sign a key state under one. - val walletPolicy = when (val tag = DkgRitualEvents.parseWalletPolicy(innerEvent.tags)) { - WalletPolicyTag.Result.Absent -> null - WalletPolicyTag.Result.Unreadable -> { - logger.w("DKG proposal $sessionId carries a wallet policy that does not read; dropping") - return null - } - is WalletPolicyTag.Result.Present -> tag.policy - } - if (walletPolicy != null && DkgRitualEvents.parseParentChatRoomId(innerEvent.tags) == null) { - logger.w("DKG proposal $sessionId carries a wallet policy and names no parent; dropping") - return null - } - - // The same for the delay: a guarded subgroup's only, and in range. An - // admin shown no delay must not be asked to sign a certificate under one. - val guardianDelay = when (val tag = DkgRitualEvents.parseGuardianDelay(innerEvent.tags)) { - GuardianDelayTag.Result.Absent -> null - GuardianDelayTag.Result.Unreadable -> { - logger.w("DKG proposal $sessionId carries a guardian delay that does not read; dropping") - return null - } - is GuardianDelayTag.Result.Present -> tag.delay - } - if (guardianDelay != null && walletPolicy != SubgroupWalletPolicy.GUARDED) { - logger.w("DKG proposal $sessionId carries a guardian delay for a subgroup that is not guarded; dropping") - return null - } - val session = DkgSession( id = sessionId, chatRoomId = localChatRoom.chatRoom.id, @@ -561,10 +499,10 @@ object ChillDkgRitualManager { // on it, and the certificate the parent's quorum signs is over this // name, so an admin who dislikes it declines that. subject = DkgRitualEvents.parseSubject(innerEvent.tags), - // What the subgroup's wallet is to be, as claimed -- shown at the join - // gate, so joining is agreeing to it. See the checks above. - walletPolicy = walletPolicy?.tagValue, - guardianDelay = guardianDelay, + // What a Bennu coordinator said the subgroup's wallet is to be, as + // written: Giza does not join a guarded one (W5), and the join screen + // says so. docs/giza-wallet-removal.md. + walletPolicy = DkgRitualEvents.parseWalletPolicy(innerEvent.tags), hostPublicKey = deriveHostPublicKey(nostrPrivateKey).value.toHex(), round1Random = RandomInstance.bytes(32).toHex(), round2AuxRandom = RandomInstance.bytes(32).toHex(), @@ -1270,6 +1208,15 @@ object ChillDkgRitualManager { return } + // A guarded subgroup's ceremony is one Giza does not join: its certificate + // has to be guarded, and Giza takes no part in wallets (W5, + // docs/giza-wallet-removal.md). The join screen says so and offers no + // button; this is the backstop. + if (step == DkgApprovalStep.HOST_KEY && session.isGuardedSubgroup) { + logger.w("Ritual $sessionId makes a guarded subgroup; not joining") + return + } + val now = Clock.System.now() update(database, session) { when (step) { @@ -1535,9 +1482,6 @@ object ChillDkgRitualManager { threshold = if (includeThreshold) session.threshold else null, parentChatRoomId = if (includeParent) session.parentChatRoomId else null, subject = subject, - // With the parent, and for the same reason: only on the proposal. - walletPolicy = if (includeParent) session.subgroupWalletPolicy else null, - guardianDelay = if (includeParent) session.guardianDelay else null ) val createdAt = Clock.System.now().epochSeconds 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 e1648c22..c703505a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt @@ -1,20 +1,8 @@ package mobi.giza.compose.managers -import mobi.giza.compose.nostr.subgroup.allows import mobi.giza.compose.nostr.frost.GroupKeyStateEvent -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.wallet.GroupSpend -import fr.acinq.bitcoin.ByteVector64 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.Crypto -import fr.acinq.bitcoin.ScriptFlags -import fr.acinq.bitcoin.Transaction import fr.acinq.bitcoin.crypto.frost.TweakCache -import fr.acinq.bitcoin.psbt.Psbt -import fr.acinq.secp256k1.Hex import co.touchlab.kermit.Logger import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey @@ -57,7 +45,6 @@ import mobi.giza.compose.database.model.types.FrostSigningStage import mobi.giza.compose.extensions.toHex import mobi.giza.compose.nostr.dkg.DkgRitualEvents import mobi.giza.compose.nostr.frost.FrostSigningEvents -import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent /** * Signs a nostr event with a group's FROST threshold key, in one of its rooms. @@ -410,22 +397,14 @@ object FrostSigningManager { sessionId = sessionId, userPublicKey = userPublicKey ) - } else if (innerEvent.kind == FrostSigningEvents.TRANSACTION_PROPOSAL && FrostSigningEvents.parseSweep(innerEvent.tags) != null) { + } else if (innerEvent.kind == FrostSigningEvents.TRANSACTION_PROPOSAL) { declineWalletProposal( database = database, localChatRoom = localChatRoom, innerEvent = innerEvent, sessionId = sessionId, userPublicKey = userPublicKey, - subject = FrostSigningSubject.SWEEP - ) - } else if (innerEvent.kind == FrostSigningEvents.TRANSACTION_PROPOSAL) { - acceptSpendProposal( - database = database, - localChatRoom = localChatRoom, - innerEvent = innerEvent, - sessionId = sessionId, - userPublicKey = userPublicKey + subject = if (FrostSigningEvents.isSweep(innerEvent.tags)) FrostSigningSubject.SWEEP else FrostSigningSubject.TRANSACTION ) } else { // Not knowing the session is normal: a member catching up applies a @@ -644,34 +623,6 @@ object FrostSigningManager { return declined } - // A birth certificate's guardian keys are a promise by the group signing - // it, so they have to be the keys it grants: recomputed here from the key - // this session signs with and the group's own certificate, never taken - // from the proposer. Its wallet policy has to be one the group may make: - // a guarded group only makes guarded subgroups. Refused before anything is shown, for the reason a - // mismatched id is. - val thresholdPublicKey = key.thresholdPublicKey - unsignedEvents.forEach { rebuilt -> - if (rebuilt.kind != SubgroupBirthCertificateEvent.KIND || thresholdPublicKey == null) return@forEach - SubgroupManager.refuseCertificate(database, rebuilt.pubKey, thresholdPublicKey, rebuilt)?.let { reason -> - logger.w("Signing proposal $sessionId carries a birth certificate that $reason; dropping") - return null - } - } - - unsignedEvents.forEach { rebuilt -> - if (rebuilt.kind != GroupWalletStatementEvent.KIND) return@forEach - val guarded = GroupWalletStatementEvent.read(rebuilt.tags, rebuilt.content)?.guardians?.isNotEmpty() ?: return@forEach - val policy = SubgroupManager.walletPolicyOf(database, rebuilt.pubKey) - if (!policy.allows(guarded)) { - logger.w( - "Signing proposal $sessionId opens ${if (guarded) "a guarded" else "an unguarded"} wallet, " + - "and this group's parent decided otherwise; dropping" - ) - return null - } - } - unsignedEvents.forEach { rebuilt -> if (rebuilt.kind != GroupKeyStateEvent.KIND) return@forEach SubgroupManager.refuseKeyState(key, rebuilt)?.let { reason -> @@ -696,663 +647,6 @@ object FrostSigningManager { return session } - /** - * Opens a session over one transaction from the group's wallet, making this - * device the coordinator. - * - * A transaction is a batch: one item per input, each its own FROST instance - * over that input's BIP341 sighash, with its own nonce seed and its own - * cache -- the coin it spends is at its own address. Everything the batch - * rules say holds here too, and two of them with more force. A retry is a new - * session with new seeds, never this one again, and a fee bump is a retry. - * And the batch is all or nothing, which for a transaction is not a policy: - * a transaction with one unsigned input is not a transaction. - * - * [psbt] is checked here exactly as every other member will check it, so a - * proposal that would be refused everywhere is refused before it is sent. - * - * @throws IllegalArgumentException when the spend fails a check, with the reason - * @throws IllegalStateException when the room has no key, this device holds no - * share of it, or the group has not opened a wallet on [chain] at [account] - */ - suspend fun proposeSpend( - database: GizaDatabase, - localChatRoom: LocalChatRoom, - userPublicKey: HexKey, - psbt: Psbt, - chain: Chain, - account: Long = 0L, - ): FrostSigningSession { - val chatRoomId = localChatRoom.chatRoom.id - val ceremony = completedKey(database, chatRoomId) - ?: throw IllegalStateException("This group has no shared key to sign with") - val thresholdPublicKey = ceremony.thresholdPublicKey - ?: throw IllegalStateException("Ceremony ${ceremony.id} holds no threshold key") - val signerId = signerIdOf(database, ceremony, userPublicKey) - ?: throw IllegalStateException("This device is not a participant in ceremony ${ceremony.id}") - val wallet = GroupWalletManager.walletFor(database, chatRoomId, thresholdPublicKey, chain, account) - ?: throw IllegalStateException("This group has not opened a wallet on ${GroupWalletStatementEvent.chainName(chain)}") - - val checked = when (val result = GroupSpend.check(psbt, wallet.account).withFundings(database, chatRoomId)) { - is GroupSpend.Result.Ok -> result.checked - is GroupSpend.Result.Refused -> throw IllegalArgumentException("This spend ${result.reason}") - } - - val session = FrostSigningSession( - id = RandomInstance.bytes(32).toHex(), - chatRoomId = chatRoomId, - coordinatorPublicKey = userPublicKey, - userPublicKey = userPublicKey, - dkgSessionId = ceremony.id, - threshold = ceremony.threshold, - participantCount = ceremony.participantCount, - signerId = signerId, - // A transaction does not sign as the room: each input has its own - // derivation, and those are on the items. - derivationPath = null, - subject = FrostSigningSubject.TRANSACTION, - // Proposing a spend is already the act of agreeing to it. - signApprovedAt = Clock.System.now() - ) - writeSpend(database, session, checked, chain, account) - announceStarted(database, session) - - logger.i( - "Proposing spend ${session.id}: ${checked.inputs.size} input(s), " + - "${checked.amountSent.sat} sats out, ${checked.fee.sat} sats fee, txid ${checked.tx.txid}" - ) - - broadcast( - database = database, - localChatRoom = localChatRoom, - session = session, - kind = FrostSigningEvents.TRANSACTION_PROPOSAL, - content = GroupSpend.encode(psbt), - includeKey = true, - extraTags = FrostSigningEvents.walletTags(GroupWalletStatementEvent.chainName(chain), account) - ) - - advance(database, localChatRoom, session.id) - - return session - } - - /** - * Opens a session over one transaction from a *descendant's* guarded wallet, - * signed through this room's guardian leaf -- `docs/group-wallet-guardians.md`. - * - * The same session as [proposeSpend] in every way but three: the wallet is - * the one this room was told about rather than its own, every input is - * signed over BIP342's script-path sighash as the key this group's walk - * reaches, and the proposal names the descendant so every signer reads the - * same wallet from its own copy of the statement. - * - * @throws IllegalArgumentException when the spend fails a check, with the reason - * @throws IllegalStateException when the room has no key, this device holds no - * share of it, or the room holds no guarded wallet of [descendantChatRoomId] on - * [chain] at [account] - */ - suspend fun proposeGuardianSpend( - database: GizaDatabase, - localChatRoom: LocalChatRoom, - userPublicKey: HexKey, - psbt: Psbt, - descendantChatRoomId: String, - chain: Chain, - account: Long = 0L, - ): FrostSigningSession { - val chatRoomId = localChatRoom.chatRoom.id - val ceremony = completedKey(database, chatRoomId) - ?: throw IllegalStateException("This group has no shared key to sign with") - val thresholdPublicKey = ceremony.thresholdPublicKey - ?: throw IllegalStateException("Ceremony ${ceremony.id} holds no threshold key") - val signerId = signerIdOf(database, ceremony, userPublicKey) - ?: throw IllegalStateException("This device is not a participant in ceremony ${ceremony.id}") - val guarded = GuardianManager.guardedWalletFor(database, chatRoomId, descendantChatRoomId, chain, account) - ?: throw IllegalStateException("This group guards no wallet of $descendantChatRoomId on ${GroupWalletStatementEvent.chainName(chain)}") - - val checked = when (val result = GroupSpend.check(psbt, guarded.account, guarded.spender(thresholdPublicKey)).withFundings(database, chatRoomId)) { - is GroupSpend.Result.Ok -> result.checked - is GroupSpend.Result.Refused -> throw IllegalArgumentException("This spend ${result.reason}") - } - - val session = FrostSigningSession( - id = RandomInstance.bytes(32).toHex(), - chatRoomId = chatRoomId, - coordinatorPublicKey = userPublicKey, - userPublicKey = userPublicKey, - dkgSessionId = ceremony.id, - threshold = ceremony.threshold, - participantCount = ceremony.participantCount, - signerId = signerId, - derivationPath = null, - subject = FrostSigningSubject.TRANSACTION, - signApprovedAt = Clock.System.now() - ) - writeSpend(database, session, checked, chain, account, guardedChatRoomId = descendantChatRoomId) - announceStarted(database, session) - - logger.i( - "Proposing guardian spend ${session.id} from $descendantChatRoomId: ${checked.inputs.size} input(s), " + - "${checked.amountSent.sat} sats out, ${checked.fee.sat} sats fee, txid ${checked.tx.txid}" - ) - - broadcast( - database = database, - localChatRoom = localChatRoom, - session = session, - kind = FrostSigningEvents.TRANSACTION_PROPOSAL, - content = GroupSpend.encode(psbt), - includeKey = true, - extraTags = FrostSigningEvents.walletTags(GroupWalletStatementEvent.chainName(chain), account) + - FrostSigningEvents.guardedTags(descendantChatRoomId) - ) - - advance(database, localChatRoom, session.id) - - return session - } - - /** - * Records a proposed spend, after every check [GroupSpend.check] makes. - * Returns the session, whether it was just created or already known. - * - * Publishes nothing, for the reason [acceptProposal] gives -- and trusts - * nothing the proposer computed. The account comes from the room's own - * verified statement, under *this ceremony's* key; the proposal's tags only - * say which statement. A ceremony that is not the room's -- a subgroup's, - * held in its parent's room -- cannot reach a statement the room signed, so - * a spend opened against one is refused here rather than signed for a - * wallet nobody opened. - */ - private suspend fun acceptSpendProposal( - database: GizaDatabase, - localChatRoom: LocalChatRoom, - innerEvent: Event, - sessionId: String, - userPublicKey: HexKey - ): FrostSigningSession? { - val psbt = GroupSpend.decode(innerEvent.content) - - database.frostSigningSessionDao().getSessionById(sessionId)?.let { existing -> - // 7. Write-once. Every item's seed is already committed to its - // sighash; a different transaction under the same id would have those - // seeds produce a second partial signature over a second message. - val stored = database.groupTransactionDao().getBySessionId(sessionId) - ?.let { GroupSpend.decode(it.psbt)?.global?.tx } - if (existing.subject != FrostSigningSubject.TRANSACTION || stored == null || stored != psbt?.global?.tx) { - logger.w("Session $sessionId re-proposed with a different transaction; ignoring") - } - return existing - } - - if (psbt == null) { - logger.w("Spend proposal $sessionId does not carry a PSBT; dropping") - return null - } - - val key = FrostSigningEvents.parseKey(innerEvent.tags) - ?.let { database.dkgSessionDao().getSessionById(it) } - ?.takeIf { it.stage == DkgRitualStage.COMPLETE } - val thresholdPublicKey = key?.thresholdPublicKey - if (key == null || thresholdPublicKey == null) { - logger.w("Spend proposal $sessionId names a key this device does not hold; dropping") - return null - } - - val signerId = signerIdOf(database, key, userPublicKey) - if (signerId == null) { - logger.w("Spend proposal $sessionId is for a ceremony this device did not take part in; dropping") - return null - } - - val (chainName, account) = FrostSigningEvents.parseWallet(innerEvent.tags) ?: run { - logger.w("Spend proposal $sessionId names no wallet; dropping") - return null - } - val chain = GroupWalletStatementEvent.chainNamed(chainName) ?: run { - logger.w("Spend proposal $sessionId names a network this build does not know, $chainName; dropping") - return null - } - - // 1. There is a wallet, and it is the room's -- or, for a guardian's - // spend, a descendant's this room was told about and holds a leaf in. - // Either way read from this device's own copy of the statement. - val guardedChatRoomId = FrostSigningEvents.parseGuarded(innerEvent.tags) - val (walletAccount, spender) = if (guardedChatRoomId == null) { - val wallet = GroupWalletManager.walletFor(database, localChatRoom.chatRoom.id, thresholdPublicKey, chain, account) - if (wallet == null) { - logger.w("Spend proposal $sessionId spends from a wallet the group has not opened on $chainName; dropping") - return null - } - wallet.account to GroupSpend.Spender.Owner - } else { - // The leaf is the room's, so the key signing it has to be the room's - // own -- not a subgroup ceremony held in this room. - if (GroupWalletManager.thresholdKeyFor(database, localChatRoom.chatRoom.id) != thresholdPublicKey) { - logger.w("Guardian spend proposal $sessionId names a key that is not this room's; dropping") - return null - } - val guarded = GuardianManager.guardedWalletFor(database, localChatRoom.chatRoom.id, guardedChatRoomId, chain, account) - if (guarded == null) { - logger.w("Guardian spend proposal $sessionId spends from a wallet this room guards none of; dropping") - return null - } - guarded.account to guarded.spender(thresholdPublicKey) - } - - val checked = when (val result = GroupSpend.check(psbt, walletAccount, spender).withFundings(database, localChatRoom.chatRoom.id)) { - is GroupSpend.Result.Ok -> result.checked - is GroupSpend.Result.Refused -> { - logger.w("Spend proposal $sessionId ${result.reason}; dropping") - return null - } - } - - val session = FrostSigningSession( - id = sessionId, - chatRoomId = localChatRoom.chatRoom.id, - coordinatorPublicKey = innerEvent.pubKey, - userPublicKey = userPublicKey, - dkgSessionId = key.id, - threshold = key.threshold, - participantCount = key.participantCount, - signerId = signerId, - derivationPath = null, - subject = FrostSigningSubject.TRANSACTION, - ) - writeSpend(database, session, checked, chain, account, guardedChatRoomId) - announceStarted(database, session) - - logger.i( - "Recorded spend $sessionId: ${checked.inputs.size} input(s), ${checked.amountSent.sat} sats out, " + - "${checked.fee.sat} sats fee; awaiting approval" - ) - - announceApprovalNeeded(database, session) - replayStoredMessages(database, localChatRoom, session) - - return session - } - - /** - * The session, an item per input carrying that input's sighash and place - * under the account, and the transaction row -- the three things a spend is. - */ - private suspend fun writeSpend( - database: GizaDatabase, - session: FrostSigningSession, - checked: GroupSpend.Checked, - chain: Chain, - account: Long, - guardedChatRoomId: String? = null, - ) { - database.frostSigningSessionDao().upsert(session) - database.frostSigningSessionDao().upsertItems( - checked.inputs.map { input -> - FrostSigningItem( - sessionId = session.id, - itemIndex = input.index, - unsignedEventJson = derivationPayload(input.derivation), - eventId = input.sighash.toHex(), - // Independent per input, for the reason [itemsOver] gives. - nonceRandom = RandomInstance.bytes(32).toHex(), - inputIndex = input.index, - ) - } - ) - database.groupTransactionDao().insertIfAbsent( - GroupTransaction( - frostSigningSessionId = session.id, - chatRoomId = session.chatRoomId, - chain = GroupWalletStatementEvent.chainName(chain), - account = account, - guardedChatRoomId = guardedChatRoomId, - psbt = GroupSpend.encode(checked.psbt), - txid = checked.tx.txid.toString(), - ) - ) - } - - /** An input's place under the account, as the item's payload carries it. */ - private fun derivationPayload(derived: GroupWalletDerivation.Derived): String = - """{"change":${derived.change},"index":${derived.index}}""" - - private val DERIVATION_PAYLOAD = Regex("""^\{"change":(\d+),"index":(\d+)\}$""") - - /** - * The account a spend session signs under and where each of its inputs is, - * rebuilt on every pass from the ceremony's key and the transaction row -- - * the same rule as a room's path: stored inputs, rederived, never cached. - */ - /** - * One cache per input: the address's key path for the room's own spend, read - * off the items as always; the guardian's leaf for a spend through it, read - * off the spend checked again -- the leaf, the walk and the sighash are one - * computation, and a cache taken apart from it could sign for another leaf. - */ - private suspend fun spendCaches( - database: GizaDatabase, - session: FrostSigningSession, - thresholdPublicKey: HexKey, - items: List, - ): List? { - val transaction = database.groupTransactionDao().getBySessionId(session.id) ?: return null - if (transaction.guardedChatRoomId == null) { - return spendDerivations(database, session, thresholdPublicKey, items)?.map { it.cache } - } - val checked = checkedSpend(database, session.id) ?: return null - return checked.inputs.map { it.cache }.takeIf { it.size == items.size } - } - - private suspend fun spendDerivations( - database: GizaDatabase, - session: FrostSigningSession, - thresholdPublicKey: HexKey, - items: List, - ): List? { - val account = spendAccount(database, session, thresholdPublicKey)?.second ?: return null - - return items.map { item -> - val (change, index) = DERIVATION_PAYLOAD.matchEntire(item.payload)?.destructured ?: return null - GroupWalletDerivation.derive(account, change.toLong(), index.toLong()) - } - } - - /** What a spend session signs under: its transaction row, the account its coins are in, and who signs them. */ - private data class SpendContext( - val transaction: GroupTransaction, - val account: GroupWalletDerivation.Account, - val spender: GroupSpend.Spender, - ) - - /** - * [spendAccount], and for a guardian's spend the descendant's guarded wallet - * as this room holds it, with this group as the spender. - */ - private suspend fun spendContext( - database: GizaDatabase, - session: FrostSigningSession, - thresholdPublicKey: HexKey, - ): SpendContext? { - val transaction = database.groupTransactionDao().getBySessionId(session.id) ?: return null - val guardedChatRoomId = transaction.guardedChatRoomId - ?: return spendAccount(database, session, thresholdPublicKey)?.let { (row, account) -> SpendContext(row, account, GroupSpend.Spender.Owner) } - val chain = GroupWalletStatementEvent.chainNamed(transaction.chain) ?: return null - val guarded = GuardianManager.guardedWalletFor(database, transaction.chatRoomId, guardedChatRoomId, chain, transaction.account) ?: return null - return SpendContext(transaction, guarded.account, guarded.spender(thresholdPublicKey)) - } - - private suspend fun spendAccount( - database: GizaDatabase, - session: FrostSigningSession, - thresholdPublicKey: HexKey, - ): Pair? { - val transaction = database.groupTransactionDao().getBySessionId(session.id) ?: return null - val chain = GroupWalletStatementEvent.chainNamed(transaction.chain) ?: return null - // The account as the room's statement opened it: a guarded one's - // addresses carry its guardians' leaves, and the bare derivation would be - // a plain account at the same key, whose addresses none of these coins are at. - val opened = GroupWalletManager.walletFor(database, transaction.chatRoomId, thresholdPublicKey, chain, transaction.account) - return transaction to (opened?.account ?: GroupWalletDerivation.account(thresholdPublicKey, chain, transaction.account)) - } - - /** - * The spend a transaction session signs, checked again from its stored PSBT, - * or null for an event session or one whose spend no longer checks out. - * - * What the approval screen and the proposal list show. Checked rather than - * decoded, so that what a member reads is exactly what [GroupSpend.check] - * vouched for: every input's place under the account, which outputs are - * change, and a fee computed from amounts the sighashes commit to. - */ - suspend fun checkedSpend(database: GizaDatabase, sessionId: String): GroupSpend.Checked? { - val session = database.frostSigningSessionDao().getSessionById(sessionId) ?: return null - if (session.subject != FrostSigningSubject.TRANSACTION) return null - val thresholdPublicKey = database.dkgSessionDao().getSessionById(session.dkgSessionId)?.thresholdPublicKey - ?: return null - val context = spendContext(database, session, thresholdPublicKey) ?: return null - val psbt = GroupSpend.decode(context.transaction.psbt) ?: return null - return (GroupSpend.check(psbt, context.account, context.spender).withFundings(database, context.transaction.chatRoomId) as? GroupSpend.Result.Ok)?.checked - } - - /** - * A checked spend with its payments into descendants' guarded wallets read - * against the ones [chatRoomId] holds -- `GroupSpend.fundingsOf` -- or - * refused for a claim that does not derive. Every place a spend is checked - * for a member to read or sign reads its fundings here, so the label a - * signer sees is the one every other signer's device derived too. - * - * A spend none of whose payments claims anything -- every spend to a typed - * address -- reads no guarded wallets at all. - */ - private suspend fun GroupSpend.Result.withFundings(database: GizaDatabase, chatRoomId: String): GroupSpend.Result { - val checked = (this as? GroupSpend.Result.Ok)?.checked ?: return this - if (checked.payments.all { checked.psbt.outputs[it.index].taprootDerivationPaths.isEmpty() }) return this - return when (val reading = GroupSpend.fundingsOf(checked, GuardianManager.guardedWalletsOf(database, chatRoomId))) { - is GroupSpend.FundingReading.Ok -> GroupSpend.Result.Ok(checked.copy(fundings = reading.fundings)) - is GroupSpend.FundingReading.Refused -> GroupSpend.Result.Refused(reading.reason) - } - } - - /** - * The coins a room's open spends are already spending, which a new spend - * should leave alone. A failed session releases its coins; every other one - * holds them, a finished one included -- until its transaction is on chain, - * the coins are still unspent as far as Electrum can say. - */ - suspend fun reservedOutPoints(database: GizaDatabase, chatRoomId: String): Set = - openSpends(database, chatRoomId) - .flatMap { psbt -> psbt.global.tx.txIn.map { it.outPoint } } - .toSet() - - /** - * The change addresses a room's open spends pay back to, under [account], - * which a new spend should not pay to as well. Held by the same sessions as - * [reservedOutPoints], for the same reason: until a spend is on chain, its - * change address reads as unused, and the next spend would pick it again. - */ - suspend fun reservedChangeIndices( - database: GizaDatabase, - chatRoomId: String, - account: GroupWalletDerivation.Account, - ): Set = - openSpends(database, chatRoomId) - .flatMap { GroupSpend.claimedChangeIndices(it, account) } - .toSet() - - /** - * The receive addresses of [account] -- a descendant's guarded wallet -- that - * a room's open spends fund, which a new funding should not pay as well. - * Held by the same sessions as [reservedOutPoints], for the reason - * [reservedChangeIndices] gives. - */ - suspend fun reservedFundingIndices( - database: GizaDatabase, - chatRoomId: String, - account: GroupWalletDerivation.Account, - ): Set = - openSpends(database, chatRoomId) - .flatMap { GroupSpend.claimedFundingIndices(it, account) } - .toSet() - - /** The PSBT of every spend in the room whose session has not failed. */ - private suspend fun openSpends(database: GizaDatabase, chatRoomId: String): List = - database.groupTransactionDao().getByChatRoomId(chatRoomId) - .filter { database.frostSigningSessionDao().getSessionById(it.frostSigningSessionId)?.stage != FrostSigningStage.FAILED } - .mapNotNull { GroupSpend.decode(it.psbt) } - - /** - * A spend seen confirmed: recorded, and every other spend of the same coins - * settled by it. - * - * Only one spend of a coin can ever confirm, so the rest are over whatever - * stage they are in. One still collecting is abandoned -- its signatures, if - * it ever got them, would be over a transaction nobody can mine. One already - * signed is a transaction this one replaced, a fee bump or a race, and is - * marked so rather than failed: it was signed, and saying otherwise would - * misreport what the group did. - * - * Once per transaction, by the read of `confirmedAt` before the write; the - * transcript line rides on the same guard. - */ - suspend fun recordConfirmed(database: GizaDatabase, sessionId: String, at: Instant = Clock.System.now()) { - val confirmed = database.groupTransactionDao().getBySessionId(sessionId) ?: return - if (confirmed.confirmedAt != null) return - val session = database.frostSigningSessionDao().getSessionById(sessionId) ?: return - - database.groupTransactionDao().upsert(confirmed.copy(confirmedAt = at, seenAt = confirmed.seenAt ?: at)) - - settleSpendsOf(database, confirmed.chatRoomId, coinsOf(confirmed), byTxid = confirmed.txid, except = sessionId) - - val sent = checkedSpend(database, sessionId)?.amountSent - announce( - database = database, - session = session, - messageType = ChatMessage.TYPE_GROUP_TRANSACTION_CONFIRMED, - content = if (sent != null) "The group's transaction confirmed: ${sent.sat} sats sent." - else "The group's transaction confirmed.", - actor = session.coordinatorPublicKey - ) - } - - /** - * A spend whose coins a transaction the room never proposed has taken, as - * [conflictTxid] confirmed: marked replaced, and every other spend of the same - * coins settled with it. - * - * A guarded wallet's coins have two kinds of spender. The child's own spend - * can lose a coin to a guardian's, and a guardian's to the child's, and the - * winner is never a row in the loser's room -- so [recordConfirmed] cannot be - * what settles the loser. The watcher is: it asks the chain whether a signed - * spend's coins are still there, and calls this when one was taken by a - * confirmed transaction. Once per spend, by the read of `replacedByTxid`. - */ - suspend fun recordReplaced(database: GizaDatabase, sessionId: String, conflictTxid: String) { - val lost = database.groupTransactionDao().getBySessionId(sessionId) ?: return - if (lost.confirmedAt != null || lost.replacedByTxid != null) return - - database.groupTransactionDao().upsert(lost.copy(replacedByTxid = conflictTxid)) - settleSpendsOf(database, lost.chatRoomId, coinsOf(lost), byTxid = conflictTxid, except = sessionId) - logger.i("Spend $sessionId lost its coins to $conflictTxid") - } - - /** - * Every spend in [chatRoomId] other than [except] that wants any of [coins], - * settled by [byTxid] having taken them: only one spend of a coin can ever - * confirm, so the rest are over whatever stage they are in. One still - * collecting is abandoned -- its signatures, if it ever got them, would be - * over a transaction nobody can mine. One already signed is a transaction - * [byTxid] replaced, a fee bump or a race, and is marked so rather than - * failed: it was signed, and saying otherwise would misreport what the group - * did. - */ - private suspend fun settleSpendsOf( - database: GizaDatabase, - chatRoomId: String, - coins: Set, - byTxid: String, - except: String, - ) { - database.groupTransactionDao().getByChatRoomId(chatRoomId) - .filter { it.frostSigningSessionId != except && (coinsOf(it) intersect coins).isNotEmpty() } - .forEach { other -> - val otherSession = database.frostSigningSessionDao().getSessionById(other.frostSigningSessionId) - ?: return@forEach - when (otherSession.stage) { - FrostSigningStage.COMPLETE -> if (other.confirmedAt == null && other.replacedByTxid == null) { - database.groupTransactionDao().upsert(other.copy(replacedByTxid = byTxid)) - } - - FrostSigningStage.FAILED -> Unit - - else -> fail( - database = database, - session = otherSession, - reason = "Spent by another transaction", - content = "abandoned a spend: another transaction spent its coins first. " + - "Nothing was signed." - ) - } - } - } - - private fun coinsOf(transaction: GroupTransaction): Set = - GroupSpend.decode(transaction.psbt)?.global?.tx?.txIn?.map { it.outPoint }?.toSet().orEmpty() - - /** - * Verifies the group's signatures, puts them on the transaction, and closes - * the session -- for a spend, the counterpart of [complete]. - * - * Each signature is checked against the output key of the coin it spends, - * and then the whole transaction against the script interpreter: a signature - * that verifies over the wrong sighash is a perfectly good signature and a - * transaction nobody can mine, and `correctlySpends` is the only check that - * asks the question the network will. Nothing is applied and nothing is - * filed as a `GroupSignedEvent` -- this is not an event, and the chronicle - * reads that table. - */ - private suspend fun completeSpend( - database: GizaDatabase, - session: FrostSigningSession, - items: List, - ) { - val key = database.dkgSessionDao().getSessionById(session.dkgSessionId) - val thresholdPublicKey = key?.thresholdPublicKey - ?: throw IllegalStateException("The ceremony this spend signs under is gone") - val (transaction, account, spender) = spendContext(database, session, thresholdPublicKey) - ?: throw IllegalStateException("This spend has no transaction on file") - val psbt = GroupSpend.decode(transaction.psbt) - ?: throw IllegalStateException("This spend's PSBT can no longer be read") - val checked = when (val result = GroupSpend.check(psbt, account, spender)) { - is GroupSpend.Result.Ok -> result.checked - is GroupSpend.Result.Refused -> throw IllegalStateException("This spend ${result.reason}") - } - - val signatures = items.mapIndexed { index, item -> - val input = checked.inputs[index] - val signature = ByteVector64(item.signature!!) - if (!Crypto.verifySignatureSchnorr(input.sighash, signature, input.signingKey)) { - throw IllegalStateException("The aggregated signature for input $index does not verify against its coin") - } - signature - } - - val signed = checked.witnessed(signatures) - signed.correctlySpends( - checked.inputs.associate { it.outPoint to it.txOut }, - ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS - ) - - update(database, session) { it.copy(stage = FrostSigningStage.COMPLETE) } - - // The signature is made and valid either way; a row this device could not - // write is logged, not a failed ceremony -- the same rule as - // [recordSignedEvents]. - try { - database.groupTransactionDao().upsert( - transaction.copy(signedTransaction = Hex.encode(Transaction.write(signed))) - ) - } catch (e: Throwable) { - logger.e("Signed spend ${session.id} but could not record it", e) - } - - announce( - database = database, - session = session, - messageType = ChatMessage.TYPE_FROST_COMPLETE, - content = when (val guardian = checked.spender as? GroupSpend.Spender.Guardian) { - null -> "The group signed a transaction sending ${checked.amountSent.sat} sats, " - else -> "The group signed a transaction sending ${checked.amountSent.sat} sats from " + - "${mobi.giza.compose.text.ProposedSpend.guardedWallet(guardian.name, guardian.label)}, " - } + "with ${checked.fee.sat} sats in fees. It took ${session.threshold} of " + - "${session.participantCount} members.", - actor = session.coordinatorPublicKey - ) - - logger.i("Spend ${session.id} complete: txid ${signed.txid}") - } - /** * Feeds in every message of this session that arrived before the proposal did. * @@ -1701,22 +995,16 @@ object FrostSigningManager { val items = database.frostSigningSessionDao().getItems(sessionId) if (items.isEmpty()) return - // One cache per item. Every item of an event session signs as the - // room, so they share one; every input of a transaction is a coin at - // its own address, so each has its own -- and signing an input with - // its neighbour's cache aggregates to a perfectly good signature for a - // key that coin is not at. + // One cache for every item: each signs as the room. A transaction or a + // sweep is a Bennu peer's, declined on arrival, and never reaches here. val tweakCaches: List = when (session.subject) { FrostSigningSubject.EVENTS -> SharedKeyDerivation .derive(thresholdPublicKey, session.pathIndices()) .cache .let { cache -> List(items.size) { cache } } - FrostSigningSubject.TRANSACTION -> spendCaches(database, session, thresholdPublicKey, items) - ?: throw IllegalStateException("The coins this transaction spends no longer derive under the group's wallet") - - // Declined on arrival, so never approved, and never here. - FrostSigningSubject.SWEEP -> throw IllegalStateException("This device does not sign sweeps") + FrostSigningSubject.TRANSACTION, FrostSigningSubject.SWEEP -> + throw IllegalStateException("This device does not sign for wallets") } val messages = items.map { ByteVector(it.eventId.hexToByteArray()) } @@ -1902,12 +1190,9 @@ object FrostSigningManager { val items = database.frostSigningSessionDao().getItems(session.id) if (items.isEmpty() || items.any { !it.isSigned() }) return - if (session.subject == FrostSigningSubject.TRANSACTION) { - completeSpend(database, session, items) - return - } - // Declined on arrival, so never signed, and never here. - if (session.subject == FrostSigningSubject.SWEEP) return + // A Bennu peer's transaction or sweep: declined on arrival, so never signed + // by this device, and nothing of it is this device's to complete. + if (session.subject != FrostSigningSubject.EVENTS) return // Every signature is checked before any event is applied. A batch is // all-or-nothing, so a bad one anywhere has to fail the session rather @@ -2886,25 +2171,10 @@ object FrostSigningManager { Triple(FrostSigningEvents.PROPOSAL, FrostSigningEvents.encodeProposal(unsigned), emptyArray>()) } - // Byte for byte the PSBT that was proposed -- it is what every item's - // sighash was computed from, and a member who already holds the - // session ignores any other. - FrostSigningSubject.TRANSACTION -> { - val transaction = database.groupTransactionDao().getBySessionId(sessionId) - if (transaction == null) { - logger.w("Session $sessionId: no transaction on file; nothing to resend") - return false - } - Triple( - FrostSigningEvents.TRANSACTION_PROPOSAL, - transaction.psbt, - FrostSigningEvents.walletTags(transaction.chain, transaction.account) - ) - } - - // Declined on arrival: this device proposed none, so has none to resend. - FrostSigningSubject.SWEEP -> { - logger.w("Session $sessionId: a sweep, which this device does not propose; nothing to resend") + // A Bennu peer's, declined on arrival: this device proposed none, so has + // none to resend. + FrostSigningSubject.TRANSACTION, FrostSigningSubject.SWEEP -> { + logger.w("Session $sessionId: a wallet's, which this device does not propose; nothing to resend") return false } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt index cfb647f2..e76b6fd1 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt @@ -423,19 +423,6 @@ object GroupKeyStateManager { return null } - // A wallet policy present and unreadable must never look absent: an - // undecided child is offered both wallets, so a corrupt `guarded` would - // hand it the plain one its parent took away -- the lesson of - // [GroupKeyStateEvent.claimsParentage], one tag further on. - // `docs/subgroup-wallet-policy.md`. - if (SubgroupBirthCertificateEvent.parseWalletPolicy(certificate.tags) == null) { - logger.w( - "Key state for $announced carries a certificate whose wallet policy does not " + - "read, or contradicts its guardian keys; dropping" - ) - return null - } - return Parentage( SubgroupParentage(parentChatRoomId = parentChatRoomId, certificate = certificate) ) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupWalletDerivation.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupWalletDerivation.kt deleted file mode 100644 index 6f737e11..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupWalletDerivation.kt +++ /dev/null @@ -1,318 +0,0 @@ -package mobi.giza.compose.managers - -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray -import fr.acinq.bitcoin.Bitcoin -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -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 -import fr.acinq.bitcoin.Script -import fr.acinq.bitcoin.ScriptTree -import fr.acinq.bitcoin.XonlyPublicKey -import fr.acinq.bitcoin.crypto.Pack -import fr.acinq.bitcoin.crypto.frost.TweakCache -import fr.acinq.bitcoin.utils.Either - -/** - * The group's on-chain wallet keys, derived from its ChillDKG threshold key. - * - * A wallet address here is BIP86's -- a taproot key-path output with no script - * tree -- at BIP86's own unhardened tail, `//`, under an account - * key that the threshold key is publicly tweaked to: - * - * ``` - * I = HMAC-SHA512("bennu/group-wallet/account/v1", serP(K) || chainHash || ser32(account)) - * K_a = K + I[0:32]·G, chain code I[32:64] an ordinary depth-0 xpub - * P = xonly(CKDpub(CKDpub(K_a, change), index)) BIP86 internal key - * Q = P + H_TapTweak(P)·G BIP86 output key - * ``` - * - * See `docs/group-chain-wallet.md` for why each level is what it is. In short: - * every hardened level of `m/86'/0'/0'` needs the parent private key, which in a - * threshold group nobody holds; the ceremony is what isolates one group's key - * from another's, and the account step does what `coin'` and `account'` do -- - * mainnet and test networks, and account 0 and account 1, are unrelated keys. - * Below the account the derivation is plain BIP32, which is what lets the group - * export a descriptor any watch-only wallet can follow. - * - * ### Not [SharedKeyDerivation], and never to be confused with it - * - * That object derives nostr keys -- the room's own id among them -- with x-only - * tweaks at every step and a SHA-256 scalar. This one uses plain tweaks and - * HMAC-SHA512 until the last step. The two never share a key, and the wallet - * never sits on the room's key: a wallet at the room's key would be findable by - * anyone who can see the room's id. - * - * ### The rule this inherits - * - * Every tweak is publicly computable from the threshold key, so a leaked private - * key for any address recovers the group's threshold key -- the room, every - * address of every account, and every event the group can sign. Nothing here or - * anywhere else reconstructs one. The only export is the account xpub. - * - * ### A guarded account - * - * An account opened with guardians -- the keys a subgroup's birth certificate - * grants it, see `GuardianDerivation` -- is the same account with one change at - * the very end: each address commits to a tree of one leaf per guardian, so the - * last tweak is BIP341's script-path tweak over that tree rather than BIP86's - * empty one. The internal key, and so the group's own key-path spend, is - * untouched. `docs/group-wallet-guardians.md` says why. - */ -object GroupWalletDerivation { - /** BIP44's external chain: addresses handed out to be paid. */ - const val RECEIVE: Long = 0L - - /** BIP44's internal chain: where a spend sends what it does not pay out. */ - const val CHANGE: Long = 1L - - /** - * The key of the account step's HMAC. An input to every wallet key, so it is - * frozen the moment a group holds coins under it: changing it moves every - * address, and the coins at the old ones are found by nobody. A rename is a - * protocol fork and belongs in a `v2`, never in an edit to this one. That includes - * the `bennu/` prefix, which is not a brand string: it stayed when the app was forked - * as Giza, as `mantra/` stayed through the rebrands before it, and it is why a Bennu - * member and a Giza member derive the same wallet (docs/giza-rebrand.md). Every other - * `bennu/` tag in this package stays for the same reason. - */ - private const val ACCOUNT_TAG = "bennu/group-wallet/account/v1" - - /** The largest unhardened BIP32 index. Hardened ones cannot be walked here. */ - internal const val MAX_INDEX: Long = 0x7FFFFFFFL - - /** - * One account of one group on one network: the extended public key every - * address of it is derived under, and the cache that signs as its key. - * - * [extendedPublicKey] is safe to hand out -- it reveals the account's - * addresses and balance, and nothing about the threshold key or the room. - */ - class Account internal constructor( - val chain: Chain, - val account: Long, - val extendedPublicKey: DeterministicWallet.ExtendedPublicKey, - /** The threshold key tweaked to [extendedPublicKey]'s key: what the account's sessions start from. */ - internal val cache: TweakCache, - /** - * The ancestors that can spend from every address of this account, nearest - * first -- empty for an account nobody guards, which is every account a - * group that is nobody's subgroup opens. - */ - val guardians: List = emptyList(), - ) { - /** Whether its addresses carry guardian leaves. */ - val isGuarded: Boolean get() = guardians.isNotEmpty() - - /** The account key's own fingerprint, as a descriptor's key origin and a PSBT's derivation name it. */ - val fingerprint: Long get() = extendedPublicKey.fingerprint() - - val fingerprintHex: String get() = fingerprint.toString(16).padStart(8, '0') - - /** `xpub` on mainnet, `tpub` on every test network -- BIP86 has no SLIP-132 prefix of its own. */ - val xpub: String - get() = extendedPublicKey.encode( - if (chain.isMainnet()) DeterministicWallet.xpub else DeterministicWallet.tpub - ) - - /** - * The receive branch as a ranged `tr()` descriptor over the account xpub, with the - * account's fingerprint as its key origin and a checksum -- what a watch-only - * wallet imports. - */ - val receiveDescriptor: String get() = descriptor(RECEIVE) - - /** The change branch, as [receiveDescriptor] gives the receive branch. */ - val changeDescriptor: String get() = descriptor(CHANGE) - - private fun descriptor(change: Long): String { - val tree = if (isGuarded) "," + GuardianDerivation.descriptorTree(guardians, chain, account, change) else "" - val body = "tr([$fingerprintHex]$xpub/$change/*$tree)" - return "$body#${Descriptor.checksum(body)}" - } - - /** The same account with [guardians] in every address. */ - fun guardedBy(guardians: List): Account = - Account(chain, account, extendedPublicKey, cache, guardians) - - override fun equals(other: Any?): Boolean = - other is Account && chain == other.chain && account == other.account && - extendedPublicKey == other.extendedPublicKey && guardians == other.guardians - - override fun hashCode(): Int = extendedPublicKey.hashCode() * 31 + guardians.hashCode() - } - - /** - * One address of an account, and the cache a signing session for it needs. - * - * [cache] is not an optimisation, for the same reason [SharedKeyDerivation.Derived]'s - * is not: a session created with any other cache aggregates to a signature - * that is perfectly valid for some other key, and the coins are at [outputKey]. - */ - data class Derived( - val change: Long, - val index: Long, - /** BIP86's internal key `P`. */ - val internalKey: XonlyPublicKey, - /** BIP86's output key `Q`: the key in the output script, and the key a spend's signature verifies against. */ - val outputKey: XonlyPublicKey, - val cache: TweakCache, - /** The guardian leaves this address commits to, or null for BIP86's empty tree. */ - val tree: ScriptTree? = null, - ) { - /** The tweak from [internalKey] to [outputKey]: over [tree] when there is one, BIP86's otherwise. */ - val taprootTweak: Crypto.TaprootTweak - get() = tree?.let { Crypto.TaprootTweak.ScriptPathTweak(it.hash()) } ?: Crypto.TaprootTweak.KeyPathTweak - - /** `OP_1 `. */ - val pubkeyScript: ByteVector - get() = ByteVector(Script.write(Script.pay2tr(internalKey, taprootTweak))) - - fun address(chain: Chain): String = when (tree) { - null -> Bitcoin.computeBIP86Address(internalKey, chain.chainHash) - else -> Bitcoin.addressFromPublicKeyScript(chain.chainHash, pubkeyScript.toByteArray()).right - ?: throw IllegalStateException("a taproot output always has an address") - } - - /** The path below the account, as a PSBT's `tap_bip32_derivation` carries it. */ - val keyPath: KeyPath get() = KeyPath(listOf(change, index)) - } - - /** - * The account step: the threshold key tweaked by a tagged HMAC over itself, - * the network and the account number. - * - * @throws IllegalArgumentException if the threshold key is not a valid point, - * or the HMAC lands on an invalid scalar -- around 2^-127, and BIP32 throws at - * the same place. - */ - fun account( - thresholdPublicKey: HexKey, - chain: Chain, - account: Long = 0L, - guardians: List = emptyList(), - ): Account { - require(account in 0L..MAX_INDEX) { "account $account is not an unhardened index" } - - val root = PublicKey(ByteVector(thresholdPublicKey.hexToByteArray())) - require(root.isValid()) { "the threshold key is not a valid point" } - - val (tweak, chainCode) = accountStep(root, chain, account) - - val accountKey = root + PrivateKey(tweak).publicKey() - val cache = plainTweak(TweakCache.create(root), tweak, "the account step") - // The cache tracks the full point; the point arithmetic above is the - // reference it has to agree with, or every session for this account signs - // for a key nobody's coins are at. - require(cache.tweakedPublicKey == accountKey.xOnly()) { "the account cache does not reach the account key" } - - return Account( - chain = chain, - account = account, - extendedPublicKey = DeterministicWallet.ExtendedPublicKey( - publickeybytes = accountKey.value, - chaincode = chainCode, - depth = 0, - path = KeyPath.empty, - parent = 0L, - ), - cache = cache, - guardians = guardians, - ) - } - - /** - * The account step's tweak and chain code for [root]: `I[0:32]` and - * `I[32:64]` of the tagged HMAC over the key, the network and the account. - * - * Split out for the one holder of a key path who has its private key -- a - * member wallet, `MemberWalletDerivation` -- which adds the same tweak to - * the scalar that [account] adds to the point. - */ - internal fun accountStep(root: PublicKey, chain: Chain, account: Long): Pair { - val i = Crypto.hmac512( - ACCOUNT_TAG.encodeToByteArray(), - root.value.toByteArray() + chain.chainHash.value.toByteArray() + Pack.writeInt32BE(account.toInt()) - ) - val tweak = i.copyOfRange(0, 32) - require(Crypto.isPrivKeyValid(tweak)) { "the account step for account $account landed on an invalid scalar" } - return ByteVector32(tweak) to ByteVector32(i.copyOfRange(32, 64)) - } - - /** - * The address at `//` under [account]. - * - * Computed twice -- as points through [DeterministicWallet.ExtendedPublicKey.derivePublicKey], - * and as tweaks on the account's cache -- and refused if the two disagree. - * They are `require`s rather than tests because they are what stands between - * a parity mistake in the cache and a wallet whose signatures do not verify. - */ - fun derive(account: Account, change: Long, index: Long): Derived = - deriveBelow( - account.extendedPublicKey, - account.cache, - change, - index, - tree = GuardianDerivation.treeAt(account.guardians, account.chain, account.account, change, index), - ) - - /** - * The tail on its own: BIP32 public derivation and the BIP341 tweak -- over - * [tree] when there is one, BIP86's key-path tweak otherwise -- from any - * account-level key and the cache that signs as it. Split out so the tail can - * be tested against BIP86's published vectors, which start from a seed's - * account key rather than from a threshold key. - */ - internal fun deriveBelow( - accountKey: DeterministicWallet.ExtendedPublicKey, - accountCache: TweakCache, - change: Long, - index: Long, - tree: ScriptTree? = null, - ): Derived { - require(change == RECEIVE || change == CHANGE) { "change must be $RECEIVE or $CHANGE, not $change" } - require(index in 0L..MAX_INDEX) { "index $index is not an unhardened index" } - require(accountCache.tweakedPublicKey == accountKey.publicKey.xOnly()) { "the cache does not sign as this account key" } - - val branchKey = accountKey.derivePublicKey(change) - val childKey = branchKey.derivePublicKey(index) - - var cache = plainTweak(accountCache, childTweak(accountKey, change), "branch $change") - cache = plainTweak(cache, childTweak(branchKey, index), "index $index") - - val internalKey = childKey.publicKey.xOnly() - require(cache.tweakedPublicKey == internalKey) { "the cache does not reach the internal key at $change/$index" } - - val taprootTweak = tree?.let { Crypto.TaprootTweak.ScriptPathTweak(it.hash()) } ?: Crypto.TaprootTweak.KeyPathTweak - cache = when (val tweaked = cache.tweak(internalKey.tweak(taprootTweak), isXonly = true)) { - is Either.Left -> throw IllegalArgumentException("Could not apply the taproot tweak at $change/$index", tweaked.value) - is Either.Right -> tweaked.value.first - } - - val outputKey = internalKey.outputKey(taprootTweak).first - require(cache.tweakedPublicKey == outputKey) { "the cache does not reach the output key at $change/$index" } - - return Derived(change = change, index = index, internalKey = internalKey, outputKey = outputKey, cache = cache, tree = tree) - } - - /** BIP32's `I_L` for one unhardened step: the scalar CKDpub adds, which a FROST cache takes as a plain tweak. */ - internal fun childTweak(parent: DeterministicWallet.ExtendedPublicKey, index: Long): ByteVector32 = - ByteVector32( - Crypto.hmac512( - parent.chaincode.toByteArray(), - parent.publickeybytes.toByteArray() + Pack.writeInt32BE(index.toInt()) - ).copyOfRange(0, 32) - ) - - internal fun plainTweak(cache: TweakCache, tweak: ByteVector32, step: String): TweakCache = - when (val tweaked = cache.tweak(tweak, isXonly = false)) { - is Either.Left -> throw IllegalArgumentException("Could not apply $step to the group's key", tweaked.value) - is Either.Right -> tweaked.value.first - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupWalletManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupWalletManager.kt deleted file mode 100644 index 5a76b291..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupWalletManager.kt +++ /dev/null @@ -1,125 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.nostr.subgroup.WalletPolicyReading -import mobi.giza.compose.database.GizaDatabase -import mobi.giza.compose.nostr.wallet.GroupWallet -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.Chain - -/** - * Where a room's wallet is read from: its threshold key, and the statement the - * group signed opening a wallet under it. - */ -object GroupWalletManager { - /** - * The threshold key [chatRoomId] signs with, or null for a room without one. - * - * The room's verified key state first -- which every member who was in the - * ceremony holds, whether or not they are a signer -- and the key this device - * would sign with behind it, for a room whose state this device never filed. - * Either way it is a key the room's id rederives from, so a wallet read under - * it is the room's. - */ - suspend fun thresholdKeyFor(database: GizaDatabase, chatRoomId: String): HexKey? = - GroupKeyStateManager.keyStateFor(database, chatRoomId) - ?.takeIf { it.verifies() } - ?.thresholdPublicKey - ?: FrostSigningManager.completedKey(database, chatRoomId)?.thresholdPublicKey - - /** The account [chatRoomId] would open on [chain], whether or not it has: what a statement proposing it carries. */ - suspend fun accountFor( - database: GizaDatabase, - chatRoomId: String, - chain: Chain, - account: Long = 0L, - ): GroupWalletDerivation.Account? = - thresholdKeyFor(database, chatRoomId)?.let { GroupWalletDerivation.account(it, chain, account) } - - /** A guarded account a room could open, and the certificate that granted its guardians, which the statement carries. */ - data class GuardedOpening( - val account: GroupWalletDerivation.Account, - val certificate: Event, - ) - - /** - * The guarded account [chatRoomId] would open on [chain], or null for a room - * whose certificate grants it no guardian keys -- a room nobody's subgroup, - * or one certified before certificates carried them. - * - * Off the verified key state, the one place a certificate this device - * believes is kept. A member who holds no key state cannot open one; that - * member cannot sign, either. - */ - suspend fun guardedAccountFor( - database: GizaDatabase, - chatRoomId: String, - chain: Chain, - account: Long = 0L, - ): GuardedOpening? { - val thresholdPublicKey = thresholdKeyFor(database, chatRoomId) ?: return null - val certificate = GroupKeyStateManager.keyStateFor(database, chatRoomId) - ?.takeIf { it.verifies() } - ?.birthCertificateJson - ?.let { Event.fromJsonOrNull(it) } - ?: return null - val guardians = SubgroupBirthCertificateEvent.parseGuardians(certificate.tags) - ?.takeIf { it.isNotEmpty() } - ?: return null - - return GuardedOpening(GroupWalletDerivation.account(thresholdPublicKey, chain, account, guardians), certificate) - } - - /** - * The wallet [chatRoomId] has opened on [chain] under [thresholdPublicKey], or - * null when the room signed no statement that key rederives. - * - * The form a signing session uses: it names the ceremony it signs under, and - * a statement is only that ceremony's wallet if that ceremony's key reaches it. - */ - suspend fun walletFor( - database: GizaDatabase, - chatRoomId: String, - thresholdPublicKey: HexKey, - chain: Chain, - account: Long, - ): GroupWallet? = GroupWallet.newestAmong( - signedEvents = database.groupSignedEventDao() - .getByChatRoomIdAndKind(chatRoomId, GroupWalletStatementEvent.KIND), - thresholdPublicKey = thresholdPublicKey, - chain = chain, - account = account, - policy = walletPolicyFor(database, chatRoomId), - ) - - /** The wallet [chatRoomId] has opened on [chain], or null when the group has not opened one. */ - suspend fun walletFor( - database: GizaDatabase, - chatRoomId: String, - chain: Chain, - account: Long = 0L, - ): GroupWallet? { - val thresholdPublicKey = thresholdKeyFor(database, chatRoomId) ?: return null - - return GroupWallet.newestAmong( - signedEvents = database.groupSignedEventDao() - .getByChatRoomIdAndKind(chatRoomId, GroupWalletStatementEvent.KIND), - thresholdPublicKey = thresholdPublicKey, - chain = chain, - account = account, - policy = walletPolicyFor(database, chatRoomId), - ) - } - - /** - * What [chatRoomId]'s parent decided about its wallet at its birth, or null - * for a room with no certificate -- `docs/subgroup-wallet-policy.md`. The - * same reading the picker and every parent signer make, through - * `SubgroupManager.walletPolicyOf`, so the wallet a device opens, offers and - * signs for cannot disagree with what the group was made as. - */ - suspend fun walletPolicyFor(database: GizaDatabase, chatRoomId: String): WalletPolicyReading? = - SubgroupManager.walletPolicyOf(database, chatRoomId) -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GuardianDerivation.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GuardianDerivation.kt deleted file mode 100644 index 5931842c..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GuardianDerivation.kt +++ /dev/null @@ -1,315 +0,0 @@ -package mobi.giza.compose.managers - -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.Crypto -import fr.acinq.bitcoin.DeterministicWallet -import fr.acinq.bitcoin.KeyPath -import fr.acinq.bitcoin.OP_CHECKSEQUENCEVERIFY -import fr.acinq.bitcoin.OP_CHECKSIGVERIFY -import fr.acinq.bitcoin.OP_PUSHDATA -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.PublicKey -import fr.acinq.bitcoin.Script -import fr.acinq.bitcoin.ScriptElt -import fr.acinq.bitcoin.ScriptEltMapping -import fr.acinq.bitcoin.ScriptTree -import fr.acinq.bitcoin.XonlyPublicKey -import fr.acinq.bitcoin.crypto.Pack -import fr.acinq.bitcoin.crypto.frost.TweakCache - -/** - * The keys an ancestor group holds in a subgroup's wallet, and the leaves they - * sit in. - * - * Every group has one guardian root, a tagged HMAC away from its threshold key, - * which it never hands out. What a parent writes into a child's birth - * certificate is that root one public BIP32 step further, at an index taken - * from the child's room id -- and, behind it, every key the parent's own - * ancestors gave the parent, each one step further at the same index: - * - * ``` - * I = HMAC-SHA512("bennu/group-wallet/guardian/v1", serP(K_A)) - * R_A = K_A + I[0:32]·G, chain code I[32:64] A's guardian root - * i(C) = taggedHash("bennu/group-wallet/guardian/child/v1", C)[0:4] & 0x7fffffff - * grant(C) = [R_A/i(C)] ++ [g/i(C) for g in grant(A)] nearest first - * L = xonly(g / network / account / change / index) a leaf key in one address - * ``` - * - * See `docs/group-wallet-guardians.md` for why each step is what it is. In - * short: a fresh key per child is what lets the parent *agree* to guard it, a - * root nobody publishes is what keeps a guardian spend unlinkable to a Marmot - * room, and re-deriving every inherited key per child is what keeps a parent's - * wallet and its child's from sharing a leaf. - * - * ### The same rule as the wallet's - * - * Every step is a public tweak of the threshold key, so a leaked leaf private - * key recovers the group's threshold key. Nothing reconstructs one: a leaf is - * signed for by a FROST session over [signingCache]. - */ -object GuardianDerivation { - /** - * The fewest blocks a coin can sit confirmed before an ancestor can take it: - * about an hour, so the child's own spends always go first -- a guardian - * cannot race the child for a payment that has only just arrived. - * `docs/guardian-delay.md`. - */ - const val MIN_DELAY: Long = 6L - - /** - * The most: BIP68's block-based relative lock is the low 16 bits of - * `nSequence`, so 65,535 blocks, about 15 months. Staying within it also - * keeps bit 22 clear, so the lock always counts blocks, and keeps every - * guardian input far below `GroupSpend.MAX_SEQUENCE`, so a guardian spend - * can still be bumped. - */ - const val MAX_DELAY: Long = 0xFFFFL - - /** Every delay a leaf may carry. A guardian tag outside it does not read. */ - val DELAY_RANGE: LongRange = MIN_DELAY..MAX_DELAY - - /** - * The delay a parent is offered first for its own leaf, and the one every - * certificate carried before parents chose: two hours. Each guardian's own - * delay is written into its tag, and each ancestor's travels down the tree - * unchanged -- [Guardian.grantedTo] copies it -- so this is a default, not - * the delay. `docs/guardian-delay.md`. - */ - const val DEFAULT_DELAY: Long = 12L - - /** - * The key of the guardian root's HMAC. An input to every guardian key, so it - * is frozen the moment a certificate carries one: a rename moves every leaf. - * The `bennu/` prefix included -- see [GroupWalletDerivation]'s account tag. - */ - private const val ROOT_TAG = "bennu/group-wallet/guardian/v1" - - /** The tag of the hash a child's index is taken from. Frozen for the same reason. */ - private const val CHILD_TAG = "bennu/group-wallet/guardian/child/v1" - - /** - * One ancestor's guardian key as granted to one group: whose it is, and the - * extended public key that group's addresses derive that ancestor's leaves - * from. - * - * Held as the key and the chain code rather than as an - * [DeterministicWallet.ExtendedPublicKey], whose depth, parent fingerprint and - * path would make two grants of the same key compare unequal depending on how - * each was reached. Only the 65 bytes take part in a derivation. - */ - data class Guardian( - /** The ancestor's room id, which its leaf is named by. */ - val chatRoomId: String, - val publicKey: PublicKey, - val chainCode: ByteVector32, - val delay: Long = DEFAULT_DELAY, - ) { - /** As a depth-0 extended key, the form every derivation below starts from. */ - val extendedPublicKey: DeterministicWallet.ExtendedPublicKey - get() = DeterministicWallet.ExtendedPublicKey( - publickeybytes = publicKey.value, - chaincode = chainCode, - depth = 0, - path = KeyPath.empty, - parent = 0L, - ) - - /** `xpub` on mainnet and `tpub` on every test network, as the wallet's own xpub is. */ - fun encoded(chain: Chain): String = - extendedPublicKey.encode(if (chain.isMainnet()) DeterministicWallet.xpub else DeterministicWallet.tpub) - - /** The same ancestor, one public step further, for [childChatRoomId] -- and at the same delay. */ - fun grantedTo(childChatRoomId: String): Guardian { - val child = extendedPublicKey.derivePublicKey(childIndex(childChatRoomId)) - return copy(publicKey = child.publicKey, chainCode = child.chaincode) - } - } - - /** A group's guardian root, and the cache that signs as it. */ - class Root internal constructor( - val publicKey: PublicKey, - val chainCode: ByteVector32, - internal val cache: TweakCache, - ) { - val extendedPublicKey: DeterministicWallet.ExtendedPublicKey - get() = DeterministicWallet.ExtendedPublicKey(publicKey.value, chainCode, 0, KeyPath.empty, 0L) - } - - /** One guardian's leaf in one address, and -- on the guardian's side -- the cache that signs as it. */ - data class Signing( - val leafKey: XonlyPublicKey, - val cache: TweakCache, - ) - - /** - * The guardian root of the group holding [thresholdPublicKey]. - * - * @throws IllegalArgumentException if the key is not a point, or the HMAC - * lands on an invalid scalar -- around 2^-127, and BIP32 throws at the same place. - */ - fun root(thresholdPublicKey: HexKey): Root { - val threshold = PublicKey(ByteVector(thresholdPublicKey.hexToByteArray())) - require(threshold.isValid()) { "the threshold key is not a valid point" } - - val i = Crypto.hmac512(ROOT_TAG.encodeToByteArray(), threshold.value.toByteArray()) - val tweak = i.copyOfRange(0, 32) - require(Crypto.isPrivKeyValid(tweak)) { "the guardian root landed on an invalid scalar" } - - val rootKey = threshold + PrivateKey(tweak).publicKey() - val cache = GroupWalletDerivation.plainTweak(TweakCache.create(threshold), ByteVector32(tweak), "the guardian root") - require(cache.tweakedPublicKey == rootKey.xOnly()) { "the guardian root's cache does not reach its key" } - - return Root(publicKey = rootKey, chainCode = ByteVector32(i.copyOfRange(32, 64)), cache = cache) - } - - /** - * The unhardened index a child's keys are derived at: the first four bytes - * of a tagged hash of its room id, top bit cleared. - */ - fun childIndex(childChatRoomId: String): Long { - val roomId = childChatRoomId.lowercase().hexToByteArray() - require(roomId.size == 32) { "a room id is 32 bytes, not ${roomId.size}" } - return Pack.int32BE(Crypto.taggedHash(roomId, CHILD_TAG).toByteArray(), 0).toLong() and GroupWalletDerivation.MAX_INDEX - } - - /** - * The network's index under a guardian key. Not BIP44's coin type: the - * networks this app knows, numbered once, so a guardian key granted for no - * network in particular gives each one unrelated leaves. - */ - fun networkIndex(chain: Chain): Long = when (chain) { - Chain.Mainnet -> 0L - Chain.Testnet3 -> 1L - Chain.Testnet4 -> 2L - Chain.Signet -> 3L - Chain.Regtest -> 4L - } - - /** - * What the group holding [thresholdPublicKey], whose room is [ownChatRoomId], - * writes into [childChatRoomId]'s certificate: its own root one step further, - * then each of [inherited] -- the keys its own certificate carries, nearest - * first -- one step further, in the same order. - * - * The same function a signer's device runs to check a proposed certificate: - * a certificate whose guardians are not exactly this list is not one the - * group agreed to. - * - * [delay] is the parent's own leaf's, which it chooses for this child. An - * inherited key keeps the delay its own ancestor chose: a group cannot - * shorten or lengthen another group's terms in its child's wallet. - */ - fun grant( - thresholdPublicKey: HexKey, - ownChatRoomId: String, - inherited: List, - childChatRoomId: String, - delay: Long = DEFAULT_DELAY, - ): List { - require(delay in DELAY_RANGE) { "a guardian's delay is $MIN_DELAY to $MAX_DELAY blocks, not $delay" } - val own = root(thresholdPublicKey).extendedPublicKey.derivePublicKey(childIndex(childChatRoomId)) - return listOf(Guardian(ownChatRoomId, own.publicKey, own.chaincode, delay)) + - inherited.map { it.grantedTo(childChatRoomId) } - } - - /** [guardian]'s key one level above the leaves of [account]'s `change` branch. */ - private fun branchKey(guardian: Guardian, chain: Chain, account: Long, change: Long): DeterministicWallet.ExtendedPublicKey = - guardian.extendedPublicKey.derivePublicKey(listOf(networkIndex(chain), account, change)) - - /** [guardian]'s leaf key in the address at `change/index` of [account] on [chain]. */ - fun leafKey(guardian: Guardian, chain: Chain, account: Long, change: Long, index: Long): XonlyPublicKey = - branchKey(guardian, chain, account, change).derivePublicKey(index).publicKey.xOnly() - - /** - * ` OP_CHECKSIGVERIFY OP_CHECKSEQUENCEVERIFY` -- miniscript's - * `and_v(v:pk(key),older(delay))`. A delay of 1-16 is the single opcode for - * it, as miniscript writes it; anything else is a minimal number push. - */ - fun leafScript(key: XonlyPublicKey, delay: Long): List { - require(delay in DELAY_RANGE) { "a guardian's delay is $MIN_DELAY to $MAX_DELAY blocks, not $delay" } - val lock = if (delay <= 16) ScriptEltMapping.code2elt.getValue(0x50 + delay.toInt()) - else OP_PUSHDATA(Script.encodeNumber(delay)) - return listOf(OP_PUSHDATA(key), OP_CHECKSIGVERIFY, lock, OP_CHECKSEQUENCEVERIFY) - } - - /** One leaf per guardian in the address at `change/index`, nearest first. */ - fun leaves(guardians: List, chain: Chain, account: Long, change: Long, index: Long): List = - guardians.map { ScriptTree.Leaf(leafScript(leafKey(it, chain, account, change, index), it.delay)) } - - /** - * The leaves as a caterpillar, nearest first: the first leaf at depth one, - * the rest one level further down each. Every guardian can act at the same - * moment, so the order decides only whose control block is shortest -- and - * the parent, who knows the child best, gets the cheapest spend. - */ - fun tree(leaves: List): ScriptTree { - require(leaves.isNotEmpty()) { "a tree needs a leaf" } - return leaves.dropLast(1).foldRight(leaves.last() as ScriptTree) { leaf, rest -> ScriptTree.Branch(leaf, rest) } - } - - /** The tree in the address at `change/index`, or null for an unguarded one. */ - fun treeAt(guardians: List, chain: Chain, account: Long, change: Long, index: Long): ScriptTree? = - guardians.takeIf { it.isNotEmpty() }?.let { tree(leaves(it, chain, account, change, index)) } - - /** - * The tree half of a `tr()` descriptor over a whole branch: `{a,{b,c}}`, the - * same caterpillar [tree] builds, each leaf ranged over the branch's indices. - */ - fun descriptorTree(guardians: List, chain: Chain, account: Long, change: Long): String { - require(guardians.isNotEmpty()) { "a tree needs a leaf" } - val leaves = guardians.map { guardian -> - val path = "${networkIndex(chain)}/$account/$change/*" - "and_v(v:pk(${guardian.encoded(chain)}/$path),older(${guardian.delay}))" - } - return leaves.dropLast(1).foldRight(leaves.last()) { leaf, rest -> "{$leaf,$rest}" } - } - - /** - * The room ids an ancestor walks from its own root down to [childChatRoomId], - * through the line of descent [guardians] -- a certificate's guardian list, - * nearest first -- names. Null when [ancestorChatRoomId] is not among them. - * - * For `guardians = [A1, A2, A3]` and `ancestor = A3`, that is `[A2, A1, C]`: - * the generations below A3, its own child first. - */ - fun lineage(guardians: List, childChatRoomId: String, ancestorChatRoomId: String): List? { - val position = guardians.indexOfFirst { it.chatRoomId.equals(ancestorChatRoomId, ignoreCase = true) } - if (position < 0) return null - return guardians.take(position).map { it.chatRoomId }.reversed() + childChatRoomId - } - - /** - * The cache the group holding [thresholdPublicKey] signs a leaf with: its - * guardian root, then one plain step per generation down [lineage], then - * the network, the account and the address. Every step is a plain tweak, so - * the cache tracks exactly the point the descendant derives from its grant. - * - * No TapTweak follows: a script-path signature is by the leaf key itself. - */ - fun signingCache( - thresholdPublicKey: HexKey, - lineage: List, - chain: Chain, - account: Long, - change: Long, - index: Long, - ): Signing { - val root = root(thresholdPublicKey) - val path = lineage.map(::childIndex) + listOf(networkIndex(chain), account, change, index) - - var key = root.extendedPublicKey - var cache = root.cache - path.forEach { step -> - cache = GroupWalletDerivation.plainTweak(cache, GroupWalletDerivation.childTweak(key, step), "guardian step $step") - key = key.derivePublicKey(step) - } - - val leafKey = key.publicKey.xOnly() - require(cache.tweakedPublicKey == leafKey) { "the guardian cache does not reach its leaf key" } - return Signing(leafKey = leafKey, cache = cache) - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GuardianManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GuardianManager.kt deleted file mode 100644 index 3fb7a27e..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GuardianManager.kt +++ /dev/null @@ -1,722 +0,0 @@ -package mobi.giza.compose.managers - -import mobi.giza.compose.nostr.subgroup.allows -import co.touchlab.kermit.Logger -import mobi.giza.compose.database.GizaDatabase -import mobi.giza.compose.database.model.ChatMessage -import mobi.giza.compose.database.model.MarmotInnerEvent -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -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.wallet.GroupSpend -import mobi.giza.compose.wallet.GroupWalletRollout -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.OutPoint -import fr.acinq.bitcoin.Satoshi -import fr.acinq.bitcoin.Transaction -import fr.acinq.bitcoin.TxId -import fr.acinq.bitcoin.TxOut -import fr.acinq.lightning.utils.sum -import kotlin.time.Clock -import kotlin.time.Instant - -/** - * What an ancestor group knows of the guarded wallets beneath it, and how it - * comes to know. - * - * A descendant opens a guarded wallet in its own room. Its ancestors are not in - * that room, so a member who sits in both carries the signed statement across - * as a [GuardedWalletNoticeEvent]; every device in the ancestor's room checks it - * for itself, and from then on watches the wallet and can propose spending from - * it through its own leaf. See `docs/group-wallet-guardians.md`, "How an - * ancestor finds the coins". - * - * A notice forwarded into a middle group can be forwarded again from there, so - * a root needs a member in common with each generation, not with the grandchild. - */ -object GuardianManager { - private const val TAG = "GuardianManager" - - private val logger = Logger.withTag(TAG) - - /** - * Whose guarded wallet it is: a subgroup's, under its quorum's key, or one - * member's, under a key only they hold -- `docs/member-guarded-wallets.md`. - * Either way [id] is what the line of descent ends in, so every guardian - * signs for its leaf the same way. - */ - sealed interface GuardedSubject { - /** A room id, or a member wallet's `W`. */ - val id: String - - data class Subgroup(override val id: String, val name: String?) : GuardedSubject - - data class Member( - override val id: String, - val ownerPublicKey: HexKey, - val label: String?, - /** The member's profile name on this device, where one is known; filled where a database is to hand. */ - val ownerName: String? = null, - /** - * The group that directly guards it, by its founding name where this - * device can check a birth certificate for it, else its room name here; - * null when neither is known. Filled where a database is to hand. - * `docs/member-wallet-guarding-group.md`, D2. - */ - val guardianName: String? = null, - /** The holding group's own child it sits under, named the same way; null when the holder guards it directly. */ - val branchName: String? = null, - ) : GuardedSubject - } - - /** A descendant's guarded wallet, as one of its ancestors holds it. */ - data class GuardedWallet( - /** The ancestor holding it: the room it was told to. */ - val ancestorChatRoomId: String, - /** [subject]'s id: the descendant's room, or a member wallet's `W`. */ - val descendantChatRoomId: String, - /** - * What the ancestor believes it on, whole: a subgroup's signed statement, - * or the member wallet certificate the guarding group signed. - */ - val statement: Event, - /** The account the statement opens, rederived from the descendant's key. */ - val account: GroupWalletDerivation.Account, - /** A subgroup's birth certificate, carried in the statement -- or, for a member, the certificate itself. */ - val certificate: Event, - /** The rooms the ancestor walks from its own child down to the descendant -- `GuardianDerivation.lineage`. */ - val lineage: List, - val subject: GuardedSubject = GuardedSubject.Subgroup(descendantChatRoomId, SubgroupBirthCertificateEvent.parseName(certificate.tags)), - /** - * For a member's wallet: the birth certificate of the group that directly - * guards it, checked, where this device holds one -- what a notice - * carries upward so the groups above can name that group. - * `docs/member-wallet-guarding-group.md`, D4. - */ - val guardianCertificate: Event? = null, - ) { - /** What the descendant's parent certified it as, for a subgroup. The founding name: a rename does not reach it. */ - val name: String? get() = (subject as? GuardedSubject.Subgroup)?.name - - val chain: Chain get() = account.chain - - val openedAt: Instant get() = Instant.fromEpochSeconds(statement.createdAt) - - /** Where the ancestor sits among the guardians: whose leaf, in every address, is its. */ - val position: Int get() = account.guardians.indexOfFirst { it.chatRoomId.equals(ancestorChatRoomId, ignoreCase = true) } - - /** - * How long a coin here waits before this ancestor can take it: the delay - * on its own leaf, which the group that granted it chose and which two of - * an ancestor's descendants can have set differently. - * `docs/guardian-delay.md`. - */ - val delay: Long get() = account.guardians[position].delay - - /** - * The group that directly guards it: the nearest guardian, which for a - * member's wallet is the group that signed its certificate -- - * `MemberWalletRequestEvent.verified` refuses a request whose nearest - * guardian is not the group it asks. `docs/member-wallet-guarding-group.md`, D1. - */ - val directGuardianChatRoomId: String get() = account.guardians.first().chatRoomId - - /** True when the ancestor holding it is the group that directly guards it. */ - val isGuardedHere: Boolean get() = position == 0 - - /** - * The ancestor's own child the wallet sits under -- the branch of its tree - * -- or null when the ancestor guards it directly. The ancestor signed - * that child's birth certificate, so it can always name it. - */ - val branchChatRoomId: String? get() = lineage.takeIf { position > 0 }?.first() - - /** The ancestor as the spender of a spend from this wallet, signing as [thresholdPublicKey] -- null to only build one. */ - fun spender(thresholdPublicKey: HexKey? = null): GroupSpend.Spender.Guardian = - GroupSpend.Spender.Guardian(position = position, lineage = lineage, thresholdPublicKey = thresholdPublicKey, name = displayName, label = label) - - /** A member's label for it, where they gave one; null for a subgroup's. */ - val label: String? get() = (subject as? GuardedSubject.Member)?.label - - /** How a spend from it names it: a subgroup's founding name, or `@` and a member's. */ - val displayName: String? - get() = when (val subject = subject) { - is GuardedSubject.Subgroup -> subject.name - is GuardedSubject.Member -> "@" + (subject.ownerName ?: subject.ownerPublicKey.take(8)) - } - } - - /** - * A guarded wallet statement believed on its own merits -- everything - * [verify] checks except the walk down from an ancestor's own guardian root, - * which only a device holding that ancestor's key can make. What a forwarder - * checks before passing a statement on (`docs/guarded-wallet-forwarding.md`, - * D2): a notice it would copy into every group above should be one it - * believes itself. - */ - data class Believable( - val statement: Event, - /** The descendant's room id, or a member wallet's `W`: what the line of descent ends in. */ - val descendantId: String, - /** The account the statement opens, rederived from the descendant's key. */ - val account: GroupWalletDerivation.Account, - /** A subgroup's birth certificate, carried in the statement -- or, for a member, the certificate itself. */ - val certificate: Event, - val subject: GuardedSubject, - ) { - /** Every guardian, nearest first: the groups that can be told. */ - val guardians: List get() = account.guardians - - val chain: Chain get() = account.chain - } - - /** - * [statement] believed, or null: - * - * 1. it is a wallet statement, and the room it is authored by signed it; - * 2. it is guarded, and carries the certificate its guardians came from; - * 3. the certificate's key makes that room, and the statement's xpub, tree - * and descriptors all rederive from it -- `Reading.verifiedAgainst`, which - * also checks the certificate certifies the room and grants exactly those - * guardians. - */ - fun believable(statement: Event): Believable? = runCatching { - if (statement.kind != GroupWalletStatementEvent.KIND) return null - val descendantChatRoomId = statement.pubKey - if (!GroupKeyStateEvent.isSignedByRoom(statement, descendantChatRoomId)) return null - - val reading = GroupWalletStatementEvent.read(statement.tags, statement.content) ?: return null - if (reading.guardians.isEmpty()) return null - val certificate = reading.certificate ?: return null - // A guarded wallet the certificate's own policy does not allow -- one it - // contradicts, or decided unguarded -- is not one an honest descendant - // opens, so it is not one to list. docs/subgroup-wallet-policy.md. - if (!SubgroupBirthCertificateEvent.parseWalletPolicy(certificate.tags).let { it != null && it.allows(guarded = true) }) return null - - val descendantKey = SubgroupBirthCertificateEvent.parseThresholdPublicKey(certificate.tags) ?: return null - if (!SharedKeyDerivation.marmotGroupId(descendantKey).equals(descendantChatRoomId, ignoreCase = true)) return null - val account = reading.verifiedAgainst(descendantKey) ?: return null - - Believable( - statement = statement, - descendantId = descendantChatRoomId, - account = account, - certificate = certificate, - subject = GuardedSubject.Subgroup(descendantChatRoomId, SubgroupBirthCertificateEvent.parseName(certificate.tags)), - ) - }.getOrNull() - - /** - * [statement] as a guarded wallet [ancestorChatRoomId] guards, or null when - * it is not one -- believed on its own merits, never on the word of whoever - * forwarded it: [believable], and - * - * 4. the ancestor is among the guardians, and the key the statement names - * for it is the key [ancestorThresholdPublicKey]'s guardian root reaches - * down the line of descent the guardians name. A key it does not reach is - * a leaf this group cannot sign, whatever the statement calls it. The - * line ends in the descendant's room, or in a member wallet's id. - */ - fun verify(statement: Event, ancestorChatRoomId: String, ancestorThresholdPublicKey: HexKey): GuardedWallet? = runCatching { - val believed = believable(statement) ?: return null - val account = believed.account - - val lineage = GuardianDerivation.lineage(account.guardians, believed.descendantId, ancestorChatRoomId) ?: return null - val named = account.guardians.first { it.chatRoomId.equals(ancestorChatRoomId, ignoreCase = true) } - val walked = GuardianDerivation.root(ancestorThresholdPublicKey).extendedPublicKey - .derivePublicKey(lineage.map(GuardianDerivation::childIndex)) - if (walked.publicKey != named.publicKey || walked.chaincode != named.chainCode) return null - - GuardedWallet( - ancestorChatRoomId = ancestorChatRoomId, - descendantChatRoomId = believed.descendantId, - statement = statement, - account = account, - certificate = believed.certificate, - lineage = lineage, - subject = believed.subject, - ) - }.getOrNull() - - /** - * [wallet] with its member's profile name, and the names of the group that - * directly guards it and of the branch it sits under, where this device knows - * them. [known] are birth certificates that came to hand some other way -- - * those the statements told to the holding room carry. - */ - private suspend fun named(database: GizaDatabase, wallet: GuardedWallet, known: List = emptyList()): GuardedWallet { - val member = wallet.subject as? GuardedSubject.Member ?: return wallet - val name = database.profileDao().getProfileByPublicKey(member.ownerPublicKey)?.humanReadableNameOrPubkey() - val guardians = wallet.account.guardians - - suspend fun certificateOf(position: Int): Event? = - guardians.getOrNull(position + 1)?.let { parent -> foundingCertificateOf(database, guardians[position].chatRoomId, parent.chatRoomId, known) } - - // Founding name first, then the room's name here: the order D2 of - // docs/member-wallet-guarding-group.md gives, so the card agrees with a - // subgroup row in the same list naming the same room. - suspend fun nameOf(position: Int, certificate: Event?): String? = - certificate?.let { SubgroupBirthCertificateEvent.parseName(it.tags) } - ?: database.chatRoomDao().findChatRoomById(guardians[position].chatRoomId)?.chatRoom?.subject?.takeIf { it.isNotBlank() } - - val guardianCertificate = certificateOf(0) - return wallet.copy( - subject = member.copy( - ownerName = name, - guardianName = nameOf(0, guardianCertificate), - branchName = wallet.position.takeIf { it > 0 }?.let { nameOf(it - 1, certificateOf(it - 1)) }, - ), - guardianCertificate = guardianCertificate, - ) - } - - /** - * What [roomId] was called at its founding, read off a birth certificate - * [parentRoomId] signed for it -- or null when this device holds none it can - * check. Each candidate is checked with `SubgroupBirthCertificateEvent.certifies`, - * whoever handed it over: [carried] first, then the certificates the parent - * signed (every device in the parent holds them), then the one in [roomId]'s - * own key state (every device in the room). `docs/member-wallet-guarding-group.md`, D3. - */ - suspend fun foundingNameOf( - database: GizaDatabase, - roomId: String, - parentRoomId: String, - carried: List = emptyList(), - ): String? = foundingCertificateOf(database, roomId, parentRoomId, carried)?.let { SubgroupBirthCertificateEvent.parseName(it.tags) } - - /** The birth certificate [foundingNameOf] reads the name off, checked, or null. */ - suspend fun foundingCertificateOf( - database: GizaDatabase, - roomId: String, - parentRoomId: String, - carried: List = emptyList(), - ): Event? { - fun List.certifying(): Event? = firstOrNull { SubgroupBirthCertificateEvent.certifies(it, roomId, parentRoomId) } - - carried.certifying()?.let { return it } - database.groupSignedEventDao() - .getByChatRoomIdAndKind(parentRoomId, SubgroupBirthCertificateEvent.KIND) - .map { it.toEvent() } - .certifying()?.let { return it } - return listOfNotNull( - database.groupKeyStateDao().getByChatRoomId(roomId)?.birthCertificateJson?.let { Event.fromJsonOrNull(it) } - ).certifying() - } - - /** - * The guardian rooms a statement is told to from [chatRoomId]: those after it - * in [guardians], nearest first -- upward only - * (`docs/guarded-wallet-forwarding.md`, D3). A room the list does not name is - * the wallet's own, a subgroup's, and is told to every guardian. - * - * Every guardian *except* the room, which is what the button used to take, - * reaches down as well as up: from a root holding a grandchild's statement it - * would tell the middle group, which told the root. - */ - fun upwardOf(guardians: List, chatRoomId: String): List { - val position = guardians.indexOfFirst { it.chatRoomId.equals(chatRoomId, ignoreCase = true) } - return guardians.drop(position + 1).map { it.chatRoomId } - } - - /** - * Of [candidates] -- the members of both a room and a group above it, as this - * device's participant lists have them -- the one who sends a notice the - * moment a wallet arrives: the lowest key. Everybody else waits for the - * catch-up, by when the elected device's notice has usually arrived - * (`docs/guarded-wallet-forwarding.md`, D4). Null when there are none. - */ - fun electedSender(candidates: Set): HexKey? = candidates.map { it.lowercase() }.minOrNull() - - /** - * Every guarded wallet [ancestorChatRoomId] has been told about and can sign - * for, one per descendant account on each network. - * - * Read off the notices the room's inbound path filed, checked again each - * time. Where two statements describe one account, the rules - * `GroupWallet.newestAmong` applies to the descendant's own copy apply here: - * the earliest decides the guardians and a later one naming others is - * ignored, so a forwarder cannot move the addresses an ancestor watches. - */ - suspend fun guardedWalletsOf(database: GizaDatabase, ancestorChatRoomId: String): List { - val thresholdPublicKey = GroupWalletManager.thresholdKeyFor(database, ancestorChatRoomId) ?: return emptyList() - val order = compareBy({ it.openedAt }, { it.statement.id }) - - // What it was told, and -- for its own members' wallets -- what it signed: - // the group holds a member wallet certificate it signed, and needs no - // notice to learn of it. - val notices = database.marmotInnerEventDao() - .getByChatRoomAndKinds(ancestorChatRoomId, listOf(GuardedWalletNoticeEvent.KIND)) - val told = notices.mapNotNull { row -> Event.fromJsonOrNull(row.content) } - - // Birth certificates the room was handed: the one a subgroup's statement - // carries, and the guardian's a member wallet's notice carries. Pooled, - // since each is checked against the room and parent it is used for, and - // one that certifies neither is never used. - val known = told.filter { it.kind == GroupWalletStatementEvent.KIND } - .mapNotNull { GroupWalletStatementEvent.read(it.tags, it.content)?.certificate } + - notices.mapNotNull { GuardedWalletNoticeEvent.certificateIn(it.tags) } - - return told - .mapNotNull { verify(it, ancestorChatRoomId, thresholdPublicKey) } - .map { named(database, it, known) } - .groupBy { Triple(it.descendantChatRoomId, it.chain, it.account.account) } - .mapNotNull { (_, statements) -> - val first = statements.minWithOrNull(order) ?: return@mapNotNull null - statements.filter { it.account.guardians == first.account.guardians }.maxWithOrNull(order) - } - .sortedBy { it.name ?: it.descendantChatRoomId } - } - - /** The guarded wallet [ancestorChatRoomId] holds for [descendantChatRoomId] on [chain] at [account], or null. */ - suspend fun guardedWalletFor( - database: GizaDatabase, - ancestorChatRoomId: String, - descendantChatRoomId: String, - chain: Chain, - account: Long, - ): GuardedWallet? = guardedWalletsOf(database, ancestorChatRoomId).firstOrNull { - it.descendantChatRoomId.equals(descendantChatRoomId, ignoreCase = true) && it.chain == chain && it.account.account == account - } - - /** A guarded statement this device can carry upward, and the rooms it can carry it into. */ - data class Shareable( - val statement: Event, - /** What the statement's room was certified as, for the screen. Null for a member's wallet. */ - val name: String?, - val rooms: List, - /** For a member's wallet: the member, and their profile name where this device knows one. */ - val ownerPublicKey: HexKey? = null, - val ownerName: String? = null, - /** For a member's wallet: its guardian's birth certificate, carried on the notice -- `GuardedWalletNoticeEvent`. */ - val certificate: Event? = null, - ) - - /** - * The guarded statements this device can tell to groups above [chatRoomId]: - * the room's own guarded wallet, and every one the room was itself told - * about -- passed on a generation further. Each with the guardian rooms this - * device is a member of and has not told yet. - */ - suspend fun shareableFrom(database: GizaDatabase, chatRoomId: String, chain: Chain): List { - val own = GroupWalletManager.walletFor(database, chatRoomId, chain) - ?.takeIf { it.account.isGuarded } - ?.let { wallet -> - val statement = wallet.signedEvent.toEvent() - val certificate = GroupWalletStatementEvent.read(statement.tags, statement.content)?.certificate - statement to (certificate?.let { SubgroupBirthCertificateEvent.parseName(it.tags) }) - } - // Everything it guards or was told of -- its own members' wallets among - // them, since it holds those certificates itself -- passed on a - // generation further. - val passedOn = guardedWalletsOf(database, chatRoomId) - .filter { it.chain == chain } - - val candidates = listOfNotNull(own?.let { (statement, name) -> Shareable(statement, name, emptyList()) }) + - passedOn.map { wallet -> - val member = wallet.subject as? GuardedSubject.Member - Shareable(wallet.statement, wallet.name, emptyList(), member?.ownerPublicKey, member?.ownerName, wallet.guardianCertificate) - } - - return candidates.mapNotNull { candidate -> - val rooms = targetsFor(database, candidate.statement, fromChatRoomId = chatRoomId, withCertificate = candidate.certificate != null) - rooms.takeIf { it.isNotEmpty() }?.let { candidate.copy(rooms = it) } - } - } - - /** - * The groups above [fromChatRoomId] that [statement] should be told to and - * this device can tell: [upwardOf] the room, Marmot rooms this device holds, - * belonging to the same profile as the room it is told from -- one database - * holds every profile, and a device must never post into a room as a - * profile that is not the one in it -- and not told yet. Nothing for a - * statement this device does not believe ([believable]). - */ - private suspend fun targetsFor(database: GizaDatabase, statement: Event, fromChatRoomId: String, withCertificate: Boolean = false): List { - val believed = believable(statement) ?: return emptyList() - val profile = database.chatRoomDao().findChatRoomById(fromChatRoomId)?.chatRoom?.userPublicKey - - return upwardOf(believed.guardians, fromChatRoomId) - .mapNotNull { database.chatRoomDao().findChatRoomById(it) } - .filter { it.chatRoom.mlsGroupState != null } - .filter { profile == null || it.chatRoom.userPublicKey.equals(profile, ignoreCase = true) } - .filterNot { room -> told(database, room.chatRoom.id, statement.id, withCertificate) } - } - - /** - * Whether [chatRoomId] holds the statement [statementId] in any form: a - * notice carrying it, or the signed event itself -- which is how a group - * holds a member wallet certificate it signed, and never as a notice. - * - * With [withCertificate] -- this device has the guardian's birth certificate - * to add -- a notice counts only if it carries one: a room told before - * notices carried it is told again, once, so the name reaches it. - * `docs/member-wallet-guarding-group.md`, D5. - */ - internal suspend fun told(database: GizaDatabase, chatRoomId: String, statementId: HexKey, withCertificate: Boolean = false): Boolean = - database.groupSignedEventDao().getById(statementId)?.chatRoomId.equals(chatRoomId, ignoreCase = true) || - database.marmotInnerEventDao() - .getByChatRoomAndKinds(chatRoomId, listOf(GuardedWalletNoticeEvent.KIND)) - .any { Event.fromJsonOrNull(it.content)?.id == statementId && (!withCertificate || GuardedWalletNoticeEvent.certificateIn(it.tags) != null) } - - /** - * For a member wallet's certificate, the birth certificate of the group that - * signed it, checked, where this device holds one -- what a notice from - * [chatRoomId] carries upward so the groups above can name that group. - * Null for a subgroup's statement, which carries its own. - * `docs/member-wallet-guarding-group.md`, D4. - */ - @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 - * has not been told, about [statement] -- as the profile that is in - * [chatRoomId]. `docs/guarded-wallet-forwarding.md`, Phase 2. - * - * With [whenElected], only the groups this device is the elected sender for - * ([electedSender] over the members of both rooms, as this device's - * participant lists have them, itself always among them): the moment a wallet - * arrives every device in both rooms has it, and only one of them should - * post at once. The catch-up passes false, and tells whatever is still left. - * - * Returns the rooms told. - */ - suspend fun forward(database: GizaDatabase, statement: Event, chatRoomId: String, whenElected: Boolean): List { - val sender = database.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom?.userPublicKey ?: return emptyList() - val members = database.participantDao().findParticipantsByChatRoomId(chatRoomId).map { it.participantPublicKey.lowercase() }.toSet() - - val certificate = guardianCertificateFor(database, statement, chatRoomId) - val targets = targetsFor(database, statement, fromChatRoomId = chatRoomId, withCertificate = certificate != null).filter { target -> - if (!whenElected) return@filter true - val both = database.participantDao().findParticipantsByChatRoomId(target.chatRoom.id) - .map { it.participantPublicKey.lowercase() } - .filter { it in members } - .toSet() + sender.lowercase() - electedSender(both).equals(sender, ignoreCase = true) - } - if (targets.isNotEmpty()) share(database, statement, targets, sender, certificate = certificate) - return targets - } - - /** Every network a guarded wallet can be on: the catch-up forwards them all. */ - private val CHAINS: List = listOf(Chain.Mainnet, Chain.Testnet3, Chain.Testnet4, Chain.Signet, Chain.Regtest) - - /** - * The catch-up: everything [shareableFrom] would list from [chatRoomId], on - * every network, through [forward] without the election -- whatever the - * elected device never sent, whatever arrived while this one was offline, - * and everything filed before forwarding existed. - * `docs/guarded-wallet-forwarding.md`, Phase 4. Run as the group's chat and - * its wallet screen open. Returns how many groups were told. - */ - suspend fun forwardAll(database: GizaDatabase, chatRoomId: String): Int { - if (!GroupWalletRollout.FORWARDS_GUARDED_WALLETS) return 0 - val own = CHAINS.mapNotNull { chain -> - GroupWalletManager.walletFor(database, chatRoomId, chain)?.takeIf { it.account.isGuarded }?.signedEvent?.toEvent() - } - val held = guardedWalletsOf(database, chatRoomId).map { it.statement } - - return (own + held).distinctBy { it.id }.sumOf { statement -> - runCatching { forward(database, statement, chatRoomId, whenElected = false).size } - .onFailure { logger.e("Could not forward ${statement.id.take(8)} from $chatRoomId", it) } - .getOrDefault(0) - } - } - - /** - * [forward] on arrival, from the inbound path: elected, behind - * `GroupWalletRollout.FORWARDS_GUARDED_WALLETS`, and never failing the - * arrival it rides on -- forwarding is an extra, and the arrival is the thing. - */ - suspend fun forwardOnArrival(database: GizaDatabase, statement: Event, chatRoomId: String) { - if (!GroupWalletRollout.FORWARDS_GUARDED_WALLETS) return - runCatching { forward(database, statement, chatRoomId, whenElected = true) } - .onSuccess { told -> if (told.isNotEmpty()) logger.i("Forwarded ${statement.id.take(8)} from $chatRoomId to ${told.size} group(s) above") } - .onFailure { logger.e("Could not forward ${statement.id.take(8)} from $chatRoomId", it) } - } - - /** - * Tells every room in [rooms] about [statement], as [userPublicKey]: one - * notice each, queued for the outbound pipeline the way every inner event - * is. Returns how many were queued. - * - * Each notice names its room in an `h` tag. Without it, one statement told - * to a grandchild's parent and grandparent in the same second is one id -- - * and one row, the last room's -- so the parent was never told. - * - * [certificate], for a member's wallet, is its guardian's birth certificate, - * carried as a tag -- `GuardedWalletNoticeEvent`. - */ - suspend fun share( - database: GizaDatabase, - statement: Event, - rooms: List, - userPublicKey: HexKey, - createdAt: Long = Clock.System.now().epochSeconds, - certificate: Event? = null, - ): Int { - val content = statement.toJson() - - // The sender is never handed its own MLS message back, so the line the - // other members' devices write when it arrives is written here for the - // sender's own -- before the notice, which then finds a line already - // there. docs/guarded-wallet-forwarding.md, D6. - val line = believable(statement)?.let { describe(named(database, it.subject)) } - - rooms.forEach { room -> - val tags = listOfNotNull(arrayOf("h", room.chatRoom.id), certificate?.let(GuardedWalletNoticeEvent::certificateTag)).toTypedArray() - val id = EventHasher.hashId(userPublicKey, createdAt, GuardedWalletNoticeEvent.KIND, tags, content) - line?.takeIf { firstNoticeOf(database, room.chatRoom.id, statement.id, excludingNotice = id) }?.let { - database.chatMessageDao().upsert( - ChatMessage( - giftWrapPayloadId = null, - messageType = ChatMessage.TYPE_GUARDED_WALLET_SHARED, - marmotGroupEventId = null, - marmotInnerEventId = null, - senderPublicKey = userPublicKey, - isUserMessage = true, - chatRoomId = room.chatRoom.id, - createdAt = Instant.fromEpochSeconds(createdAt), - content = it, - ) - ) - } - database.marmotInnerEventDao().upsert( - MarmotInnerEvent( - id = id, - publicKey = userPublicKey, - kind = GuardedWalletNoticeEvent.KIND, - createdAt = Instant.fromEpochSeconds(createdAt), - tags = tags, - content = content, - chatRoomId = room.chatRoom.id, - ) - ) - logger.i("Told ${room.chatRoom.id} about ${statement.pubKey}'s guarded wallet") - } - - return rooms.size - } - - /** Coins of a guarded wallet one of its guardians took, in one transaction. */ - data class Taken( - val txid: TxId, - val guardian: GuardianDerivation.Guardian, - val amount: Satoshi, - ) - - /** - * Which guardians of [account] took which of [coins] in [spending] -- one - * entry per guardian -- read off the witnesses alone. - * - * A guardian's input carries three things: a signature, a leaf, and the - * control block proving the leaf is in the address. The leaf is matched - * against the guardian leaves of the address the coin was at, so a leaf is - * named only by a guardian whose key it is; anything else -- the wallet's own - * key-path spend, a witness of another shape -- names nobody. - */ - fun takenIn( - spending: Transaction, - account: GroupWalletDerivation.Account, - coins: Map>, - ): List { - if (!account.isGuarded) return emptyList() - - return spending.txIn.mapNotNull { input -> - val (txOut, derivation) = coins[input.outPoint] ?: return@mapNotNull null - val stack = input.witness.stack.takeIf { it.size == 3 } ?: return@mapNotNull null - val leaves = GuardianDerivation.leaves(account.guardians, account.chain, account.account, derivation.change, derivation.index) - val position = leaves.indexOfFirst { it.script == stack[1] }.takeIf { it >= 0 } ?: return@mapNotNull null - account.guardians[position] to txOut.amount - } - .groupBy({ it.first }, { it.second }) - .map { (guardian, amounts) -> Taken(spending.txid, guardian, amounts.sum()) } - } - - /** - * Writes a transcript line in [chatRoomId] for each of [taken] it has no line - * for yet. Returns how many it wrote. - * - * The whole of the child's notice that an ancestor spent from its wallet -- - * there is no channel from the ancestor's room into this one -- so it is - * written by whichever device reads the chain first, and every device that - * reads it afterwards finds it already there. - */ - suspend fun recordTaken(database: GizaDatabase, chatRoomId: String, taken: List): Int { - val written = database.chatMessageDao().getChatMessagesByChatRoomId(chatRoomId) - .map { it.chatMessage } - .filter { it.messageType == ChatMessage.TYPE_GUARDIAN_SPEND } - .map { it.content } - - val fresh = taken.filter { spend -> written.none { it.contains(spend.txid.toString()) } } - fresh.forEach { spend -> - val name = database.chatRoomDao().findChatRoomById(spend.guardian.chatRoomId)?.chatRoom?.subject - ?.takeIf { it.isNotBlank() } - ?: "A group above this one" - database.chatMessageDao().upsert( - ChatMessage( - senderPublicKey = spend.guardian.chatRoomId, - isUserMessage = false, - giftWrapPayloadId = null, - marmotGroupEventId = null, - marmotInnerEventId = null, - chatRoomId = chatRoomId, - content = "$name took ${spend.amount.sat} sats from this wallet through its guardian leaf, " + - "in transaction ${spend.txid}.", - messageType = ChatMessage.TYPE_GUARDIAN_SPEND, - ) - ) - logger.i("${spend.guardian.chatRoomId} took ${spend.amount.sat} sats from $chatRoomId's guarded wallet in ${spend.txid}") - } - return fresh.size - } - - /** - * What a notice that arrived in [chatRoomId] says, for its transcript line -- - * or null when it is not one this room can believe, which gets no line: a - * line saying a wallet was shared would read as the group being told - * something it was not. - */ - suspend fun describeNotice(database: GizaDatabase, chatRoomId: String, notice: Event): String? { - val statement = GuardedWalletNoticeEvent.statementOf(notice) ?: return null - val thresholdPublicKey = GroupWalletManager.thresholdKeyFor(database, chatRoomId) ?: return null - val wallet = verify(statement, chatRoomId, thresholdPublicKey) ?: return null - // One line per wallet per group: a second notice of a statement this room - // already holds -- told before, by another forwarder, or signed here -- - // is filed and silent. docs/guarded-wallet-forwarding.md, D6. - if (!firstNoticeOf(database, chatRoomId, statement.id, excludingNotice = notice.id)) return null - - return describe(named(database, wallet).subject) - } - - private fun describe(subject: GuardedSubject): String = when (subject) { - is GuardedSubject.Member -> "Shared @${subject.ownerName ?: subject.ownerPublicKey.take(8)}'s guarded wallet with this group." - is GuardedSubject.Subgroup -> subject.name?.let { "Shared the guarded wallet of $it with this group." } - ?: "Shared a subgroup's guarded wallet with this group." - } - - /** [subject] with its member's profile name, where this device knows one. */ - private suspend fun named(database: GizaDatabase, subject: GuardedSubject): GuardedSubject { - val member = subject as? GuardedSubject.Member ?: return subject - val name = database.profileDao().getProfileByPublicKey(member.ownerPublicKey)?.humanReadableNameOrPubkey() - return member.copy(ownerName = name) - } - - /** - * Whether a notice of [statementId] -- [excludingNotice], the one being - * filed or sent -- is the first [chatRoomId] holds: no other notice in the - * room carries the statement, and the room did not sign it itself. - */ - private suspend fun firstNoticeOf(database: GizaDatabase, chatRoomId: String, statementId: HexKey, excludingNotice: HexKey): Boolean { - if (database.groupSignedEventDao().getById(statementId)?.chatRoomId.equals(chatRoomId, ignoreCase = true)) return false - return database.marmotInnerEventDao() - .getByChatRoomAndKinds(chatRoomId, listOf(GuardedWalletNoticeEvent.KIND)) - .none { it.id != excludingNotice && Event.fromJsonOrNull(it.content)?.id == statementId } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/SubgroupManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/SubgroupManager.kt index 067993eb..ae281054 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/SubgroupManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/SubgroupManager.kt @@ -1,10 +1,6 @@ package mobi.giza.compose.managers import mobi.giza.compose.nostr.frost.GroupKeyStateEvent -import mobi.giza.compose.database.model.subgroupWalletPolicy -import mobi.giza.compose.nostr.subgroup.isDecided -import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy -import mobi.giza.compose.nostr.subgroup.WalletPolicyReading import co.touchlab.kermit.Logger import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey @@ -274,128 +270,11 @@ object SubgroupManager { adminPublicKeys = adminPublicKeys, name = subgroupName, path = path, - guardians = emptyList(), - walletPolicy = null ), content = subgroupChatRoomId ) } - /** - * The guardian keys [chatRoomId]'s own certificate grants it, nearest first: - * empty for a group with no parent, or whose certificate predates guardian - * keys -- either way it grants only its own key onward -- and null when the - * certificate carries keys this build cannot read. - * - * Off the verified key state, which only holds a certificate - * `GroupKeyStateManager.stateFrom` checked. - */ - suspend fun guardiansOf(database: GizaDatabase, chatRoomId: String): List? { - val certificate = database.groupKeyStateDao().getByChatRoomId(chatRoomId) - ?.birthCertificateJson - ?.let { Event.fromJsonOrNull(it) } - ?: return emptyList() - return SubgroupBirthCertificateEvent.parseGuardians(certificate.tags) - } - - /** - * What [chatRoomId]'s own certificate says of its wallet -- - * `docs/subgroup-wallet-policy.md` -- or null for a room with no certificate: - * a root group, or a member who holds no key state for it. - * - * Off the verified key state, like [guardiansOf]. A state whose certificate - * carries a policy that does not read is dropped before it is stored, so a - * certificate held here always reads; if one somehow does not, it is logged - * and read as none rather than guessed at. - * - * The one reader the picker, every parent signer and the wallet screen share, - * so the three cannot disagree about what a group is. - */ - suspend fun walletPolicyOf(database: GizaDatabase, chatRoomId: String): WalletPolicyReading? { - val certificate = database.groupKeyStateDao().getByChatRoomId(chatRoomId) - ?.birthCertificateJson - ?.let { Event.fromJsonOrNull(it) } - ?: return null - return SubgroupBirthCertificateEvent.parseWalletPolicy(certificate.tags) - ?: run { - logger.w("$chatRoomId's certificate carries a wallet policy that does not read") - null - } - } - - /** - * What [parentChatRoomId], signing as [thresholdPublicKey], grants - * [subgroupChatRoomId]: `GuardianDerivation.grant` over the keys its own - * certificate carries. Null when those cannot be read. - */ - suspend fun grantFor( - database: GizaDatabase, - parentChatRoomId: String, - thresholdPublicKey: HexKey, - subgroupChatRoomId: String, - delay: Long = GuardianDerivation.DEFAULT_DELAY - ): List? { - val inherited = guardiansOf(database, parentChatRoomId) ?: return null - return GuardianDerivation.grant(thresholdPublicKey, parentChatRoomId, inherited, subgroupChatRoomId, delay) - } - - /** - * Why [chatRoomId] should not sign a proposed certificate, or null when it - * may: its guardian keys are not the ones the group grants, or its wallet - * policy is not one the group may make. - * - * The check every parent signer makes before agreeing to guard a child, or - * to certify one unguarded. A coordinator who slipped a key of their own into - * the list, dropped an ancestor, or reordered the leaves would be asking the - * group to vouch for a wallet tree it did not make; one who certified an - * unguarded child of a guarded group would be taking a branch out of the - * reach of every group above it. Either way the proposal is refused rather - * than shown. - * - * The group's own policy is read off this device's verified key state, never - * off the proposal. Under a guarded group anything but a guarded certificate - * is refused -- an undecided one included, since an undecided child is - * offered the plain wallet D4 exists to take away. A certificate with no keys - * and no policy from an older proposer grants nothing, and is still signable - * under any other group. See `docs/subgroup-wallet-policy.md`. - */ - suspend fun refuseCertificate( - database: GizaDatabase, - chatRoomId: String, - thresholdPublicKey: HexKey, - certificate: Event - ): String? { - val proposed = SubgroupBirthCertificateEvent.parseGuardians(certificate.tags) - ?: return "carries a guardian key that does not read" - val policy = SubgroupBirthCertificateEvent.parseWalletPolicy(certificate.tags) - ?: return "carries a wallet policy that does not read, or that its keys contradict" - - if (walletPolicyOf(database, chatRoomId).isDecided(SubgroupWalletPolicy.GUARDED) && - !policy.isDecided(SubgroupWalletPolicy.GUARDED) - ) { - return "would make an unguarded subgroup of a guarded group" - } - - // Unguarded, or an older proposer's certificate with no keys: grants - // nothing. Phase 1's read has already refused an unguarded one with keys. - if (proposed.isEmpty()) return null - - val subgroupChatRoomId = SubgroupBirthCertificateEvent.parseSubgroupChatRoomId(certificate.tags) - ?: return "names no subgroup" - // The parent's own leaf's delay is the proposal's -- the coordinator chose - // it, in range, or the tag would not have read -- and everything else is - // recomputed: the keys, their order, and every inherited key's delay, - // which has to be the one this group's own certificate carries. A - // proposer cannot shorten or lengthen an ancestor's wait in the child's - // wallet. docs/guardian-delay.md. - val expected = runCatching { - grantFor(database, chatRoomId, thresholdPublicKey, subgroupChatRoomId, proposed.first().delay) - }.getOrNull() - ?: return "grants keys this device cannot check" - - return if (proposed == expected) null else "grants guardian keys this group does not" - } - /** * The newest certificate by [parentChatRoomId] that actually certifies * [subgroupChatRoomId], or null if this device holds none. @@ -463,9 +342,9 @@ object SubgroupManager { "cannot name a parent yet" ) - // Every other child signer refuses a certificate under another policy, so - // proposing it would only stall a quorum -- see [refuseKeyState]. - refusePolicy(key, certificate.toEvent())?.let { reason -> + // A certificate that commits the child to a wallet is one this device's + // own signers decline -- see [refuseKeyState] -- so it is not proposed. + WalletRefusal.of(certificate.toEvent())?.let { reason -> throw IllegalStateException("$parentChatRoomId's certificate for $subgroupChatRoomId $reason") } @@ -483,38 +362,16 @@ object SubgroupManager { } /** - * Why a child signer should not sign [keyState] under [key], its own - * ceremony, or null when it may: the birth certificate it carries decides a - * wallet policy other than the one the ceremony announced. - * - * Every admin was shown that policy at the join gate, so joining was agreeing - * to it. A certificate proposed later under another -- by a parent admin - * resuming the flow, or one whose device read the parent differently -- would - * be the child signing a decision none of its members agreed to. A ceremony - * that announced none, from an older build, has nothing to hold the - * certificate to. `docs/subgroup-wallet-policy.md`, Phase 5. + * Why a child signer should not sign [keyState], or null when it may: the birth + * certificate it carries commits the subgroup to a wallet -- guardian keys, or a + * policy other than `unguarded`. Giza takes no part in wallets and does not + * join a guarded subgroup's ceremony, so a key state under such a certificate + * is one it declines rather than signs. docs/giza-wallet-removal.md. */ + @Suppress("UNUSED_PARAMETER") fun refuseKeyState(key: DkgSession, keyState: Event): String? { val certificate = GroupKeyStateEvent.parseBirthCertificate(keyState.tags) ?: return null - return refusePolicy(key, certificate) - } - - private fun refusePolicy(key: DkgSession, certificate: Event): String? { - val agreed = key.subgroupWalletPolicy ?: return null - val certified = SubgroupBirthCertificateEvent.parseWalletPolicy(certificate.tags) - if (!certified.isDecided(agreed)) { - return "carries a certificate whose wallet policy is not the one this group was made under ($agreed)" - } - - // And the delay on the parent's own leaf, which the admins were shown - // at the same gate. docs/guardian-delay.md. - val agreedDelay = key.guardianDelay ?: return null - val certifiedDelay = SubgroupBirthCertificateEvent.parseGuardians(certificate.tags)?.firstOrNull()?.delay - return if (certifiedDelay == agreedDelay) { - null - } else { - "carries a certificate whose guardian delay is not the one this group was made under ($agreedDelay blocks)" - } + return WalletRefusal.of(certificate)?.let { "carries a certificate that $it" } } /** @@ -540,21 +397,6 @@ object SubgroupManager { val keyState: GroupKeyState?, ) { /** Whether this device can open the subgroup, rather than only know of it. */ - /** - * What the parent decided about the subgroup's wallet when it certified - * it -- `docs/subgroup-wallet-policy.md`. Founding history like [name]: - * decided once, and never changed by anything after. - */ - val walletPolicy: WalletPolicyReading? - get() = SubgroupBirthCertificateEvent.parseWalletPolicy(certificate.tags) - - /** - * The delay the parent gave its own leaf in the subgroup's wallet, or - * null for a certificate that grants no keys -- `docs/guardian-delay.md`. - */ - val guardianDelay: Long? - get() = SubgroupBirthCertificateEvent.parseGuardians(certificate.tags)?.firstOrNull()?.delay - val isJoined: Boolean get() = room != null } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/WalletRefusal.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/WalletRefusal.kt index 29fad5cd..c8ffbc17 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/WalletRefusal.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/WalletRefusal.kt @@ -2,6 +2,7 @@ package mobi.giza.compose.managers import com.vitorpamplona.quartz.nip01Core.core.Event import mobi.giza.compose.nostr.RetiredKinds +import mobi.giza.compose.nostr.frost.GroupKeyStateEvent import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent /** @@ -51,6 +52,10 @@ object WalletRefusal { event.kind == SubgroupBirthCertificateEvent.KIND && event.tags.any { it.firstOrNull() == WALLET_TAG && it.getOrNull(1) != UNGUARDED } -> "decides a subgroup's wallet" + // A subgroup's key state carries its birth certificate whole, and signing + // the one is agreeing to the other. + event.kind == GroupKeyStateEvent.KIND -> + GroupKeyStateEvent.parseBirthCertificate(event.tags)?.let(::of)?.let { "carries a certificate that $it" } else -> null } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/dkg/DkgRitualEvents.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/dkg/DkgRitualEvents.kt index e6bc60dd..73d3af6d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/dkg/DkgRitualEvents.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/dkg/DkgRitualEvents.kt @@ -1,13 +1,10 @@ package mobi.giza.compose.nostr.dkg -import mobi.giza.compose.nostr.subgroup.tags.GuardianDelayTag import mobi.giza.compose.nostr.dkg.tags.DkgSessionIdTag import mobi.giza.compose.nostr.dkg.tags.DkgThresholdTag import com.vitorpamplona.quartz.nip01Core.core.Kind import com.vitorpamplona.quartz.nip14Subject.SubjectTag -import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy import mobi.giza.compose.nostr.subgroup.tags.SubgroupParentTag -import mobi.giza.compose.nostr.subgroup.tags.WalletPolicyTag /** * The nostr kinds a ChillDKG ritual is carried on. @@ -85,15 +82,11 @@ object DkgRitualEvents { threshold: Int? = null, parentChatRoomId: String? = null, subject: String? = null, - walletPolicy: SubgroupWalletPolicy? = null, - guardianDelay: Long? = null ): Array> = buildList { add(DkgSessionIdTag.assemble(sessionId)) threshold?.let { add(DkgThresholdTag.assemble(it)) } parentChatRoomId?.let { add(SubgroupParentTag.assemble(it)) } subject?.ifBlank { null }?.let { add(SubjectTag.assemble(it)) } - walletPolicy?.let { add(WalletPolicyTag.assemble(it)) } - guardianDelay?.let { add(GuardianDelayTag.assemble(it)) } }.toTypedArray() fun parseSessionId(tags: Array>): String? = @@ -138,24 +131,14 @@ object DkgRitualEvents { tags.firstNotNullOfOrNull(SubjectTag::parse) /** - * The wallet policy the coordinator chose for the subgroup this ceremony - * makes -- `docs/subgroup-wallet-policy.md`. - * - * Authenticates nothing, as [parseParentChatRoomId] does not: it is what the - * admins are shown before they join, and what the certificate is later - * proposed under. Absent for an ordinary ceremony and for one from an older - * build; unreadable is told apart from absent, because a proposal whose - * policy cannot be read is not one to join on the assumption it has none. + * The `wallet` tag a Bennu coordinator put on a subgroup's ceremony -- what + * that subgroup's wallet is to be -- as written, or null for none. Giza + * writes none and decides nothing on it but one thing: it does not join a + * ceremony for a subgroup whose wallet is to be guarded (W5, + * docs/giza-wallet-removal.md). Authenticates nothing. */ - fun parseWalletPolicy(tags: Array>): WalletPolicyTag.Result = - WalletPolicyTag.parseOne(tags) + fun parseWalletPolicy(tags: Array>): String? = + tags.firstOrNull { it.size > 1 && it[0] == WALLET_TAG }?.get(1) - /** - * The delay the coordinator chose for the parent's own leaf, beside a - * guarded policy -- `docs/guardian-delay.md`. Authenticates nothing, as the - * policy does not: it is what the admins are shown, and what the certificate - * is proposed under. - */ - fun parseGuardianDelay(tags: Array>): GuardianDelayTag.Result = - GuardianDelayTag.parseOne(tags) + private const val WALLET_TAG = "wallet" } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/FrostSigningEvents.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/FrostSigningEvents.kt index dec58a01..575a9dda 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/FrostSigningEvents.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/frost/FrostSigningEvents.kt @@ -102,18 +102,11 @@ object FrostSigningEvents { val DECLINE: Kind = 30330 /** - * Opens a session over a transaction from the group's wallet. Content is the - * PSBT, base64; the key is named in [FrostKeyTag] as for [PROPOSAL], and the - * wallet in a `chain` and an `account` tag -- which pick the room's statement - * to check against, and nothing more. - * - * A kind of its own rather than a PSBT inside a [PROPOSAL]. A build that does - * not know this kind does not route it, so an old device never signs a - * transaction it cannot show its owner: it is a member who did not sign, and - * a quorum without them still can. Every message after the proposal is the - * kinds above, unchanged, with one value per input. - * - * 30332 because 30331 is the wallet statement it is opened against. + * A Bennu peer's session over a transaction or a sweep from the group's + * wallet. Giza proposes none and signs none: it is routed only so that it can + * be declined out loud, which the group counts, rather than ignored, which it + * cannot tell from a phone in a pocket (docs/giza-wallet-removal.md). The + * number is Bennu's and stays retired -- see `RetiredKinds`. */ val TRANSACTION_PROPOSAL: Kind = 30332 @@ -152,50 +145,11 @@ object FrostSigningEvents { silentMembers?.takeIf { it.isNotEmpty() }?.let { add(FrostSilentMembersTag.assemble(it)) } }.toTypedArray() - /** Whether [kind] opens a session -- over events or over a transaction. */ + /** Whether [kind] opens a session: over events, or a Bennu peer's over a transaction. */ fun isProposal(kind: Kind): Boolean = kind == PROPOSAL || kind == TRANSACTION_PROPOSAL - private const val CHAIN_TAG = "chain" - private const val ACCOUNT_TAG = "account" - - /** The wallet a [TRANSACTION_PROPOSAL] spends from, as tags. */ - fun walletTags(chain: String, account: Long): Array> = - arrayOf(arrayOf(CHAIN_TAG, chain), arrayOf(ACCOUNT_TAG, account.toString())) - - private const val SWEEP_TAG = "sweep" - - /** - * The tags of a [TRANSACTION_PROPOSAL] that is a sweep from the Lightning wallet [lightningWallet] into - * the onchain wallet: the wallet's tags, and which Lightning wallet the outputs are from. - */ - fun sweepTags(chain: String, account: Long, lightningWallet: Long): Array> = - walletTags(chain, account) + arrayOf(arrayOf(SWEEP_TAG, lightningWallet.toString())) - - /** The Lightning wallet a sweep proposal sweeps from, or null for an ordinary spend. */ - fun parseSweep(tags: Array>): Long? = - tags.firstOrNull { it.size >= 2 && it[0] == SWEEP_TAG }?.get(1)?.toLongOrNull() - - /** The network and account a [TRANSACTION_PROPOSAL] names, or null when it names either badly. */ - fun parseWallet(tags: Array>): Pair? { - val chain = tags.firstOrNull { it.size >= 2 && it[0] == CHAIN_TAG }?.get(1) ?: return null - val account = tags.firstOrNull { it.size >= 2 && it[0] == ACCOUNT_TAG }?.get(1)?.toLongOrNull() ?: return null - return chain to account - } - - private const val GUARDED_TAG = "guarded" - - /** - * On a [TRANSACTION_PROPOSAL] from an ancestor's room: the descendant whose - * guarded wallet it spends from, through the room's guardian leaf. Absent - * for a spend from the room's own wallet. Which wallet it is is all this - * says; every signer then reads that wallet from the statement its own room - * was told, never from the proposal. - */ - fun guardedTags(descendantChatRoomId: String): Array> = arrayOf(arrayOf(GUARDED_TAG, descendantChatRoomId)) - - /** The descendant a guardian's [TRANSACTION_PROPOSAL] names, or null for the room's own wallet. */ - fun parseGuarded(tags: Array>): String? = - tags.firstOrNull { it.size >= 2 && it[0] == GUARDED_TAG }?.get(1)?.takeIf { it.isNotBlank() } + /** Whether a [TRANSACTION_PROPOSAL] is a sweep from a Lightning wallet, by its `sweep` tag. */ + fun isSweep(tags: Array>): Boolean = tags.any { it.size >= 2 && it[0] == "sweep" } fun parseSessionId(tags: Array>): String? = tags.firstNotNullOfOrNull(FrostSessionIdTag::parse)?.sessionId diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/subgroup/SubgroupBirthCertificateEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/subgroup/SubgroupBirthCertificateEvent.kt index 08568309..ad7cad7d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/subgroup/SubgroupBirthCertificateEvent.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/subgroup/SubgroupBirthCertificateEvent.kt @@ -5,14 +5,11 @@ import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.core.Kind import com.vitorpamplona.quartz.nip01Core.tags.dTag.DTag import com.vitorpamplona.quartz.nip01Core.tags.people.PTag -import mobi.giza.compose.managers.GuardianDerivation import mobi.giza.compose.managers.SharedKeyDerivation import mobi.giza.compose.nostr.frost.GroupKeyStateEvent import mobi.giza.compose.nostr.frost.tags.FrostDerivationPathTag -import mobi.giza.compose.nostr.subgroup.tags.GuardianTag import mobi.giza.compose.nostr.subgroup.tags.SubgroupKeyTag import mobi.giza.compose.nostr.subgroup.tags.SubgroupParentTag -import mobi.giza.compose.nostr.subgroup.tags.WalletPolicyTag /** * A group saying, with a quorum, that another group is its child. @@ -53,27 +50,14 @@ import mobi.giza.compose.nostr.subgroup.tags.WalletPolicyTag * can check `marmotGroupId(key, path) == content` for itself, which is the * difference between approving a hash and approving a group. * - * ### Guardian keys + * ### Wallet tags * - * A certificate may also carry [GuardianTag]s: the parent's own guardian key for - * this child, and behind it every key the parent's ancestors granted the parent, - * each one public step further -- `GuardianDerivation.grant`. Carrying them is - * the parent agreeing to guard the child's wallet, if the child ever opens a - * guarded one; it delegates nothing on its own. They are not among the checks in - * [certifies], which is about lineage. Whether they are the keys the parent - * grants is checked by every parent signer before the certificate is signed -- - * `SubgroupManager.refuseCertificate` -- and nowhere after, because nobody else holds - * the key that check needs and nobody else needs it: the parent's quorum can - * already spend through its own leaf whatever the others would let it. - * - * ### The wallet policy - * - * A certificate may carry a [WalletPolicyTag]: the parent deciding whether the - * child's wallet is guarded or unguarded, rather than leaving it to the child -- - * `docs/subgroup-wallet-policy.md`. A guarded certificate carries the guardian - * keys and an unguarded one carries none, and [parseWalletPolicy] refuses one - * whose policy and keys disagree. Like the keys, the policy is not among the - * checks in [certifies]: it is read where it is used. + * A Bennu parent may also put guardian keys and a wallet policy on a certificate + * (`guardian`, `wallet`). Giza writes neither and reads neither: they are not + * among the checks in [certifies], which is about lineage, and a certificate + * that carries them still certifies. Giza declines to sign one that carries them + * -- `WalletRefusal` -- and does not offer a subgroup under a parent whose own + * certificate says `wallet=guarded`. docs/giza-wallet-removal.md. * * ### What [certifies] deliberately does not check * @@ -121,52 +105,13 @@ object SubgroupBirthCertificateEvent { adminPublicKeys: List, name: String, path: List = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH, - guardians: List = emptyList(), - walletPolicy: SubgroupWalletPolicy? = null ): Array> = arrayOf( DTag.assemble(subgroupChatRoomId), SubgroupParentTag.assemble(parentChatRoomId), SubgroupKeyTag.assemble(thresholdPublicKey), FrostDerivationPathTag.assemble(path), arrayOf(NAME_TAG_NAME, name) - ) + adminPublicKeys.distinct().map { PTag.assemble(it, null) } + - guardians.map(GuardianTag::assemble) + - listOfNotNull(walletPolicy?.let(WalletPolicyTag::assemble)) - - /** - * What the certificate says about the child's wallet: [WalletPolicyReading.Undecided] - * when it carries no policy, as every certificate from before policies does, - * and null when the reading cannot be used -- - * - * - a `wallet` tag that does not read, or two of them; - * - guardian keys that do not read; - * - a policy that contradicts the keys beside it: `guarded` with none, or - * `unguarded` with some. - * - * A certificate that says one thing in its policy and another in its keys is - * not a thing to guess the meaning of, and a policy present and unreadable - * must never read as absent -- that would hand the child the choice the - * parent took away. - */ - fun parseWalletPolicy(tags: Array>): WalletPolicyReading? { - val guardians = parseGuardians(tags) ?: return null - return when (val tag = WalletPolicyTag.parseOne(tags)) { - WalletPolicyTag.Result.Absent -> WalletPolicyReading.Undecided - WalletPolicyTag.Result.Unreadable -> null - is WalletPolicyTag.Result.Present -> when (tag.policy) { - SubgroupWalletPolicy.GUARDED -> WalletPolicyReading.Decided(tag.policy).takeIf { guardians.isNotEmpty() } - SubgroupWalletPolicy.UNGUARDED -> WalletPolicyReading.Decided(tag.policy).takeIf { guardians.isEmpty() } - } - } - } - - /** - * The guardian keys the parent grants the child, nearest first -- empty for a - * certificate that carries none, and null when one is unreadable, so that a - * list with an entry quietly dropped is never mistaken for the list. - */ - fun parseGuardians(tags: Array>): List? = - GuardianTag.parseAll(tags) + ) + adminPublicKeys.distinct().map { PTag.assemble(it, null) } /** The child this certificate is about, or null if it names none. */ fun parseSubgroupChatRoomId(tags: Array>): String? = diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/subgroup/SubgroupWalletPolicy.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/subgroup/SubgroupWalletPolicy.kt deleted file mode 100644 index 35bae1b2..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/subgroup/SubgroupWalletPolicy.kt +++ /dev/null @@ -1,60 +0,0 @@ -package mobi.giza.compose.nostr.subgroup - -/** - * What a parent decided, at a subgroup's birth, about the subgroup's wallet -- - * `docs/subgroup-wallet-policy.md`. - * - * Chosen by the coordinator on the subgroup picker, carried on the ceremony - * proposal so every admin sees it before joining, and signed by the parent's - * quorum into the birth certificate. Every honest device then offers, signs, - * derives and watches only the wallet it allows. - * - * Not a rule the chain enforces: the child's key is the child's, and a quorum of - * modified clients can sign whatever it likes with it. It is the parent's signed - * decision, which every client running this app keeps. - */ -enum class SubgroupWalletPolicy(val tagValue: String) { - /** - * The child can only open a guarded wallet, and its certificate carries the - * guardian keys that wallet's leaves are built from. A guarded group's own - * subgroups are guarded too. - */ - GUARDED("guarded"), - - /** - * The child can only open a plain wallet. Its certificate carries no guardian - * keys, so nothing above it can reach its wallet or anything beneath it. - */ - UNGUARDED("unguarded"); - - companion object { - fun fromTagValue(value: String): SubgroupWalletPolicy? = entries.firstOrNull { it.tagValue == value } - } -} - -/** What a birth certificate says about the child's wallet. */ -sealed interface WalletPolicyReading { - /** The parent decided, and signed it. */ - data class Decided(val policy: SubgroupWalletPolicy) : WalletPolicyReading - - /** - * No policy tag: a certificate from before policies, which leaves the choice - * to the child -- a guarded wallet if its certificate carries keys, a plain - * one beside it either way. - */ - data object Undecided : WalletPolicyReading -} - -/** Whether this reading is the parent having decided [policy]. */ -fun WalletPolicyReading?.isDecided(policy: SubgroupWalletPolicy): Boolean = - (this as? WalletPolicyReading.Decided)?.policy == policy - -/** - * Whether a wallet that is [guarded] -- or plain, when false -- is one this - * reading allows: a decided policy allows its own kind only, and an undecided - * or absent one allows either, as before policies. - */ -fun WalletPolicyReading?.allows(guarded: Boolean): Boolean = when (this) { - is WalletPolicyReading.Decided -> guarded == (policy == SubgroupWalletPolicy.GUARDED) - WalletPolicyReading.Undecided, null -> true -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/subgroup/tags/GuardianDelayTag.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/subgroup/tags/GuardianDelayTag.kt deleted file mode 100644 index 9adca41e..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/subgroup/tags/GuardianDelayTag.kt +++ /dev/null @@ -1,44 +0,0 @@ -package mobi.giza.compose.nostr.subgroup.tags - -import mobi.giza.compose.managers.GuardianDerivation - -/** - * The delay a coordinator chose for the parent's own leaf in a guarded - * subgroup's wallet, on the subgroup's ceremony proposal: - * - * ``` - * ["guardian_delay", ""] - * ``` - * - * Shown to every admin at the join gate, and what the certificate is later - * proposed under. Beside `["wallet", "guarded"]` and nowhere else. See - * `docs/guardian-delay.md`. - * - * Shape and range only. Whether it is the delay the certificate carries is the - * child signers' question, asked of the certificate. - */ -object GuardianDelayTag { - const val TAG_NAME = "guardian_delay" - - fun assemble(delay: Long): Array = arrayOf(TAG_NAME, delay.toString()) - - /** - * The delay [tags] carry: [Result.Absent] for none, the delay for exactly one - * that reads and is in `GuardianDerivation.DELAY_RANGE`, and - * [Result.Unreadable] otherwise -- a delay present and unusable is never - * mistaken for one absent. - */ - fun parseOne(tags: Array>): Result { - val named = tags.filter { it.isNotEmpty() && it[0] == TAG_NAME } - if (named.isEmpty()) return Result.Absent - if (named.size > 1) return Result.Unreadable - val delay = named.single().getOrNull(1)?.toLongOrNull()?.takeIf { it in GuardianDerivation.DELAY_RANGE } - return delay?.let { Result.Present(it) } ?: Result.Unreadable - } - - sealed interface Result { - data object Absent : Result - data object Unreadable : Result - data class Present(val delay: Long) : Result - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/subgroup/tags/GuardianTag.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/subgroup/tags/GuardianTag.kt deleted file mode 100644 index 375dbc4f..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/subgroup/tags/GuardianTag.kt +++ /dev/null @@ -1,71 +0,0 @@ -package mobi.giza.compose.nostr.subgroup.tags - -import mobi.giza.compose.managers.GuardianDerivation -import com.vitorpamplona.quartz.nip01Core.core.has -import com.vitorpamplona.quartz.utils.ensure -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.PublicKey - -/** - * One ancestor's guardian key, as granted to the group a statement is about: - * - * ``` - * ["guardian", , <33-byte key hex>, <32-byte chain code hex>, ] - * ``` - * - * On a birth certificate it is the parent agreeing to guard the child -- its - * own key and every key its own ancestors gave it, one step further each, in - * that order -- and on a guarded wallet statement it is the child agreeing to be - * guarded by exactly those keys. See `GuardianDerivation` and - * `docs/group-wallet-guardians.md`. - * - * Shape only, as `SubgroupKeyTag` is. Whether a key is the one the ancestor - * actually grants is settled by rederiving it, never by looking at it. - */ -object GuardianTag { - const val TAG_NAME = "guardian" - - private val ROOM_ID = Regex("^[0-9a-f]{64}$") - private val KEY = Regex("^0[23][0-9a-f]{64}$") - private val CHAIN_CODE = Regex("^[0-9a-f]{64}$") - - fun assemble(guardian: GuardianDerivation.Guardian): Array = arrayOf( - TAG_NAME, - guardian.chatRoomId.lowercase(), - guardian.publicKey.toString(), - guardian.chainCode.toHex(), - guardian.delay.toString(), - ) - - /** The guardian [tag] names, or null when it is not a guardian tag or any of its fields is the wrong shape. */ - fun parse(tag: Array): GuardianDerivation.Guardian? { - ensure(tag.has(4)) { return null } - ensure(tag[0] == TAG_NAME) { return null } - ensure(ROOM_ID.matches(tag[1])) { return null } - ensure(KEY.matches(tag[2])) { return null } - ensure(CHAIN_CODE.matches(tag[3])) { return null } - // Within the range a leaf may carry, so a delay a modified client wrote - // below the floor is a tag that does not read, rather than a leaf that - // lets a guardian race the child. Every tag before this said 12. - val delay = tag[4].toLongOrNull()?.takeIf { it in GuardianDerivation.DELAY_RANGE } ?: return null - - val publicKey = runCatching { PublicKey.fromHex(tag[2]) }.getOrNull()?.takeIf { it.isValid() } ?: return null - return GuardianDerivation.Guardian( - chatRoomId = tag[1], - publicKey = publicKey, - chainCode = ByteVector32(tag[3]), - delay = delay, - ) - } - - /** - * Every guardian in [tags], in order -- or null when any tag *named* - * `guardian` fails to read. A list with one entry quietly dropped is a - * different list, and the order is the tree. - */ - fun parseAll(tags: Array>): List? { - val named = tags.filter { it.isNotEmpty() && it[0] == TAG_NAME } - val parsed = named.mapNotNull(::parse) - return parsed.takeIf { it.size == named.size } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/subgroup/tags/WalletPolicyTag.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/subgroup/tags/WalletPolicyTag.kt deleted file mode 100644 index fdca987f..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/subgroup/tags/WalletPolicyTag.kt +++ /dev/null @@ -1,49 +0,0 @@ -package mobi.giza.compose.nostr.subgroup.tags - -import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy - -/** - * A subgroup's wallet policy, as its parent decided it: - * - * ``` - * ["wallet", "guarded" | "unguarded"] - * ``` - * - * On a key ceremony's proposal it is what the coordinator chose, shown to every - * admin before they join; on a birth certificate it is the parent's quorum - * signing that choice. See `SubgroupWalletPolicy` and - * `docs/subgroup-wallet-policy.md`. - * - * Shape only, as `GuardianTag` is. Whether a policy agrees with the guardian - * keys beside it is the certificate's question, not the tag's. - */ -object WalletPolicyTag { - const val TAG_NAME = "wallet" - - fun assemble(policy: SubgroupWalletPolicy): Array = arrayOf(TAG_NAME, policy.tagValue) - - /** The policy [tag] names, or null when it is not a wallet tag or names no policy this build knows. */ - fun parse(tag: Array): SubgroupWalletPolicy? { - if (tag.size < 2 || tag[0] != TAG_NAME) return null - return SubgroupWalletPolicy.fromTagValue(tag[1]) - } - - /** - * The policy [tags] carry: null for none, the policy for exactly one readable - * tag -- and [Unreadable] when a tag *named* `wallet` fails to read or there - * are two, so that a policy present and unreadable is never mistaken for one - * absent. - */ - fun parseOne(tags: Array>): Result { - val named = tags.filter { it.isNotEmpty() && it[0] == TAG_NAME } - if (named.isEmpty()) return Result.Absent - if (named.size > 1) return Result.Unreadable - return parse(named.single())?.let { Result.Present(it) } ?: Result.Unreadable - } - - sealed interface Result { - data object Absent : Result - data object Unreadable : Result - data class Present(val policy: SubgroupWalletPolicy) : Result - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/wallet/GroupWallet.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/wallet/GroupWallet.kt deleted file mode 100644 index 4ab43202..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/wallet/GroupWallet.kt +++ /dev/null @@ -1,94 +0,0 @@ -package mobi.giza.compose.nostr.wallet - -import mobi.giza.compose.nostr.subgroup.allows -import mobi.giza.compose.nostr.subgroup.WalletPolicyReading -import mobi.giza.compose.database.model.GroupSignedEvent -import mobi.giza.compose.managers.GroupWalletDerivation -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.Chain -import kotlin.time.Instant - -/** - * A wallet the group has opened: its statement, and the account that statement - * rederives to. - * - * There is no table. A wallet is a signed event plus a derivation, and every - * address, every balance and every check below is recomputed from the room's - * threshold key -- [account] is what [GroupWalletStatementEvent.Reading.verifiedAgainst] - * returned, never what the statement said. - * - * Read off [GroupSignedEvent] and gated on [GroupSignedEvent.verifies]: only an - * event the room itself authored is the group speaking. - */ -data class GroupWallet( - val signedEvent: GroupSignedEvent, - val account: GroupWalletDerivation.Account, -) { - val chain: Chain get() = account.chain - - /** When the group opened it. */ - val openedAt: Instant get() = signedEvent.createdAt - - companion object { - /** - * The wallet one signed event opens, or null when it does not open one. - * - * Four refusals: the wrong kind, a signature that is not the room's, tags - * that do not read as a statement, and a statement [thresholdPublicKey] - * does not rederive. - */ - fun of(signedEvent: GroupSignedEvent, thresholdPublicKey: HexKey): GroupWallet? { - if (signedEvent.kind != GroupWalletStatementEvent.KIND) return null - if (!signedEvent.verifies()) return null - - val account = GroupWalletStatementEvent.read(signedEvent.tags, signedEvent.content) - ?.verifiedAgainst(thresholdPublicKey) - ?: return null - - return GroupWallet(signedEvent = signedEvent, account = account) - } - - /** - * The newest wallet the group opened on [chain] at [account], or null for - * one it never has. - * - * Newest by the group's own timestamp with the id breaking a tie, because - * two devices reading the same events in different orders have to agree. - * - * Two rules first, for a guarded account, each of which keeps a later - * statement from moving every address of one already holding coins: - * - * 1. a guarded statement outranks a plain one -- an account opened guarded - * stays guarded, whatever a client that predates guardians signs later; - * 2. among guarded ones the earliest decides the guardians, and a later one - * naming others is ignored. Changing who guards a wallet is another - * account. - * - * And before either, a statement [policy] does not allow is no wallet at - * all -- `docs/subgroup-wallet-policy.md`. Under a parent that decided - * *guarded* a plain statement is ignored even with no guarded one beside - * it, which is stronger than rule 1: an older client's plain wallet then - * opens nothing on this device, no addresses derived and no coins - * watched, rather than a wallet the rest of the group refuses to spend. - */ - fun newestAmong( - signedEvents: List, - thresholdPublicKey: HexKey, - chain: Chain, - account: Long = 0L, - policy: WalletPolicyReading? = null, - ): GroupWallet? { - val order = compareBy({ it.openedAt }, { it.signedEvent.id }) - val opened = signedEvents - .mapNotNull { of(it, thresholdPublicKey) } - .filter { it.chain == chain && it.account.account == account } - .filter { policy.allows(it.account.isGuarded) } - - val guarded = opened.filter { it.account.isGuarded } - val first = guarded.minWithOrNull(order) - ?: return opened.maxWithOrNull(order) - - return guarded.filter { it.account.guardians == first.account.guardians }.maxWithOrNull(order) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/wallet/GroupWalletStatementEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/wallet/GroupWalletStatementEvent.kt deleted file mode 100644 index f128a72c..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/wallet/GroupWalletStatementEvent.kt +++ /dev/null @@ -1,204 +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.SharedKeyDerivation -import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent -import mobi.giza.compose.nostr.subgroup.tags.GuardianTag -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 -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import fr.acinq.bitcoin.Chain -import kotlin.time.Clock - -/** - * The group saying it keeps coins on chain, at one account on one network. - * - * Every room with a key *could* receive coins without this -- the addresses are a - * function of the threshold key -- and that is the wrong default for money. A - * member should not be able to show an address the group never agreed to look - * after, and somebody paying one deserves to know the group said so. So a wallet - * exists when a quorum has signed one of these, and not before. - * - * ``` - * member --[ 30320 proposal over a 30331 ]-> the room - * ...a signing session... - * everyone holds the signed 30331 "the group keeps a wallet at this account" - * ``` - * - * ### Trusted no further than it can be checked - * - * Content is the account's xpub; the tags carry the network, the account number - * and the two descriptors. A reader accepts a statement only when the room signed - * it *and* [GroupWalletDerivation.account] rederives every one of those values - * from the room's threshold key -- the same two checks `GroupKeyStateEvent` asks - * of a key state. The second is the load-bearing one. This is a record that the - * group agreed, not a source of keys: nothing reads an address out of it, and a - * statement naming any xpub but the rederived one is not the group's wallet, - * whoever signed it. - * - * ### A guarded statement - * - * A subgroup whose birth certificate grants it guardian keys may open its wallet - * *guarded*: every address carries a leaf per ancestor, and the statement is the - * child's quorum agreeing to that. It carries the guardians as [GuardianTag]s - * and the certificate itself, whole, so that a member who holds no key state -- - * one welcomed in after the founding -- can still check every address, and so - * that an ancestor it is forwarded to can check where its own key came from. - * See `docs/group-wallet-guardians.md`. - * - * ### Never on a relay - * - * The xpub is every address and the whole balance, to whoever has it. Like the - * signing kinds this only ever lives inside an encryption a relay cannot open, - * and nothing in the app sends a group-signed event to a relay. - * - * ### Why 30331 - * - * Next to the signing family in the app's private inner-event space. 30327-30330 - * were taken by the chronicle, its request, the subgroup certificate and the - * decline (the last also shared with the direct-message envelope), so this is the - * first free number past them, and the transaction proposal that is opened - * against it sits beside it at 30332. - */ -object GroupWalletStatementEvent { - val KIND: Kind = 30331 - - private const val D_TAG = "d" - private const val CHAIN_TAG = "chain" - private const val ACCOUNT_TAG = "account" - private const val DESCRIPTOR_TAG = "descriptor" - private const val RECEIVE_MARKER = "receive" - private const val CHANGE_MARKER = "change" - - /** - * What a statement says, read but not yet believed. [verifiedAgainst] is what - * turns it into a wallet. - */ - data class Reading( - val chain: Chain, - val account: Long, - val xpub: String, - val receiveDescriptor: String, - val changeDescriptor: String, - /** The guardians it names, nearest first; empty for a plain statement. */ - val guardians: List = emptyList(), - /** The birth certificate a guarded statement carries, unverified. */ - val certificate: Event? = null, - ) { - /** - * The account this statement describes, if [thresholdPublicKey] rederives - * every value it carries; null otherwise. - * - * For a guarded one, also: the certificate certifies the room the key - * makes, it names that key, and its guardian keys are exactly the ones - * the statement names -- the guardians come from the parent's signature - * and the child's agreement together, or the statement opens nothing. - */ - fun verifiedAgainst(thresholdPublicKey: HexKey): GroupWalletDerivation.Account? { - if (guardians.isNotEmpty() && !guardiansCheckOut(thresholdPublicKey)) return null - - val account = runCatching { GroupWalletDerivation.account(thresholdPublicKey, chain, account, guardians) } - .getOrNull() - ?: return null - - return account.takeIf { - it.xpub == xpub && - it.receiveDescriptor == receiveDescriptor && - it.changeDescriptor == changeDescriptor - } - } - - private fun guardiansCheckOut(thresholdPublicKey: HexKey): Boolean = runCatching { - val certificate = certificate ?: return false - val chatRoomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) - val parentChatRoomId = SubgroupBirthCertificateEvent.parseParentChatRoomId(certificate.tags) ?: return false - - SubgroupBirthCertificateEvent.certifies(certificate, chatRoomId, parentChatRoomId) && - SubgroupBirthCertificateEvent.parseThresholdPublicKey(certificate.tags).equals(thresholdPublicKey, ignoreCase = true) && - SubgroupBirthCertificateEvent.parseGuardians(certificate.tags) == guardians - }.getOrDefault(false) - } - - /** - * The `d` tag: one statement per network and account, the newest winning, so a - * group that signs a second one for the same account replaces rather than adds. - */ - fun identifier(chain: Chain, account: Long): String = "${chainName(chain)}:$account" - - /** - * The statement opening [account]. A guarded account needs the [certificate] - * its guardians were granted in, which the statement carries whole. - */ - fun template( - account: GroupWalletDerivation.Account, - certificate: Event? = null, - createdAt: Long = Clock.System.now().epochSeconds, - ): EventTemplate<*> { - require(!account.isGuarded || certificate != null) { "a guarded wallet's statement carries the certificate that granted its guardians" } - - val guarded = if (account.isGuarded) { - account.guardians.map(GuardianTag::assemble) + listOf(SubgroupBirthCertificateTag.assemble(certificate!!)) - } else { - emptyList() - } - - return EventTemplate( - createdAt = createdAt, - kind = KIND, - tags = arrayOf( - arrayOf(D_TAG, identifier(account.chain, account.account)), - arrayOf(CHAIN_TAG, chainName(account.chain)), - arrayOf(ACCOUNT_TAG, account.account.toString()), - arrayOf(DESCRIPTOR_TAG, account.receiveDescriptor, RECEIVE_MARKER), - arrayOf(DESCRIPTOR_TAG, account.changeDescriptor, CHANGE_MARKER), - ) + guarded, - content = account.xpub, - ) - } - - /** The statement's fields, or null when any is missing or unreadable. Nothing is verified here. */ - fun read(tags: Array>, content: String): Reading? { - fun value(name: String): String? = tags.firstOrNull { it.size >= 2 && it[0] == name }?.get(1) - fun descriptor(marker: String): String? = - tags.firstOrNull { it.size >= 3 && it[0] == DESCRIPTOR_TAG && it[2] == marker }?.get(1) - - val chain = value(CHAIN_TAG)?.let(::chainNamed) ?: return null - val account = value(ACCOUNT_TAG)?.toLongOrNull() ?: return null - val receive = descriptor(RECEIVE_MARKER) ?: return null - val change = descriptor(CHANGE_MARKER) ?: return null - if (content.isBlank()) return null - // A `d` tag that disagrees with the fields would let two statements for one - // account both stand; reading it back here keeps "newest per account" one rule. - if (value(D_TAG) != identifier(chain, account)) return null - - // Guardians that do not all read are not a shorter list of guardians. - val guardians = GuardianTag.parseAll(tags) ?: return null - val certificate = tags.firstNotNullOfOrNull(SubgroupBirthCertificateTag::parse)?.certificate - - return Reading(chain, account, content, receive, change, guardians, certificate) - } - - /** - * Lower-case names, written into a tag. Spelled out rather than taken from - * [Chain.name], whose capitalisation is the library's to change. - */ - fun chainName(chain: Chain): String = when (chain) { - Chain.Mainnet -> "mainnet" - Chain.Testnet3 -> "testnet3" - Chain.Testnet4 -> "testnet4" - Chain.Signet -> "signet" - Chain.Regtest -> "regtest" - } - - fun chainNamed(name: String): Chain? = when (name) { - "mainnet" -> Chain.Mainnet - "testnet3" -> Chain.Testnet3 - "testnet4" -> Chain.Testnet4 - "signet" -> Chain.Signet - "regtest" -> Chain.Regtest - else -> null - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/wallet/GuardedWalletNoticeEvent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/wallet/GuardedWalletNoticeEvent.kt deleted file mode 100644 index b411d7c1..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/wallet/GuardedWalletNoticeEvent.kt +++ /dev/null @@ -1,76 +0,0 @@ -package mobi.giza.compose.nostr.wallet - -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.Kind - -/** - * A member telling an ancestor group about a descendant's guarded wallet. - * - * The descendant's quorum signed a guarded `GroupWalletStatementEvent` in its - * own room, and the ancestors whose keys are in it are not in that room. A - * member who sits in both carries the statement across, whole, as the content of - * one of these in the ancestor's MLS room: - * - * ``` - * descendant's room every member holds the signed 30331 "we keep a guarded wallet" - * member in both --[ 30333 carrying it ]-> the ancestor's room - * every ancestor device checks it on its own, and watches the wallet - * ``` - * - * The forwarder vouches for nothing. A device believes the statement inside for - * the same reasons a descendant member does -- the descendant's room signed it, - * a certificate it carries certifies that room, the xpub rederives from the key - * the certificate names -- plus one of its own: its own guardian key in the - * statement is the key its group's walk reaches. See `GuardianManager.verify`. - * - * No table: the row the inbound path files for every inner event is the record, - * and each read checks it again. - * - * ### The guardian's birth certificate - * - * A notice carrying a member's wallet certificate (30334) also carries, where - * the forwarder holds it, the birth certificate of the group that signed it -- - * the 30329 its own parent signed: - * - * ``` - * kind: 30333 - * content: - * tags: - * ["h", ] - * ["certificate", ] - * ``` - * - * It is what lets a device in a group above, never in the guarding group's - * room, show the wallet under that group's founding name. It is a tag so an - * older build, which reads the content and nothing else, still believes the - * wallet; and it is checked rather than trusted, as everything here is -- a - * certificate that does not certify that group is ignored, and the wallet is - * believed all the same. `docs/member-wallet-guarding-group.md`, D4. - * - * ### Never on a relay - * - * The statement inside is an xpub, which is every address and the whole - * balance. Like the statement, this only ever lives inside an encryption a relay - * cannot open: it is an MLS application message and nothing else. - * - * ### Why 30333 - * - * The first free number past the transaction proposal (30332), beside the - * statement it carries. - */ -object GuardedWalletNoticeEvent { - val KIND: Kind = 30333 - - const val CERTIFICATE_TAG = "certificate" - - /** The statement a notice carries, or null when its content is not an event. Nothing is verified here. */ - fun statementOf(notice: Event): Event? = - notice.takeIf { it.kind == KIND }?.let { Event.fromJsonOrNull(it.content) } - - /** The guardian's birth certificate a notice's [tags] carry, or null. Nothing is verified here. */ - fun certificateIn(tags: Array>): Event? = - tags.firstOrNull { it.size >= 2 && it[0] == CERTIFICATE_TAG }?.let { Event.fromJsonOrNull(it[1]) } - - /** The tag carrying [certificate]. */ - fun certificateTag(certificate: Event): Array = arrayOf(CERTIFICATE_TAG, certificate.toJson()) -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt index ce7a228d..5b87e2d8 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -1,12 +1,5 @@ package mobi.giza.compose.repository -import mobi.giza.compose.managers.GuardianDerivation -import mobi.giza.compose.nostr.subgroup.WalletPolicyReading -import fr.acinq.bitcoin.Chain -import mobi.giza.compose.managers.GroupWalletDerivation -import mobi.giza.compose.managers.GroupWalletManager -import mobi.giza.compose.managers.GuardianManager -import mobi.giza.compose.nostr.wallet.GroupWallet import mobi.giza.compose.database.model.ChatRoom import mobi.giza.compose.database.model.GiftWrapPayload import mobi.giza.compose.database.model.GroupKeyState @@ -87,57 +80,6 @@ interface ChatRepository { */ suspend fun parentOf(chatRoomId: String): HexKey? - /** - * What this room's own birth certificate says of its wallet, or null for a - * room with none. See `SubgroupManager.walletPolicyOf`. - */ - suspend fun walletPolicyOf(chatRoomId: String): WalletPolicyReading? - - /** - * The guardian keys this room's own certificate grants it, nearest first -- - * empty for a room with none, null when they do not read. See - * `SubgroupManager.guardiansOf`. - */ - suspend fun guardiansOf(chatRoomId: String): List? - - /** - * The wallet this group has opened on [chain], or null when it has not -- - * read off the group's signed statement and rederived from the room's key. - */ - suspend fun groupWallet(chatRoomId: String, chain: Chain): GroupWallet? - - - /** - * The account this group *would* open on [chain], whether or not it has, or - * null for a room with no key: what a statement proposing the wallet carries. - */ - suspend fun groupWalletAccount(chatRoomId: String, chain: Chain): GroupWalletDerivation.Account? - - /** - * The guarded account this group could open on [chain] instead, and the - * certificate granting its guardians -- or null for a group whose birth - * certificate grants it none. - */ - suspend fun groupWalletGuardedOpening(chatRoomId: String, chain: Chain): GroupWalletManager.GuardedOpening? - - /** The guarded wallets of groups below this one that it has been told about and can sign for. */ - suspend fun guardedWallets(chatRoomId: String): List - - /** The guarded statements this device can carry from this group to the groups above it, with where to. */ - suspend fun shareableGuardedWallets(chatRoomId: String, chain: Chain): List - - /** Tells the groups in [shareable] about its statement, as [userPublicKey]. Returns how many were told. */ - suspend fun shareGuardedWallet(shareable: GuardianManager.Shareable, userPublicKey: HexKey): Int - - /** - * Tells the groups above this one about every guarded wallet it holds that - * they have not heard of -- the catch-up of `docs/guarded-wallet-forwarding.md`. - * Returns how many groups were told. Nothing, by default. - */ - suspend fun forwardGuardedWallets(chatRoomId: String): Int = 0 - - /** Writes a transcript line for each guardian spend from this group's wallet it has none for yet. */ - suspend fun recordGuardianSpends(chatRoomId: String, taken: List): Int /** * Whether this device holds a share of the group's key, and so could take @@ -365,39 +307,6 @@ interface ChatRepository { override suspend fun parentOf(chatRoomId: String): HexKey? = null - override suspend fun walletPolicyOf(chatRoomId: String): WalletPolicyReading? = null - - override suspend fun guardiansOf(chatRoomId: String): List? = emptyList() - - override suspend fun groupWallet(chatRoomId: String, chain: Chain): GroupWallet? = null - - override suspend fun groupWalletAccount( - chatRoomId: String, - chain: Chain - ): GroupWalletDerivation.Account? = null - - override suspend fun groupWalletGuardedOpening( - chatRoomId: String, - chain: Chain - ): GroupWalletManager.GuardedOpening? = null - - override suspend fun guardedWallets(chatRoomId: String): List = emptyList() - - override suspend fun shareableGuardedWallets( - chatRoomId: String, - chain: Chain - ): List = emptyList() - - override suspend fun shareGuardedWallet( - shareable: GuardianManager.Shareable, - userPublicKey: HexKey - ): Int = 0 - - override suspend fun recordGuardianSpends( - chatRoomId: String, - taken: List - ): Int = 0 - override suspend fun canSign(chatRoomId: String): Boolean = false override suspend fun refuseSubgroup( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/DkgRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/DkgRepository.kt index 9a7bce2b..99cfd194 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/DkgRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/DkgRepository.kt @@ -1,6 +1,5 @@ package mobi.giza.compose.repository -import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy import mobi.giza.compose.database.model.DkgParticipantMessage import mobi.giza.compose.database.model.DkgSession import mobi.giza.compose.database.model.FrostSigningSession @@ -86,9 +85,7 @@ interface DkgRepository { threshold: Int, parentChatRoomId: HexKey? = null, participantPublicKeys: Set? = null, - subject: String? = null, - walletPolicy: SubgroupWalletPolicy? = null, - guardianDelay: Long? = null + subject: String? = null ): DkgSession? /** What the ritual is waiting on this device's owner for, if anything. */ @@ -229,9 +226,7 @@ interface DkgRepository { threshold: Int, parentChatRoomId: HexKey?, participantPublicKeys: Set?, - subject: String?, - walletPolicy: SubgroupWalletPolicy?, - guardianDelay: Long? + subject: String? ): DkgSession? = null override suspend fun pendingApproval(session: DkgSession): DkgApprovalStep? = null diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/FrostSigningRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/FrostSigningRepository.kt index 69af4af4..0bfffe8f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/FrostSigningRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/FrostSigningRepository.kt @@ -1,11 +1,5 @@ package mobi.giza.compose.repository -import mobi.giza.compose.database.model.GroupTransaction -import mobi.giza.compose.managers.GroupWalletDerivation -import mobi.giza.compose.wallet.GroupSpend -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.OutPoint -import fr.acinq.bitcoin.psbt.Psbt import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.core.Kind @@ -229,46 +223,6 @@ interface FrostSigningRepository { /** The finished events, or empty while any of them is still running. */ fun signedEvents(items: List): List - /** - * Opens a session over one transaction from the group's wallet, or null when - * the spend could not be proposed -- it failed a check, or the group has no - * wallet on [chain]. See `FrostSigningManager.proposeSpend`. - */ - suspend fun proposeSpend( - localChatRoom: LocalChatRoom, - userPublicKey: HexKey, - psbt: Psbt, - chain: Chain, - ): FrostSigningSession? - - /** - * Opens a session over one transaction from [descendantChatRoomId]'s guarded - * wallet, signed through this room's guardian leaf, or null when it could not - * be proposed. See `FrostSigningManager.proposeGuardianSpend`. - */ - suspend fun proposeGuardianSpend( - localChatRoom: LocalChatRoom, - userPublicKey: HexKey, - psbt: Psbt, - descendantChatRoomId: String, - chain: Chain, - ): FrostSigningSession? - - /** The spend a transaction session signs, checked again; null for anything else. */ - suspend fun checkedSpend(sessionId: String): GroupSpend.Checked? - - - /** The coins the room's open spends are already spending. */ - suspend fun reservedOutPoints(chatRoomId: String): Set - - /** The change indices under [account] the room's open spends already pay back to. */ - suspend fun reservedChangeIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set - - /** The receive indices of [account], a descendant's guarded wallet, the room's open spends already fund. */ - suspend fun reservedFundingIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set - - /** Every spend the room has proposed, newest first, as it moves from proposed to confirmed. */ - fun observeGroupTransactions(chatRoomId: String): Flow> companion object { val NO_OP_FROST_SIGNING_REPOSITORY: FrostSigningRepository = object : FrostSigningRepository { @@ -337,29 +291,6 @@ interface FrostSigningRepository { override fun unsignedEvents(items: List): List = emptyList() - override suspend fun proposeSpend( - localChatRoom: LocalChatRoom, - userPublicKey: HexKey, - psbt: Psbt, - chain: Chain, - ): FrostSigningSession? = null - - override suspend fun proposeGuardianSpend( - localChatRoom: LocalChatRoom, - userPublicKey: HexKey, - psbt: Psbt, - descendantChatRoomId: String, - chain: Chain, - ): FrostSigningSession? = null - - override suspend fun checkedSpend(sessionId: String): GroupSpend.Checked? = null - - override suspend fun reservedOutPoints(chatRoomId: String): Set = emptySet() - override suspend fun reservedChangeIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set = emptySet() - override suspend fun reservedFundingIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set = emptySet() - - override fun observeGroupTransactions(chatRoomId: String): Flow> = flowOf(emptyList()) - override fun signedEvents(items: List): List = emptyList() } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/BlockDuration.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/BlockDuration.kt deleted file mode 100644 index 307449a7..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/BlockDuration.kt +++ /dev/null @@ -1,71 +0,0 @@ -package mobi.giza.compose.text - -import kotlin.math.abs -import kotlin.math.roundToInt - -/** - * A number of blocks said in time, roughly -- `docs/guardian-delay.md`, D5. - * - * Always beside the block count, never instead of it: blocks are what a - * guardian's leaf counts, and ten minutes is the target, not a promise, so a - * delay of 144 blocks can take twenty hours or thirty. Hence *about*. - * - * The rule: - * - * 1. within 5% of exactly one hour, day, month or year, that unit, singular -- - * 6 blocks is *about 1 hour*, 4,320 *about 1 month*; - * 2. otherwise the largest of years, months, days, hours and minutes in which - * the delay comes to at least 2, rounded -- 216 blocks is *about 36 hours*, - * 65,535 *about 15 months*. - * - * Years therefore appear only near exactly one year: the longest delay a leaf - * can carry is 1.25 years, and *about 15 months* says more than *about 1 year*. - */ -object BlockDuration { - /** Bitcoin's target, and the testnets' and signet's. Regtest has none. */ - const val MINUTES_PER_BLOCK: Long = 10L - - /** The units, each with its length in minutes: a month is a twelfth of a Julian year. */ - enum class Unit(val minutes: Double) { - MINUTES(1.0), - HOURS(60.0), - DAYS(1_440.0), - MONTHS(43_830.0), - YEARS(525_960.0), - } - - data class Approximate(val count: Int, val unit: Unit) - - /** How close to exactly one of a unit a delay has to be to be said as one. */ - private const val ONE_TOLERANCE = 0.05 - - fun approximate(blocks: Long): Approximate { - require(blocks > 0) { "a duration is at least one block, not $blocks" } - val minutes = (blocks * MINUTES_PER_BLOCK).toDouble() - val largestFirst = Unit.entries.reversed() - - largestFirst.filter { it != Unit.MINUTES }.forEach { unit -> - if (abs(minutes / unit.minutes - 1.0) <= ONE_TOLERANCE) return Approximate(1, unit) - } - largestFirst.forEach { unit -> - val count = minutes / unit.minutes - if (count >= 2.0) return Approximate(count.roundToInt(), unit) - } - return Approximate(minutes.roundToInt(), Unit.MINUTES) - } -} - -/** A count of blocks, its thousands grouped: `65,535`. */ -fun Long.groupedBlocks(): String = toString().reversed().chunked(3).joinToString(",").reversed() - -/** - * *144 blocks, about 1 day*, in fixed English: for the words that are not - * composables -- a proposal's summary -- as the rest of `ProposedEvent` is. - * Screens use `delayText`, which reads the catalogue. - */ -fun BlockDuration.describe(blocks: Long): String { - val approximate = approximate(blocks) - val unit = approximate.unit.name.lowercase().let { if (approximate.count == 1) it.removeSuffix("s") else it } - val count = if (blocks == 1L) "1 block" else "${blocks.groupedBlocks()} blocks" - return "$count, about ${approximate.count} $unit" -} 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 4bcf3bb2..1896cfe4 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedEvent.kt @@ -1,7 +1,5 @@ package mobi.giza.compose.text -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.managers.SharedKeyDerivation @@ -9,7 +7,6 @@ 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 /** * An event a group is being asked to sign, said in words. @@ -35,6 +32,12 @@ object ProposedEvent { * person: a caller with profiles to hand passes them, and one without gets * the summary without a name rather than a wrong one. */ + /** + * What a session over a Bennu peer's wallet says: a transaction, a sweep, or a + * wallet's event. Declined on arrival, so said without reading what it spends. + */ + val WALLET = Summary(label = "A wallet's to sign", detail = WalletRefusal.REASON) + fun summarize(event: Event, nameOf: (HexKey) -> String? = { null }): Summary = when (event.kind) { // The one thing a group signs that is about the group rather than about // its work, and the only one a member sees before the room has done @@ -63,52 +66,12 @@ object ProposedEvent { .size .takeIf { it > 0 } ?.let { "run by $it members" }, - // The promise this certificate makes on the group's behalf, said - // as one: a guardian key is this group, and every group above it, - // able to spend from the subgroup's wallet if it opens a guarded one. - SubgroupBirthCertificateEvent.parseGuardians(event.tags) - ?.size - ?.takeIf { it > 0 } - ?.let { count -> - when (count) { - 1 -> "this group can spend from its wallet" - 2 -> "this group and the one above it can spend from its wallet" - else -> "this group and the ${count - 1} above it can spend from its wallet" - } - }, - // How long this group's own leaf waits, which its coordinator - // chose; every inherited one keeps its own. docs/guardian-delay.md. - SubgroupBirthCertificateEvent.parseGuardians(event.tags) - ?.firstOrNull() - ?.let { "this group after ${BlockDuration.describe(it.delay)}" }, - // The decision this certificate makes for the child, said in both - // directions: an absent line is not a decision anybody can be said - // to have read. An older certificate decides nothing and says so - // by saying nothing, as it always has. - when (SubgroupBirthCertificateEvent.parseWalletPolicy(event.tags)) { - WalletPolicyReading.Decided(SubgroupWalletPolicy.GUARDED) -> "its wallet must be guarded" - WalletPolicyReading.Decided(SubgroupWalletPolicy.UNGUARDED) -> "its wallet will not be guarded" - else -> null - } ).joinToString(" · ") ) - // The group opening a wallet. What a member is agreeing to is that the - // group keeps coins here, so the summary names the network -- the one - // thing that changes what the coins are worth -- and the account, and - // not the xpub, which is a derivation of the room's key nobody can check - // by eye. - GroupWalletStatementEvent.KIND -> Summary( - label = "Open a group onchain wallet", - detail = GroupWalletStatementEvent.read(event.tags, event.content)?.let { statement -> - "On ${GroupWalletStatementEvent.chainName(statement.chain)}, account ${statement.account}" - } ?: "A wallet statement this device cannot read" - ) - // A Bennu wallet's: declined on arrival, and said as what it is rather than // as a number. docs/giza-wallet-removal.md. - in RetiredKinds.WALLET, in RetiredKinds.GROUP_LIGHTNING -> - Summary(label = "A wallet's to sign", detail = WalletRefusal.REASON) + in RetiredKinds.WALLET, in RetiredKinds.GROUP_LIGHTNING -> WALLET else -> Summary(label = "Event of kind ${event.kind}", detail = event.content) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedSpend.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedSpend.kt deleted file mode 100644 index 8111f073..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/text/ProposedSpend.kt +++ /dev/null @@ -1,68 +0,0 @@ -package mobi.giza.compose.text - -import mobi.giza.compose.managers.WalletRefusal - -import mobi.giza.compose.wallet.GroupSpend -import fr.acinq.bitcoin.Bitcoin -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.Satoshi - -/** - * A spend the group is being asked to sign, said in words -- [ProposedEvent]'s - * counterpart for a transaction, and for the same reason not a composable: the - * signing screen and the room's list of proposals say it the same way. - */ -object ProposedSpend { - fun summarize(spend: GroupSpend.Checked, chain: Chain): ProposedEvent.Summary = - ProposedEvent.Summary( - // A guardian's spend takes a descendant's coins, so whose they are - // is the first thing a signer reads. - // A funding comes next: where the money goes, as every signer's - // device derived it -- never the proposer's word for it. - label = when (val guardian = spend.spender as? GroupSpend.Spender.Guardian) { - null -> spend.fundings.singleOrNull()?.takeIf { spend.payments.size == 1 } - ?.let { "Fund ${walletOf(it)}" } - ?: "Spend from the group's wallet" - else -> "Spend from ${guardedWallet(guardian.name, guardian.label)}" - }, - detail = when (val payment = spend.payments.singleOrNull()) { - null -> "Send ${spend.amountSent.grouped()} sats to ${spend.payments.size} addresses" + when (val funding = spend.fundings.singleOrNull()) { - null -> if (spend.fundings.isEmpty()) "" else - ", ${Satoshi(spend.fundings.sumOf { spend.tx.txOut[it.outputIndex].amount.sat }).grouped()} of them to ${spend.fundings.size} guarded wallets" - else -> ", ${spend.tx.txOut[funding.outputIndex].amount.grouped()} of them to ${walletOf(funding)}" - } - else -> when (val funding = spend.fundings.singleOrNull()) { - null -> "Send ${payment.txOut.amount.grouped()} sats to ${addressOf(payment.txOut.publicKeyScript, chain)}" - else -> "Send ${payment.txOut.amount.grouped()} sats to ${walletOf(funding)}, address ${funding.derived.index}" - } - } - ) - - private fun walletOf(funding: GroupSpend.Funding): String = guardedWallet(funding.wallet.displayName, funding.wallet.label) - - /** - * A guarded wallet in a sentence: *#Translation's guarded wallet*, *@alice's - * guarded wallet* -- and, for a member's wallet with a label, *@alice's - * guarded wallet “Savings”*, since one person can have several and a signer - * should know which is being spent from. `docs/member-wallet-guarding-group.md`, Phase 5. - */ - fun guardedWallet(name: String?, label: String?): String = - "${name ?: "a subgroup"}'s guarded wallet" + (label?.let { " “$it”" } ?: "") - - /** The address [script] pays, or the script itself where it has no address. */ - fun addressOf(script: ByteVector, chain: Chain): String = - Bitcoin.addressFromPublicKeyScript(chain.chainHash, script.toByteArray()).right ?: script.toHex() - - /** A sweep from a Bennu group's Lightning wallet, which this device declined on arrival. */ - val SWEEP = ProposedEvent.Summary( - label = "Sweep into the group's onchain wallet", - detail = WalletRefusal.REASON - ) - - /** What a summary says for a spend this device cannot check: nothing a member could sign on. */ - val UNREADABLE = ProposedEvent.Summary( - label = "Spend from the group's wallet", - detail = "A spend this device cannot check" - ) -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/DkgApprovalScaffold.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/DkgApprovalScaffold.kt index 47997f73..b8b60f2e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/DkgApprovalScaffold.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/DkgApprovalScaffold.kt @@ -70,6 +70,8 @@ internal fun DkgApprovalScaffold( chatRepository: ChatRepository, dkgRepository: DkgRepository, onDone: () -> Unit, + /** Whether this step can be approved at all; false leaves only *Not now*. */ + canApprove: (DkgRitualUIState.Loaded) -> Boolean = { true }, body: @Composable (DkgRitualUIState.Loaded) -> Unit, ) { val dkgRitualViewModel: DkgRitualViewModel = viewModel( @@ -188,7 +190,7 @@ internal fun DkgApprovalScaffold( // press: closing clears the view model and would cancel // the publish with it. The button spins meanwhile. onClick = { dkgRitualViewModel.approve(step, onApproved = onDone) }, - enabled = !isActionPending, + enabled = !isActionPending && canApprove(state), modifier = Modifier.weight(1f) ) { if (isActionPending) { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/DkgJoinApprovalScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/DkgJoinApprovalScreen.kt index 4032d96c..add63732 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/DkgJoinApprovalScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/DkgJoinApprovalScreen.kt @@ -1,12 +1,8 @@ package mobi.giza.compose.ui.composable -import mobi.giza.compose.ui.composable.widgets.delayText -import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy -import mobi.giza.compose.managers.GuardianDerivation -import mobi.giza.compose.database.model.subgroupWalletPolicy import org.jetbrains.compose.resources.stringResource -import mobi.giza.compose.resources.the_subgroup_s_wallet_will_not_be_guarded -import mobi.giza.compose.resources.the_subgroup_s_wallet_will_be_guarded +import mobi.giza.compose.resources.this_subgroup_s_wallet_is_to_be_guarded +import mobi.giza.compose.database.model.isGuardedSubgroup import mobi.giza.compose.resources.Res import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column @@ -15,7 +11,6 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier -import androidx.compose.ui.unit.dp import mobi.giza.compose.database.model.types.DkgApprovalStep import mobi.giza.compose.repository.ChatRepository import mobi.giza.compose.repository.DkgRepository @@ -56,7 +51,8 @@ fun DkgJoinApprovalScreen( activeIdentityStateFlow = activeIdentityStateFlow, chatRepository = chatRepository, dkgRepository = dkgRepository, - onDone = onDone + onDone = onDone, + canApprove = { state -> !state.session.isGuardedSubgroup }, ) { state -> val session = state.session val group = state.localChatRoom.chatRoom.subject ?: "this group" @@ -67,24 +63,14 @@ fun DkgJoinApprovalScreen( style = MaterialTheme.typography.bodyLarge ) - // What the subgroup's wallet will be, as the coordinator chose it and the - // parent's quorum will sign it -- the one place an admin is told before - // joining is agreeing to it. A ceremony with no policy says nothing. - // See docs/subgroup-wallet-policy.md. - session.subgroupWalletPolicy?.let { policy -> + // A Bennu subgroup whose wallet is to be guarded: its certificate has to + // be guarded, which Giza does not sign, so it does not join (W5, + // docs/giza-wallet-removal.md). Said rather than hidden. + if (session.isGuardedSubgroup) { Text( - text = when (policy) { - // The parent's own leaf's delay, as the coordinator chose it -- - // or the default an older build's ceremony is certified at. - // An inherited ancestor's is not here: a member deciding - // whether to join cannot check it. docs/guardian-delay.md. - SubgroupWalletPolicy.GUARDED -> stringResource( - Res.string.the_subgroup_s_wallet_will_be_guarded, - delayText(session.guardianDelay ?: GuardianDerivation.DEFAULT_DELAY) - ) - SubgroupWalletPolicy.UNGUARDED -> stringResource(Res.string.the_subgroup_s_wallet_will_not_be_guarded) - }, - style = MaterialTheme.typography.bodyLarge + text = stringResource(Res.string.this_subgroup_s_wallet_is_to_be_guarded), + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.error ) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/FrostSigningScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/FrostSigningScreen.kt index 8b011060..446bd673 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/FrostSigningScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/FrostSigningScreen.kt @@ -53,7 +53,6 @@ import mobi.giza.compose.resources.don_t_sign import mobi.giza.compose.resources.events_signed_together import mobi.giza.compose.resources.everyone_has_answered_this_session import mobi.giza.compose.resources.everyone_has_signed_this_session -import mobi.giza.compose.resources.fee_s_sats_at_s_sats_per_byte import mobi.giza.compose.resources.has_not_taken_part_yet import mobi.giza.compose.resources.members import mobi.giza.compose.resources.members_have_not_answered @@ -61,16 +60,10 @@ import mobi.giza.compose.resources.one_member_has_not_answered import mobi.giza.compose.resources.one_signer_has_not_signed import mobi.giza.compose.resources.read_to_the_end_of_the_list_to_sign import mobi.giza.compose.resources.ready_to_sign -import mobi.giza.compose.resources.s_sats -import mobi.giza.compose.resources.s_sats_back_to_the_group_as_change import mobi.giza.compose.resources.sign import mobi.giza.compose.resources.sign_with_the_group_s_key -import mobi.giza.compose.resources.signed_by_the_group_any_member_can_send_it import mobi.giza.compose.resources.signed_their_part import mobi.giza.compose.resources.signers_have_not_signed -import mobi.giza.compose.resources.spend_from_the_group_s_wallet -import mobi.giza.compose.resources.spends_s_of_the_group_s_coins -import mobi.giza.compose.resources.this_spend_could_not_be_checked import mobi.giza.compose.database.model.ChatRoom import mobi.giza.compose.database.model.FrostSigningSession import mobi.giza.compose.database.model.intermdiate.LocalChatRoom @@ -80,8 +73,6 @@ import mobi.giza.compose.managers.FrostSigningManager import mobi.giza.compose.repository.ChatRepository import mobi.giza.compose.repository.FrostSigningRepository import mobi.giza.compose.text.ProposedEvent -import mobi.giza.compose.text.ProposedSpend -import mobi.giza.compose.text.grouped import mobi.giza.compose.ui.composable.widgets.Decorative import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState import mobi.giza.compose.ui.composable.widgets.NavigateBackButton @@ -93,7 +84,6 @@ import mobi.giza.compose.ui.theme.readableContent import mobi.giza.compose.ui.theme.spacing import mobi.giza.compose.ui.view.model.FrostSigningViewModel import mobi.giza.compose.ui.view.state.FrostSigningUIState -import mobi.giza.compose.wallet.GroupSpend import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import org.jetbrains.compose.resources.stringResource @@ -188,27 +178,19 @@ fun FrostSigningScreen( // flash an error on the way in. val session = state.session ?: return@Scaffold Loading(padding) - val isSpend = session.subject == FrostSigningSubject.TRANSACTION - val isSweep = session.subject == FrostSigningSubject.SWEEP - val proposed = if (isSpend || isSweep) emptyList() else frostSigningViewModel.proposedEvents(state.items) + // A Bennu peer's transaction or sweep: declined on arrival, never put + // to this device, and said as what it is rather than read. + val isWallet = session.subject != FrostSigningSubject.EVENTS + val proposed = if (isWallet) emptyList() else frostSigningViewModel.proposedEvents(state.items) // Every event of the batch has to be readable before any of it can // be signed. A member cannot check what they cannot see, and a // batch is all-or-nothing: agreeing to the two that rendered would - // be agreeing to the third as well. A spend is readable when this - // device has checked it, every input accounted for. - val readable = state.items.isNotEmpty() && if (isSpend) { - state.spend?.inputs?.size == state.items.size - } else if (isSweep) { - // Declined on arrival: a sweep is never put to this device. - false - } else { - proposed.size == state.items.size - } + // be agreeing to the third as well. + val readable = !isWallet && state.items.isNotEmpty() && proposed.size == state.items.size - // What has to be scrolled past before signing: each event of a - // batch, or each output of a spend. - val listed = if (isSpend) state.spend?.outputs?.size ?: 0 else if (isSweep) 1 else proposed.size + // What has to be scrolled past before signing: each event of a batch. + val listed = if (isWallet) 1 else proposed.size val scrollState = rememberScrollState() @@ -222,8 +204,7 @@ fun FrostSigningScreen( verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space200) ) { when { - isSpend -> WhatIsBeingSpent(state.spend) - isSweep -> Text(text = WalletRefusal.REASON, color = MaterialTheme.colorScheme.error) + isWallet -> Text(text = WalletRefusal.REASON, color = MaterialTheme.colorScheme.error) else -> WhatIsBeingSigned(proposed, state.items.size) } @@ -521,62 +502,6 @@ private fun WhatIsBeingSigned(events: List, expected: Int) { } } -@Composable -private fun WhatIsBeingSpent(spend: GroupSpend.Checked?) { - if (spend == null) { - Text( - text = stringResource(Res.string.this_spend_could_not_be_checked), - color = MaterialTheme.colorScheme.error - ) - return - } - - Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space200)) { - Text( - text = stringResource(Res.string.spend_from_the_group_s_wallet), - style = MaterialTheme.typography.labelMedium - ) - - spend.outputs.forEach { output -> - Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space50)) { - Text( - text = ProposedSpend.addressOf(output.txOut.publicKeyScript, spend.account.chain), - style = MaterialTheme.typography.titleMedium - ) - Text( - text = if (output.isChange) { - stringResource(Res.string.s_sats_back_to_the_group_as_change, output.txOut.amount.grouped()) - } else { - stringResource(Res.string.s_sats, output.txOut.amount.grouped()) - }, - style = MaterialTheme.typography.bodyMedium, - color = if (output.isChange) MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.onSurface - ) - } - HorizontalDivider() - } - - Text( - text = stringResource( - Res.string.fee_s_sats_at_s_sats_per_byte, - spend.fee.grouped(), - spend.feeratePerVbyte.toString() - ), - style = MaterialTheme.typography.bodyMedium - ) - Text( - text = stringResource(Res.string.spends_s_of_the_group_s_coins, spend.inputs.size.toString()), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - Text( - text = stringResource(Res.string.signed_by_the_group_any_member_can_send_it), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } -} - /** One event of the batch, described as the thing it is. */ @Composable private fun OneThingBeingSigned(event: Event) { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupSendScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupSendScreen.kt deleted file mode 100644 index 7b345e06..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupSendScreen.kt +++ /dev/null @@ -1,485 +0,0 @@ -package mobi.giza.compose.ui.composable - -import mobi.giza.compose.resources.only_coins_confirmed_for_can_be_spent -import mobi.giza.compose.ui.composable.widgets.delayText -import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.runtime.MutableState -import fr.acinq.bitcoin.Satoshi -import mobi.giza.compose.resources.finding_your_coins -import mobi.giza.compose.resources.s_sats_come_back_to_this_wallet_as_change -import mobi.giza.compose.resources.this_wallet_has_nothing_confirmed_to_spend -import mobi.giza.compose.resources.this_wallet_doesn_t_have_that_much_confirmed -import mobi.giza.compose.resources.while_the_wallet_is_new_at_most_s_sats -import androidx.compose.material3.OutlinedCard -import androidx.compose.ui.text.font.FontFamily -import mobi.giza.compose.resources.address_s -import mobi.giza.compose.resources.finding_an_address_in_s_s_wallet -import mobi.giza.compose.resources.fund_s_s_guarded_wallet -import mobi.giza.compose.resources.fund_s_s_guarded_wallet_s -import mobi.giza.compose.resources.spend_from_s_s_guarded_wallet_s -import mobi.giza.compose.resources.sends_s_sats_to_s_s_guarded_wallet_with_a_fee_of_s_sats -import mobi.giza.compose.resources.this_group_can_spend_these_coins_again -import mobi.giza.compose.resources.to -import mobi.giza.compose.resources.s_s_guarded_wallet -import mobi.giza.compose.resources.wait_for_this_group_s_open_payments_to_s -import mobi.giza.compose.managers.GuardianDerivation -import mobi.giza.compose.ui.view.state.FundingTarget -import androidx.compose.foundation.selection.toggleable -import androidx.compose.material3.minimumInteractiveComponentSize -import androidx.compose.ui.semantics.Role -import androidx.compose.ui.text.input.ImeAction -import mobi.giza.compose.resources.sats -import mobi.giza.compose.resources.s_sats_confirmed_and_free_to_spend -import mobi.giza.compose.wallet.GroupWalletRollout -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.text.KeyboardOptions -import androidx.compose.foundation.text.input.TextFieldLineLimits -import androidx.compose.foundation.verticalScroll -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.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.OutlinedTextField -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Switch -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.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.input.KeyboardType -import androidx.compose.ui.text.style.TextOverflow -import androidx.lifecycle.viewmodel.compose.viewModel -import mobi.giza.compose.resources.Res -import mobi.giza.compose.resources.address -import mobi.giza.compose.resources.amount_in_sats -import mobi.giza.compose.resources.ask_the_group_to_send -import mobi.giza.compose.resources.couldn_t_ask_the_group_to_send -import mobi.giza.compose.resources.feerate_in_sats_per_byte -import mobi.giza.compose.resources.finding_the_group_s_coins -import mobi.giza.compose.resources.nothing_leaves_until_a_quorum_signs -import mobi.giza.compose.resources.s_sats_come_back_to_the_group_as_change -import mobi.giza.compose.resources.send_everything -import mobi.giza.compose.resources.send_from_the_group_s_wallet -import mobi.giza.compose.resources.sending_needs_a_share_and_a_node -import mobi.giza.compose.resources.sends_s_sats_with_a_fee_of_s_sats -import mobi.giza.compose.resources.that_is_too_little_to_send -import mobi.giza.compose.resources.that_isn_t_an_address_on_s -import mobi.giza.compose.resources.the_group_doesn_t_have_that_much_confirmed -import mobi.giza.compose.resources.the_group_has_nothing_confirmed_to_spend -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import mobi.giza.compose.repository.ChatRepository -import mobi.giza.compose.repository.FrostSigningRepository -import mobi.giza.compose.resources.sats_are_whole_numbers -import mobi.giza.compose.resources.s_sats_left_over_go_to_the_fee -import mobi.giza.compose.resources.too_many_spends_are_open_with_change -import mobi.giza.compose.resources.that_is_more_sats_than_there_will_ever_be -import mobi.giza.compose.resources.that_isn_t_an_amount_in_sats -import mobi.giza.compose.text.GroupedSats -import mobi.giza.compose.text.SatsInput -import mobi.giza.compose.text.grouped -import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute -import mobi.giza.compose.ui.composable.navigation.routes.Route -import mobi.giza.compose.ui.composable.widgets.Decorative -import mobi.giza.compose.ui.composable.widgets.EmptyState -import mobi.giza.compose.ui.composable.widgets.ErrorState -import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator -import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState -import mobi.giza.compose.ui.composable.widgets.NavigateBackButton -import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition -import mobi.giza.compose.ui.composable.widgets.rememberNotifier -import mobi.giza.compose.ui.theme.readableContent -import mobi.giza.compose.ui.theme.spacing -import mobi.giza.compose.ui.view.model.GroupSendViewModel -import mobi.giza.compose.ui.view.state.GroupSendUIState -import mobi.giza.compose.wallet.GroupOnchainWallets -import mobi.giza.compose.wallet.GroupSpendBuilder -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.Chain -import org.jetbrains.compose.resources.stringResource -import mobi.giza.compose.resources.spend_from_s_s_guarded_wallet -import mobi.giza.compose.resources.a_subgroup -import mobi.giza.compose.wallet.GroupSpend - -/** - * A spend from the group's wallet, proposed. - * - * The form says what it would build as it is filled in -- what leaves, the fee, - * what comes back as change -- from the same build the proposal is made of, so - * nothing a member reads here is an estimate of something else. Proposing it - * moves onto the signing session: nothing has left the wallet, and nothing will - * until a quorum has seen it and signed. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun GroupSendScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - chain: Chain, - initialGroupSendUIState: GroupSendUIState = GroupSendUIState.Loading, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - wallets: GroupOnchainWallets, - guardedChatRoomId: String? = null, - fundChatRoomId: String? = null, - onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val groupSendViewModel: GroupSendViewModel = viewModel( - factory = GroupSendViewModel.factory( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - chain = chain, - initialGroupSendUIState = initialGroupSendUIState, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository, - wallets = wallets, - guardedChatRoomId = guardedChatRoomId, - fundChatRoomId = fundChatRoomId, - ) - ) - - LaunchedEffect(true) { - if (initialGroupSendUIState == GroupSendUIState.Loading) groupSendViewModel.initiate() - } - - val notify = rememberNotifier(rememberCoroutineScope()) - val couldNotSend = stringResource(Res.string.couldn_t_ask_the_group_to_send) - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { - // Whose wallet is in the title: a guardian's spend takes a - // descendant's coins, and nothing else on the form says so -- - // and a funding pays one, which the title says the same way. - val ready = groupSendViewModel.groupSendUIState as? GroupSendUIState.Ready - val guardian = ready?.spender as? GroupSpend.Spender.Guardian - val funded = ready?.funding?.wallet - Text( - text = when { - // A member's label says which of their wallets. - guardian?.label != null -> stringResource(Res.string.spend_from_s_s_guarded_wallet_s, guardian.name ?: stringResource(Res.string.a_subgroup), guardian.label) - guardian != null -> stringResource(Res.string.spend_from_s_s_guarded_wallet, guardian.name ?: stringResource(Res.string.a_subgroup)) - funded != null -> funded.label?.let { label -> stringResource(Res.string.fund_s_s_guarded_wallet_s, funded.displayName ?: stringResource(Res.string.a_subgroup), label) } - ?: stringResource(Res.string.fund_s_s_guarded_wallet, funded.displayName ?: stringResource(Res.string.a_subgroup)) - else -> stringResource(Res.string.send_from_the_group_s_wallet) - }, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - }, - navigationIcon = { NavigateBackButton(onNavigateBack) } - ) - } - ) { padding -> - ScreenStateTransition(groupSendViewModel.groupSendUIState) { uiState -> - when (val state = uiState) { - is GroupSendUIState.Error -> ErrorState( - modifier = Modifier.padding(padding), - message = state.message, - onRetry = null - ) - - GroupSendUIState.Loading -> LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding)) - - GroupSendUIState.Unavailable -> EmptyState( - modifier = Modifier.padding(padding).readableContent(), - message = stringResource(Res.string.sending_needs_a_share_and_a_node), - icon = Icons.Default.AccountBalanceWallet, - ) - - is GroupSendUIState.Ready -> Column( - modifier = Modifier.padding(padding).readableContent().fillMaxSize() - .verticalScroll(rememberScrollState()) - .padding(MaterialTheme.spacing.screenMargin), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) - ) { - val preview = groupSendViewModel.preview() - - // A funding's destination is fixed, not typed: the title names - // the wallet, and an address field could make it pay another. - // A funded wallet's address not known yet is said on its card. - SpendForm( - addressField = groupSendViewModel.addressField, - amountField = groupSendViewModel.amountField, - feerateField = groupSendViewModel.feerateField, - sendEverything = groupSendViewModel.sendEverything, - spendable = groupSendViewModel.spendable(), - guardianDelay = groupSendViewModel.guardianDelay(), - cap = GroupWalletRollout.capFor(chain), - preview = preview, - amountProblem = preview?.takeIf { groupSendViewModel.isAboutTheAmount(it) }, - coinsKnown = state.walletState != null, - chain = chain, - destination = state.funding?.let { funding -> { FundingDestination(funding) } }, - fundedName = state.funding?.wallet?.let { it.displayName ?: stringResource(Res.string.a_subgroup) }, - waitingOnFunding = state.funding != null && state.funding.address == null, - ) - - Text( - text = stringResource(Res.string.nothing_leaves_until_a_quorum_signs), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - - Button( - enabled = preview is GroupSpendBuilder.Result.Built && !groupSendViewModel.isActionPending.value, - onClick = { - groupSendViewModel.propose( - onSuccess = { sessionId -> - // Onto the session: the spend exists once it is - // signed, and this form has done its part. - onNavigateToRouteAndPopUpInclusive( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId, - ) - ) - }, - onFailure = { notify(couldNotSend) }, - ) - } - ) { - Icon(Icons.Default.Send, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.ask_the_group_to_send)) - } - } - } - } - } -} - -/** - * The fields of a send and what they would build: the address, send - * everything, the amount, the feerate, and the preview -- one form for every - * wallet that spends, so the group's and a member's cannot drift. The button - * under it is the caller's, because what it does is not the same: a group asks - * its quorum, a member signs alone. - * - * [ownWallet] is a member spending their own guarded wallet, which changes the - * words -- "your coins", "this wallet" -- and nothing else. [destination], when - * there is one, takes the address field's place: a funding pays a wallet the - * form names rather than an address somebody types. - */ -@Composable -internal fun SpendForm( - addressField: TextFieldState, - amountField: TextFieldState, - feerateField: TextFieldState, - sendEverything: MutableState, - /** The confirmed coins free to spend, or null before Electrum has answered. */ - spendable: Satoshi?, - cap: Satoshi?, - /** - * A guardian's own leaf's delay, when the form spends a descendant's guarded - * wallet as its guardian -- what makes its balance lower than the wallet's. - * `docs/guardian-delay.md`. - */ - guardianDelay: Long? = null, - preview: GroupSpendBuilder.Result?, - /** A problem with the amount, said on the amount field, beside what caused it. */ - amountProblem: GroupSpendBuilder.Result?, - coinsKnown: Boolean, - chain: Chain, - ownWallet: Boolean = false, - destination: (@Composable () -> Unit)? = null, - /** The wallet a funding pays, as the preview names it. */ - fundedName: String? = null, - /** A funding whose address is not known yet: its card says so, and there is no preview to show. */ - waitingOnFunding: Boolean = false, -) { - // No column of its own: the fields go into the caller's, under its spacing, - // exactly as they did before the form was shared. - destination?.invoke() ?: OutlinedTextField( - modifier = Modifier.fillMaxWidth(), - state = addressField, - lineLimits = TextFieldLineLimits.SingleLine, - label = { Text(stringResource(Res.string.address)) }, - ) - - // The row is the target, so the label toggles too: one 48dp control with one name. - Row( - modifier = Modifier.fillMaxWidth() - .toggleable( - value = sendEverything.value, - role = Role.Switch, - onValueChange = { sendEverything.value = it }, - ) - .minimumInteractiveComponentSize(), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.SpaceBetween, - ) { - Text(stringResource(Res.string.send_everything)) - Switch(checked = sendEverything.value, onCheckedChange = null) - } - - // Hidden rather than cleared, so turning send-everything off again finds the amount typed. - if (!sendEverything.value) { - OutlinedTextField( - modifier = Modifier.fillMaxWidth(), - state = amountField, - outputTransformation = GroupedSats, - lineLimits = TextFieldLineLimits.SingleLine, - keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Next), - label = { Text(stringResource(Res.string.amount_in_sats)) }, - suffix = { Text(stringResource(Res.string.sats)) }, - isError = amountProblem != null, - supportingText = if (amountProblem == null && spendable == null && cap == null) null else { - { - if (amountProblem != null) { - Text(problemWith(amountProblem, chain, ownWallet)) - } else Column { - spendable?.let { Text(stringResource(Res.string.s_sats_confirmed_and_free_to_spend, it.grouped())) } - // Why a guardian's balance can be lower than the wallet's: - // only coins past its own leaf's lock. - guardianDelay?.let { Text(stringResource(Res.string.only_coins_confirmed_for_can_be_spent, delayText(it, chain))) } - cap?.let { Text(stringResource(Res.string.while_the_wallet_is_new_at_most_s_sats, it.grouped())) } - } - } - }, - ) - } - - OutlinedTextField( - modifier = Modifier.fillMaxWidth(), - state = feerateField, - lineLimits = TextFieldLineLimits.SingleLine, - keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), - label = { Text(stringResource(Res.string.feerate_in_sats_per_byte)) }, - ) - - // Still finding change is still finding coins: neither is anything to correct. - if (!coinsKnown || preview == GroupSpendBuilder.Result.FindingChange) { - LoadingDataIndicator(fillScreen = false, text = stringResource(if (ownWallet) Res.string.finding_your_coins else Res.string.finding_the_group_s_coins)) - } else if (amountProblem == null && !waitingOnFunding) { - preview?.let { SendPreview(it, chain, ownWallet, fundedName) } - } -} - -/** - * Where a funding goes: the descendant's wallet, the address in it this send - * pays and its index, and what the group keeps over the coins once they land. - * While the address is not known yet, or every one is held, it says that instead. - */ -@Composable -private fun FundingDestination(funding: FundingTarget) { - val name = funding.wallet.displayName ?: stringResource(Res.string.a_subgroup) - OutlinedCard(modifier = Modifier.fillMaxWidth()) { - Column( - modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap), - ) { - Text(text = stringResource(Res.string.to), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) - Text(text = stringResource(Res.string.s_s_guarded_wallet, name), style = MaterialTheme.typography.titleMedium) - val address = funding.address - when { - address != null -> { - Text( - text = address.address, - style = MaterialTheme.typography.bodyMedium.copy(fontFamily = FontFamily.Monospace), - maxLines = 1, - overflow = TextOverflow.MiddleEllipsis, - ) - Text( - text = stringResource(Res.string.address_s, address.derivation.index.toString()), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - funding.allHeld -> Text( - text = stringResource(Res.string.wait_for_this_group_s_open_payments_to_s, name), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.error, - ) - else -> LoadingDataIndicator(fillScreen = false, text = stringResource(Res.string.finding_an_address_in_s_s_wallet, name)) - } - // What funding a guarded wallet means for this group: the coins come - // back within its reach, through its own leaf, after that leaf's - // lock -- which the group that granted it chose. docs/guardian-delay.md. - Text( - text = stringResource(Res.string.this_group_can_spend_these_coins_again, delayText(funding.wallet.delay, funding.wallet.chain)), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } -} - -/** What the form would build, or why it cannot. [fundedName] names the wallet a funding pays. */ -@Composable -private fun SendPreview(result: GroupSpendBuilder.Result, chain: Chain, ownWallet: Boolean, fundedName: String? = null) { - when (result) { - is GroupSpendBuilder.Result.Built -> Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { - Text( - text = if (result.funded != null && fundedName != null) { - stringResource(Res.string.sends_s_sats_to_s_s_guarded_wallet_with_a_fee_of_s_sats, result.amount.grouped(), fundedName, result.fee.grouped()) - } else { - stringResource(Res.string.sends_s_sats_with_a_fee_of_s_sats, result.amount.grouped(), result.fee.grouped()) - }, - style = MaterialTheme.typography.bodyLarge, - ) - result.change?.let { change -> - Text( - text = stringResource( - if (ownWallet) Res.string.s_sats_come_back_to_this_wallet_as_change else Res.string.s_sats_come_back_to_the_group_as_change, - change.grouped(), - ), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - if (result.absorbed.sat > 0) { - Text( - text = stringResource(Res.string.s_sats_left_over_go_to_the_fee, result.absorbed.grouped()), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - - else -> Text( - text = problemWith(result, chain, ownWallet), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.error, - ) - } -} - -/** Why [result] cannot be proposed, in words. */ -@Composable -private fun problemWith(result: GroupSpendBuilder.Result, chain: Chain, ownWallet: Boolean): String = when (result) { - GroupSpendBuilder.Result.NotAnAddress -> - stringResource(Res.string.that_isn_t_an_address_on_s, GroupWalletStatementEvent.chainName(chain)) - GroupSpendBuilder.Result.NothingToSpend -> stringResource( - if (ownWallet) Res.string.this_wallet_has_nothing_confirmed_to_spend else Res.string.the_group_has_nothing_confirmed_to_spend - ) - GroupSpendBuilder.Result.NotEnough -> stringResource( - if (ownWallet) Res.string.this_wallet_doesn_t_have_that_much_confirmed else Res.string.the_group_doesn_t_have_that_much_confirmed - ) - GroupSpendBuilder.Result.TooManyOpen -> stringResource(Res.string.too_many_spends_are_open_with_change) - is GroupSpendBuilder.Result.OverCap -> stringResource(Res.string.while_the_wallet_is_new_at_most_s_sats, result.cap.grouped()) - is GroupSpendBuilder.Result.InvalidAmount -> when (result.input) { - SatsInput.NotWhole -> stringResource(Res.string.sats_are_whole_numbers) - SatsInput.TooLarge -> stringResource(Res.string.that_is_more_sats_than_there_will_ever_be) - else -> stringResource(Res.string.that_isn_t_an_amount_in_sats) - } - else -> stringResource(Res.string.that_is_too_little_to_send) -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupWalletAddressesScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupWalletAddressesScreen.kt deleted file mode 100644 index cb7a4089..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupWalletAddressesScreen.kt +++ /dev/null @@ -1,357 +0,0 @@ -package mobi.giza.compose.ui.composable - -import androidx.compose.foundation.clickable -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.text.selection.SelectionContainer -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.ContentCopy -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.ListItem -import androidx.compose.material3.ListItemDefaults -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar -import androidx.compose.material3.minimumInteractiveComponentSize -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalClipboardManager -import androidx.compose.ui.text.buildAnnotatedString -import androidx.compose.ui.text.font.FontFamily -import androidx.compose.ui.text.style.TextOverflow -import androidx.lifecycle.viewmodel.compose.viewModel -import mobi.giza.compose.resources.Res -import mobi.giza.compose.resources.address_copied -import mobi.giza.compose.resources.address_s -import mobi.giza.compose.resources.address_s_was_just_paid -import mobi.giza.compose.resources.addresses -import mobi.giza.compose.resources.addresses_explainer -import mobi.giza.compose.resources.being_handed_out_now -import mobi.giza.compose.resources.change -import mobi.giza.compose.resources.copy_address -import mobi.giza.compose.resources.copy_address_s -import mobi.giza.compose.resources.finding_the_group_s_coins -import mobi.giza.compose.resources.not_used_yet -import mobi.giza.compose.resources.paid_s_sats -import mobi.giza.compose.resources.paid_spent_since -import mobi.giza.compose.resources.show_as_a_qr_code -import mobi.giza.compose.repository.ChatRepository -import mobi.giza.compose.text.grouped -import mobi.giza.compose.ui.composable.widgets.Decorative -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.dialogs.ModalBottomSheet -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.GroupWalletAddressesViewModel -import mobi.giza.compose.ui.view.state.GroupWalletAddressesUIState -import mobi.giza.compose.wallet.GroupAddress -import mobi.giza.compose.wallet.GroupOnchainWallets -import mobi.giza.compose.wallet.bip21Uri -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.Satoshi -import org.jetbrains.compose.resources.stringResource - -/** - * The group wallet's receive addresses, newest first: every one paid, the one - * the wallet screen is handing out, and the few after it. - * - * Modelled on Phoenix's swap-in address list, with the look-ahead cut to what is - * worth handing out. The addresses after the current one are there so that two - * members sharing the wallet at once can each give a payer a different one; - * the sentence above the list says so, or nobody would use anything but the top. - * Tapping an unused one opens it as a QR code, in a sheet that closes itself if - * the address is paid while it is open. - * - * No block explorer: a tap that sends every address of the group's wallet to a - * third party's server is the leak the watch-only export warns about, made - * without asking. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun GroupWalletAddressesScreen( - chatRoomId: String, - chain: Chain, - initialUIState: GroupWalletAddressesUIState = GroupWalletAddressesUIState.Loading, - chatRepository: ChatRepository, - wallets: GroupOnchainWallets, - onNavigateBack: () -> Unit, -) { - val addressesViewModel: GroupWalletAddressesViewModel = viewModel( - factory = GroupWalletAddressesViewModel.factory( - chatRoomId = chatRoomId, - chain = chain, - initialUIState = initialUIState, - chatRepository = chatRepository, - wallets = wallets, - ) - ) - - LaunchedEffect(true) { - if (initialUIState == GroupWalletAddressesUIState.Loading) { - addressesViewModel.initiate() - } - } - - val notify = rememberNotifier(rememberCoroutineScope()) - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { - Text( - text = stringResource(Res.string.addresses), - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - }, - navigationIcon = { NavigateBackButton(onNavigateBack) } - ) - } - ) { padding -> - ScreenStateTransition(addressesViewModel.uiState) { uiState -> - when (val state = uiState) { - is GroupWalletAddressesUIState.Error -> { - // Nothing to retry: the room came from a navigation argument. - ErrorState( - modifier = Modifier.padding(padding), - message = state.message, - onRetry = null - ) - } - - GroupWalletAddressesUIState.Loading -> { - LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding)) - } - - is GroupWalletAddressesUIState.Loaded -> { - val receive = state.receive - if (receive == null) { - LoadingDataIndicator( - modifier = Modifier.fillMaxWidth().padding(padding), - text = stringResource(Res.string.finding_the_group_s_coins) - ) - } else { - AddressList( - modifier = Modifier.padding(padding), - receive = receive, - change = state.change, - notify = notify, - onShow = { index, paid -> addressesViewModel.show(index) { notify(paid) } }, - ) - - val shown = addressesViewModel.shown?.let { index -> receive.firstOrNull { it.derivation.index == index } } - if (shown != null) { - AddressSheet( - address = shown, - notify = notify, - onDismiss = addressesViewModel::dismiss, - ) - } - } - } - } - } - } -} - -@Composable -private fun AddressList( - modifier: Modifier, - receive: List, - change: List, - notify: (String) -> Unit, - onShow: (index: Long, paidMessage: String) -> Unit, -) { - val clipboardManager = LocalClipboardManager.current - val addressCopied = stringResource(Res.string.address_copied) - val copy = { address: GroupAddress -> - clipboardManager.setText(buildAnnotatedString { append(address.address) }) - notify(addressCopied) - } - // Both branches start at index 0, so the index alone is not a row's identity. - val key = { address: GroupAddress -> "${address.derivation.change}/${address.derivation.index}" } - - LazyColumn( - modifier = modifier.readableContent().fillMaxSize() - .padding(MaterialTheme.spacing.screenMargin), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) - ) { - item { - Text( - text = stringResource(Res.string.addresses_explainer), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - - items(receive, key = key) { address -> - // Read here rather than in the click: the index is the row's, and a - // click handler is not composable. - val paid = stringResource(Res.string.address_s_was_just_paid, address.derivation.index.toString()) - AddressRow( - address = address, - onCopy = { copy(address) }, - // A used address is never offered for scanning: copying it is for - // checking, a QR code is for being paid. - onShow = if (address.status != GroupAddress.Status.USED) { - { onShow(address.derivation.index, paid) } - } else null, - ) - } - - // The group's money too, and what a watch-only import will show beside - // the receive addresses -- but chosen by a spend, so never offered here. - if (change.isNotEmpty()) { - item { - Text( - text = stringResource(Res.string.change), - style = MaterialTheme.typography.titleMedium, - modifier = Modifier.padding(top = MaterialTheme.spacing.sectionGap), - ) - } - items(change, key = key) { address -> - AddressRow(address = address, onCopy = { copy(address) }, onShow = null) - } - } - } -} - -/** - * One unused address, ready to be paid: what the wallet screen's receive card - * shows for the current address, for whichever one this member is handing out. - * - * The title carries the index so a member reading it to a payer can say which - * one they gave. - */ -@Composable -private fun AddressSheet( - address: GroupAddress, - notify: (String) -> Unit, - onDismiss: () -> Unit, -) { - val clipboardManager = LocalClipboardManager.current - val addressCopied = stringResource(Res.string.address_copied) - - ModalBottomSheet( - onDismiss = onDismiss, - skipPartiallyExpanded = true, - horizontalAlignment = Alignment.CenterHorizontally, - ) { - Column( - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) - ) { - Text( - text = stringResource(Res.string.address_s, address.derivation.index.toString()), - style = MaterialTheme.typography.titleMedium, - ) - Text( - text = address.status.label(address.balance), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - // BIP21, so a scanning wallet knows what the text is. - QRCodeView(bip21Uri(address.address)) - SelectionContainer { - Text(text = address.address, style = MaterialTheme.typography.bodyMedium) - } - TextButton( - onClick = { - clipboardManager.setText(buildAnnotatedString { append(address.address) }) - notify(addressCopied) - } - ) { - Icon(Icons.Default.ContentCopy, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.copy_address)) - } - } - } -} - -/** - * One address: its index, the address itself, and what it has been used for. - * - * The current address takes the secondary container rather than Phoenix's - * leading bar, so the emphasis is a colour pairing the theme has already - * measured in all six schemes. - */ -@Composable -private fun AddressRow(address: GroupAddress, onCopy: () -> Unit, onShow: (() -> Unit)?) { - val showLabel = stringResource(Res.string.show_as_a_qr_code) - val colors = if (address.status == GroupAddress.Status.CURRENT) { - val onContainer = MaterialTheme.colorScheme.onSecondaryContainer - ListItemDefaults.colors( - containerColor = MaterialTheme.colorScheme.secondaryContainer, - headlineColor = onContainer, - supportingColor = onContainer, - leadingIconColor = onContainer, - trailingIconColor = onContainer, - ) - } else { - ListItemDefaults.colors() - } - - ListItem( - modifier = if (onShow != null) { - Modifier.clickable(onClickLabel = showLabel, onClick = onShow).minimumInteractiveComponentSize() - } else Modifier, - colors = colors, - leadingContent = { - Text( - text = address.derivation.index.toString(), - style = MaterialTheme.typography.labelLarge, - ) - }, - headlineContent = { - Text( - text = address.address, - style = MaterialTheme.typography.bodyMedium.copy(fontFamily = FontFamily.Monospace), - maxLines = 1, - overflow = TextOverflow.MiddleEllipsis, - ) - }, - supportingContent = { Text(address.status.label(address.balance)) }, - trailingContent = { - IconButton(onClick = onCopy) { - Icon( - Icons.Default.ContentCopy, - contentDescription = stringResource(Res.string.copy_address_s, address.derivation.index.toString()) - ) - } - }, - ) -} - -@Composable -private fun GroupAddress.Status.label(balance: Satoshi): String = when (this) { - GroupAddress.Status.CURRENT -> stringResource(Res.string.being_handed_out_now) - GroupAddress.Status.NEXT -> stringResource(Res.string.not_used_yet) - GroupAddress.Status.USED -> if (balance > Satoshi(0)) { - stringResource(Res.string.paid_s_sats, balance.grouped()) - } else { - stringResource(Res.string.paid_spent_since) - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupWalletScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupWalletScreen.kt deleted file mode 100644 index 601b908a..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupWalletScreen.kt +++ /dev/null @@ -1,1014 +0,0 @@ -package mobi.giza.compose.ui.composable - -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import mobi.giza.compose.resources.a_group_below_s -import mobi.giza.compose.resources.a_group_below_this_one -import mobi.giza.compose.resources.fund_s_s_guarded_wallet_s -import mobi.giza.compose.resources.fund_s_s_wallet_guarded_by_s -import mobi.giza.compose.resources.guarded_by_n_groups -import mobi.giza.compose.resources.guarded_by_s -import mobi.giza.compose.resources.guarded_by_s_below_s -import mobi.giza.compose.resources.members_wallets -import mobi.giza.compose.resources.n_wallets -import mobi.giza.compose.resources.s_comma_s -import mobi.giza.compose.resources.spend_from_s_s_guarded_wallet_s -import mobi.giza.compose.resources.spend_from_s_s_wallet_guarded_by_s -import mobi.giza.compose.resources.this_group -import androidx.compose.foundation.clickable -import androidx.compose.material3.minimumInteractiveComponentSize -import androidx.compose.ui.unit.dp -import mobi.giza.compose.ui.composable.navigation.routes.ProfilePreviewRoute -import mobi.giza.compose.ui.composable.widgets.profile.ProfileAvatar -import mobi.giza.compose.ui.view.state.PersonGuardedWallets -import mobi.giza.compose.ui.view.state.byPerson -import org.jetbrains.compose.resources.pluralStringResource -import mobi.giza.compose.resources.this_group_s_delay_in_this_wallet -import mobi.giza.compose.resources.a_group_above_this_one -import mobi.giza.compose.resources.guardian_after -import mobi.giza.compose.ui.composable.widgets.delayText -import mobi.giza.compose.resources.the_group_above_decided_this_wallet_is_not_guarded -import mobi.giza.compose.resources.the_group_above_decided_this_wallet_is_guarded -import mobi.giza.compose.nostr.subgroup.WalletPolicyReading -import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy -import androidx.compose.foundation.layout.FlowRow -import androidx.compose.material3.OutlinedCard -import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.semantics -import mobi.giza.compose.resources.fund -import mobi.giza.compose.resources.fund_s_s_guarded_wallet -import mobi.giza.compose.resources.s_sats_arriving -import mobi.giza.compose.resources.spend_from_s_s_guarded_wallet -import androidx.compose.foundation.layout.Row -import mobi.giza.compose.text.ProposedSpend -import mobi.giza.compose.ui.view.state.SpendRow -import mobi.giza.compose.ui.view.state.SpendStatus -import mobi.giza.compose.wallet.GroupTransactionWatcher -import mobi.giza.compose.resources.spends -import mobi.giza.compose.resources.waiting_for_signatures -import mobi.giza.compose.resources.abandoned -import mobi.giza.compose.resources.signed_sending_it_to_the_network -import mobi.giza.compose.resources.sent_waiting_for_a_confirmation -import mobi.giza.compose.resources.confirmed -import mobi.giza.compose.resources.replaced_by_a_later_spend -import mobi.giza.compose.resources.send_again -import mobi.giza.compose.resources.bump_the_fee -import mobi.giza.compose.resources.sent_again -import mobi.giza.compose.resources.couldn_t_bump_the_fee -import androidx.compose.material.icons.filled.Send -import mobi.giza.compose.resources.send -import mobi.giza.compose.ui.composable.navigation.routes.GroupSendRoute -import mobi.giza.compose.ui.composable.navigation.routes.GroupWalletAddressesRoute -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.text.selection.SelectionContainer -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.AccountBalanceWallet -import androidx.compose.material.icons.filled.ContentCopy -import androidx.compose.material.icons.filled.FormatListNumbered -import androidx.compose.material.icons.filled.Visibility -import androidx.compose.material3.Button -import androidx.compose.material3.OutlinedButton -import androidx.compose.material3.Card -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Icon -import androidx.compose.material3.ListItem -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalClipboardManager -import androidx.compose.ui.text.buildAnnotatedString -import androidx.compose.ui.text.style.TextOverflow -import androidx.lifecycle.viewmodel.compose.viewModel -import mobi.giza.compose.resources.Res -import mobi.giza.compose.resources.address_copied -import mobi.giza.compose.resources.all_addresses -import mobi.giza.compose.resources.anyone_with_these_can_see_every_address -import mobi.giza.compose.resources.balance -import mobi.giza.compose.resources.balance_not_known_yet -import mobi.giza.compose.resources.change -import mobi.giza.compose.resources.coins -import mobi.giza.compose.resources.copy_address -import mobi.giza.compose.resources.couldn_t_ask_the_group_to_open_a_wallet -import mobi.giza.compose.resources.each_member_s_share_is_stored_unencrypted -import mobi.giza.compose.resources.export_watch_only -import mobi.giza.compose.resources.finding_the_group_s_coins -import mobi.giza.compose.resources.group_wallet -import mobi.giza.compose.resources.s_onchain_wallet -import mobi.giza.compose.resources.nothing_has_been_sent_to_this_wallet_yet -import mobi.giza.compose.resources.open_a_group_wallet -import mobi.giza.compose.resources.open_a_guarded_wallet -import mobi.giza.compose.resources.a_subgroup -import mobi.giza.compose.resources.at_s -import mobi.giza.compose.resources.couldn_t_share_the_wallet -import mobi.giza.compose.resources.guarded_wallets -import mobi.giza.compose.resources.not_yet_shared_with_the_groups_above -import mobi.giza.compose.resources.s_sats_within_this_group_s_reach -import mobi.giza.compose.resources.share -import mobi.giza.compose.resources.spend -import mobi.giza.compose.resources.shared_with_the_groups_above -import mobi.giza.compose.resources.tell_the_groups_above -import mobi.giza.compose.resources.this_device_shares_these_on_its_own_when_it_can -import mobi.giza.compose.resources.wallets_of_groups_below_this_one -import mobi.giza.compose.managers.GuardianManager -import mobi.giza.compose.ui.view.state.GuardedWalletRow -import androidx.compose.foundation.lazy.LazyListScope -import mobi.giza.compose.resources.open_without_guardians -import mobi.giza.compose.resources.the_groups_above_this_one_have_agreed_to_guard_it -import mobi.giza.compose.resources.guarded_the_groups_above_this_one_can_spend -import mobi.giza.compose.managers.GuardianDerivation -import mobi.giza.compose.resources.opening_a_wallet_asks_the_group_to_agree -import mobi.giza.compose.resources.receive_address -import mobi.giza.compose.resources.received -import mobi.giza.compose.resources.s_confirmations -import mobi.giza.compose.resources.s_dot_s -import mobi.giza.compose.resources.s_sats -import mobi.giza.compose.resources.s_sats_on_the_way -import mobi.giza.compose.resources.this_group_has_not_opened_a_wallet -import mobi.giza.compose.resources.waiting_for_a_confirmation -import mobi.giza.compose.resources.watch_only_descriptors_copied -import mobi.giza.compose.managers.GroupWalletDerivation -import mobi.giza.compose.repository.ChatRepository -import mobi.giza.compose.repository.FrostSigningRepository -import mobi.giza.compose.text.grouped -import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute -import mobi.giza.compose.ui.composable.navigation.routes.Route -import mobi.giza.compose.ui.composable.widgets.Decorative -import mobi.giza.compose.ui.composable.widgets.EmptyState -import mobi.giza.compose.ui.composable.widgets.ErrorState -import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator -import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState -import mobi.giza.compose.ui.composable.widgets.NavigateBackButton -import mobi.giza.compose.ui.composable.widgets.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.GroupWalletViewModel -import mobi.giza.compose.ui.view.state.GroupWalletUIState -import mobi.giza.compose.wallet.GroupOnchainWallets -import mobi.giza.compose.wallet.bip21Uri -import mobi.giza.compose.wallet.GroupUtxo -import mobi.giza.compose.wallet.GroupWalletState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.Chain -import org.jetbrains.compose.resources.stringResource - -/** - * The group's wallet: what it holds, where to pay it, and the coins themselves. - * - * Pushed from its row on the group's screen. A group that has not opened a - * wallet gets an empty state that says so -- and, for a member holding a share, - * the way to ask the group to open one, with what that asks of everybody. - * - * The address is the only thing on the screen a person acts on outside the app, - * so it is shown three ways: as a QR code, as selectable text, and on a copy - * button. Every one of them is derived on this device from the room's key; the - * statement the group signed is what says the wallet exists, never where it is. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun GroupWalletScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - chain: Chain, - initialGroupWalletUIState: GroupWalletUIState = GroupWalletUIState.Loading, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - wallets: GroupOnchainWallets, - watcher: GroupTransactionWatcher? = null, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val groupWalletViewModel: GroupWalletViewModel = viewModel( - factory = GroupWalletViewModel.factory( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - chain = chain, - initialGroupWalletUIState = initialGroupWalletUIState, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository, - wallets = wallets, - watcher = watcher, - ) - ) - - LaunchedEffect(true) { - if (initialGroupWalletUIState == GroupWalletUIState.Loading) { - groupWalletViewModel.initiate() - } - } - - val notify = rememberNotifier(rememberCoroutineScope()) - val couldNotOpen = stringResource(Res.string.couldn_t_ask_the_group_to_open_a_wallet) - val sentAgain = stringResource(Res.string.sent_again) - val couldNotBump = stringResource(Res.string.couldn_t_bump_the_fee) - val shared = stringResource(Res.string.shared_with_the_groups_above) - val couldNotShare = stringResource(Res.string.couldn_t_share_the_wallet) - // Behind the same two gates as the room's own send: a share to propose - // with, and a node to see the descendant's coins with. - val toGuardianSpend = { row: GuardedWalletRow -> - onNavigateToRoute( - GroupSendRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = null, - guardedChatRoomId = row.wallet.descendantChatRoomId, - ) - ) - } - // Behind the room's own send's gates, since a funding is one: a share to - // propose with, and a node to see this group's coins with. - val toGuardianFund = { row: GuardedWalletRow -> - onNavigateToRoute( - GroupSendRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = null, - fundChatRoomId = row.wallet.descendantChatRoomId, - ) - ) - } - // A member's wallets are gathered under them, and their header opens them: - // a person is someone to look at, not a room to go into. - val toPerson = { publicKey: HexKey -> - onNavigateToRoute(ProfilePreviewRoute(activeUserPublicKey = activeUserPublicKey, profilePublicKey = publicKey)) - } - val onShare = { shareable: GuardianManager.Shareable -> - groupWalletViewModel.share(shareable, onShared = { notify(shared) }, onFailure = { notify(couldNotShare) }) - } - val toSession = { sessionId: String -> - onNavigateToRoute(FrostSigningRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, sessionId = sessionId)) - } - - // Named for its group once the room is known; a room with no subject, and - // the moment before it loads, fall back to the generic name. - val groupName = when (val state = groupWalletViewModel.groupWalletUIState) { - is GroupWalletUIState.NotOpened -> state.localChatRoom.chatRoom.subject - is GroupWalletUIState.Loaded -> state.localChatRoom.chatRoom.subject - else -> null - } - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { - Text( - text = groupName?.let { stringResource(Res.string.s_onchain_wallet, it) } - ?: stringResource(Res.string.group_wallet), - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - }, - navigationIcon = { NavigateBackButton(onNavigateBack) } - ) - } - ) { padding -> - ScreenStateTransition(groupWalletViewModel.groupWalletUIState) { uiState -> - when (val state = uiState) { - is GroupWalletUIState.Error -> { - // Nothing to retry: the room came from a navigation argument. - ErrorState( - modifier = Modifier.padding(padding), - message = state.message, - onRetry = null - ) - } - - GroupWalletUIState.Loading -> { - LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding)) - } - - is GroupWalletUIState.NotOpened -> { - val notOpened = @Composable { modifier: Modifier -> EmptyState( - modifier = modifier, - message = stringResource(Res.string.this_group_has_not_opened_a_wallet), - icon = Icons.Default.AccountBalanceWallet, - // Hidden rather than disabled, the way every gated way in - // on the group's screens is: a device with no share cannot - // propose, and a room with no key has nothing to open. - action = if (state.canSign && state.account != null && (state.offersPlain || state.guarded != null)) { - { - OpenWalletAction( - isPending = groupWalletViewModel.isActionPending.value, - guardedOffered = state.guarded != null, - plainOffered = state.offersPlain, - decided = (state.policy as? WalletPolicyReading.Decided)?.policy, - guardians = state.guarded?.account?.guardians.orEmpty(), - guardianNames = state.guardianNames, - chain = chain, - onOpen = { guarded -> - groupWalletViewModel.openWallet( - guarded = guarded, - onSuccess = { sessionId -> - // Onto the session: the wallet does - // not exist until a quorum signs. - onNavigateToRoute( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - ) - }, - onFailure = { notify(couldNotOpen) } - ) - } - ) - } - } else null - ) } - - if (state.guardedWallets.isEmpty() && state.shareable.isEmpty()) { - notOpened(Modifier.padding(padding).readableContent()) - } else { - // A group with no wallet of its own can still guard others', - // and still carry a descendant's upward. - LazyColumn( - modifier = Modifier.padding(padding).readableContent().fillMaxSize() - .padding(MaterialTheme.spacing.screenMargin), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) - ) { - item { notOpened(Modifier) } - guardianItems( - guardedWallets = state.guardedWallets, - shareable = state.shareable, - isPending = groupWalletViewModel.isActionPending.value, - onShare = onShare, - onSpend = if (state.canSign && wallets != null) toGuardianSpend else null, - // A group with no wallet of its own has nothing to fund with. - onFund = null, - onOpenPerson = toPerson, - ) - } - } - } - - is GroupWalletUIState.Loaded -> { - OpenWallet( - modifier = Modifier.padding(padding), - state = state, - notify = notify, - // Behind both gates: a share to propose with, and a node to - // see the coins with -- a spend built blind is not one. - onSend = if (state.canSign) { - { - onNavigateToRoute( - GroupSendRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = null, - chain = GroupWalletStatementEvent.chainName(chain) - ) - ) - } - } else null, - onOpenAddresses = { - onNavigateToRoute( - GroupWalletAddressesRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - chain = GroupWalletStatementEvent.chainName(chain) - ) - ) - }, - onOpenSpend = toSession, - onSendAgain = if (watcher != null) { - { sessionId -> groupWalletViewModel.sendAgain(sessionId) { notify(sentAgain) } } - } else null, - onBump = if (state.canSign) { - { sessionId -> - groupWalletViewModel.bumpFee(sessionId, onSuccess = toSession, onFailure = { notify(couldNotBump) }) - } - } else null, - isPending = groupWalletViewModel.isActionPending.value, - onShare = onShare, - onSpend = if (state.canSign) toGuardianSpend else null, - onFund = if (state.canSign) toGuardianFund else null, - onOpenPerson = toPerson, - ) - } - } - } - } -} - -/** - * What opening a wallet asks of the group, said before the button rather than - * after it: that any quorum can then spend together and nobody alone, and what - * an unencrypted share on a member's device means once there are coins behind it. - */ -@Composable -private fun OpenWalletAction( - isPending: Boolean, - guardedOffered: Boolean, - plainOffered: Boolean, - /** What the room's parent decided at its birth, or null when it left it to the room. */ - decided: SubgroupWalletPolicy?, - /** The guardians a guarded wallet would name, nearest first, each with its own delay. */ - guardians: List, - guardianNames: Map, - chain: Chain, - onOpen: (guarded: Boolean) -> Unit, -) { - Column( - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) - ) { - Text( - text = stringResource(Res.string.opening_a_wallet_asks_the_group_to_agree), - style = MaterialTheme.typography.bodyMedium, - ) - Text( - text = stringResource(Res.string.each_member_s_share_is_stored_unencrypted), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - if (decided != null) { - // The parent decided at the room's birth, and its quorum signed it: - // one way in, and the line says whose decision it was. Every other - // member refuses the other statement, so offering it would only - // strand a quorum. See docs/subgroup-wallet-policy.md. - Text( - text = when (decided) { - SubgroupWalletPolicy.GUARDED -> stringResource(Res.string.the_group_above_decided_this_wallet_is_guarded) - SubgroupWalletPolicy.UNGUARDED -> stringResource(Res.string.the_group_above_decided_this_wallet_is_not_guarded) - }, - style = MaterialTheme.typography.bodyMedium, - ) - if (decided == SubgroupWalletPolicy.GUARDED) GuardianDelays(guardians, guardianNames, chain) - val guarded = decided == SubgroupWalletPolicy.GUARDED - if (guarded && guardedOffered || !guarded && plainOffered) { - Button(onClick = { onOpen(guarded) }, enabled = !isPending) { - Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(if (guarded) Res.string.open_a_guarded_wallet else Res.string.open_a_group_wallet)) - } - } - } else if (guardedOffered) { - // Undecided: a subgroup certified before parents decided. The default - // for one whose parent agreed to guard it, and the plain wallet beside - // it rather than hidden: being guarded is then the group's own choice, - // and its quorum signing the statement is it making that choice. - Text( - text = stringResource(Res.string.the_groups_above_this_one_have_agreed_to_guard_it), - style = MaterialTheme.typography.bodyMedium, - ) - GuardianDelays(guardians, guardianNames, chain) - Button(onClick = { onOpen(true) }, enabled = !isPending) { - Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.open_a_guarded_wallet)) - } - OutlinedButton(onClick = { onOpen(false) }, enabled = !isPending) { - Text(stringResource(Res.string.open_without_guardians)) - } - } else { - Button(onClick = { onOpen(false) }, enabled = !isPending) { - Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.open_a_group_wallet)) - } - } - } -} - -@Composable -private fun OpenWallet( - modifier: Modifier, - state: GroupWalletUIState.Loaded, - notify: (String) -> Unit, - onSend: (() -> Unit)?, - onOpenAddresses: () -> Unit, - onOpenSpend: (sessionId: String) -> Unit, - onSendAgain: ((sessionId: String) -> Unit)?, - onBump: ((sessionId: String) -> Unit)?, - isPending: Boolean, - onShare: (GuardianManager.Shareable) -> Unit, - onSpend: ((GuardedWalletRow) -> Unit)?, - onFund: ((GuardedWalletRow) -> Unit)?, - onOpenPerson: (HexKey) -> Unit, -) { - val clipboardManager = LocalClipboardManager.current - val addressCopied = stringResource(Res.string.address_copied) - val descriptorsCopied = stringResource(Res.string.watch_only_descriptors_copied) - val walletState = state.walletState - - LazyColumn( - modifier = modifier.readableContent().fillMaxSize() - .padding(MaterialTheme.spacing.screenMargin), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) - ) { - item { BalanceCard(walletState) } - - if (state.wallet.account.isGuarded) { - item { - Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { - Text( - text = stringResource(Res.string.guarded_the_groups_above_this_one_can_spend), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - GuardianDelays(state.wallet.account.guardians, state.guardianNames, state.wallet.chain) - } - } - } - - onSend?.let { send -> - item { - Button(onClick = send) { - Icon(Icons.Default.Send, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.send)) - } - } - } - - when { - walletState?.receiveAddress == null -> item { - LoadingDataIndicator( - fillScreen = false, - text = stringResource(Res.string.finding_the_group_s_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( - text = stringResource(Res.string.receive_address), - style = MaterialTheme.typography.titleMedium, - ) - // BIP21, so a scanning wallet knows what the text is. - 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)) - } - // In the card because it answers the question the card - // raises: which address to give, when somebody else in - // the group may be giving this one. - TextButton(onClick = onOpenAddresses) { - Icon(Icons.Default.FormatListNumbered, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.all_addresses)) - } - } - } - } - - item { - Text( - 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)) - } - } - } - } - - // Under the coins and for every member, node or not: a spend is the - // group's decision, and a member who cannot see the chain can still see - // what the group has asked of it and where each request has got to. - if (state.spends.isNotEmpty()) { - item { - Text( - text = stringResource(Res.string.spends), - style = MaterialTheme.typography.titleMedium, - ) - } - items(state.spends, key = { it.transaction.frostSigningSessionId }) { row -> - SpendRowCard( - row = row, - chain = state.wallet.chain, - onOpen = { onOpenSpend(row.transaction.frostSigningSessionId) }, - onSendAgain = onSendAgain?.takeIf { row.canSendAgain }?.let { { it(row.transaction.frostSigningSessionId) } }, - onBump = onBump?.takeIf { row.canBump }?.let { { it(row.transaction.frostSigningSessionId) } }, - ) - } - } - - item { - Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { - TextButton( - onClick = { - val account = state.wallet.account - clipboardManager.setText( - buildAnnotatedString { - append(account.receiveDescriptor) - append("\n") - append(account.changeDescriptor) - } - ) - notify(descriptorsCopied) - } - ) { - Icon(Icons.Default.Visibility, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.export_watch_only)) - } - Text( - text = stringResource(Res.string.anyone_with_these_can_see_every_address), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - - guardianItems( - guardedWallets = state.guardedWallets, - shareable = state.shareable, - isPending = isPending, - onShare = onShare, - onSpend = onSpend, - onFund = onFund, - onOpenPerson = onOpenPerson, - ) - } -} - -/** One spend: what it sends, where it has got to, and what can still be done about it. */ -@Composable -private fun SpendRowCard( - row: SpendRow, - chain: Chain, - onOpen: () -> Unit, - onSendAgain: (() -> Unit)?, - onBump: (() -> Unit)?, -) { - Card(modifier = Modifier.fillMaxWidth(), onClick = onOpen) { - ListItem( - headlineContent = { - Text( - text = (row.spend?.let { ProposedSpend.summarize(it, chain) } ?: ProposedSpend.UNREADABLE).detail, - maxLines = 2, - overflow = TextOverflow.Ellipsis, - ) - }, - supportingContent = { Text(stringResource(row.status.label())) }, - ) - if (onSendAgain != null || onBump != null) { - Row( - modifier = Modifier.fillMaxWidth().padding(horizontal = MaterialTheme.spacing.compactPadding), - horizontalArrangement = Arrangement.End, - ) { - onSendAgain?.let { TextButton(onClick = it) { Text(stringResource(Res.string.send_again)) } } - onBump?.let { TextButton(onClick = it) { Text(stringResource(Res.string.bump_the_fee)) } } - } - } - } -} - -private fun SpendStatus.label() = when (this) { - SpendStatus.WAITING_FOR_SIGNATURES -> Res.string.waiting_for_signatures - SpendStatus.ABANDONED -> Res.string.abandoned - SpendStatus.SIGNED -> Res.string.signed_sending_it_to_the_network - SpendStatus.SENT -> Res.string.sent_waiting_for_a_confirmation - SpendStatus.CONFIRMED -> Res.string.confirmed - SpendStatus.REPLACED -> Res.string.replaced_by_a_later_spend -} - -/** Confirmed and on-the-way said apart: only the first can be spent by a send-all. */ -/** - * The guarded wallets of groups below this one, and the guarded statements this - * device can still carry to the groups above. Both under the room's own wallet, - * or in place of it for a group that has none. - */ -private fun LazyListScope.guardianItems( - guardedWallets: List, - shareable: List, - isPending: Boolean, - onShare: (GuardianManager.Shareable) -> Unit, - onSpend: ((GuardedWalletRow) -> Unit)?, - onFund: ((GuardedWalletRow) -> Unit)?, - onOpenPerson: (HexKey) -> Unit, -) { - if (guardedWallets.isNotEmpty()) { - item { - Text(text = stringResource(Res.string.guarded_wallets), style = MaterialTheme.typography.titleMedium) - } - item { - Text( - text = stringResource(Res.string.wallets_of_groups_below_this_one), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - // Subgroups' wallets, each a room; then members', gathered by person, so - // that one member's wallets under different groups below read as one - // person's. docs/member-wallet-guarding-group.md, D6. - val subgroups = guardedWallets.filter { it.wallet.subject is GuardianManager.GuardedSubject.Subgroup } - items(subgroups, key = { "guarded-" + it.wallet.statement.id }) { row -> - GuardedWalletCard(row = row, onSpend = onSpend, onFund = onFund) - } - val people = guardedWallets.byPerson() - if (people.isNotEmpty()) { - item { - Text(text = stringResource(Res.string.members_wallets), style = MaterialTheme.typography.titleSmall) - } - people.forEach { person -> - item(key = "person-" + person.ownerPublicKey) { - PersonHeader(person = person, onOpen = { onOpenPerson(person.ownerPublicKey) }) - } - items(person.rows, key = { "guarded-" + it.wallet.statement.id }) { row -> - GuardedWalletCard( - row = row, - onSpend = onSpend, - onFund = onFund, - // Under the header, so the cards read as the person's. - modifier = Modifier.padding(start = MaterialTheme.spacing.containerPadding), - ) - } - } - } - } - - if (shareable.isNotEmpty()) { - item { - Text(text = stringResource(Res.string.tell_the_groups_above), style = MaterialTheme.typography.titleMedium) - } - // What is left here is what the automatic forwarding could not send -- - // a notice lost on the wire, most often -- so the section says so, once. - // docs/guarded-wallet-forwarding.md, Phase 6. - item { - Text( - text = stringResource(Res.string.this_device_shares_these_on_its_own_when_it_can), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - items(shareable, key = { "shareable-" + it.statement.id }) { candidate -> - ListItem( - headlineContent = { - Text( - text = candidate.ownerPublicKey?.let { stringResource(Res.string.at_s, candidate.ownerName ?: it.take(8)) } - ?: candidate.name - ?: stringResource(Res.string.a_subgroup), - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - }, - supportingContent = { Text(stringResource(Res.string.not_yet_shared_with_the_groups_above)) }, - trailingContent = { - TextButton(onClick = { onShare(candidate) }, enabled = !isPending) { - Text(stringResource(Res.string.share)) - } - }, - ) - } - } -} - -/** - * Each guardian of a guarded wallet with its own delay, nearest first: - * *#Council: after 144 blocks, about 1 day*. One sentence with one number in it - * stopped being true once each group chose its own -- `docs/guardian-delay.md`. - */ -@Composable -private fun GuardianDelays( - guardians: List, - names: Map, - chain: Chain, -) { - Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { - guardians.forEach { guardian -> - Text( - text = stringResource( - Res.string.guardian_after, - names[guardian.chatRoomId] ?: stringResource(Res.string.a_group_above_this_one), - delayText(guardian.delay, chain), - ), - style = MaterialTheme.typography.bodyMedium, - ) - } - } -} - -/** - * One descendant's guarded wallet: its name and what is within reach, and under - * them the actions, in the card's own row rather than the list item's trailing - * slot. Two buttons there would leave the name -- the one thing that says which - * wallet this is -- a few characters at large text sizes, and a flow row wraps - * them instead. Each button names its wallet, since a screen reader hears every - * row's *Fund* and *Spend* alike. See `docs/guarded-wallet-funding.md`, Phase 5. - */ -@Composable -private fun GuardedWalletCard( - row: GuardedWalletRow, - onSpend: ((GuardedWalletRow) -> Unit)?, - onFund: ((GuardedWalletRow) -> Unit)?, - modifier: Modifier = Modifier, -) { - val name = guardedName(row.wallet.subject) - val member = row.wallet.subject as? GuardianManager.GuardedSubject.Member - val guardedBy = member?.let { guardedByLine(row.wallet, it) } - // A member's card sits under their header, so it is named by its label -- - // or, with none, by the group that guards it, which still tells two of one - // person's wallets apart. - val headline = when { - member == null -> name - else -> member.label ?: guardedBy.orEmpty() - } - OutlinedCard(modifier = modifier.fillMaxWidth()) { - ListItem( - leadingContent = { Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) }, - // Two lines, since the name is what says which wallet the buttons act on. - headlineContent = { Text(headline, maxLines = 2, overflow = TextOverflow.Ellipsis) }, - supportingContent = { - val reach = row.withinReach?.let { stringResource(Res.string.s_sats_within_this_group_s_reach, it.grouped()) } - val arriving = row.arriving?.takeIf { it.sat > 0 }?.let { stringResource(Res.string.s_sats_arriving, it.grouped()) } - val amounts = when { - reach == null -> stringResource(Res.string.balance_not_known_yet) - arriving == null -> reach - else -> stringResource(Res.string.s_dot_s, reach, arriving) - } - Column { - // Which group below guards it, where the headline does not say. - if (member?.label != null && guardedBy != null) Text(guardedBy) - Text(amounts) - // This group's own leaf, which two of its descendants can have - // set differently. docs/guardian-delay.md. - Text(stringResource(Res.string.this_group_s_delay_in_this_wallet, delayText(row.wallet.delay, row.wallet.chain))) - } - }, - ) - if (onFund != null || onSpend != null) { - // Each names its wallet and not only its person: one member can have - // several here, and a screen reader hears every one's *Fund* alike. - val fundLabel = when { - member == null -> stringResource(Res.string.fund_s_s_guarded_wallet, name) - member.label != null -> stringResource(Res.string.fund_s_s_guarded_wallet_s, name, member.label) - else -> stringResource(Res.string.fund_s_s_wallet_guarded_by_s, name, guardianPhrase(row.wallet, member)) - } - val spendLabel = when { - member == null -> stringResource(Res.string.spend_from_s_s_guarded_wallet, name) - member.label != null -> stringResource(Res.string.spend_from_s_s_guarded_wallet_s, name, member.label) - else -> stringResource(Res.string.spend_from_s_s_wallet_guarded_by_s, name, guardianPhrase(row.wallet, member)) - } - FlowRow( - modifier = Modifier.fillMaxWidth().padding( - start = MaterialTheme.spacing.containerPadding, - end = MaterialTheme.spacing.containerPadding, - bottom = MaterialTheme.spacing.compactPadding, - ), - horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.targetGap, Alignment.End), - ) { - // Money in before money out, at equal weight: neither is the one - // every member wants, and a filled button would say it was. - onFund?.let { fund -> - TextButton(onClick = { fund(row) }, modifier = Modifier.semantics { contentDescription = fundLabel }) { - Text(stringResource(Res.string.fund)) - } - } - onSpend?.let { spend -> - TextButton(onClick = { spend(row) }, modifier = Modifier.semantics { contentDescription = spendLabel }) { - Text(stringResource(Res.string.spend)) - } - } - } - } - } -} - -/** - * One member, heading their wallets in an ancestor's list: how many this group - * guards, and under how many groups below it -- the summary that shows a person - * with wallets in more than one branch. Opens their profile. - */ -@Composable -private fun PersonHeader(person: PersonGuardedWallets, onOpen: () -> Unit) { - val name = stringResource(Res.string.at_s, person.ownerName ?: person.ownerPublicKey.take(8)) - val wallets = pluralStringResource(Res.plurals.n_wallets, person.rows.size, person.rows.size) - val groups = pluralStringResource(Res.plurals.guarded_by_n_groups, person.guardianCount, person.guardianCount) - ListItem( - modifier = Modifier.clickable(onClick = onOpen).minimumInteractiveComponentSize(), - // 40dp is the avatar's size, a dimension: M3's list item leading avatar. - leadingContent = { ProfileAvatar(size = 40.dp, publicKey = person.ownerPublicKey, picture = null, name = person.ownerName) }, - headlineContent = { Text(name, maxLines = 1, overflow = TextOverflow.Ellipsis) }, - supportingContent = { Text(stringResource(Res.string.s_comma_s, wallets, groups)) }, - ) -} - -/** - * The group that directly guards a member's wallet, as a phrase inside a - * sentence: *this group*, its name, or -- with no name this device can check -- - * where it sits, *a group below #P*. `docs/member-wallet-guarding-group.md`, D2. - */ -@Composable -internal fun guardianPhrase(wallet: GuardianManager.GuardedWallet, member: GuardianManager.GuardedSubject.Member): String = when { - wallet.isGuardedHere -> stringResource(Res.string.this_group) - member.guardianName != null -> member.guardianName - member.branchName != null -> stringResource(Res.string.a_group_below_s, member.branchName) - else -> stringResource(Res.string.a_group_below_this_one) -} - -/** - * *Guarded by #N*, or *Guarded by #M, below #P* where the group is further down - * than this one's own child -- the branch, so wallets from one part of the tree - * read as being from there. `docs/member-wallet-guarding-group.md`, D6. - */ -@Composable -internal fun guardedByLine(wallet: GuardianManager.GuardedWallet, member: GuardianManager.GuardedSubject.Member): String = - if (wallet.position >= 2 && member.guardianName != null && member.branchName != null) { - stringResource(Res.string.guarded_by_s_below_s, member.guardianName, member.branchName) - } else { - stringResource(Res.string.guarded_by_s, guardianPhrase(wallet, member)) - } - -/** - * A guarded wallet as an ancestor's list names it: a subgroup by the name its - * parent certified -- `#Translation` -- and a member by their profile's name -- - * `@alice` -- falling back to the start of their key. A person's name is theirs - * and live; the certificate fixes who they are, not what they are called. - */ -@Composable -internal fun guardedName(subject: GuardianManager.GuardedSubject): String = when (subject) { - is GuardianManager.GuardedSubject.Subgroup -> subject.name ?: stringResource(Res.string.a_subgroup) - is GuardianManager.GuardedSubject.Member -> stringResource(Res.string.at_s, subject.ownerName ?: subject.ownerPublicKey.take(8)) -} - -@Composable -internal fun BalanceCard(walletState: GroupWalletState?) { - Card(modifier = Modifier.fillMaxWidth()) { - Column( - modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) - ) { - Text( - text = stringResource(Res.string.balance), - style = MaterialTheme.typography.titleMedium, - ) - Text( - text = walletState?.let { stringResource(Res.string.s_sats, it.confirmedBalance.grouped()) } - ?: stringResource(Res.string.balance_not_known_yet), - style = MaterialTheme.typography.headlineMedium, - ) - walletState?.pendingBalance?.takeIf { it.sat > 0 }?.let { pending -> - Text( - text = stringResource(Res.string.s_sats_on_the_way, pending.grouped()), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - } -} - -@Composable -internal fun CoinRow(utxo: GroupUtxo, confirmations: Int) { - ListItem( - leadingContent = { Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) }, - headlineContent = { Text(stringResource(Res.string.s_sats, utxo.amount.grouped())) }, - supportingContent = { - val branch = stringResource( - if (utxo.derivation.change == GroupWalletDerivation.CHANGE) Res.string.change else Res.string.received - ) - val depth = if (confirmations == 0) { - stringResource(Res.string.waiting_for_a_confirmation) - } else { - stringResource(Res.string.s_confirmations, confirmations.toString()) - } - Text(text = stringResource(Res.string.s_dot_s, branch, depth), maxLines = 1, overflow = TextOverflow.Ellipsis) - } - ) -} 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 b990a85d..7ba054d6 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,5 @@ package mobi.giza.compose.ui.composable.navigation -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import mobi.giza.compose.ui.composable.GroupSendScreen -import mobi.giza.compose.ui.composable.navigation.routes.GroupSendRoute import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Surface import androidx.compose.material3.MaterialTheme @@ -44,8 +41,6 @@ import mobi.giza.compose.ui.composable.CreateSharedKeyScreen import mobi.giza.compose.ui.composable.DkgRitualScreen import mobi.giza.compose.ui.composable.DkgRound1ApprovalScreen import mobi.giza.compose.ui.composable.DkgRound2ApprovalScreen -import mobi.giza.compose.ui.composable.GroupWalletScreen -import mobi.giza.compose.ui.composable.GroupWalletAddressesScreen import mobi.giza.compose.ui.composable.HomeScreen import mobi.giza.compose.ui.composable.ImplementationPendingScreen import mobi.giza.compose.ui.composable.KeyPackageManagementScreen @@ -138,11 +133,6 @@ import kotlinx.coroutines.IO import kotlinx.coroutines.SupervisorJob 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.wallet.GroupOnchainWallets -import mobi.giza.compose.wallet.GroupTransactionWatcher -import fr.acinq.phoenix.managers.NodeParamsManager import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute import mobi.giza.compose.ui.composable.navigation.routes.ProposalListRoute import mobi.giza.compose.ui.composable.FrostSigningScreen @@ -220,12 +210,6 @@ fun GizaNavHost( ) } - // Giza keeps no wallet: no Electrum client, no group wallets, no group Lightning - // nodes and no transaction watcher are built (docs/giza-wallet-removal.md, Phase 1). - // The routes below that still take them get nothing, and nothing navigates there. - val groupOnchainWallets: GroupOnchainWallets? = null - val groupTransactionWatcher: GroupTransactionWatcher? = null - val navigationViewModel: NavigationViewModel = viewModel ( factory = NavigationViewModel.factory( activeIdentity = sovereignWalletViewModel.activeIdentity, @@ -1107,67 +1091,6 @@ fun GizaNavHost( }, ) } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - // Null only with no identity, for the frame between a profile - // switch and the startup screen: there is no chain to show yet. - val wallets = groupOnchainWallets ?: return@composable - - GroupWalletScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - chain = route.chain?.let(GroupWalletStatementEvent::chainNamed) ?: NodeParamsManager.chain, - chatRepository = databaseChatRepository, - frostSigningRepository = databaseFrostSigningRepository, - wallets = wallets, - watcher = groupTransactionWatcher, - onNavigateToRoute = { actionRoute -> - navController.navigate(route = actionRoute) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - val wallets = groupOnchainWallets ?: return@composable - - GroupWalletAddressesScreen( - chatRoomId = route.chatRoomId, - chain = route.chain?.let(GroupWalletStatementEvent::chainNamed) ?: NodeParamsManager.chain, - chatRepository = databaseChatRepository, - wallets = wallets, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - val wallets = groupOnchainWallets ?: return@composable - - GroupSendScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - chain = route.chain?.let(GroupWalletStatementEvent::chainNamed) ?: NodeParamsManager.chain, - chatRepository = databaseChatRepository, - frostSigningRepository = databaseFrostSigningRepository, - wallets = wallets, - guardedChatRoomId = route.guardedChatRoomId, - fundChatRoomId = route.fundChatRoomId, - onNavigateToRouteAndPopUpInclusive = { signingRoute -> - // Replace the form so back returns to the wallet rather - // than to a spend that has already been proposed. - navController.navigate(route = signingRoute) { - popUpTo { inclusive = true } - } - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } composable { backStackEntry -> val route = backStackEntry.toRoute() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupSendRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupSendRoute.kt deleted file mode 100644 index 4beda630..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupSendRoute.kt +++ /dev/null @@ -1,23 +0,0 @@ -package mobi.giza.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** - * The form a member proposes a spend from the group's wallet with -- or, with - * [guardedChatRoomId], from that descendant's guarded wallet, through the - * group's guardian leaf. - * - * [fundChatRoomId] is where the coins go instead of where they come from: the - * descendant whose guarded wallet a send from the group's own wallet pays. A - * route naming both is not one the form opens -- `docs/guarded-wallet-funding.md`, D6. - */ -@Serializable -data class GroupSendRoute( - val activeUserPublicKey: String, - val chatRoomId: String, - val relayHint: String?, - val guardedChatRoomId: String? = null, - val fundChatRoomId: String? = null, - /** The wallet's network, as `GroupWalletStatementEvent.chainName` spells it; null for the node's own. */ - val chain: String? = null, -): Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupWalletAddressesRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupWalletAddressesRoute.kt deleted file mode 100644 index 15ac76e1..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupWalletAddressesRoute.kt +++ /dev/null @@ -1,15 +0,0 @@ -package mobi.giza.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** - * The group wallet's receive addresses: every one paid, the one being handed - * out, and the next few -- pushed from the wallet screen's receive card. - */ -@Serializable -data class GroupWalletAddressesRoute( - val activeUserPublicKey: String, - val chatRoomId: String, - /** The wallet's network, as `GroupWalletStatementEvent.chainName` spells it; null for the node's own. */ - val chain: String? = null, -): Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupWalletRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupWalletRoute.kt deleted file mode 100644 index dbeec53b..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupWalletRoute.kt +++ /dev/null @@ -1,16 +0,0 @@ -package mobi.giza.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** - * The group's on-chain wallet: its balance, the address to be paid at, its - * coins, and -- for a group that has not opened one -- the way to ask it to. - */ -@Serializable -data class GroupWalletRoute( - val activeUserPublicKey: String, - val chatRoomId: String, - val relayHint: String?, - /** The wallet's network, as `GroupWalletStatementEvent.chainName` spells it; null for the node's own. */ - val chain: String? = null, -): Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/DelayText.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/DelayText.kt deleted file mode 100644 index 802dc659..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/DelayText.kt +++ /dev/null @@ -1,46 +0,0 @@ -package mobi.giza.compose.ui.composable.widgets - -import androidx.compose.runtime.Composable -import mobi.giza.compose.resources.Res -import mobi.giza.compose.resources.about_n_days -import mobi.giza.compose.resources.about_n_hours -import mobi.giza.compose.resources.about_n_minutes -import mobi.giza.compose.resources.about_n_months -import mobi.giza.compose.resources.about_n_years -import mobi.giza.compose.resources.blocks_and_about -import mobi.giza.compose.resources.n_blocks -import mobi.giza.compose.text.BlockDuration -import mobi.giza.compose.text.groupedBlocks -import fr.acinq.bitcoin.Chain -import org.jetbrains.compose.resources.pluralStringResource -import org.jetbrains.compose.resources.stringResource - -/** - * A guardian's delay as a member reads it: *144 blocks, about 1 day*. - * `docs/guardian-delay.md`, D5. - * - * Blocks only on regtest, whose blocks come when somebody mines one, so a time - * there would be wrong. [chain] is null where a delay is for no network in - * particular -- a birth certificate is not -- and then the estimate is - * mainnet's, as every network but regtest shares its target. - */ -@Composable -fun delayText(blocks: Long, chain: Chain? = null): String { - val count = pluralStringResource(Res.plurals.n_blocks, blocks.toInt(), blocks.groupedBlocks()) - if (chain == Chain.Regtest) return count - return stringResource(Res.string.blocks_and_about, count, approximateDuration(blocks)) -} - -/** *about 1 day*: [BlockDuration.approximate] in words. */ -@Composable -fun approximateDuration(blocks: Long): String { - val approximate = BlockDuration.approximate(blocks) - val plural = when (approximate.unit) { - BlockDuration.Unit.MINUTES -> Res.plurals.about_n_minutes - BlockDuration.Unit.HOURS -> Res.plurals.about_n_hours - BlockDuration.Unit.DAYS -> Res.plurals.about_n_days - BlockDuration.Unit.MONTHS -> Res.plurals.about_n_months - BlockDuration.Unit.YEARS -> Res.plurals.about_n_years - } - return pluralStringResource(plural, approximate.count, approximate.count) -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/GuardianDelayChooser.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/GuardianDelayChooser.kt deleted file mode 100644 index 78cf6198..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/GuardianDelayChooser.kt +++ /dev/null @@ -1,109 +0,0 @@ -package mobi.giza.compose.ui.composable.widgets - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.ExperimentalLayoutApi -import androidx.compose.foundation.layout.FlowRow -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.text.KeyboardOptions -import androidx.compose.material3.FilterChip -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.input.KeyboardType -import mobi.giza.compose.resources.Res -import mobi.giza.compose.resources.delay_custom -import mobi.giza.compose.resources.delay_in_blocks -import mobi.giza.compose.resources.delay_longest -import mobi.giza.compose.resources.delay_one_day -import mobi.giza.compose.resources.delay_one_hour -import mobi.giza.compose.resources.delay_one_month -import mobi.giza.compose.resources.delay_one_week -import mobi.giza.compose.resources.delay_six_months -import mobi.giza.compose.resources.delay_two_hours -import mobi.giza.compose.ui.theme.spacing -import mobi.giza.compose.ui.view.model.GuardianDelayInput -import org.jetbrains.compose.resources.stringResource - -/** - * How long a coin waits before a group can take it through its own leaf: in a - * guarded subgroup's wallet (`docs/guardian-delay.md`) or in the wallets it - * guards for its members (`docs/member-wallet-delay.md`). Presets for what - * people mean, and a field for the exact number of blocks, which says what it - * works out to while it is typed. - * - * The words are the caller's -- [title], and [consequence], the trade a long - * delay makes -- because *the subgroup* and *the member* differ. - */ -@OptIn(ExperimentalLayoutApi::class) -@Composable -fun GuardianDelayChooser( - title: String, - consequence: String, - input: String, - delay: Long?, - isCustom: Boolean, - problem: String?, - onPreset: (Long) -> Unit, - onCustom: () -> Unit, - onInput: (String) -> Unit, -) { - Column( - modifier = Modifier.fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) - ) { - Text( - text = title, - style = MaterialTheme.typography.titleSmall - ) - FlowRow( - horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) - ) { - GuardianDelayInput.PRESETS.forEach { preset -> - FilterChip( - selected = !isCustom && delay == preset, - onClick = { onPreset(preset) }, - label = { Text(presetLabel(preset)) } - ) - } - FilterChip( - selected = isCustom, - onClick = onCustom, - label = { Text(stringResource(Res.string.delay_custom)) } - ) - } - if (isCustom) { - OutlinedTextField( - value = input, - onValueChange = onInput, - modifier = Modifier.fillMaxWidth(), - singleLine = true, - keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), - label = { Text(stringResource(Res.string.delay_in_blocks)) }, - isError = problem != null, - supportingText = { Text(problem ?: delay?.let { delayText(it) }.orEmpty()) } - ) - } else if (delay != null && problem == null) { - Text(text = delayText(delay), style = MaterialTheme.typography.bodyMedium) - } - Text( - text = consequence, - style = MaterialTheme.typography.bodySmall - ) - } -} - -/** What a preset chip calls its delay: the time it was chosen to be, not its estimate. */ -@Composable -private fun presetLabel(blocks: Long): String = when (blocks) { - 6L -> stringResource(Res.string.delay_one_hour) - 12L -> stringResource(Res.string.delay_two_hours) - 144L -> stringResource(Res.string.delay_one_day) - 1_008L -> stringResource(Res.string.delay_one_week) - 4_320L -> stringResource(Res.string.delay_one_month) - 26_280L -> stringResource(Res.string.delay_six_months) - else -> stringResource(Res.string.delay_longest) -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatMessageListViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatMessageListViewModel.kt index 38f3da2a..89452998 100755 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatMessageListViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatMessageListViewModel.kt @@ -1,6 +1,5 @@ package mobi.giza.compose.ui.view.model -import mobi.giza.compose.text.ProposedSpend import mobi.giza.compose.database.model.types.FrostSigningSubject import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.items @@ -236,13 +235,9 @@ class ChatMessageListViewModel( // The first item that can be read, not the first item: // a batch whose lead is unreadable is still about // something, and the notice should say what. - lead = if (local.session.subject == FrostSigningSubject.TRANSACTION) { - // Said without reading the PSBT: the notice only has - // to say what kind of thing is waiting, and the - // signing screen is where the spend is checked. - ProposedSpend.UNREADABLE.copy(detail = "") - } else if (local.session.subject == FrostSigningSubject.SWEEP) { - ProposedSpend.SWEEP.copy(detail = "") + lead = if (local.session.subject != FrostSigningSubject.EVENTS) { + // A Bennu peer's wallet, said without reading it. + ProposedEvent.WALLET.copy(detail = "") } else { local.items.firstNotNullOfOrNull { item -> Event.fromJsonOrNull(item.unsignedEventJson) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/FrostSigningViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/FrostSigningViewModel.kt index d2f9484e..d58232c9 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/FrostSigningViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/FrostSigningViewModel.kt @@ -1,7 +1,5 @@ package mobi.giza.compose.ui.view.model -import mobi.giza.compose.wallet.GroupSpend -import mobi.giza.compose.database.model.types.FrostSigningSubject import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -85,12 +83,6 @@ class FrostSigningViewModel( // `FrostSigningRepository.membersOwing`. val owed = session?.let { frostSigningRepository.membersOwing(it) } ?: emptySet() - // Checked once: the PSBT is write-once, so what it says cannot - // change under a session that is still being collected. - if (session?.subject == FrostSigningSubject.TRANSACTION && checkedSpend == null) { - checkedSpend = frostSigningRepository.checkedSpend(session.id) - } - frostSigningUIState = FrostSigningUIState.Loaded( localChatRoom = localChatRoom, session = session, @@ -109,14 +101,11 @@ class FrostSigningViewModel( .map { it.signerPublicKey } .toSet(), silent = owed, - spend = checkedSpend, ) } } } - private var checkedSpend: GroupSpend.Checked? = null - /** One emission of everything the screen is drawn from -- the fourth flow outgrew `Triple`. */ private data class Observed( val session: FrostSigningSession?, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupSendViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupSendViewModel.kt deleted file mode 100644 index d18498b0..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupSendViewModel.kt +++ /dev/null @@ -1,299 +0,0 @@ -package mobi.giza.compose.ui.view.model - -import mobi.giza.compose.wallet.GroupWalletRollout -import mobi.giza.compose.wallet.GroupSpend -import mobi.giza.compose.nostr.wallet.GroupWallet -import mobi.giza.compose.database.model.GroupSignedEvent -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.repository.ChatRepository -import mobi.giza.compose.repository.FrostSigningRepository -import mobi.giza.compose.text.SatsInput -import mobi.giza.compose.text.parseSats -import mobi.giza.compose.ui.view.state.FundingTarget -import mobi.giza.compose.ui.view.state.GroupSendUIState -import mobi.giza.compose.wallet.GroupOnchainWallets -import mobi.giza.compose.wallet.GroupSpendBuilder -import mobi.giza.compose.wallet.GroupWalletState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.Satoshi -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.Job -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.combine -import kotlinx.coroutines.flow.flowOf -import kotlinx.coroutines.flow.mapLatest -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext - -/** - * A spend from the group's wallet, built as the member types and proposed when - * they ask. - * - * The preview the screen shows is [preview] over the same inputs the proposal is - * built from, so the fee a member reads before pressing the button is the fee - * the group is then asked to sign -- there is no second build. - */ -class GroupSendViewModel( - val activeUserPublicKey: HexKey, - val chatRoomId: String, - val chain: Chain, - initialGroupSendUIState: GroupSendUIState, - val chatRepository: ChatRepository, - val frostSigningRepository: FrostSigningRepository, - private val wallets: GroupOnchainWallets, - /** The descendant whose guarded wallet this form spends from, or null for the room's own. */ - val guardedChatRoomId: String? = null, - /** The descendant whose guarded wallet this form pays, or null for a payment to a typed address. */ - val fundChatRoomId: String? = null, -): ViewModel() { - private val logger = Logger.withTag(TAG) - - var groupSendUIState: GroupSendUIState by mutableStateOf(initialGroupSendUIState) - 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 localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - if (localChatRoom == null) { - groupSendUIState = GroupSendUIState.Error("Couldn't find the group") - return@launch - } - - // Spending from one descendant's wallet into another's is a decision - // of its own, not one this form makes -- docs/guarded-wallet-funding.md, D6. - if (guardedChatRoomId != null && fundChatRoomId != null) { - groupSendUIState = GroupSendUIState.Unavailable - return@launch - } - - // A descendant's guarded wallet, as this room was told it, with the - // group as its guardian -- or the room's own wallet. - val heldByRoom = if (guardedChatRoomId != null || fundChatRoomId != null) chatRepository.guardedWallets(chatRoomId) else emptyList() - fun held(descendant: String?) = descendant?.let { - heldByRoom.firstOrNull { wallet -> wallet.descendantChatRoomId.equals(it, ignoreCase = true) && wallet.chain == chain } - } - val guarded = held(guardedChatRoomId) - // The wallet a send from the room's own pays, when it funds one. - val funded = held(fundChatRoomId) - val wallet = when { - guardedChatRoomId == null -> chatRepository.groupWallet(chatRoomId, chain) - guarded == null -> null - else -> GroupWallet(GroupSignedEvent.fromEvent(guarded.statement, chatRoomId = guarded.descendantChatRoomId), guarded.account) - } - val canSign = localChatRoom.chatRoom.mlsGroupState != null && chatRepository.canSign(chatRoomId) - if (wallet == null || !canSign || (fundChatRoomId != null && funded == null)) { - groupSendUIState = GroupSendUIState.Unavailable - return@launch - } - - val ready = GroupSendUIState.Ready( - localChatRoom = localChatRoom, - wallet = wallet, - walletState = null, - reserved = frostSigningRepository.reservedOutPoints(chatRoomId), - reservedChange = frostSigningRepository.reservedChangeIndices(chatRoomId, wallet.account), - spender = guarded?.spender() ?: GroupSpend.Spender.Owner, - funding = funded?.let { FundingTarget(it, walletState = null, reserved = frostSigningRepository.reservedFundingIndices(chatRoomId, it.account)) }, - ) - groupSendUIState = ready - - wallets.suggestedFeeratePerVbyte(chain)?.let { suggested -> - withContext(Dispatchers.Main) { - if (feerateField.text.isEmpty()) feerateField.setTextAndPlaceCursorAtEnd(suggested.toString()) - } - } - - follow(ready, wallets.walletFor(wallet.account).state, funded?.let { wallets.walletFor(it.account).state }) - } - } - - /** - * Keeps [ready] current: the coins from [chainState], and which of them -- - * and which change addresses -- the room's open spends hold, re-read every - * time a spend is proposed, fails or settles. Read once, a spend another - * member proposed while this form was open would still look free, and - * sending everything would ask the group to sign a second spend of coins - * only one spend can have. - * - * One state from both, as the wallet screen does, so no frame shows new - * coins against old reservations. Apart from [initiate] so that it can be - * followed without an Electrum client. - * - * A send that funds a descendant's wallet follows [fundingState] too, and - * the addresses the room's open fundings hold: if the address it was going - * to pay is paid or taken while the form is open, the next one is shown. - */ - @OptIn(ExperimentalCoroutinesApi::class) - internal fun follow( - ready: GroupSendUIState.Ready, - chainState: Flow, - fundingState: Flow? = null, - ) { - val account = ready.wallet.account - val fundedAccount = ready.funding?.wallet?.account - val reservations = frostSigningRepository.observeGroupTransactions(chatRoomId).mapLatest { - Triple( - frostSigningRepository.reservedOutPoints(chatRoomId), - frostSigningRepository.reservedChangeIndices(chatRoomId, account), - fundedAccount?.let { frostSigningRepository.reservedFundingIndices(chatRoomId, it) }.orEmpty(), - ) - } - watching?.cancel() - watching = viewModelScope.launch(Dispatchers.IO) { - combine(chainState, fundingState ?: flowOf(null), reservations) { state, funded, (reserved, reservedChange, reservedFunding) -> - ready.copy( - walletState = state, - reserved = reserved, - reservedChange = reservedChange, - funding = ready.funding?.copy(walletState = funded, reserved = reservedFunding), - ) - }.collect { groupSendUIState = it } - } - } - - /** What the amount field says, read the one way everything that reads it does. */ - fun amount(): SatsInput = parseSats(amountField.text) - - /** The confirmed coins no open spend holds, summed, or null before Electrum has answered. */ - /** - * How long a coin has to have waited before this group, as a guardian, can - * spend it -- its own leaf's delay -- or null when the group spends its own - * wallet. `docs/guardian-delay.md`. - */ - fun guardianDelay(): Long? { - val state = groupSendUIState as? GroupSendUIState.Ready ?: return null - val guardian = state.spender as? GroupSpend.Spender.Guardian ?: return null - return state.wallet.account.guardians.getOrNull(guardian.position)?.delay - } - - fun spendable(): Satoshi? { - val state = groupSendUIState as? GroupSendUIState.Ready ?: return null - return state.walletState?.let { GroupSpendBuilder.spendableBalance(it, state.reserved, state.spender) } - } - - /** - * Whether [result] is about the amount typed, and so belongs on the amount - * field rather than under the form. Never while sending everything: there - * is no amount field then, and a send-all too small or over the cap is the - * form's problem as a whole. - */ - 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 right now, or null while it is incomplete -- - * no wallet state yet, no feerate, no amount. An amount that is not one is - * not incomplete, and says so before the rest of the form is filled in. - */ - fun preview(): GroupSpendBuilder.Result? { - val state = groupSendUIState as? GroupSendUIState.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 - // A funding pays the address its target chose, never one typed: the - // title says whose wallet it is, and a typed one would make that a claim. - val destination = when (val funding = state.funding) { - null -> GroupSpendBuilder.Destination.Address(addressField.text.toString().trim().takeIf { it.isNotEmpty() } ?: return null) - else -> GroupSpendBuilder.Destination.Funding(funding.wallet.account, funding.address?.derivation ?: return null) - } - - val built = if (amount == null) { - GroupSpendBuilder.sendAll(walletState, destination, feerate, state.reserved, state.spender) - } else { - GroupSpendBuilder.send(walletState, destination, amount, feerate, state.reserved, state.reservedChange, state.spender) - } - return GroupSpendBuilder.capped(built, GroupWalletRollout.capFor(chain)) - } - - fun propose(onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) { - val state = groupSendUIState as? GroupSendUIState.Ready ?: return - val built = preview() as? GroupSpendBuilder.Result.Built ?: return - if (isActionPending.value) return - isActionPending.value = true - - viewModelScope.launch(Dispatchers.IO) { - val session = runCatching { - when (val descendant = guardedChatRoomId.takeIf { state.spender is GroupSpend.Spender.Guardian }) { - null -> frostSigningRepository.proposeSpend( - localChatRoom = state.localChatRoom, - userPublicKey = activeUserPublicKey, - psbt = built.psbt, - chain = chain, - ) - else -> frostSigningRepository.proposeGuardianSpend( - localChatRoom = state.localChatRoom, - userPublicKey = activeUserPublicKey, - psbt = built.psbt, - descendantChatRoomId = descendant, - chain = chain, - ) - } - }.onFailure { logger.e("Failed to propose a spend from $chatRoomId", it) }.getOrNull() - - withContext(Dispatchers.Main) { - if (session != null) onSuccess(session.id) else onFailure() - } - isActionPending.value = false - } - } - - companion object { - private const val TAG = "GroupSendViewModel" - - fun factory( - activeUserPublicKey: HexKey, - chatRoomId: String, - chain: Chain, - initialGroupSendUIState: GroupSendUIState = GroupSendUIState.Loading, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - wallets: GroupOnchainWallets, - guardedChatRoomId: String? = null, - fundChatRoomId: String? = null, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - GroupSendViewModel( - activeUserPublicKey, chatRoomId, chain, initialGroupSendUIState, - chatRepository, frostSigningRepository, wallets, guardedChatRoomId, fundChatRoomId, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupWalletAddressesViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupWalletAddressesViewModel.kt deleted file mode 100644 index ab5352e0..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupWalletAddressesViewModel.kt +++ /dev/null @@ -1,103 +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.repository.ChatRepository -import mobi.giza.compose.ui.view.state.GroupWalletAddressesUIState -import mobi.giza.compose.wallet.GroupAddress -import mobi.giza.compose.wallet.GroupOnchainWallets -import fr.acinq.bitcoin.Chain -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext - -/** - * The group wallet's addresses, watched for as long as the screen is open. - * - * [wallets] hands back the wallet the wallet screen is already watching, so the - * list costs no subscriptions of its own and agrees with that screen about which - * address is current. - */ -class GroupWalletAddressesViewModel( - val chatRoomId: String, - val chain: Chain, - initialUIState: GroupWalletAddressesUIState, - val chatRepository: ChatRepository, - private val wallets: GroupOnchainWallets, -): ViewModel() { - var uiState: GroupWalletAddressesUIState by mutableStateOf(initialUIState) - private set - - /** The index of the address the sheet is showing as a QR code, or null when it is closed. */ - var shown: Long? by mutableStateOf(null) - private set - - private var onShownPaid: (() -> Unit)? = null - - /** - * Opens the sheet on the receive address at [index]. [onPaid] runs once if - * that address is paid while the sheet is open, as the sheet closes: whoever - * is scanning it then has already paid, and nobody else should. - */ - fun show(index: Long, onPaid: () -> Unit) { - shown = index - onShownPaid = onPaid - } - - fun dismiss() { - shown = null - onShownPaid = null - } - - fun initiate() { - viewModelScope.launch(Dispatchers.IO) { - val wallet = chatRepository.groupWallet(chatRoomId, chain) - if (wallet == null) { - uiState = GroupWalletAddressesUIState.Error("This group has not opened a wallet") - return@launch - } - - uiState = GroupWalletAddressesUIState.Loaded(receive = null) - wallets.walletFor(wallet.account).state.collect { state -> - val receive = state.receiveAddresses - uiState = GroupWalletAddressesUIState.Loaded(receive = receive, change = state.changeAddresses.orEmpty()) - - val index = shown ?: return@collect - val status = receive?.firstOrNull { it.derivation.index == index }?.status ?: return@collect - if (status == GroupAddress.Status.USED) { - val paid = onShownPaid - withContext(Dispatchers.Main) { - dismiss() - paid?.invoke() - } - } - } - } - } - - companion object { - fun factory( - chatRoomId: String, - chain: Chain, - initialUIState: GroupWalletAddressesUIState = GroupWalletAddressesUIState.Loading, - chatRepository: ChatRepository, - wallets: GroupOnchainWallets, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - GroupWalletAddressesViewModel( - chatRoomId = chatRoomId, - chain = chain, - initialUIState = initialUIState, - chatRepository = chatRepository, - wallets = wallets, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupWalletViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupWalletViewModel.kt deleted file mode 100644 index 56ecfaf9..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupWalletViewModel.kt +++ /dev/null @@ -1,343 +0,0 @@ -package mobi.giza.compose.ui.view.model - -import mobi.giza.compose.managers.GuardianDerivation -import mobi.giza.compose.nostr.subgroup.isDecided -import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy -import mobi.giza.compose.database.model.GroupTransaction -import mobi.giza.compose.ui.view.state.SpendRow -import mobi.giza.compose.ui.view.state.SpendStatus -import mobi.giza.compose.wallet.GroupSpend -import mobi.giza.compose.wallet.GroupSpendBuilder -import mobi.giza.compose.wallet.GroupTransactionWatcher -import mobi.giza.compose.wallet.GroupWalletRollout -import mobi.giza.compose.managers.GuardianManager -import mobi.giza.compose.ui.view.state.GuardedWalletRow -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.combine -import kotlinx.coroutines.flow.flowOf -import kotlinx.coroutines.flow.map -import kotlinx.coroutines.flow.distinctUntilChangedBy -import mobi.giza.compose.managers.GroupWalletDerivation -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.nostr.wallet.GroupWalletStatementEvent -import mobi.giza.compose.repository.ChatRepository -import mobi.giza.compose.repository.FrostSigningRepository -import mobi.giza.compose.ui.view.state.GroupWalletUIState -import mobi.giza.compose.wallet.GroupOnchainWallets -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.Chain -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.Job -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext - -/** - * The group's wallet, read once for what the group has signed and then watched - * for what the chain says. - * - * The statement is a read, like every other group-signed thing's screen; the - * coins are a watch, because a payment arriving while the screen is open is the - * one moment somebody is looking at it. - * - * [wallets] watch on the identity's Electrum client: its node's, or for an nsec - * or npub profile one of its own (docs/standalone-electrum.md). - */ -class GroupWalletViewModel( - val activeUserPublicKey: HexKey, - val chatRoomId: String, - val chain: Chain, - initialGroupWalletUIState: GroupWalletUIState, - val chatRepository: ChatRepository, - val frostSigningRepository: FrostSigningRepository, - private val wallets: GroupOnchainWallets, - private val watcher: GroupTransactionWatcher? = null, -): ViewModel() { - private val logger = Logger.withTag(TAG) - - var groupWalletUIState: GroupWalletUIState by mutableStateOf(initialGroupWalletUIState) - private set - - val isActionPending: MutableState = mutableStateOf(false) - - private var watching: Job? = null - - fun initiate() { - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - if (localChatRoom == null) { - groupWalletUIState = GroupWalletUIState.Error("Couldn't find the group") - return@launch - } - - val canSign = localChatRoom.chatRoom.mlsGroupState != null && chatRepository.canSign(chatRoomId) - val wallet = chatRepository.groupWallet(chatRoomId, chain) - val guarded = chatRepository.guardedWallets(chatRoomId).filter { it.chain == chain } - // The catch-up first, so what the screen offers to share is only what - // could not be sent. docs/guarded-wallet-forwarding.md, Phase 4. - chatRepository.forwardGuardedWallets(chatRoomId) - val shareable = chatRepository.shareableGuardedWallets(chatRoomId, chain) - val guardedRows = guarded.map { GuardedWalletRow(it, walletState = null) } - - watching?.cancel() - - if (wallet == null) { - // What the room's parent decided at its birth: a decided policy - // leaves one way in, and an undecided or absent one both, as - // before policies. docs/subgroup-wallet-policy.md. - val policy = chatRepository.walletPolicyOf(chatRoomId) - val offersGuarded = !policy.isDecided(SubgroupWalletPolicy.UNGUARDED) && - GroupWalletRollout.offersGuardiansOn(chain) - val notOpened = GroupWalletUIState.NotOpened( - localChatRoom = localChatRoom, - account = chatRepository.groupWalletAccount(chatRoomId, chain), - canSign = canSign, - guarded = if (offersGuarded) { - chatRepository.groupWalletGuardedOpening(chatRoomId, chain) - } else null, - policy = policy, - offersPlain = !policy.isDecided(SubgroupWalletPolicy.GUARDED), - guardedWallets = guardedRows, - shareable = shareable, - ).let { it.copy(guardianNames = namesOf(it.guarded?.account?.guardians.orEmpty())) } - groupWalletUIState = notOpened - if (guarded.isNotEmpty()) { - watching = viewModelScope.launch(Dispatchers.IO) { - guardedStates(guarded).collect { rows -> groupWalletUIState = notOpened.copy(guardedWallets = rows) } - } - } - return@launch - } - - val loaded = GroupWalletUIState.Loaded( - localChatRoom = localChatRoom, - wallet = wallet, - walletState = null, - canSign = canSign, - guardedWallets = guardedRows, - shareable = shareable, - guardianNames = namesOf(wallet.account.guardians), - ) - groupWalletUIState = loaded - - // The chain, the room's spends and the wallets it guards, as one - // state: any of them changing redraws the screen, and none may - // overwrite another. - val chainState = wallets.walletFor(wallet.account).state - noticeGuardianSpends(wallet.account) - watching = viewModelScope.launch(Dispatchers.IO) { - combine( - chainState, - frostSigningRepository.observeGroupTransactions(chatRoomId), - guardedStates(guarded), - ) { state, transactions, guardedWallets -> - Triple(state, transactions.map { rowOf(it) }, guardedWallets) - }.collect { (state, rows, guardedWallets) -> - groupWalletUIState = loaded.copy(walletState = state, spends = rows, guardedWallets = guardedWallets) - } - } - } - } - - /** - * What this device calls each of [guardians]' rooms, for the ones it holds: - * the wallet screen lists each guardian with its own delay, and a room id is - * not a name. A guardian whose room this device does not have is left out, - * and the screen says *a group above this one*. - */ - private suspend fun namesOf(guardians: List): Map = - guardians.mapNotNull { guardian -> - chatRepository.getChatRoomByIdentifier(guardian.chatRoomId)?.chatRoom?.subject?.let { guardian.chatRoomId to it } - }.toMap() - - /** Each guarded wallet with what the chain says of it, on the identity's Electrum client. */ - private suspend fun guardedStates(guarded: List): Flow> { - if (guarded.isEmpty()) return flowOf(emptyList()) - - val states = guarded.map { wallet -> wallets.walletFor(wallet.account).state.map { GuardedWalletRow(wallet, it) } } - return combine(states) { it.toList() } - } - - private var noticing: Job? = null - - /** - * For a guarded wallet: each time its coins change, reads the chain for - * spends a guardian made from it and writes the transcript line for any that - * has none -- the group's only notice, since nobody in it signed them. - */ - private suspend fun noticeGuardianSpends(account: GroupWalletDerivation.Account) { - if (!account.isGuarded) return - val onchain = wallets.walletFor(account) - - noticing?.cancel() - noticing = viewModelScope.launch(Dispatchers.IO) { - onchain.state - .distinctUntilChangedBy { state -> state.utxos.map { it.utxo.outPoint }.toSet() } - .collect { state -> chatRepository.recordGuardianSpends(chatRoomId, wallets.guardianSpends(state)) } - } - } - - /** - * Tells the groups above about [shareable]'s guarded wallet: one notice into - * each of their rooms this device is in. What is told stays told, so the - * row goes from the screen once it is sent. - */ - fun share(shareable: GuardianManager.Shareable, onShared: () -> Unit, onFailure: () -> Unit) { - if (isActionPending.value) return - isActionPending.value = true - - viewModelScope.launch(Dispatchers.IO) { - val told = chatRepository.shareGuardedWallet(shareable, activeUserPublicKey) - if (told > 0) { - groupWalletUIState = when (val state = groupWalletUIState) { - is GroupWalletUIState.Loaded -> state.copy(shareable = state.shareable - shareable) - is GroupWalletUIState.NotOpened -> state.copy(shareable = state.shareable - shareable) - else -> state - } - } - withContext(Dispatchers.Main) { if (told > 0) onShared() else onFailure() } - isActionPending.value = false - } - } - - /** Checked once per session: the PSBT is write-once, so what it says cannot change. */ - private val checkedSpends = mutableMapOf() - - private suspend fun rowOf(transaction: GroupTransaction): SpendRow { - val sessionId = transaction.frostSigningSessionId - val spend = checkedSpends.getOrPut(sessionId) { frostSigningRepository.checkedSpend(sessionId) } - val stage = frostSigningRepository.getSessionById(sessionId)?.stage - return SpendRow(transaction = transaction, status = SpendStatus.of(stage, transaction), spend = spend) - } - - /** Sends a signed spend again now. Only worth anything while Electrum has not reported it back. */ - fun sendAgain(sessionId: String, onSent: () -> Unit) { - val watcher = watcher ?: return - viewModelScope.launch(Dispatchers.IO) { - if (runCatching { watcher.broadcastAgain(sessionId) }.getOrDefault(false)) { - withContext(Dispatchers.Main) { onSent() } - } - } - } - - /** - * Asks the group to sign [sessionId]'s spend again at twice its feerate: the - * same coins, the extra out of the change. A new session with new signatures -- - * a retry is never the old session again -- and whichever of the two confirms - * settles the other. - */ - fun bumpFee(sessionId: String, onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) { - val state = groupWalletUIState as? GroupWalletUIState.Loaded ?: return - val spend = state.spends.firstOrNull { it.transaction.frostSigningSessionId == sessionId }?.spend ?: return - if (isActionPending.value) return - - val built = GroupSpendBuilder.bump(spend, spend.feeratePerVbyte * 2) as? GroupSpendBuilder.Result.Built - if (built == null) { - onFailure() - return - } - isActionPending.value = true - - // A guardian's spend is bumped as one: the same leaf, the same descendant. - val guardedChatRoomId = state.spends.first { it.transaction.frostSigningSessionId == sessionId }.transaction.guardedChatRoomId - - viewModelScope.launch(Dispatchers.IO) { - val session = runCatching { - when (guardedChatRoomId) { - null -> frostSigningRepository.proposeSpend(state.localChatRoom, activeUserPublicKey, built.psbt, chain) - else -> frostSigningRepository.proposeGuardianSpend(state.localChatRoom, activeUserPublicKey, built.psbt, guardedChatRoomId, chain) - } - }.onFailure { logger.e("Failed to bump $sessionId", it) }.getOrNull() - - withContext(Dispatchers.Main) { - if (session != null) onSuccess(session.id) else onFailure() - } - isActionPending.value = false - } - } - - /** - * Asks the group to open its wallet: one signing session over one statement. - * - * Never batched with anything, for the reason `GroupWalletStatementEvent` - * gives -- every spend is opened against this, and it should never be as - * available as its worst co-passenger. - * - * [guarded] opens the guarded account the room's certificate grants instead - * of the plain one: the statement then names the guardians and carries the - * certificate, and the group's quorum signing it is the group agreeing to be - * guarded. - */ - fun openWallet(guarded: Boolean = false, onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) { - val state = groupWalletUIState as? GroupWalletUIState.NotOpened ?: return - val template = if (guarded) { - val opening = state.guarded ?: return - GroupWalletStatementEvent.template(opening.account, opening.certificate) - } else { - // Not under a parent that decided this wallet is guarded: no state - // offers it, and every other member would refuse it anyway. - if (!state.offersPlain) return - GroupWalletStatementEvent.template(state.account ?: return) - } - // A second statement for the same account is harmless -- the same values - // under the same `d` tag -- but it is a second quorum asked for nothing. - if (isActionPending.value) return - isActionPending.value = true - - viewModelScope.launch(Dispatchers.IO) { - val session = runCatching { - frostSigningRepository.proposeSigning( - localChatRoom = state.localChatRoom, - userPublicKey = activeUserPublicKey, - kind = template.kind, - tags = template.tags, - content = template.content, - ) - }.onFailure { error -> - logger.e("Failed to propose a wallet for $chatRoomId", error) - }.getOrNull() - - withContext(Dispatchers.Main) { - if (session != null) onSuccess(session.id) else onFailure() - } - - isActionPending.value = false - } - } - - companion object { - private const val TAG = "GroupWalletViewModel" - - fun factory( - activeUserPublicKey: HexKey, - chatRoomId: String, - chain: Chain, - initialGroupWalletUIState: GroupWalletUIState = GroupWalletUIState.Loading, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - wallets: GroupOnchainWallets, - watcher: GroupTransactionWatcher? = null, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - GroupWalletViewModel( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - chain = chain, - initialGroupWalletUIState = initialGroupWalletUIState, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository, - wallets = wallets, - watcher = watcher, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GuardianDelayInput.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GuardianDelayInput.kt deleted file mode 100644 index 4e3de3e6..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GuardianDelayInput.kt +++ /dev/null @@ -1,70 +0,0 @@ -package mobi.giza.compose.ui.view.model - -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.mutableStateOf -import mobi.giza.compose.managers.GuardianDerivation -import mobi.giza.compose.text.groupedBlocks - -/** - * A guardian delay as somebody is choosing it -- a preset, or blocks typed -- - * for the two screens that choose one: the subgroup picker - * (`docs/guardian-delay.md`) and the group's member-wallet policy - * (`docs/member-wallet-delay.md`). - * - * Holds the text as typed and never clamps it, so the field can say *at most - * 65,535 blocks* about the number somebody actually entered. - */ -class GuardianDelayInput(initial: Long = GuardianDerivation.DEFAULT_DELAY) { - /** The delay, in blocks, as typed or picked. */ - val input: MutableState = mutableStateOf(initial.toString()) - - /** Whether the delay is being typed rather than picked from a preset. */ - val isCustom: MutableState = mutableStateOf(initial !in PRESETS) - - /** Picks a preset. */ - fun pick(blocks: Long) { - isCustom.value = false - input.value = blocks.toString() - } - - /** Switches to typing, starting from the delay already chosen. */ - fun useCustom() { - isCustom.value = true - } - - /** What was typed, digits only, kept as typed. */ - fun type(value: String) { - input.value = value.filter { it in '0'..'9' }.take(MAX_DIGITS) - } - - /** Starts again from [blocks]: a preset as its chip, anything else in the field. */ - fun reset(blocks: Long) { - input.value = blocks.toString() - isCustom.value = blocks !in PRESETS - } - - /** The delay typed or picked, or null while the field holds no number. */ - fun delay(): Long? = input.value.toLongOrNull() - - /** Why the delay cannot be used, or null when it can. */ - fun problem(): String? { - val delay = delay() ?: return "Give the delay in blocks." - return when { - delay < GuardianDerivation.MIN_DELAY -> "A delay is at least ${GuardianDerivation.MIN_DELAY} blocks." - delay > GuardianDerivation.MAX_DELAY -> "A delay is at most ${GuardianDerivation.MAX_DELAY.groupedBlocks()} blocks." - else -> null - } - } - - companion object { - /** - * The delays offered as chips, in blocks -- `docs/guardian-delay.md`, D4: - * an hour, two (the default), a day, a week, a month, six months, and the - * longest a leaf can carry. - */ - val PRESETS: List = listOf(6L, 12L, 144L, 1_008L, 4_320L, 26_280L, GuardianDerivation.MAX_DELAY) - - /** Enough digits for anything past the ceiling, so the field can say so. */ - private const val MAX_DIGITS = 7 - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ProposalListViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ProposalListViewModel.kt index 91f5d56b..bf50c27a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ProposalListViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ProposalListViewModel.kt @@ -1,6 +1,5 @@ package mobi.giza.compose.ui.view.model -import mobi.giza.compose.text.ProposedSpend import mobi.giza.compose.database.model.types.FrostSigningSubject import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -163,14 +162,8 @@ class ProposalListViewModel( else -> local.proposer?.humanReadableNameOrPubkey() ?: local.session.coordinatorPublicKey.shortened() }, - signs = if (local.session.subject == FrostSigningSubject.TRANSACTION) { - listOf( - frostSigningRepository.checkedSpend(local.session.id) - ?.let { ProposedSpend.summarize(it, it.account.chain) } - ?: ProposedSpend.UNREADABLE - ) - } else if (local.session.subject == FrostSigningSubject.SWEEP) { - listOf(ProposedSpend.SWEEP) + signs = if (local.session.subject != FrostSigningSubject.EVENTS) { + listOf(ProposedEvent.WALLET) } else { events.map { ProposedEvent.summarize(it) } }, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/FrostSigningUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/FrostSigningUIState.kt index d7b61d6e..b0849f65 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/FrostSigningUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/FrostSigningUIState.kt @@ -1,6 +1,5 @@ package mobi.giza.compose.ui.view.state -import mobi.giza.compose.wallet.GroupSpend import com.vitorpamplona.quartz.nip01Core.core.HexKey import kotlin.time.Clock import kotlin.time.Instant @@ -58,13 +57,6 @@ sealed interface FrostSigningUIState { */ val silent: Set = emptySet(), - /** - * For a session over a transaction, the spend as [mobi.giza.compose.wallet.GroupSpend.check] - * vouched for it -- every output, which are change, and the fee. Null for - * an event session, and for a spend this device could not check, which - * the screen refuses to let anybody sign. - */ - val spend: GroupSpend.Checked? = null, ): FrostSigningUIState { /** * The members the session can be answered by, as rows to draw. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupSendUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupSendUIState.kt deleted file mode 100644 index ae997e28..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupSendUIState.kt +++ /dev/null @@ -1,58 +0,0 @@ -package mobi.giza.compose.ui.view.state - -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.managers.GuardianManager -import mobi.giza.compose.wallet.GroupAddress -import mobi.giza.compose.nostr.wallet.GroupWallet -import mobi.giza.compose.wallet.GroupSpend -import mobi.giza.compose.wallet.GroupWalletState -import fr.acinq.bitcoin.OutPoint - -sealed interface GroupSendUIState { - /** - * A wallet this device can propose a spend from: it holds a share, and it has - * a node to see the coins with. [walletState] is null until Electrum answers. - */ - data class Ready( - val localChatRoom: LocalChatRoom, - val wallet: GroupWallet, - val walletState: GroupWalletState?, - /** The coins open spends already hold, which a new one leaves alone. */ - val reserved: Set, - /** The change indices open spends already pay back to, which a new one pays past. */ - val reservedChange: Set = emptySet(), - /** - * Who would sign: the room's own group, or -- spending from a descendant's - * guarded wallet -- the group as that wallet's guardian. [wallet] is then - * the descendant's. - */ - val spender: GroupSpend.Spender = GroupSpend.Spender.Owner, - /** The descendant's guarded wallet this send pays, or null for a send to a typed address. */ - val funding: FundingTarget? = null, - ): GroupSendUIState - - /** A room this device cannot propose from -- no wallet, no share, or no node. */ - data object Unavailable: GroupSendUIState - - data class Error(val message: String): GroupSendUIState - - data object Loading: GroupSendUIState -} - -/** - * A descendant's guarded wallet a send funds, with where it is up to: its chain - * state as this device watches it, and the receive indices the room's open - * fundings already hold. See `docs/guarded-wallet-funding.md`. - */ -data class FundingTarget( - val wallet: GuardianManager.GuardedWallet, - /** Null until Electrum has answered for the descendant's addresses. */ - val walletState: GroupWalletState?, - val reserved: Set = emptySet(), -) { - /** The address the send pays, moving on whenever the one before it is paid or held. */ - val address: GroupAddress? get() = walletState?.fundingAddress(reserved) - - /** Electrum has answered, and open fundings hold every address the wallet watches. */ - val allHeld: Boolean get() = walletState?.receiveAddress != null && address == null -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupWalletAddressesUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupWalletAddressesUIState.kt deleted file mode 100644 index 0a78aa70..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupWalletAddressesUIState.kt +++ /dev/null @@ -1,24 +0,0 @@ -package mobi.giza.compose.ui.view.state - -import mobi.giza.compose.wallet.GroupAddress - -sealed interface GroupWalletAddressesUIState { - /** - * The wallet's addresses as the chain last said. - * - * [receive] is null until Electrum has said which are used: before that every - * address reads as unused, and a list that called `/0/0` current would be - * wrong about a group paid there before. - */ - data class Loaded( - val receive: List?, - /** The change addresses that have been used, newest first: empty for a wallet that has never sent. */ - val change: List = emptyList(), - ): GroupWalletAddressesUIState - - data class Error( - val message: String - ): GroupWalletAddressesUIState - - data object Loading: GroupWalletAddressesUIState -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupWalletUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupWalletUIState.kt deleted file mode 100644 index 16a43755..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupWalletUIState.kt +++ /dev/null @@ -1,185 +0,0 @@ -package mobi.giza.compose.ui.view.state - -import mobi.giza.compose.nostr.subgroup.WalletPolicyReading -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.managers.GroupWalletDerivation -import mobi.giza.compose.managers.GroupWalletManager -import mobi.giza.compose.managers.GuardianManager -import fr.acinq.bitcoin.Satoshi -import fr.acinq.lightning.utils.sum -import mobi.giza.compose.nostr.wallet.GroupWallet -import mobi.giza.compose.wallet.GroupWalletState -import mobi.giza.compose.wallet.GroupSpend -import mobi.giza.compose.database.model.GroupTransaction -import mobi.giza.compose.database.model.types.FrostSigningStage -import com.vitorpamplona.quartz.nip01Core.core.HexKey - -sealed interface GroupWalletUIState { - /** - * A room whose group has not signed a wallet statement. - * - * [account] is what a statement would carry, or null for a room with no key - * at all -- there is nothing to open then. [canSign] gates the way in, for - * the reason every proposing screen gives: `proposeSigning` throws for a - * device holding no share. - * - * [guarded] is the guarded account a subgroup could open instead, when its - * birth certificate grants it guardian keys and guarded wallets are offered - * on this network -- see `docs/group-wallet-guardians.md`. - * - * [policy] is what the room's own certificate decided about its wallet, or - * null for a room with none -- `docs/subgroup-wallet-policy.md`. A decided - * policy leaves one way in: [guarded] alone for *guarded*, the plain - * [account] alone for *unguarded*, which [offersPlain] and [guarded] say. - */ - data class NotOpened( - val localChatRoom: LocalChatRoom, - val account: GroupWalletDerivation.Account?, - val canSign: Boolean, - val guarded: GroupWalletManager.GuardedOpening? = null, - val policy: WalletPolicyReading? = null, - /** What this device calls each guardian's room, by room id, for the ones it holds. */ - val guardianNames: Map = emptyMap(), - /** Whether a plain wallet may be opened: false only when the parent decided this one is guarded. */ - val offersPlain: Boolean = true, - /** Guarded wallets of groups below this one. A group with no wallet of its own can still guard others'. */ - val guardedWallets: List = emptyList(), - /** Guarded statements this device can carry to the groups above. */ - val shareable: List = emptyList(), - ): GroupWalletUIState - - /** - * An open wallet. - * - * [walletState] is null before Electrum's first answer. - */ - data class Loaded( - val localChatRoom: LocalChatRoom, - val wallet: GroupWallet, - val walletState: GroupWalletState?, - val canSign: Boolean, - /** The room's spends, newest first. */ - val spends: List = emptyList(), - /** Guarded wallets of groups below this one. */ - val guardedWallets: List = emptyList(), - /** Guarded statements this device can carry to the groups above. */ - val shareable: List = emptyList(), - /** What this device calls each guardian's room, by room id, for the ones it holds. */ - val guardianNames: Map = emptyMap(), - ): GroupWalletUIState - - data class Error( - val message: String - ): GroupWalletUIState - - data object Loading: GroupWalletUIState -} - -/** A descendant's guarded wallet, as an ancestor's wallet screen lists it. */ -data class GuardedWalletRow( - val wallet: GuardianManager.GuardedWallet, - /** Null before Electrum's first answer, and for a profile that cannot watch the chain. */ - val walletState: GroupWalletState?, -) { - /** - * What this group could spend now: coins confirmed at least as deep as its - * own leaf's lock -- not the default's, since the group that granted the - * leaf chose it. Null while the chain is not known. - */ - val withinReach: Satoshi? - get() = walletState?.let { state -> - state.utxos.filter { state.confirmations(it) >= wallet.delay }.map { it.amount }.sum() - } - - /** - * Coins in the wallet not yet within reach: in the mempool, or confirmed - * less deeply than this group's own leaf's lock, the same one [withinReach] - * counts past. What a funding looks like for the two - * hours after it lands -- without it, [withinReach] would make the money - * look gone. Every such coin, whoever paid it, which is all this group can - * know. Null while the chain is not known. - */ - val arriving: Satoshi? - get() = walletState?.let { state -> - state.utxos.filter { state.confirmations(it) < wallet.delay }.map { it.amount }.sum() - } -} - -/** - * One member's wallets as an ancestor's list gathers them, so a group can see - * at a glance that one person has several, guarded by different groups below - * it. `docs/member-wallet-guarding-group.md`, D6. - */ -data class PersonGuardedWallets( - val ownerPublicKey: HexKey, - /** The member's profile name on this device, or null. */ - val ownerName: String?, - /** Nearest first, then by the guarding group's name: wallets from one branch sit together. */ - val rows: List, -) { - /** How many groups below this one directly guard these wallets. */ - val guardianCount: Int get() = rows.map { it.wallet.directGuardianChatRoomId.lowercase() }.distinct().size -} - -/** - * The member wallets among these rows, by person, people by name and then key. - * Subgroups' wallets are left out: a row there is a room, not a person. - */ -fun List.byPerson(): List = - mapNotNull { row -> (row.wallet.subject as? GuardianManager.GuardedSubject.Member)?.let { it to row } } - .groupBy { (member, _) -> member.ownerPublicKey.lowercase() } - .map { (_, owned) -> - val member = owned.first().first - PersonGuardedWallets( - ownerPublicKey = member.ownerPublicKey, - ownerName = owned.firstNotNullOfOrNull { (it, _) -> it.ownerName }, - rows = owned.map { it.second }.sortedWith( - compareBy( - { it.wallet.position }, - { (it.wallet.subject as GuardianManager.GuardedSubject.Member).guardianName?.lowercase() ?: it.wallet.directGuardianChatRoomId }, - { (it.wallet.subject as GuardianManager.GuardedSubject.Member).label?.lowercase() }, - ) - ), - ) - } - .sortedWith(compareBy({ it.ownerName?.lowercase() ?: it.ownerPublicKey }, { it.ownerPublicKey })) - -/** Where one of the room's spends has got to, as one fact a member reads. */ -enum class SpendStatus { - WAITING_FOR_SIGNATURES, - ABANDONED, - SIGNED, - SENT, - CONFIRMED, - REPLACED; - - companion object { - /** - * The session decides until the group has signed; the chain decides after. - * Sent means Electrum has reported it back -- a broadcast reports success - * whatever the server said, so sending is not evidence of having been sent. - */ - fun of(stage: FrostSigningStage?, transaction: GroupTransaction): SpendStatus = when { - transaction.replacedByTxid != null -> REPLACED - transaction.confirmedAt != null -> CONFIRMED - transaction.seenAt != null -> SENT - transaction.signedTransaction != null -> SIGNED - stage == FrostSigningStage.FAILED -> ABANDONED - else -> WAITING_FOR_SIGNATURES - } - } -} - -/** One of the room's spends, as the wallet screen lists it. */ -data class SpendRow( - val transaction: GroupTransaction, - val status: SpendStatus, - /** The spend, checked again; null where this device cannot check it. */ - val spend: GroupSpend.Checked?, -) { - /** Signed, never reported back: the one moment sending it again is worth anything. */ - val canSendAgain: Boolean get() = status == SpendStatus.SIGNED - - /** Signed and not yet decided by a block: RBF is still possible. */ - val canBump: Boolean get() = (status == SpendStatus.SIGNED || status == SpendStatus.SENT) && spend != null -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/GroupChainClients.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/GroupChainClients.kt deleted file mode 100644 index 08d9c8a6..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/GroupChainClients.kt +++ /dev/null @@ -1,55 +0,0 @@ -package mobi.giza.compose.wallet - -import fr.acinq.bitcoin.Chain -import fr.acinq.lightning.blockchain.electrum.IElectrumClient -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock - -/** - * The Electrum connection each network's group wallets watch through, for one identity. - * - * The identity has one for the network its node runs on -- the node's own, or for a profile with no - * node the one `IdentityElectrum` gives it -- and every wallet on that network shares it. A group may - * keep a wallet on another network as well -- testnet3, while its Lightning wallet is tried there - * (`docs/group-lightning-wallet.md`, Phase 4) -- and that network gets a [StandaloneElectrum] of its - * own, made the first time a wallet on it asks and kept for the identity's life, for the reason - * [GroupOnchainWallets] keeps its wallets: a subscription is cheap and the first answer slow. Being the - * same loop as the identity's own, it follows the profile's Tor setting. - */ -class GroupChainClients( - private val nodeChain: Chain, - private val nodeClient: IElectrumClient, - private val connect: suspend (Chain) -> Connection, -) { - /** A connection this object made, and how to close it. */ - class Connection(val client: IElectrumClient, val close: () -> Unit) - - private val mutex = Mutex() - private val others = mutableMapOf() - - suspend fun clientFor(chain: Chain): IElectrumClient = - if (chain == nodeChain) nodeClient else mutex.withLock { others.getOrPut(chain) { connect(chain) }.client } - - suspend fun stop() = mutex.withLock { - others.values.forEach { it.close() } - others.clear() - } - - companion object { - /** Every network on one client: for a test, whose fake client answers for whatever it is asked. */ - fun single(client: IElectrumClient): GroupChainClients = - GroupChainClients(Chain.Mainnet, client) { Connection(client) {} } - - /** - * The identity's client for its own network -- its node's, or the one a profile with no node - * is given -- and, for any other network a group keeps a wallet on, a [StandaloneElectrum] - * from [standaloneFor]: the same connection loop the identity's own uses, so the same - * server choice, the same pauses, and the same refusal of a clearnet server while Tor is on. - */ - fun forNode(nodeChain: Chain, nodeClient: IElectrumClient, standaloneFor: (Chain) -> StandaloneElectrum): GroupChainClients = - GroupChainClients(nodeChain, nodeClient) { chain -> - val standalone = standaloneFor(chain).also { it.start() } - Connection(standalone.client) { standalone.stop() } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/GroupOnchainWallet.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/GroupOnchainWallet.kt deleted file mode 100644 index 3fbdbc55..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/GroupOnchainWallet.kt +++ /dev/null @@ -1,305 +0,0 @@ -package mobi.giza.compose.wallet - -import co.touchlab.kermit.Logger -import mobi.giza.compose.managers.GroupWalletDerivation -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.Satoshi -import fr.acinq.lightning.blockchain.electrum.ElectrumConnectionStatus -import fr.acinq.lightning.blockchain.electrum.ElectrumMiniWallet -import fr.acinq.lightning.blockchain.electrum.HeaderSubscriptionResponse -import fr.acinq.lightning.blockchain.electrum.IElectrumClient -import fr.acinq.lightning.blockchain.electrum.WalletState -import fr.acinq.lightning.utils.sum -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.combine -import kotlinx.coroutines.flow.filterIsInstance -import kotlinx.coroutines.launch - -/** - * A group's wallet on chain: the counterpart of Phoenix's `FinalWallet`, watching - * the addresses [account] derives. - * - * Phoenix's final wallet watches one address forever. A group hands addresses out - * from several devices and keeps change, so this watches both BIP44 branches, each - * gap-limited -- and because an `ElectrumMiniWallet` holds one address generator, - * that is two of them. Both share the identity's Electrum client, which is safe: - * each ignores script hashes it does not know. - * - * In memory, as Phoenix's is. Everything it knows is fetched again from Electrum - * when it starts, and nothing about the wallet is stored -- the addresses are a - * derivation, and the coins are on chain. - */ -class GroupOnchainWallet( - val account: GroupWalletDerivation.Account, - electrum: IElectrumClient, - scope: CoroutineScope, - logger: Logger = Logger.withTag("GroupOnchainWallet"), -) { - private val receive = ElectrumMiniWallet(account.chain.chainHash, electrum, scope, logger, lookAhead = RECEIVE_LOOKAHEAD) - private val change = ElectrumMiniWallet(account.chain.chainHash, electrum, scope, logger, lookAhead = CHANGE_LOOKAHEAD) - - private val tip = MutableStateFlow((electrum.connectionStatus.value as? ElectrumConnectionStatus.Connected)?.height) - - /** The best block this wallet has heard of, or null before Electrum has connected. */ - val tipHeight: StateFlow = tip.asStateFlow() - - init { - receive.addAddressGenerator { index -> addressAt(GroupWalletDerivation.RECEIVE, index) } - change.addAddressGenerator { index -> addressAt(GroupWalletDerivation.CHANGE, index) } - - // The tip, for confirmations. A connection reports the height it found and - // every new block arrives as a header notification on the shared client. - scope.launch { - electrum.connectionStatus.filterIsInstance().collect { connected -> - tip.value = maxOf(tip.value ?: 0, connected.height) - } - } - scope.launch { - electrum.notifications.filterIsInstance().collect { header -> - tip.value = maxOf(tip.value ?: 0, header.blockHeight) - } - } - } - - /** Both branches and the tip, as one value. */ - val state: Flow = - combine(receive.walletStateFlow, change.walletStateFlow, tip) { receiveState, changeState, height -> - GroupWalletState(account, receiveState, changeState, height) - } - - fun stop() { - receive.stop() - change.stop() - } - - private fun addressAt(change: Long, index: Int): String = - GroupWalletDerivation.derive(account, change, index.toLong()).address(account.chain) - - companion object { - /** - * Receive addresses watched past the first unused one. Phoenix's swap-in - * wallet uses 3; a group has several devices showing "the next address", - * so two members can each hand one out before either is paid. - */ - const val RECEIVE_LOOKAHEAD: UInt = 10u - - /** - * Change addresses watched, counting the first unused one. Each open - * spend with change holds one until it confirms, and several members - * can each have one open, so this is how many such spends a group can - * have at once before the next is told to wait. - */ - const val CHANGE_LOOKAHEAD: UInt = 10u - - /** - * Unused receive addresses the address list offers past the current one, - * so several members can each hand out a different one. Every one of them - * has to be watched already, or a payment to it would go unseen. - */ - const val ADDRESSES_AHEAD: Int = 2 - - init { - require(ADDRESSES_AHEAD < RECEIVE_LOOKAHEAD.toInt()) { "the address list would offer addresses the wallet does not watch" } - } - } -} - -/** One of the wallet's addresses as the address list shows it. */ -data class GroupAddress( - val derivation: GroupWalletDerivation.Derived, - val address: String, - val status: Status, - /** What it holds now: zero for an address never paid, and for one paid and spent. */ - val balance: Satoshi, -) { - enum class Status { - /** The address the wallet screen is handing out. */ - CURRENT, - - /** Not paid yet, and past the current one. */ - NEXT, - - /** Paid at least once, whether or not the coins have moved since. */ - USED, - } -} - -/** - * One coin the group holds, and where under the account it is. - * - * [derivation] is what a spend needs to sign it -- the cache -- and what a signer - * checks the coin's script against. - */ -data class GroupUtxo( - val utxo: WalletState.Utxo, - val derivation: GroupWalletDerivation.Derived, -) { - val amount: Satoshi get() = utxo.amount - val isConfirmed: Boolean get() = utxo.blockHeight > 0 -} - -/** - * The group's wallet at one moment: both branches' coins, the next addresses to - * use, and how deep each coin is. - */ -data class GroupWalletState( - val account: GroupWalletDerivation.Account, - val receive: WalletState, - val change: WalletState, - val tipHeight: Int?, -) { - /** Every coin, receive and change alike, with the derivation that spends it. */ - val utxos: List by lazy { - listOf(GroupWalletDerivation.RECEIVE to receive, GroupWalletDerivation.CHANGE to change).flatMap { (branch, state) -> - state.utxos.mapNotNull { utxo -> - val index = utxo.addressMeta.indexOrNull ?: return@mapNotNull null - GroupUtxo(utxo, GroupWalletDerivation.derive(account, branch, index.toLong())) - } - } - } - - val confirmedBalance: Satoshi get() = utxos.filter { it.isConfirmed }.map { it.amount }.sum() - - /** In the mempool: the group's, but not yet spendable by the send-all builder. */ - val pendingBalance: Satoshi get() = utxos.filterNot { it.isConfirmed }.map { it.amount }.sum() - - /** - * The address to hand out, or null until Electrum has said which are used. - * - * Null rather than index 0 on purpose: before the first answer every address - * reads as unused, and showing `/0/0` to a group that has been paid there - * fifty times would be address reuse with a straight face. - */ - val receiveAddress: String? get() = receive.firstUnusedDerivedAddress?.first - - /** - * The receive addresses worth listing, newest first: every one paid, the one - * being handed out, and [GroupOnchainWallet.ADDRESSES_AHEAD] after it -- or - * null until Electrum has said which are used, for the reason - * [receiveAddress] is. - * - * The list reaches the highest paid address even past the current one plus - * the addresses ahead: the current address is the *lowest* unused one, so a - * watch-only wallet paid further up leaves it where it was. - */ - val receiveAddresses: List? by lazy { - val current = receive.firstUnusedDerivedAddress?.second?.index ?: return@lazy null - listed(GroupWalletDerivation.RECEIVE, receive, current) - } - - /** - * The change addresses that have been used, newest first, or null until - * Electrum has answered. Never a current or a next one: change is chosen by - * a spend, and is not handed out to be paid. - */ - val changeAddresses: List? by lazy { - change.firstUnusedDerivedAddress ?: return@lazy null - listed(GroupWalletDerivation.CHANGE, change, current = null) - } - - /** - * [branch]'s addresses up to the highest used one, and -- given the branch's - * [current] index -- up to [GroupOnchainWallet.ADDRESSES_AHEAD] past that. - * Without a current index, only the used ones. - */ - private fun listed(branch: Long, state: WalletState, current: Int?): List { - val derived = state.addresses.mapNotNull { (address, addressState) -> - (addressState.meta as? WalletState.AddressMeta.Derived)?.let { Triple(address, it.index, addressState) } - } - val highestUsed = derived.filter { it.third.alreadyUsed }.maxOfOrNull { it.second } ?: -1 - val last = current?.let { maxOf(it + GroupOnchainWallet.ADDRESSES_AHEAD, highestUsed) } ?: highestUsed - - return derived - .filter { (_, index, addressState) -> index <= last && (current != null || addressState.alreadyUsed) } - .sortedByDescending { (_, index, _) -> index } - .map { (address, index, addressState) -> - GroupAddress( - derivation = GroupWalletDerivation.derive(account, branch, index.toLong()), - address = address, - status = when { - addressState.alreadyUsed -> GroupAddress.Status.USED - index == current -> GroupAddress.Status.CURRENT - else -> GroupAddress.Status.NEXT - }, - balance = addressState.utxos.map { it.amount }.sum(), - ) - } - } - - /** - * The receive address an ancestor pays when it funds this wallet: the lowest - * unused index from [GroupOnchainWallet.ADDRESSES_AHEAD] past the current one - * that [reserved] -- the indices open fundings already pay -- does not hold, - * and that the wallet watches. Null before Electrum has answered, for the - * reason [receiveAddress] is, and when every such index is held. - * - * Not the current address: the wallet's own members are handing that one - * out, and every device computes the same one. Starting at the top of the - * address list's window and going up keeps an ancestor out of their way. - * See `docs/guarded-wallet-funding.md`, D2. - */ - fun fundingAddress(reserved: Set = emptySet()): GroupAddress? { - val current = receive.firstUnusedDerivedAddress?.second?.index ?: return null - val window = (current + GroupOnchainWallet.ADDRESSES_AHEAD) until (current + GroupOnchainWallet.RECEIVE_LOOKAHEAD.toInt()) - val (address, index) = receive.addresses.entries - .filterNot { it.value.alreadyUsed } - .mapNotNull { (address, addressState) -> addressState.meta.indexOrNull?.let { address to it } } - .filter { (_, index) -> index in window && index.toLong() !in reserved } - .minByOrNull { (_, index) -> index } - ?: return null - return GroupAddress( - derivation = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, index.toLong()), - address = address, - status = GroupAddress.Status.NEXT, - balance = Satoshi(0), - ) - } - - /** Whether Electrum has answered for any change address yet: before it has, there is no next one to name. */ - val changeKnown: Boolean get() = change.addresses.values.any { !it.alreadyUsed } - - /** - * The change index a spend should pay back to: the lowest this wallet - * watches that is unused and not in [reserved] -- the indices open spends - * already pay to. Null when there is none: before Electrum has answered, - * or when open spends hold every one inside the watched window, past which - * change would land on an address nobody is watching. - */ - fun nextChangeIndex(reserved: Set = emptySet()): Long? = - change.addresses.values - .filterNot { it.alreadyUsed } - .mapNotNull { it.meta.indexOrNull?.toLong() } - .filterNot { it in reserved } - .minOrNull() - - /** How many confirmations [utxo] has: 0 in the mempool, and 0 until the tip is known. */ - fun confirmations(utxo: GroupUtxo): Int { - val height = tipHeight ?: return 0 - val confirmedAt = utxo.utxo.blockHeight.toInt() - return if (confirmedAt == 0) 0 else height - confirmedAt + 1 - } - - /** - * Where under the account [script] is, among the addresses this wallet has - * generated, or null if it is not one of them. - * - * The generated range is the bound on how far a check of somebody else's - * claim will look: a derivation the wallet has never watched is not one it - * will vouch for. - */ - fun derivationOf(script: ByteVector): GroupWalletDerivation.Derived? = - listOf(GroupWalletDerivation.RECEIVE to receive, GroupWalletDerivation.CHANGE to change) - .asSequence() - .flatMap { (branch, state) -> - state.addresses.values.asSequence().mapNotNull { it.meta.indexOrNull }.map { branch to it.toLong() } - } - .map { (branch, index) -> GroupWalletDerivation.derive(account, branch, index) } - .firstOrNull { it.pubkeyScript == script } -} - -/** A BIP21 URI for [address], so a scanning wallet knows what the text it read is. */ -fun bip21Uri(address: String): String = "bitcoin:$address" diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/GroupOnchainWallets.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/GroupOnchainWallets.kt deleted file mode 100644 index c7ce42e6..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/GroupOnchainWallets.kt +++ /dev/null @@ -1,117 +0,0 @@ -package mobi.giza.compose.wallet - -import mobi.giza.compose.managers.GroupWalletDerivation -import fr.acinq.bitcoin.Chain -import mobi.giza.compose.managers.GuardianManager -import fr.acinq.bitcoin.Crypto -import fr.acinq.bitcoin.OutPoint -import fr.acinq.bitcoin.Transaction -import fr.acinq.bitcoin.TxId -import fr.acinq.bitcoin.byteVector32 -import fr.acinq.lightning.blockchain.electrum.IElectrumClient -import fr.acinq.lightning.blockchain.fee.FeeratePerByte -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock - -/** - * The group wallets one identity is watching, each on the Electrum client for its network - * ([GroupChainClients]): the identity's own node for the network it runs on, a connection of its own - * for any other. - * - * One per identity, made where the identity's node is, and stopped with it: a - * profile switch is a restart, and a wallet left watching on the last profile's - * connection would be a wallet nobody can see subscribing to addresses nobody - * asked about. Wallets are made on first use -- opening a group's wallet screen - * -- and kept for the life of the identity, because an Electrum subscription is - * cheap and the first answer is slow. - */ -class GroupOnchainWallets( - private val clients: GroupChainClients, - private val scope: CoroutineScope, -) { - /** Every network on [electrum]: what the tests, whose fake client answers anything, construct. */ - constructor(electrum: IElectrumClient, scope: CoroutineScope) : this(GroupChainClients.single(electrum), scope) - - private val mutex = Mutex() - private val wallets = mutableMapOf() - - /** - * The wallet watching [account], made the first time it is asked for. Keyed - * by its receive descriptor, which names one account of one group on one - * network *and* the guardians in its addresses -- an xpub alone would hand a - * guarded account the plain one's addresses. - */ - suspend fun walletFor(account: GroupWalletDerivation.Account): GroupOnchainWallet = mutex.withLock { - wallets.getOrPut(account.receiveDescriptor) { GroupOnchainWallet(account, clients.clientFor(account.chain), scope) } - } - - /** - * A feerate to start the send form at, in sats per virtual byte: Electrum's - * estimate for six blocks, or null when it has none. A suggestion the member - * edits, never a value a spend is built on without them seeing it. - */ - suspend fun suggestedFeeratePerVbyte(chain: Chain): Long? = - clients.clientFor(chain).estimateFees(6)?.let { FeeratePerByte(it).feerate.sat }?.coerceAtLeast(1) - - /** Transactions fetched for [guardianSpends], which never change once mined or seen. */ - private val transactions = mutableMapOf() - - /** - * Every spend a guardian of [state]'s account made from it, read off the - * history of each address the wallet has used. Empty for an unguarded - * account, and for whatever Electrum cannot answer right now -- the next look - * asks again. - * - * History rather than a watch on coins disappearing: a device asleep when the - * coin moved still finds it, since the chain keeps the record and nothing - * here has to have been running at the time. - */ - suspend fun guardianSpends(state: GroupWalletState): List { - val account = state.account - if (!account.isGuarded) return emptyList() - val electrum = clients.clientFor(account.chain) - - val used = listOf(GroupWalletDerivation.RECEIVE to state.receive, GroupWalletDerivation.CHANGE to state.change) - .flatMap { (branch, wallet) -> - wallet.addresses.values.filter { it.alreadyUsed }.mapNotNull { address -> - address.meta.indexOrNull?.let { GroupWalletDerivation.derive(account, branch, it.toLong()) } - } - } - val ours = used.associateBy { it.pubkeyScript } - - val history = used.flatMap { derived -> - runCatching { electrum.getScriptHashHistory(Crypto.sha256(derived.pubkeyScript).byteVector32().reversed()) } - .getOrDefault(emptyList()) - .map { it.txid } - }.distinct().mapNotNull { txid -> transactionOf(txid, electrum) } - - val coins = history.flatMap { tx -> - tx.txOut.mapIndexedNotNull { index, out -> ours[out.publicKeyScript]?.let { OutPoint(tx, index.toLong()) to (out to it) } } - }.toMap() - - return history.flatMap { GuardianManager.takenIn(it, account, coins) } - } - - private suspend fun transactionOf(txid: TxId, electrum: IElectrumClient): Transaction? = - mutex.withLock { transactions[txid] } - ?: runCatching { electrum.getTx(txid) }.getOrNull()?.also { tx -> mutex.withLock { transactions[txid] = tx } } - - /** - * Hands [tx] to Electrum -- for a spend a member signed alone, which has no - * session for `GroupTransactionWatcher` to follow. Electrum reports success - * whatever the server said, so this is not evidence it reached the network: - * [confirmationsOf] is. - */ - suspend fun broadcast(tx: Transaction, chain: Chain) { - clients.clientFor(chain).broadcastTransaction(tx) - } - - /** How deep [tx] is on [chain]: 0 in the mempool, null while Electrum has not heard of it or cannot be asked. */ - suspend fun confirmationsOf(tx: Transaction, chain: Chain): Int? = runCatching { clients.clientFor(chain).getConfirmations(tx) }.getOrNull() - - suspend fun stop() = mutex.withLock { - wallets.values.forEach { it.stop() } - wallets.clear() - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/GroupSpend.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/GroupSpend.kt deleted file mode 100644 index 5336df5d..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/GroupSpend.kt +++ /dev/null @@ -1,487 +0,0 @@ -package mobi.giza.compose.wallet - -import mobi.giza.compose.managers.FrostSigningManager -import mobi.giza.compose.managers.GroupWalletDerivation -import mobi.giza.compose.managers.GuardianManager -import mobi.giza.compose.managers.GuardianDerivation -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.ByteVector64 -import fr.acinq.bitcoin.KeyPath -import fr.acinq.bitcoin.OutPoint -import fr.acinq.bitcoin.Satoshi -import fr.acinq.bitcoin.Script -import fr.acinq.bitcoin.ScriptTree -import fr.acinq.bitcoin.ScriptWitness -import fr.acinq.bitcoin.SigHash -import fr.acinq.bitcoin.Transaction -import fr.acinq.bitcoin.TxOut -import fr.acinq.bitcoin.XonlyPublicKey -import fr.acinq.bitcoin.crypto.frost.TweakCache -import fr.acinq.bitcoin.psbt.Input -import fr.acinq.bitcoin.psbt.Psbt -import fr.acinq.bitcoin.psbt.TaprootBip32DerivationPath -import fr.acinq.bitcoin.utils.Either -import fr.acinq.lightning.utils.sum -import kotlin.io.encoding.Base64 - -/** - * A spend from a group's wallet, checked the way every member checks it before - * putting their share behind it. - * - * Nothing here trusts the proposer. A PSBT says which coins it spends, where - * under the wallet's account each one is, and which outputs are change; every - * one of those claims is rederived from the account and refused if it does not - * reproduce the script it is about. The sighashes are then computed here, from - * the PSBT itself -- the counterpart of rebuilding a proposed event's id from - * its fields rather than taking the id on the wire. - * - * ### Why a PSBT's amounts can be believed without fetching anything - * - * Before taproot a signer had to see each spent output's whole transaction to - * trust its amount, or a proposer could lie it down and turn the difference into - * fee. BIP341's sighash commits to every spent amount and every spent script, so - * a lie here produces signatures the network rejects -- not a larger fee. That - * is what lets a member with no node of their own, and so no way to look a coin - * up, still sign safely: the worst a lying proposer gets is a transaction nobody - * can mine. - * - * ### Two ways to sign a coin - * - * The wallet's own group signs each input on its address's key path. An - * ancestor of a guarded wallet signs through its leaf instead -- a [Spender.Guardian] - * -- and then every input's sighash is BIP342's over that leaf, its sequence is - * the leaf's lock, its signature verifies against the leaf key, and its witness - * is the leaf and its control block. Everything else above holds unchanged: the - * coins are still the descendant's, at places under its account, and each claim - * is still rederived rather than believed. See `docs/group-wallet-guardians.md`. - */ -object GroupSpend { - /** - * The most inputs one spend signs: a transaction is a batch, one item per - * input, so it is the batch cap. - */ - const val MAX_INPUTS: Int = FrostSigningManager.MAX_BATCH_SIZE - - /** - * How far down a branch a claimed derivation may point. - * - * A bound on work rather than on the wallet: each claim costs one derivation - * to check, and a proposer must not be able to choose how much work everybody - * else does. A member with no node has no watched range to bound it by, so it - * is a constant, and far past any gap a group will leave. - */ - const val MAX_ADDRESS_INDEX: Long = 100_000L - - /** - * The highest feerate a spend may pay, in sats per virtual byte. - * - * Not a security check -- the approval shows the fee -- but a feerate typed - * with three zeros too many is the likeliest way for a group to lose money, - * and refusing it costs a retry. - */ - const val MAX_FEERATE_SAT_PER_VBYTE: Long = 2_000L - - /** Who signs a spend's inputs. */ - sealed interface Spender { - /** The wallet's own group, on each address's key path. */ - data object Owner : Spender - - /** - * An ancestor of a guarded wallet, through its leaf: the guardian at - * [position] in the account's guardians, whose key is [thresholdPublicKey] - * walked down [lineage] -- `GuardianDerivation.signingCache`. - * - * [thresholdPublicKey] is null for a builder, which needs the leaf and - * never the key that signs it; [check] refuses without it. - */ - data class Guardian( - val position: Int, - val lineage: List, - val thresholdPublicKey: HexKey? = null, - /** The guarded wallet's founding name, for the words a spend is shown in. */ - val name: String? = null, - /** A member's label for the wallet, where they gave one: one person can have several. */ - val label: String? = null, - ) : Spender - } - - /** One input, and what its signature has to be over and verify against. */ - data class SpentInput( - val index: Int, - val outPoint: OutPoint, - val txOut: TxOut, - val derivation: GroupWalletDerivation.Derived, - val sighash: ByteVector32, - /** The leaf a guardian signs through, or null for a key-path input. */ - val leaf: ScriptTree.Leaf? = null, - /** The key the input's signature verifies against: the address's output key, or the leaf key. */ - val signingKey: XonlyPublicKey = derivation.outputKey, - /** The cache a session signs this input with. */ - val cache: TweakCache = derivation.cache, - ) { - /** The input's witness around [signature]. */ - fun witness(signature: ByteVector64): ScriptWitness = when (leaf) { - null -> Script.witnessKeyPathPay2tr(signature) - else -> Script.witnessScriptPathPay2tr(derivation.internalKey, leaf, ScriptWitness(listOf(signature)), derivation.tree!!) - } - } - - /** One output, and -- when its claim to be the wallet's own derives -- where under the account it is. */ - data class CheckedOutput( - val index: Int, - val txOut: TxOut, - val change: GroupWalletDerivation.Derived?, - ) { - val isChange: Boolean get() = change != null - } - - data class Checked( - /** The account the spend was checked against -- and so the network its addresses are on. */ - val account: GroupWalletDerivation.Account, - val psbt: Psbt, - val inputs: List, - val outputs: List, - /** `Σ inputs − Σ outputs`, believable for the reason the object's kdoc gives. */ - val fee: Satoshi, - /** - * The finished transaction's weight. Exact before signing: a default-sighash - * signature is always 64 bytes, and a guardian's leaf and control block are - * known before it signs. - */ - val weight: Int, - val spender: Spender = Spender.Owner, - /** - * The payments that fund a descendant's guarded wallet, each claim derived - * again -- [fundingsOf]. Empty until a caller holding the room's guarded - * wallets has read them, which [check] alone cannot. - */ - val fundings: List = emptyList(), - ) { - val tx: Transaction get() = psbt.global.tx - - val payments: List get() = outputs.filterNot { it.isChange } - - /** What leaves the group: every output that is not its own change. */ - val amountSent: Satoshi get() = payments.map { it.txOut.amount }.sum() - - /** Sats per virtual byte, rounded down. */ - val feeratePerVbyte: Long get() = fee.sat / vbytes(weight) - - /** Every spent output, in input order: what every sighash and `correctlySpends` take. */ - val spentOutputs: List get() = inputs.map { it.txOut } - - /** [tx] with each input's witness around its signature, in input order. */ - fun witnessed(signatures: List): Transaction = - signatures.foldIndexed(tx) { index, partial, signature -> partial.updateWitness(index, inputs[index].witness(signature)) } - } - - sealed interface Result { - data class Ok(val checked: Checked) : Result - data class Refused(val reason: String) : Result - } - - /** A payment into a descendant's guarded wallet, at [derived] under its account -- the claim, derived again. */ - data class Funding( - val outputIndex: Int, - val wallet: GuardianManager.GuardedWallet, - val derived: GroupWalletDerivation.Derived, - ) - - sealed interface FundingReading { - data class Ok(val fundings: List) : FundingReading - data class Refused(val reason: String) : FundingReading - } - - /** - * Which of [checked]'s payments fund one of [guarded] -- the descendants' - * guarded wallets the room holds -- read off each payment's derivation and - * derived again, the way change is. `docs/guarded-wallet-funding.md`, D4: - * - * - a claim under a wallet in [guarded] that derives to the payment's script - * is a funding; - * - a claim under a wallet in [guarded] that does not -- another index, - * another branch, another key -- refuses the spend, so no proposer can put - * a descendant's name on a payment to an address it does not own; - * - a claim under any other account is not this device's to check, and the - * payment is read as the bare address it is. - * - * Fingerprints are four bytes, so every held wallet sharing one is tried - * before a claim is refused. - */ - fun fundingsOf(checked: Checked, guarded: List): FundingReading { - val fundings = checked.payments.mapNotNull { payment -> - val paths = checked.psbt.outputs[payment.index].taprootDerivationPaths - val (internalKey, path, candidates) = paths.entries.firstNotNullOfOrNull { (internalKey, path) -> - guarded.filter { it.chain == checked.account.chain && isOurs(path, it.account) } - .takeIf { it.isNotEmpty() } - ?.let { Triple(internalKey, path, it) } - } ?: return@mapNotNull null - - val (branch, index) = path.keyPath.path.takeIf { it.size == 2 && path.leaves.isEmpty() } - ?: return FundingReading.Refused("output ${payment.index} claims a place in a guarded wallet that is not one") - if (branch != GroupWalletDerivation.RECEIVE || index !in 0L..MAX_ADDRESS_INDEX) { - return FundingReading.Refused("output ${payment.index} claims $branch/$index, which is not a receive address") - } - candidates.firstNotNullOfOrNull { wallet -> - GroupWalletDerivation.derive(wallet.account, branch, index) - .takeIf { it.pubkeyScript == payment.txOut.publicKeyScript && it.internalKey == internalKey } - ?.let { Funding(payment.index, wallet, it) } - } ?: return FundingReading.Refused( - "output ${payment.index} claims $branch/$index of ${candidates.first().displayName ?: "a subgroup"}'s guarded wallet, which is not where it pays" - ) - } - return FundingReading.Ok(fundings) - } - - /** - * The checks a member makes before signing, in the order `docs/group-chain-wallet.md` - * numbers them, against [account] -- which comes from the room's verified - * statement and never from the proposal -- as [spender] would sign it. - */ - fun check(psbt: Psbt, account: GroupWalletDerivation.Account, spender: Spender = Spender.Owner): Result { - val tx = psbt.global.tx - - // A guardian's leaf, and what it locks: every one of its inputs carries - // exactly that lock, and it signs as the key its walk reaches. - val guardian = spender as? Spender.Guardian - val delay = guardian?.let { account.guardians.getOrNull(it.position)?.delay ?: return Result.Refused("names a guardian this wallet does not have") } - if (guardian != null && guardian.thresholdPublicKey == null) return Result.Refused("has no key to sign a guardian's leaf with") - - // 4. Bounded, before any per-input work. - if (tx.txIn.isEmpty()) return Result.Refused("spends nothing") - if (tx.txIn.size > MAX_INPUTS) return Result.Refused("spends ${tx.txIn.size} coins, more than the $MAX_INPUTS one spend may sign") - if (tx.txOut.isEmpty()) return Result.Refused("pays nothing") - if (tx.version != 2L) return Result.Refused("is version ${tx.version}, not 2") - if (tx.lockTime != 0L) return Result.Refused("has a lock time") - if (tx.txIn.any { it.sequence > MAX_SEQUENCE }) return Result.Refused("cannot be replaced: a sequence is above ${MAX_SEQUENCE}") - if (delay != null && tx.txIn.any { it.sequence != delay }) return Result.Refused("has an input whose sequence is not its leaf's lock of $delay blocks") - if (tx.txIn.map { it.outPoint }.toSet().size != tx.txIn.size) return Result.Refused("spends one coin twice") - - // 2 and 3. Every input is the group's, at a key path, under the default sighash. - val claimed = psbt.inputs.mapIndexed { index, input -> - val witness = input as? Input.WitnessInput.PartiallySignedWitnessInput - ?: return Result.Refused("input $index is not an unsigned segwit input") - if (input.sighashType != null && input.sighashType != SigHash.SIGHASH_DEFAULT) { - return Result.Refused("input $index asks for sighash ${input.sighashType}; only the default is signed") - } - // Script-path fields -- a leaf script, a merkle root, a script - // signature -- are ones this library does not parse, so they land - // here. Any of them means the coin is not the plain key-path output - // this wallet's addresses are. - if (input.unknown.isNotEmpty()) return Result.Refused("input $index carries fields this wallet does not sign with") - if (input.taprootKeySignature != null) return Result.Refused("input $index is already signed") - - val derivation = claimedDerivation(input.taprootDerivationPaths, account) - ?: return Result.Refused("input $index does not name a place under this wallet's account") - if (derivation.pubkeyScript != witness.txOut.publicKeyScript) { - return Result.Refused("input $index claims ${derivation.change}/${derivation.index}, which is not the coin it spends") - } - if (input.taprootInternalKey != null && input.taprootInternalKey != derivation.internalKey) { - return Result.Refused("input $index names an internal key its derivation does not reach") - } - Triple(index, witness.txOut, derivation) - } - - val spentOutputs = claimed.map { it.second } - val inputs = claimed.map { (index, txOut, derivation) -> - if (guardian == null) { - SpentInput( - index = index, - outPoint = tx.txIn[index].outPoint, - txOut = txOut, - derivation = derivation, - sighash = tx.hashForSigningTaprootKeyPath(index, spentOutputs, SigHash.SIGHASH_DEFAULT), - ) - } else { - val leaf = GuardianDerivation.leaves(account.guardians, account.chain, account.account, derivation.change, derivation.index)[guardian.position] - val signing = GuardianDerivation.signingCache( - guardian.thresholdPublicKey!!, guardian.lineage, account.chain, account.account, derivation.change, derivation.index, - ) - // The leaf in the descendant's address, and the key this group's - // walk reaches, have to be one key -- or this group would sign for - // a leaf it cannot spend. - if (leaf.script != ByteVector(Script.write(GuardianDerivation.leafScript(signing.leafKey, delay!!)))) { - return Result.Refused("input $index's leaf is not this group's to sign") - } - SpentInput( - index = index, - outPoint = tx.txIn[index].outPoint, - txOut = txOut, - derivation = derivation, - sighash = tx.hashForSigningTaprootScriptPath(index, spentOutputs, SigHash.SIGHASH_DEFAULT, leaf.hash()), - leaf = leaf, - signingKey = signing.leafKey, - cache = signing.cache, - ) - } - } - - // 5. Change is change only if it derives. - val outputs = psbt.outputs.mapIndexed { index, output -> - val txOut = tx.txOut[index] - val ours = output.taprootDerivationPaths.values.filter { isOurs(it, account) } - val change = if (ours.isEmpty()) { - null - } else { - val derivation = claimedDerivation(output.taprootDerivationPaths, account) - ?: return Result.Refused("output $index claims a place under this wallet's account that is not one") - if (derivation.pubkeyScript != txOut.publicKeyScript) { - return Result.Refused("output $index claims ${derivation.change}/${derivation.index}, which is not where it pays") - } - derivation - } - CheckedOutput(index = index, txOut = txOut, change = change) - } - - // 6. A sane fee. - val fee = spentOutputs.map { it.amount }.sum() - tx.txOut.map { it.amount }.sum() - if (fee.sat <= 0) return Result.Refused("pays out more than it spends") - val weight = inputs.fold(tx) { partial, input -> partial.updateWitness(input.index, input.witness(ByteVector64.Zeroes)) }.weight() - if (fee.sat > MAX_FEERATE_SAT_PER_VBYTE * vbytes(weight)) { - return Result.Refused("pays a fee of ${fee.sat} sats, over $MAX_FEERATE_SAT_PER_VBYTE sats per byte") - } - - return Result.Ok(Checked(account = account, psbt = psbt, inputs = inputs, outputs = outputs, fee = fee, weight = weight, spender = spender)) - } - - /** - * The change indices under [account] that [psbt]'s outputs claim: what an - * open spend holds, so the next one pays its change somewhere else. Claims, - * not checked derivations -- a spend this device would refuse still keeps - * its index from being handed out twice, and holding one too many costs - * nothing. - */ - fun claimedChangeIndices(psbt: Psbt, account: GroupWalletDerivation.Account): Set = - psbt.outputs - .flatMap { it.taprootDerivationPaths.values } - .filter { isOurs(it, account) } - .mapNotNull { path -> path.keyPath.path.takeIf { it.size == 2 && it[0] == GroupWalletDerivation.CHANGE }?.get(1) } - .toSet() - - /** - * The receive indices under [account] -- a descendant's guarded wallet -- - * that [psbt]'s outputs claim to fund: what an open funding holds, so the - * next one pays a different address. Claims, as [claimedChangeIndices] are, - * for the same reason. See `docs/guarded-wallet-funding.md`. - */ - fun claimedFundingIndices(psbt: Psbt, account: GroupWalletDerivation.Account): Set = - psbt.outputs - .flatMap { it.taprootDerivationPaths.values } - .filter { isOurs(it, account) } - .mapNotNull { path -> path.keyPath.path.takeIf { it.size == 2 && it[0] == GroupWalletDerivation.RECEIVE }?.get(1) } - .toSet() - - /** - * The one derivation under [account] a PSBT field names, or null when it names - * none, several, or one this wallet will not walk. - * - * Keyed by internal key in the PSBT, per BIP371; the key is checked against - * the derivation rather than trusted, since it is the proposer's word. - */ - private fun claimedDerivation( - paths: Map, - account: GroupWalletDerivation.Account, - ): GroupWalletDerivation.Derived? { - val (internalKey, path) = paths.entries.singleOrNull { isOurs(it.value, account) } - ?.toPair() - ?: return null - if (path.leaves.isNotEmpty()) return null - val (change, index) = path.keyPath.path.takeIf { it.size == 2 } ?: return null - if (change != GroupWalletDerivation.RECEIVE && change != GroupWalletDerivation.CHANGE) return null - if (index !in 0L..MAX_ADDRESS_INDEX) return null - - return GroupWalletDerivation.derive(account, change, index).takeIf { it.internalKey == internalKey } - } - - /** - * Whether [path] names [account] as its master key. - * - * Compared as an unsigned 32-bit value. bitcoin-kmp reads a taproot - * derivation's fingerprint back from a serialised PSBT as a *signed* int, so - * an account whose fingerprint has its top bit set -- half of them -- would - * write `3578966523` and read back `-716000773`, and every member but the - * proposer would refuse every spend from that wallet as not its own. - */ - private fun isOurs(path: TaprootBip32DerivationPath, account: GroupWalletDerivation.Account): Boolean = - (path.masterKeyFingerprint and 0xFFFFFFFFL) == account.fingerprint - - /** - * The PSBT a proposer sends: [tx] with every input's spent output and - * derivation, and every change output's derivation, so that a signer is - * *told* what is change -- and [check] is how they decide whether to believe it. - * - * A [funding] output -- one paying a descendant's guarded wallet -- carries - * its derivation the same way, under the descendant's account rather than - * this one, so it is never mistaken for change and a signer holding that - * wallet can derive it again. See `docs/guarded-wallet-funding.md`. - */ - fun psbtOf( - tx: Transaction, - spent: List>, - change: Map, - account: GroupWalletDerivation.Account, - funding: Map> = emptyMap(), - ): Psbt { - require(spent.size == tx.txIn.size) { "one spent output per input" } - - val withInputs = spent.foldIndexed(Psbt(tx)) { index, psbt, (txOut, derivation) -> - psbt.updateWitnessInput( - outPoint = tx.txIn[index].outPoint, - txOut = txOut, - taprootInternalKey = derivation.internalKey, - taprootDerivationPaths = mapOf(derivation.internalKey to pathOf(derivation, account)), - ).right ?: throw IllegalArgumentException("could not describe input $index") - } - - val outputs = change.mapValues { (_, derivation) -> account to derivation } + funding - return outputs.entries.fold(withInputs) { psbt, (index, claim) -> - val (owner, derivation) = claim - psbt.updateWitnessOutput( - outputIndex = index, - taprootInternalKey = derivation.internalKey, - taprootDerivationPaths = mapOf(derivation.internalKey to pathOf(derivation, owner)), - ).right ?: throw IllegalArgumentException("could not describe output $index") - } - } - - private fun pathOf(derivation: GroupWalletDerivation.Derived, account: GroupWalletDerivation.Account) = - TaprootBip32DerivationPath( - leaves = emptyList(), - masterKeyFingerprint = account.fingerprint, - keyPath = KeyPath(listOf(derivation.change, derivation.index)), - ) - - /** [tx] with a key-path witness on every input, in input order. */ - fun witnessed(tx: Transaction, signatures: List): Transaction = - signatures.foldIndexed(tx) { index, partial, signature -> - partial.updateWitness(index, Script.witnessKeyPathPay2tr(signature)) - } - - /** - * The witness a guardian puts on [derivation]'s coin around [signature]: its - * leaf in that address, and the control block that proves the leaf is there. - * What a builder weighs a guardian spend by, before anybody signs. - */ - fun guardianWitness( - account: GroupWalletDerivation.Account, - derivation: GroupWalletDerivation.Derived, - position: Int, - signature: ByteVector64 = ByteVector64.Zeroes, - ): ScriptWitness { - val leaf = GuardianDerivation.leaves(account.guardians, account.chain, account.account, derivation.change, derivation.index)[position] - return Script.witnessScriptPathPay2tr(derivation.internalKey, leaf, ScriptWitness(listOf(signature)), derivation.tree!!) - } - - fun encode(psbt: Psbt): String = Base64.Default.encode(Psbt.write(psbt).toByteArray()) - - fun decode(content: String): Psbt? = - runCatching { Base64.Default.decode(content.trim()) }.getOrNull() - ?.let { Psbt.read(it).right } - - /** Every sequence at or below this signals BIP125 replaceability, so a stuck spend can be bumped by a new proposal. */ - const val MAX_SEQUENCE: Long = 0xfffffffdL - - private fun vbytes(weight: Int): Long = (weight.toLong() + 3) / 4 -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/GroupSpendBuilder.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/GroupSpendBuilder.kt deleted file mode 100644 index dd6b5c9b..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/GroupSpendBuilder.kt +++ /dev/null @@ -1,293 +0,0 @@ -package mobi.giza.compose.wallet - -import mobi.giza.compose.managers.GroupWalletDerivation -import mobi.giza.compose.text.SatsInput -import fr.acinq.bitcoin.Bitcoin -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector64 -import fr.acinq.bitcoin.OutPoint -import fr.acinq.bitcoin.Satoshi -import fr.acinq.bitcoin.Script -import fr.acinq.bitcoin.Transaction -import fr.acinq.bitcoin.TxIn -import fr.acinq.bitcoin.TxOut -import fr.acinq.bitcoin.psbt.Psbt -import fr.acinq.lightning.utils.sum - -/** - * The spends a member can propose from the group's wallet: everything to one - * address, which is what Phoenix's final wallet does, or an amount with change. - * - * Confirmed coins only, as Phoenix's send-all takes, and never a coin an open - * proposal is already spending. Two proposals over one coin are not dangerous -- - * only one can confirm, and each has its own nonces -- but the second is a quorum - * asked for nothing. - * - * A guardian building a spend from a descendant's guarded wallet -- a - * [GroupSpend.Spender.Guardian] -- takes only coins its leaf's lock has already - * let go of, puts that lock on every input, and weighs each input by its leaf - * and control block. Its change, if any, goes back to the descendant. - * - * A spend can also *fund* a descendant's guarded wallet: a [Destination.Funding] - * pays the receive address `GroupWalletState.fundingAddress` chose, and the PSBT - * says so on that output, in the derivation field change already uses, so every - * signer can derive it again. See `docs/guarded-wallet-funding.md`. - */ -object GroupSpendBuilder { - /** Phoenix's floor, kept: an output below it is one no node will relay. */ - val DUST: Satoshi = Satoshi(546) - - /** Where a spend's payment goes. */ - sealed interface Destination { - /** What the member typed: whatever it is, it is not the group's to vouch for. */ - data class Address(val address: String) : Destination - - /** - * A descendant's guarded wallet, at [derived] under its [account] -- the - * receive address `GroupWalletState.fundingAddress` chose. - */ - data class Funding(val account: GroupWalletDerivation.Account, val derived: GroupWalletDerivation.Derived) : Destination - } - - sealed interface Result { - data class Built( - val psbt: Psbt, - val amount: Satoshi, - val fee: Satoshi, - val change: Satoshi?, - /** What [fee] holds beyond the feerate: change too small to send back, paid to the miner instead. */ - val absorbed: Satoshi = Satoshi(0), - /** The guarded wallet the payment funds, or null for a payment to a typed address. */ - val funded: Destination.Funding? = null, - ) : Result - data object NotAnAddress : Result - data object NothingToSpend : Result - /** Electrum has not yet said which change addresses are used, so there is none to name. */ - data object FindingChange : Result - /** Open spends already pay change to every change address the wallet watches. */ - data object TooManyOpen : Result - data object NotEnough : Result - data object BelowDust : Result - /** A bump has to pay more than the spend it replaces. */ - data object NotHigher : Result - /** More than [GroupWalletRollout.capFor] lets one spend send. */ - data class OverCap(val cap: Satoshi) : Result - /** The amount typed is not a number of sats; [input] says why. */ - data class InvalidAmount(val input: SatsInput) : Result - } - - /** - * [result] held to [cap]: the composer's gate while the wallet is new. A - * built spend sending more than the cap is refused here, before a quorum is - * asked; nothing at acceptance refuses one another build proposes. - */ - fun capped(result: Result, cap: Satoshi?): Result = - if (cap != null && result is Result.Built && result.amount > cap) Result.OverCap(cap) else result - - /** Every confirmed, unreserved coin, to [address], less the fee. */ - fun sendAll( - state: GroupWalletState, - address: String, - feeratePerVbyte: Long, - reserved: Set, - spender: GroupSpend.Spender = GroupSpend.Spender.Owner, - ): Result = sendAll(state, Destination.Address(address), feeratePerVbyte, reserved, spender) - - /** Every confirmed, unreserved coin, to [destination], less the fee. */ - fun sendAll( - state: GroupWalletState, - destination: Destination, - feeratePerVbyte: Long, - reserved: Set, - spender: GroupSpend.Spender = GroupSpend.Spender.Owner, - ): Result { - val script = scriptOf(state, destination) ?: return Result.NotAnAddress - val funded = destination as? Destination.Funding - val coins = spendable(state, reserved, spender).ifEmpty { return Result.NothingToSpend } - - val total = coins.map { it.amount }.sum() - val fee = feeOf(state, coins, listOf(script), feeratePerVbyte, spender) - val amount = total - fee - if (amount < DUST) return Result.BelowDust - - val tx = transaction(state, coins, listOf(TxOut(amount, script)), spender) - return Result.Built(psbtOf(state, tx, coins, change = emptyMap(), funded), amount, fee, change = null, funded = funded) - } - - /** - * [amount] to [address], largest coins first, with what is left over paid - * back to the next change address no open spend holds -- or to fees, when - * it would be dust. - */ - fun send( - state: GroupWalletState, - address: String, - amount: Satoshi, - feeratePerVbyte: Long, - reserved: Set, - reservedChange: Set = emptySet(), - spender: GroupSpend.Spender = GroupSpend.Spender.Owner, - ): Result = send(state, Destination.Address(address), amount, feeratePerVbyte, reserved, reservedChange, spender) - - /** [amount] to [destination], as [send] to an address does. */ - fun send( - state: GroupWalletState, - destination: Destination, - amount: Satoshi, - feeratePerVbyte: Long, - reserved: Set, - reservedChange: Set = emptySet(), - spender: GroupSpend.Spender = GroupSpend.Spender.Owner, - ): Result { - val script = scriptOf(state, destination) ?: return Result.NotAnAddress - val funded = destination as? Destination.Funding - if (amount < DUST) return Result.BelowDust - val coins = spendable(state, reserved, spender).sortedByDescending { it.amount.sat }.ifEmpty { return Result.NothingToSpend } - - if (!state.changeKnown) return Result.FindingChange - val changeIndex = state.nextChangeIndex(reservedChange) ?: return Result.TooManyOpen - val change = GroupWalletDerivation.derive(state.account, GroupWalletDerivation.CHANGE, changeIndex) - - val chosen = mutableListOf() - for (coin in coins) { - chosen += coin - val total = chosen.map { it.amount }.sum() - val withChange = feeOf(state, chosen, listOf(script, change.pubkeyScript), feeratePerVbyte, spender) - val leftover = total - amount - withChange - - if (leftover >= DUST) { - val tx = transaction(state, chosen, listOf(TxOut(amount, script), TxOut(leftover, change.pubkeyScript)), spender) - return Result.Built(psbtOf(state, tx, chosen, mapOf(1 to change), funded), amount, withChange, leftover, funded = funded) - } - - // Enough to pay without change: the remainder, under dust, goes to fees. - val withoutChange = feeOf(state, chosen, listOf(script), feeratePerVbyte, spender) - if (total - amount >= withoutChange) { - val tx = transaction(state, chosen, listOf(TxOut(amount, script)), spender) - return Result.Built( - psbtOf(state, tx, chosen, emptyMap(), funded), amount, total - amount, change = null, - absorbed = total - amount - withoutChange, - funded = funded, - ) - } - } - return Result.NotEnough - } - - /** - * [spend] again at [feeratePerVbyte]: the same coins and the same outputs, - * with the extra fee taken from the change -- or, for a send-all, from the - * one payment. RBF, which every spend allows; a new proposal, with new - * signatures, because a retry is a new session. - */ - fun bump(spend: GroupSpend.Checked, feeratePerVbyte: Long): Result { - val fee = Satoshi(feeratePerVbyte * ((spend.weight + 3) / 4)) - val extra = fee - spend.fee - if (extra.sat <= 0) return Result.NotHigher - - val target = spend.outputs.firstOrNull { it.isChange } ?: spend.payments.singleOrNull() ?: return Result.NotEnough - val reduced = target.txOut.amount - extra - if (reduced < DUST) return Result.NotEnough - - val tx = spend.tx.copy(txOut = spend.tx.txOut.mapIndexed { index, out -> if (index == target.index) out.copy(amount = reduced) else out }) - // A funding keeps its claim, or the bump would read as a payment to a bare address. - val psbt = GroupSpend.psbtOf( - tx, - spend.inputs.map { it.txOut to it.derivation }, - spend.outputs.mapNotNull { output -> output.change?.let { output.index to it } }.toMap(), - spend.account, - funding = spend.fundings.associate { it.outputIndex to (it.wallet.account to it.derived) }, - ) - return Result.Built( - psbt = psbt, - amount = if (target.isChange) spend.amountSent else reduced, - fee = fee, - change = if (target.isChange) reduced else null, - funded = spend.fundings.singleOrNull()?.let { Destination.Funding(it.wallet.account, it.derived) }, - ) - } - - /** - * The coins a new spend may use: confirmed -- for a guardian, as deep as its - * leaf's lock -- and held by no open spend. - */ - fun spendable( - state: GroupWalletState, - reserved: Set, - spender: GroupSpend.Spender = GroupSpend.Spender.Owner, - ): List { - val lock = lockOf(state, spender) - return state.utxos.filter { - it.isConfirmed && (lock == null || state.confirmations(it) >= lock) && it.utxo.outPoint !in reserved - } - } - - /** - * What [spendable] adds up to: the most a form can offer, before the fee. - * Less than the wallet's confirmed balance by whatever open spends hold. - */ - fun spendableBalance( - state: GroupWalletState, - reserved: Set, - spender: GroupSpend.Spender = GroupSpend.Spender.Owner, - ): Satoshi = spendable(state, reserved, spender).map { it.amount }.sum() - - /** The relative lock a guardian's inputs carry, or null for the wallet's own group. */ - private fun lockOf(state: GroupWalletState, spender: GroupSpend.Spender): Long? = - (spender as? GroupSpend.Spender.Guardian)?.let { state.account.guardians[it.position].delay } - - /** - * What [destination] pays: a typed address's script, or the funded wallet's - * own derivation -- never a string round trip, so a funding is always an - * address. Null for text that is not an address on this network, and for a - * funding on another network. - */ - private fun scriptOf(state: GroupWalletState, destination: Destination): ByteVector? = when (destination) { - is Destination.Address -> Bitcoin.addressToPublicKeyScript(state.account.chain.chainHash, destination.address.trim()).right - ?.let { ByteVector(Script.write(it)) } - is Destination.Funding -> destination.derived.pubkeyScript.takeIf { destination.account.chain == state.account.chain } - } - - private fun transaction(state: GroupWalletState, coins: List, outputs: List, spender: GroupSpend.Spender) = Transaction( - version = 2, - // Replaceable, so a stuck spend can be bumped by a new proposal -- and a - // guardian's lock is far below the replaceable ceiling, so its is too. - txIn = coins.map { TxIn(it.utxo.outPoint, ByteVector.empty, lockOf(state, spender) ?: GroupSpend.MAX_SEQUENCE) }, - txOut = outputs, - lockTime = 0, - ) - - /** - * The fee at [feeratePerVbyte] for spending [coins] to [scripts]: exact, - * because every signature is 64 bytes and a guardian's leaf and control - * block are known before anybody signs. - */ - private fun feeOf( - state: GroupWalletState, - coins: List, - scripts: List, - feeratePerVbyte: Long, - spender: GroupSpend.Spender, - ): Satoshi { - val tx = transaction(state, coins, scripts.map { TxOut(Satoshi(0), it) }, spender) - val weight = when (spender) { - GroupSpend.Spender.Owner -> GroupSpend.witnessed(tx, List(coins.size) { ByteVector64.Zeroes }) - is GroupSpend.Spender.Guardian -> coins.foldIndexed(tx) { index, partial, coin -> - partial.updateWitness(index, GroupSpend.guardianWitness(state.account, coin.derivation, spender.position)) - } - }.weight() - return Satoshi(feeratePerVbyte * ((weight + 3) / 4)) - } - - /** The payment is always output 0, so a funding's claim goes there. */ - private fun psbtOf( - state: GroupWalletState, - tx: Transaction, - coins: List, - change: Map, - funded: Destination.Funding?, - ) = GroupSpend.psbtOf( - tx, coins.map { it.utxo.txOut to it.derivation }, change, state.account, - funding = funded?.let { mapOf(0 to (it.account to it.derived)) }.orEmpty(), - ) -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/GroupTransactionWatcher.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/GroupTransactionWatcher.kt deleted file mode 100644 index a96e6e07..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/GroupTransactionWatcher.kt +++ /dev/null @@ -1,174 +0,0 @@ -package mobi.giza.compose.wallet - -import co.touchlab.kermit.Logger -import mobi.giza.compose.database.GizaDatabase -import mobi.giza.compose.database.model.GroupTransaction -import mobi.giza.compose.managers.FrostSigningManager -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import fr.acinq.bitcoin.Crypto -import fr.acinq.bitcoin.Transaction -import fr.acinq.bitcoin.TxId -import fr.acinq.bitcoin.byteVector32 -import fr.acinq.lightning.blockchain.electrum.IElectrumClient -import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Job -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.collectLatest -import kotlinx.coroutines.isActive -import kotlinx.coroutines.launch -import kotlin.time.Clock -import kotlin.time.Duration -import kotlin.time.Duration.Companion.minutes -import kotlin.time.Duration.Companion.seconds -import kotlin.time.Instant - -/** - * Sends the group's signed transactions to the network, and watches for them. - * - * Every member with an Electrum client broadcasts. The transaction is identical - * on every device, so a second broadcast is nothing to the network, and nobody's - * phone being asleep holds up the group -- unlike a group event, whose sending is - * a separate decision, the quorum has already decided the one thing broadcasting - * does. - * - * Electrum's broadcast reports success whatever the server said, so a broadcast - * is recorded when it was sent and nothing more; [GroupTransaction.seenAt] is - * written only when Electrum reports the transaction back, and an unseen one is - * sent again every [REBROADCAST_AFTER], which is what `IElectrumClient` asks of - * its callers. A confirmation goes through [FrostSigningManager.recordConfirmed], - * which settles every other spend of the same coins. - * - * A spend Electrum has not heard of may have lost its coins. Only the group can - * spend a plain wallet's coins, so there the loser is always another of the - * room's own spends and the winner's confirmation settles it. A guarded wallet's - * coins have a second spender, in another room: so an unseen spend asks the - * chain whether its coins are still there, and one taken by a *confirmed* - * transaction it is not goes through [FrostSigningManager.recordReplaced]. A - * conflict still in the mempool settles nothing -- ours may yet be the one that - * confirms. - */ -class GroupTransactionWatcher( - private val database: GizaDatabase, - private val clients: GroupChainClients, - private val scope: CoroutineScope, - private val now: () -> Instant = { Clock.System.now() }, -) { - /** Every network on [electrum]: what the tests construct. */ - constructor(database: GizaDatabase, electrum: IElectrumClient, scope: CoroutineScope, now: () -> Instant = { Clock.System.now() }) : - this(database, GroupChainClients.single(electrum), scope, now) - - /** The client for [transaction]'s own network, which a statement named and the row kept. */ - private suspend fun electrumFor(transaction: GroupTransaction): IElectrumClient? = - GroupWalletStatementEvent.chainNamed(transaction.chain)?.let { clients.clientFor(it) } - - private val logger = Logger.withTag("GroupTransactionWatcher") - private var job: Job? = null - - /** Runs a pass whenever a transaction is signed, and every [POLL] while any is on its way. */ - fun start() { - job?.cancel() - job = scope.launch { - database.groupTransactionDao().observeUnsettled().collectLatest { unsettled -> - while (isActive && unsettled.isNotEmpty()) { - pass() - delay(POLL) - } - } - } - } - - fun stop() { - job?.cancel() - job = null - } - - /** One look at every transaction still on its way. */ - suspend fun pass() { - database.groupTransactionDao().getUnsettled().forEach { transaction -> - try { - follow(transaction) - } catch (e: CancellationException) { - throw e - } catch (e: Throwable) { - logger.e("Could not follow transaction ${transaction.txid}", e) - } - } - } - - /** Sends [sessionId]'s transaction again now, whatever was last sent. False when there is nothing signed to send. */ - suspend fun broadcastAgain(sessionId: String): Boolean { - val transaction = database.groupTransactionDao().getBySessionId(sessionId) ?: return false - val signed = transaction.signedTransaction?.let { Transaction.read(it) } ?: return false - val electrum = electrumFor(transaction) ?: return false - electrum.broadcastTransaction(signed) - database.groupTransactionDao().upsert(transaction.copy(broadcastAt = now())) - return true - } - - private suspend fun follow(listed: GroupTransaction) { - // Read again rather than taken from the list the pass started with: a - // confirmation earlier in the same pass settles every other spend of its - // coins, and writing this row back from the stale copy would undo that. - val transaction = database.groupTransactionDao().getBySessionId(listed.frostSigningSessionId) ?: return - if (transaction.confirmedAt != null || transaction.replacedByTxid != null) return - val signed = Transaction.read(transaction.signedTransaction ?: return) - val electrum = electrumFor(transaction) ?: return - var row = transaction - - val due = row.broadcastAt?.let { now() - it >= REBROADCAST_AFTER } ?: true - if (row.seenAt == null && due) { - electrum.broadcastTransaction(signed) - row = row.copy(broadcastAt = now()) - database.groupTransactionDao().upsert(row) - } - - // Null while disconnected, or while Electrum has not heard of it -- which - // is also what a spend whose coins somebody else took looks like. - val confirmations = electrum.getConfirmations(signed) ?: run { - conflictOf(row, signed)?.let { FrostSigningManager.recordReplaced(database, row.frostSigningSessionId, it.toString()) } - return - } - if (row.seenAt == null) { - row = row.copy(seenAt = now()) - database.groupTransactionDao().upsert(row) - } - if (confirmations >= 1) { - FrostSigningManager.recordConfirmed(database, row.frostSigningSessionId, now()) - } - } - - /** - * A confirmed transaction other than [signed] that spent one of its coins, or - * null when every coin is still unspent, or was only taken by something - * unconfirmed, or the chain cannot be asked right now. - * - * Read per coin off the address it is at: is it still unspent there, and if - * not, which transaction in that address's history spent it. The address is - * the spent output's script, which the proposed PSBT carries for every input. - */ - private suspend fun conflictOf(transaction: GroupTransaction, signed: Transaction): TxId? { - val psbt = GroupSpend.decode(transaction.psbt) ?: return null - val electrum = electrumFor(transaction) ?: return null - - signed.txIn.forEachIndexed { index, input -> - val txOut = (psbt.inputs.getOrNull(index) as? fr.acinq.bitcoin.psbt.Input.WitnessInput)?.txOut ?: return@forEachIndexed - val scriptHash = Crypto.sha256(txOut.publicKeyScript).byteVector32().reversed() - - val unspent = electrum.getScriptHashUnspents(scriptHash) - .any { it.txid == input.outPoint.txid && it.outputIndex.toLong() == input.outPoint.index } - if (unspent) return@forEachIndexed - - electrum.getScriptHashHistory(scriptHash) - .filter { it.blockHeight > 0 && it.txid != signed.txid } - .firstOrNull { item -> electrum.getTx(item.txid)?.txIn?.any { it.outPoint == input.outPoint } == true } - ?.let { return it.txid } - } - return null - } - - companion object { - val POLL: Duration = 30.seconds - val REBROADCAST_AFTER: Duration = 10.minutes - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/GroupWalletRollout.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/GroupWalletRollout.kt deleted file mode 100644 index 2b20907c..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/GroupWalletRollout.kt +++ /dev/null @@ -1,81 +0,0 @@ -package mobi.giza.compose.wallet - -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.Satoshi - -/** - * The gates the group wallet ships behind -- `docs/group-chain-wallet.md`, Phase - * 10 -- in one place, each with the condition that lifts it. - * - * Entry points only. A device with a gate closed still accepts, shows and signs - * a spend another member proposes, through every check `GroupSpend` makes: a - * gate decides what this device offers, never what a quorum may decide. - */ -object GroupWalletRollout { - /** - * Whether the group's screen offers a wallet at all. Lifted when Phases 1-9 - * were in and the JVM suite passed, which they are and it did. - */ - const val ENABLED: Boolean = true - - /** - * The most one spend proposed from this device may send on mainnet -- and, - * since a member can send an amount with change on every network, the - * bound on what a builder bug in that change could put at risk. Lifts - * when a release has run real spends end to end with no session that failed - * to aggregate and no transaction that failed to confirm. Test networks have - * no cap: nothing on them is worth one. - */ - val MAINNET_CAP: Satoshi = Satoshi(100_000) - - fun capFor(chain: Chain): Satoshi? = MAINNET_CAP.takeIf { chain.isMainnet() } - - /** - * Whether a subgroup is offered a guarded wallet on mainnet -- - * `docs/group-wallet-guardians.md`. Test networks were offered one from the - * start. On: lifted by decision, ahead of the signet run its own condition - * named -- a guardian spend made by a real three-level hierarchy. What it - * still leaves open is the mixed-version risk: a member on a build that - * predates guarded statements sees no wallet, and can open a plain one whose - * addresses the rest do not watch. Every guardian spend on mainnet is held to - * [MAINNET_CAP] like any other. - */ - const val GUARDIANS_ON_MAINNET: Boolean = true - - fun offersGuardiansOn(chain: Chain): Boolean = GUARDIANS_ON_MAINNET || !chain.isMainnet() - - /** - * Whether a member is offered a guarded wallet of their own on mainnet -- - * `docs/member-guarded-wallets.md`, D8. Test networks were offered one from - * the start. On: lifted by decision, ahead of the signet run its own - * condition named -- a three-level hierarchy watching one member's wallet, - * and its root making a guardian spend from it -- as [GUARDIANS_ON_MAINNET] - * was. What it still leaves open is the mixed-version risk: a signer on a - * build that predates member wallets is shown a certificate it cannot check. - * - * The entrances only. A device with it shut still accepts, shows and signs - * a certificate somebody else asked for. - */ - const val MEMBER_WALLETS_ON_MAINNET: Boolean = true - - fun offersMemberWalletsOn(chain: Chain): Boolean = MEMBER_WALLETS_ON_MAINNET || !chain.isMainnet() - - /** - * Whether a device tells the groups above about a guarded wallet on its own - * -- as the wallet arrives, and as a group's chat or wallet screen opens -- - * rather than only when somebody taps *Share*. - * `docs/guarded-wallet-forwarding.md`, D8. A behaviour that sends messages - * without a person, so it has a switch for the release it first ships in. - * The button does not read it. - */ - const val FORWARDS_GUARDED_WALLETS: Boolean = true - - /** - * The most a member's own spend from their guarded wallet may send on - * [chain]: [MAINNET_CAP] on mainnet, as every other spend is. The gate - * lifted before the run that was to lift the cap with it, and the member's - * spend is signed by a path no group spend goes through, so the cap stays - * until that run has been made. - */ - fun memberCapFor(chain: Chain): Satoshi? = capFor(chain) -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/IdentityElectrum.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/IdentityElectrum.kt deleted file mode 100644 index 1be14a48..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/IdentityElectrum.kt +++ /dev/null @@ -1,90 +0,0 @@ -package mobi.giza.compose.wallet - -import co.touchlab.kermit.Logger -import mobi.giza.compose.identity.Identity -import fr.acinq.bitcoin.Chain -import fr.acinq.lightning.blockchain.electrum.IElectrumClient -import fr.acinq.lightning.logging.LoggerFactory -import fr.acinq.phoenix.data.WalletId -import fr.acinq.phoenix.managers.NodeParamsManager -import fr.acinq.phoenix.managers.global.NetworkMonitor -import kotlinx.coroutines.flow.flowOf - -/** - * The Electrum client the active identity watches the chain on. - * - * A profile with a node watches on the node's client; one with no node -- an nsec - * or an npub -- gets a [StandaloneElectrum] of its own. Never both: a second - * connection from a profile that has one would tell a second server the same - * addresses, and give the wallets a chain that can disagree with the node's (D1 of - * `docs/standalone-electrum.md`). The test is the node client, not the kind, as - * `switchToIdentity` tests `business`. - * - * One per app, held by the nav host. A change of identity stops the last - * standalone client *before* the next is made, so a switch between two nsec - * profiles never has two connections open; a stopped client cannot be restarted, - * so the next is always new. - */ -class IdentityElectrum( - private val standaloneFor: (Identity) -> StandaloneElectrum, -) { - private val logger = Logger.withTag("IdentityElectrum") - - private var key: Pair? = null - private var client: IElectrumClient? = null - private var standalone: StandaloneElectrum? = null - - /** - * The client for [identity], made the first time it is asked for and kept while - * it stays the same identity on the same node. Null only with no identity. - */ - fun clientFor(identity: Identity?, nodeClient: IElectrumClient? = identity?.business?.electrumClient): IElectrumClient? { - val next = identity?.let { it.id to nodeClient } - if (next == key) return client - - stop() - key = next - client = when { - identity == null -> null - nodeClient != null -> nodeClient - else -> { - logger.i { "starting an Electrum client for ${identity.id}, which has no node" } - standaloneFor(identity).also { it.start() }.also { standalone = it }.client - } - } - return client - } - - /** Stops the standalone client, if the identity has one. The node's is the node's to stop. */ - fun stop() { - standalone?.stop() - standalone = null - client = null - key = null - } - - companion object { - /** The real thing: the identity's own Electrum preferences, the device's network, the node's network. */ - fun standalone(networkMonitor: NetworkMonitor, loggerFactory: LoggerFactory): (Identity) -> StandaloneElectrum = { identity -> - standaloneOn(NodeParamsManager.chain, identity, networkMonitor, loggerFactory) - } - - /** - * A standalone client for [identity] on [chain]. On the node's own network it takes the - * identity's custom server, if one is set; on any other -- testnet3, for a group's Lightning - * wallet -- that server is for the wrong network, so it takes a random one. Tor and the - * device's network apply either way. - */ - fun standaloneOn(chain: Chain, identity: Identity, networkMonitor: NetworkMonitor, loggerFactory: LoggerFactory): StandaloneElectrum { - // Idempotent on every platform, and otherwise only the node's daemon calls it. - networkMonitor.start() - return StandaloneElectrum( - chain = chain, - networkState = networkMonitor.networkState, - isTorEnabled = identity.userPrefs.getIsTorEnabled, - customServer = if (chain == NodeParamsManager.chain) identity.userPrefs.getElectrumServer else flowOf(null), - link = ElectrumClientLink(loggerFactory), - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/StandaloneElectrum.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/StandaloneElectrum.kt deleted file mode 100644 index 71abaec2..00000000 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/wallet/StandaloneElectrum.kt +++ /dev/null @@ -1,207 +0,0 @@ -package mobi.giza.compose.wallet - -import co.touchlab.kermit.Logger -import fr.acinq.bitcoin.Chain -import fr.acinq.lightning.blockchain.electrum.ElectrumClient -import fr.acinq.lightning.blockchain.electrum.IElectrumClient -import fr.acinq.lightning.io.TcpSocket -import fr.acinq.lightning.logging.LoggerFactory -import fr.acinq.lightning.utils.Connection -import fr.acinq.lightning.utils.ServerAddress -import fr.acinq.phoenix.data.ElectrumConfig -import fr.acinq.phoenix.data.mainnetElectrumServers -import fr.acinq.phoenix.data.mainnetElectrumServersOnion -import fr.acinq.phoenix.data.platformElectrumRegtestConf -import fr.acinq.phoenix.data.testnetElectrumServers -import fr.acinq.phoenix.data.testnetElectrumServersOnion -import fr.acinq.phoenix.managers.global.NetworkState -import fr.acinq.phoenix.utils.extensions.isOnion -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.Job -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.cancel -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.collectLatest -import kotlinx.coroutines.flow.combine -import kotlinx.coroutines.flow.distinctUntilChanged -import kotlinx.coroutines.flow.map -import kotlinx.coroutines.launch -import kotlin.coroutines.CoroutineContext -import kotlin.time.Duration -import kotlin.time.Duration.Companion.seconds - -/** - * An Electrum connection for a profile with no node: an nsec or an npub. - * - * A mnemonic profile watches the chain on its node's client, which the node's - * `AppConnectionsDaemon` keeps connected. That daemon is built from a - * `PhoenixBusiness` and cannot be had without one, so this is its Electrum branch - * with the business taken out: the same server choice, the same pauses between - * attempts, the same handshake timeouts, and the same refusal of a clearnet server - * the user asked to reach only over Tor. See `docs/standalone-electrum.md`. - * - * The server comes from the identity's own preferences -- a custom server if one - * is set, a random one for [chain] if not -- and any change to them, or to Tor, or - * to the network, drops the connection and starts again, as the daemon does. - * - * One per identity, and never restarted: [stop] stops the client for good, which - * is what `ElectrumClient.stop` means, so a profile switch makes a new one. - */ -class StandaloneElectrum( - private val chain: Chain, - private val networkState: Flow, - private val isTorEnabled: Flow, - private val customServer: Flow, - private val link: ElectrumLink, - private val randomServer: (Chain, Boolean) -> ServerAddress? = ::randomElectrumServer, - context: CoroutineContext = Dispatchers.Default, -) { - private val logger = Logger.withTag("StandaloneElectrum") - private val scope = CoroutineScope(SupervisorJob() + context) - private var job: Job? = null - - /** What every wallet of the identity watches on. */ - val client: IElectrumClient get() = link.client - - /** What the connection depends on: a change in any of it is a fresh start. */ - private data class Control( - val internetIsAvailable: Boolean, - val torIsEnabled: Boolean, - val customServer: ElectrumConfig.Custom?, - ) - - fun start() { - if (job != null) return - job = scope.launch { - combine( - networkState.map { it == NetworkState.Available }, - isTorEnabled, - customServer, - ) { internet, tor, custom -> Control(internet, tor, custom) } - .distinctUntilChanged() - .collectLatest { control -> - // collectLatest has already cancelled the last loop; the socket it - // left open is closed here, so the new control starts from CLOSED. - link.disconnect() - if (control.internetIsAvailable) connectionLoop(control) - } - } - } - - /** Stops the client for good. It cannot be started again. */ - fun stop() { - job?.cancel() - job = null - link.stop() - scope.cancel() - } - - /** - * Connects whenever the connection is closed, after a pause that grows with each - * failure in a row and resets once a connection is made. The daemon's - * `connectionLoop`, for one connection. - */ - private suspend fun connectionLoop(control: Control) { - var attempt = 0 - link.client.connectionStatus.map { it.toConnectionState() }.collect { state -> - if (state is Connection.CLOSED) { - delay(pauseBefore(attempt)) - attempt++ - connect(control, attempt) - } else if (state == Connection.ESTABLISHED) { - attempt = 0 - } - } - } - - private suspend fun connect(control: Control, attempt: Int) { - val server = control.customServer?.server ?: randomServer(chain, control.torIsEnabled) - if (server == null) { - logger.w { "no Electrum server for $chain; not connecting" } - return - } - // The same rule as the node's: a custom server the user wants reached only - // through Tor is not reached at all while Tor is on and it is not an onion. - if (control.torIsEnabled && !server.isOnion && control.customServer?.requireOnionIfTorEnabled == true) { - logger.e { "not connecting to ${server.host}: Tor is on and the server must be an onion address" } - return - } - logger.i { "connecting to ${server.host}:${server.port}, attempt $attempt" } - try { - link.connect(server, handshakeTimeout(attempt, control.torIsEnabled)) - } catch (e: Exception) { - logger.e("could not connect to Electrum", e) - } - } - - companion object { - /** The daemon's `connectionPause`, unchanged. */ - fun pauseBefore(attempt: Int): Duration = when { - attempt <= 0 -> 0.1.seconds - attempt == 1 -> 0.25.seconds - attempt == 2 -> 0.5.seconds - attempt == 3 -> 1.seconds - attempt == 4 -> 2.seconds - attempt == 5 -> 4.seconds - else -> 8.seconds - } - - /** The daemon's handshake timeouts: short at first for a snappy start, longer as failures add up. */ - fun handshakeTimeout(attempt: Int, torIsEnabled: Boolean): Duration = when { - torIsEnabled && attempt <= 6 -> 20.seconds - torIsEnabled -> 40.seconds - attempt <= 3 -> 4.seconds - attempt <= 6 -> 7.seconds - attempt <= 10 -> 15.seconds - else -> 20.seconds - } - } -} - -/** - * The part of an Electrum client the loop drives, beyond what the wallets read. - * - * A seam so the loop can be tested against a connection status the test moves, - * with no socket. [ElectrumClientLink] is the real one. - */ -interface ElectrumLink { - val client: IElectrumClient - suspend fun connect(server: ServerAddress, timeout: Duration) - fun disconnect() - fun stop() -} - -/** An [ElectrumLink] over lightning-kmp's own client, with the platform's sockets. */ -class ElectrumClientLink(loggerFactory: LoggerFactory) : ElectrumLink { - // Its own scope, as PhoenixBusiness gives the node's: the client's listen job - // must not take the app's scope down with it, and [stop] cancels it. - private val electrumScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) - private val electrum = ElectrumClient(scope = electrumScope, loggerFactory = loggerFactory, pingInterval = 30.seconds, rpcTimeout = 10.seconds) - - override val client: IElectrumClient get() = electrum - - override suspend fun connect(server: ServerAddress, timeout: Duration) { - electrum.connect(server, TcpSocket.Builder(), timeout) - } - - override fun disconnect() = electrum.disconnect() - - override fun stop() { - electrum.stop() - electrumScope.cancel() - } -} - -/** - * A random server from the hard-coded list for [chain]: `AppConfigurationManager.randomElectrumServer`, - * which needs a business to be called. Null for the networks that list has no - * servers for, where the manager's own answer is `TODO()`. - */ -fun randomElectrumServer(chain: Chain, isTorEnabled: Boolean): ServerAddress? = when (chain) { - Chain.Mainnet -> if (isTorEnabled) mainnetElectrumServersOnion.random() else mainnetElectrumServers.random() - Chain.Testnet3 -> if (isTorEnabled) testnetElectrumServersOnion.random() else testnetElectrumServers.random() - Chain.Regtest -> platformElectrumRegtestConf() - else -> null -} 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 f6cc3aa7..69c64705 100644 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ForkCompatibilityTest.kt +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ForkCompatibilityTest.kt @@ -1,7 +1,6 @@ package mobi.giza.compose.managers import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Chain import fr.acinq.bitcoin.PrivateKey import fr.acinq.secp256k1.Hex import mobi.giza.compose.identity.StoredIdentity @@ -51,14 +50,6 @@ class ForkCompatibilityTest { assertEquals(PINNED_SHARED_KEY, SharedKeyDerivation.derive(threshold).hex) } - // bennu/group-wallet/account/v1, bennu/group-wallet/guardian/v1 and …/guardian/child/v1 - @Test - fun `group wallet account and guardian root`() { - assertEquals(PINNED_GROUP_ADDRESS, GroupWalletDerivation.derive(GroupWalletDerivation.account(threshold, Chain.Mainnet), GroupWalletDerivation.RECEIVE, 0L).address(Chain.Mainnet)) - assertEquals(PINNED_GUARDIAN_ROOT, GuardianDerivation.root(threshold).publicKey.toString()) - assertEquals(PINNED_GUARDIAN_CHILD_INDEX, GuardianDerivation.childIndex(room)) - } - // NIP-06's own test vector, and the id this app files a recovery phrase's profile under. // // Pinned through the code docs/giza-wallet-removal.md Phase 6 replaces: lightning-kmp's @@ -90,8 +81,5 @@ class ForkCompatibilityTest { const val PINNED_PHRASE_HOST_KEY = "03b93ca2ea2bac313457180953bbede99450d59ce01916e98d42df09fdabbbe83f" const val PINNED_HOST_KEY = "028871ab105eac8812fa7aab4b9110ad20b5dcfba9f65271431dcb417258da08af" const val PINNED_SHARED_KEY = "5eb33e9c2a5a90ae4d273b687eb1265f8b79c2bcee28f9ae9dc44dba6e788444" - 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/GroupKeyStateTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/GroupKeyStateTest.kt index e5c170b1..373f5590 100644 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/GroupKeyStateTest.kt +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/GroupKeyStateTest.kt @@ -1,7 +1,5 @@ package mobi.giza.compose.managers -import mobi.giza.compose.nostr.subgroup.tags.WalletPolicyTag -import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent import com.vitorpamplona.quartz.nip65RelayList.AdvertisedRelayListEvent @@ -889,31 +887,24 @@ class GroupKeyStateTest { assertNull(GroupKeyStateManager.stateFrom(chatRoomId, keyStateWithParent(certificate = wrongKey))) } + /** + * A Bennu parent's wallet tags decide nothing on this device: Giza takes no + * wallet decision from a certificate, so it keeps the key state as it came, + * whatever its `wallet` or `guardian` tags say. docs/giza-wallet-removal.md. + */ @Test - fun `a state whose certificate's wallet policy does not read is dropped`() { - // Present and unreadable must not read as absent: an undecided child is - // offered both wallets, so a corrupt policy would hand it the one its - // parent took away. docs/subgroup-wallet-policy.md, Phase 5. + fun `a state whose certificate carries wallet tags is kept as it came`() { listOf( arrayOf(arrayOf("wallet", "maybe")), - arrayOf(WalletPolicyTag.assemble(SubgroupWalletPolicy.GUARDED)), - arrayOf(WalletPolicyTag.assemble(SubgroupWalletPolicy.UNGUARDED), WalletPolicyTag.assemble(SubgroupWalletPolicy.UNGUARDED)), + arrayOf(arrayOf("wallet", "guarded")), + arrayOf(arrayOf("wallet", "unguarded"), arrayOf("wallet", "unguarded")), ).forEach { extraTags -> - assertNull( - GroupKeyStateManager.stateFrom(chatRoomId, keyStateWithParent(certificate = birthCertificate(extraTags = extraTags))), - "a certificate with ${extraTags.joinToString { it.joinToString() }} was believed", - ) + val certificate = birthCertificate(extraTags = extraTags) + val state = GroupKeyStateManager.stateFrom(chatRoomId, keyStateWithParent(certificate = certificate)) + assertEquals(certificate.toJson(), state?.birthCertificateJson, "a certificate with ${extraTags.joinToString { it.joinToString() }}") } } - @Test - fun `a state whose certificate decides a wallet policy keeps it`() { - val unguarded = birthCertificate(extraTags = arrayOf(WalletPolicyTag.assemble(SubgroupWalletPolicy.UNGUARDED))) - val state = GroupKeyStateManager.stateFrom(chatRoomId, keyStateWithParent(certificate = unguarded)) - - assertEquals(unguarded.toJson(), state?.birthCertificateJson) - } - @Test fun `a parentage survives the trip through the tags`() { val certificate = birthCertificate() diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/GroupWalletDerivationTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/GroupWalletDerivationTest.kt deleted file mode 100644 index 1fcabfe8..00000000 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/GroupWalletDerivationTest.kt +++ /dev/null @@ -1,168 +0,0 @@ -package mobi.giza.compose.managers - -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.DeterministicWallet -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.crypto.frost.TweakCache -import fr.acinq.secp256k1.Hex -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertNotEquals -import kotlin.test.assertTrue - -/** - * The group wallet's derivation, pinned. - * - * Three kinds of assertion, and they guard different things. BIP86's own vectors - * prove the tail *is* BIP86. The pinned vector freezes the account step -- the - * tag, the byte order of the chain hash, the order of the HMAC's inputs -- so a - * change to any of them fails here rather than moving a group's coins. And the - * parity sweep exists because a parity mistake in a cache passes half the time. - */ -class GroupWalletDerivationTest { - /** A threshold key nobody needs the secret of: the test is about public derivation. */ - private fun thresholdKey(seed: Int): String = - PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))).publicKey().toString() - - private val k = thresholdKey(0x1c0ffee) - - @Test - fun `the tail below an account key is BIP86's`() { - // m/86'/0'/0' of "abandon ... about", from BIP86 itself. - val (_, accountKey) = DeterministicWallet.ExtendedPublicKey.decode( - "xpub6BgBgsespWvERF3LHQu6CnqdvfEvtMcQjYrcRzx53QJjSxarj2afYWcLteoGVky7D3UKDP9QyrLprQ3VCECoY49yfdDEHGCtMMj92pReUsQ" - ) - val cache = TweakCache.create(accountKey.publicKey) - - val vectors = listOf( - Triple(0L to 0L, "cc8a4bc64d897bddc5fbc2f670f7a8ba0b386779106cf1223c6fc5d7cd6fc115", "bc1p5cyxnuxmeuwuvkwfem96lqzszd02n6xdcjrs20cac6yqjjwudpxqkedrcr"), - Triple(0L to 1L, "83dfe85a3151d2517290da461fe2815591ef69f2b18a2ce63f01697a8b313145", "bc1p4qhjn9zdvkux4e44uhx8tc55attvtyu358kutcqkudyccelu0was9fqzwh"), - Triple(1L to 0L, "399f1b2f4393f29a18c937859c5dd8a77350103157eb880f02e8c08214277cef", "bc1p3qkhfews2uk44qtvauqyr2ttdsw7svhkl9nkm9s9c3x4ax5h60wqwruhk7"), - ) - - vectors.forEach { (path, internalKey, address) -> - val derived = GroupWalletDerivation.deriveBelow(accountKey, cache, path.first, path.second) - assertEquals(internalKey, derived.internalKey.value.toHex(), "internal key at ${path.first}/${path.second}") - assertEquals(address, derived.address(Chain.Mainnet), "address at ${path.first}/${path.second}") - // Through the cache, not only the points: this is the key a session signs for. - assertEquals(derived.outputKey, derived.cache.tweakedPublicKey) - } - } - - @Test - fun `the account step is pinned`() { - val mainnet = GroupWalletDerivation.account(k, Chain.Mainnet) - val regtest = GroupWalletDerivation.account(k, Chain.Regtest) - val second = GroupWalletDerivation.account(k, Chain.Mainnet, account = 1) - - // Frozen. A failure here is not a test to update: it means every group's - // coins would be at different addresses after this change, and the ones - // already received would be found by nobody. - assertEquals( - "xpub661MyMwAqRbcEjmHgZBQ6WrHydBtiy96F6Lh8tj8vTzDYvMyQoqe1yLFytfUoqEkwRd9j8xqY1PZD25cnXn5LjMh5QLbywNqV3qse8Lxfdu", - mainnet.xpub - ) - assertEquals( - "tr([935b59f0]xpub661MyMwAqRbcEjmHgZBQ6WrHydBtiy96F6Lh8tj8vTzDYvMyQoqe1yLFytfUoqEkwRd9j8xqY1PZD25cnXn5LjMh5QLbywNqV3qse8Lxfdu/0/*)#mfhfa9w0", - mainnet.receiveDescriptor - ) - assertEquals( - "tr([935b59f0]xpub661MyMwAqRbcEjmHgZBQ6WrHydBtiy96F6Lh8tj8vTzDYvMyQoqe1yLFytfUoqEkwRd9j8xqY1PZD25cnXn5LjMh5QLbywNqV3qse8Lxfdu/1/*)#2ajgqs7h", - mainnet.changeDescriptor - ) - assertEquals( - "bc1p5v8nnu750wmu3sg5yee2kmj466d44dmr2cd0e0a4frwyqessayhqs442qs", - GroupWalletDerivation.derive(mainnet, 0, 0).address(Chain.Mainnet) - ) - - assertEquals( - "tpubD6NzVbkrYhZ4WoTbDgosM5KFsbzdUShJQHoMYsCSeSSTtniVCq92YbNb3vt2Ywg4njZ2JNeFtNbQStabeYpnXAUVzxYm9behJDvp5YhTvgE", - regtest.xpub - ) - assertEquals( - "bcrt1pkr33dle8ttv5p96se2dl0ujqxhkuxpw0cgapaa7g0578g5nctr9qwsyt55", - GroupWalletDerivation.derive(regtest, 0, 0).address(Chain.Regtest) - ) - - assertEquals( - "xpub661MyMwAqRbcF6PNpyzQvz1jPnpXZ785MJciQPZwyP2AhD9Gs6A2Acn9BnPHb2TUWku5CDARAwCpioDdPvrmjXWcAQbHWCXUZhW1VRyxDA2", - second.xpub - ) - assertEquals( - "bc1ptkqtyu8z5qm2l25p26nfr5ahugjw87vgc4yudevveysjkytw7caqtfjgrg", - GroupWalletDerivation.derive(second, 0, 0).address(Chain.Mainnet) - ) - } - - @Test - fun `both parities derive, at the account and below it`() { - val accountParities = mutableSetOf() - val childParities = mutableSetOf() - - (1..16).forEach { seed -> - val account = GroupWalletDerivation.account(thresholdKey(seed), Chain.Mainnet) - accountParities += account.extendedPublicKey.publicKey.isEven() - - (0L..3L).forEach { index -> - listOf(GroupWalletDerivation.RECEIVE, GroupWalletDerivation.CHANGE).forEach { change -> - // derive refuses to return if the cache and the points disagree, - // so reaching the end of this loop is the assertion. - val derived = GroupWalletDerivation.derive(account, change, index) - childParities += account.extendedPublicKey.derivePublicKey(change).derivePublicKey(index).publicKey.isEven() - assertEquals(derived.outputKey, derived.cache.tweakedPublicKey) - } - } - } - - assertEquals(setOf(true, false), accountParities, "the sweep has to cover both parities of the account key") - assertEquals(setOf(true, false), childParities, "the sweep has to cover both parities of a child key") - } - - @Test - fun `the wallet shares no key with the room or with itself`() { - val room = SharedKeyDerivation.derive(k).publicKey - val mainnet = GroupWalletDerivation.account(k, Chain.Mainnet) - val receive = GroupWalletDerivation.derive(mainnet, GroupWalletDerivation.RECEIVE, 0) - - assertNotEquals(room, receive.outputKey, "the room's key") - assertNotEquals(room, receive.internalKey, "the room's key, untweaked") - assertNotEquals( - mainnet.extendedPublicKey.publicKey.xOnly(), - fr.acinq.bitcoin.PublicKey.fromHex(k).xOnly(), - "the account key is not the threshold key, so the xpub does not reveal it" - ) - - val keys = listOf( - receive.outputKey, - GroupWalletDerivation.derive(mainnet, GroupWalletDerivation.CHANGE, 0).outputKey, - GroupWalletDerivation.derive(mainnet, GroupWalletDerivation.RECEIVE, 1).outputKey, - GroupWalletDerivation.derive(GroupWalletDerivation.account(k, Chain.Regtest), GroupWalletDerivation.RECEIVE, 0).outputKey, - GroupWalletDerivation.derive(GroupWalletDerivation.account(k, Chain.Mainnet, account = 1), GroupWalletDerivation.RECEIVE, 0).outputKey, - ) - assertEquals(keys.size, keys.toSet().size, "receive, change, index, network and account each give a different key") - } - - @Test - fun `hardened and out-of-range steps are refused`() { - val account = GroupWalletDerivation.account(k, Chain.Mainnet) - - assertFailsWith { GroupWalletDerivation.derive(account, 2, 0) } - assertFailsWith { GroupWalletDerivation.derive(account, 0, DeterministicWallet.hardened(0)) } - assertFailsWith { GroupWalletDerivation.derive(account, 0, -1) } - assertFailsWith { GroupWalletDerivation.account(k, Chain.Mainnet, DeterministicWallet.hardened(0)) } - } - - @Test - fun `descriptors carry the account's own fingerprint and a checksum`() { - val account = GroupWalletDerivation.account(k, Chain.Mainnet) - val pattern = Regex("""tr\(\[[0-9a-f]{8}]xpub[1-9A-HJ-NP-Za-km-z]+/[01]/\*\)#[qpzry9x8gf2tvdw0s3jn54khce6mua7l]{8}""") - - assertTrue(pattern.matches(account.receiveDescriptor), account.receiveDescriptor) - assertTrue(pattern.matches(account.changeDescriptor), account.changeDescriptor) - assertTrue(GroupWalletDerivation.account(k, Chain.Regtest).xpub.startsWith("tpub")) - } - - private fun ByteVector32.toHex(): String = toString() -} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/GroupWalletSpendRoundTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/GroupWalletSpendRoundTest.kt deleted file mode 100644 index 8e73d6ee..00000000 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/GroupWalletSpendRoundTest.kt +++ /dev/null @@ -1,199 +0,0 @@ -package mobi.giza.compose.managers - -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.ByteVector64 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.Crypto -import fr.acinq.bitcoin.OutPoint -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.PublicKey -import fr.acinq.bitcoin.Satoshi -import fr.acinq.bitcoin.Script -import fr.acinq.bitcoin.ScriptFlags -import fr.acinq.bitcoin.SigHash -import fr.acinq.bitcoin.Transaction -import fr.acinq.bitcoin.TxIn -import fr.acinq.bitcoin.TxOut -import fr.acinq.bitcoin.crypto.dkg.chill.ChillDKG -import fr.acinq.bitcoin.crypto.dkg.chill.ParticipantFinalizeResult -import fr.acinq.bitcoin.crypto.frost.AggregatedNonce -import fr.acinq.bitcoin.crypto.frost.IndividualNonce -import fr.acinq.bitcoin.crypto.frost.SecretNonce -import fr.acinq.bitcoin.crypto.frost.Session -import fr.acinq.bitcoin.crypto.frost.TweakCache -import kotlin.test.Test -import kotlin.test.assertFails -import kotlin.test.assertNotEquals -import kotlin.test.assertTrue - -/** - * A group's threshold key spending its own wallet, against real ChillDKG and - * real FROST, with no database and no manager in the way. - * - * This is the test the rest of the wallet is built on. `FrostSigningManager` - * will spread these same calls across messages and devices; what it cannot - * check from inside is that the calls themselves produce a transaction the - * network accepts. So the judge here is `correctlySpends` -- the script - * interpreter -- and never `verifySignatureSchnorr` alone: a signature that - * verifies against the wrong sighash, or for the wrong key, is a perfectly - * good signature and a transaction nobody can mine. - */ -class GroupWalletSpendRoundTest { - private val participants = 3 - private val threshold = 2 - - /** A real ceremony, so the shares are what a member's device actually holds. Fixed randomness, so it is the same ceremony every run. */ - private val dkg: List = run { - val hostSecretKeys = (1..participants).map { PrivateKey(ByteVector32(ByteArray(32) { i -> (it * 7 + i).toByte() })) } - val hostPublicKeys = hostSecretKeys.map { ChillDKG.hostPublicKey(it) } - val step1 = hostSecretKeys.mapIndexed { i, key -> - ChillDKG.participantStep1(key, hostPublicKeys, threshold, ByteVector32(ByteArray(32) { (i + 1).toByte() })) - } - val coordinator1 = ChillDKG.coordinatorStep1(step1.map { it.message }, hostPublicKeys, threshold) - val step2 = hostSecretKeys.mapIndexed { i, key -> - ChillDKG.participantStep2(key, step1[i].state, coordinator1.message, ByteVector32(ByteArray(32) { (i + 11).toByte() })) - } - val certificate = ChillDKG.coordinatorFinalize(coordinator1.state, step2.map { it.certEqSignature }, threshold).certificate - (0 until participants).map { i -> ChillDKG.participantFinalize(step2[i].state, certificate, participants, threshold) } - .onEach { assertTrue(it.fault.isOk, "the ceremony has to succeed for the rest to mean anything") } - } - - private val thresholdPublicKey: PublicKey = dkg[0].thresholdPublicKey!! - private val publicShares: List = dkg[0].publicShares - - private val account = GroupWalletDerivation.account(thresholdPublicKey.toString(), Chain.Regtest) - private val first = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, 0) - private val second = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, 1) - private val change = GroupWalletDerivation.derive(account, GroupWalletDerivation.CHANGE, 0) - - /** Somebody else's money, paying the group's first two receive addresses. */ - private val funding = Transaction( - version = 2, - txIn = listOf(TxIn(OutPoint(ByteVector32(ByteArray(32) { 0x42 }).let { fr.acinq.bitcoin.TxId(it) }, 0), signatureScript = ByteVector.empty, sequence = 0xffffffffL)), - txOut = listOf(TxOut(Satoshi(60_000), first.pubkeyScript), TxOut(Satoshi(40_000), second.pubkeyScript)), - lockTime = 0, - ) - - private val spentOutputs: List = funding.txOut - - /** The group pays 70,000 out, 29,000 back to its own change, 1,000 to fees. */ - private val spend = Transaction( - version = 2, - txIn = listOf( - TxIn(OutPoint(funding, 0), signatureScript = ByteVector.empty, sequence = 0xfffffffdL), - TxIn(OutPoint(funding, 1), signatureScript = ByteVector.empty, sequence = 0xfffffffdL), - ), - txOut = listOf( - TxOut(Satoshi(70_000), Script.pay2wpkh(PrivateKey(ByteVector32(ByteArray(32) { 9 })).publicKey())), - TxOut(Satoshi(29_000), change.pubkeyScript), - ), - lockTime = 0, - ) - - private val derivations = listOf(first, second) - - private fun sighash(tx: Transaction, input: Int, outputs: List = spentOutputs): ByteVector32 = - tx.hashForSigningTaprootKeyPath(input, outputs, SigHash.SIGHASH_DEFAULT) - - private class Signed(val signature: ByteVector64, val aggregatedNonce: AggregatedNonce) - - /** - * One input's FROST instance, in the order the manager runs it: a nonce per - * signer from that input's own seed, aggregated; a session over that input's - * sighash and cache; a partial signature from each signer, checked; the aggregate. - */ - private fun signInput( - message: ByteVector32, - cache: TweakCache, - seed: Int, - signerIds: List = listOf(0, 2), - ): Signed { - val nonces = signerIds.map { id -> - SecretNonce.generate( - sessionRandom = ByteVector32(ByteArray(32) { (seed * 16 + id).toByte() }), - secretShare = dkg[id].secretShare!!, - publicShare = publicShares[id], - tweakedThresholdPublicKey = cache.tweakedPublicKey, - message = message, - extraInput = null, - ) - } - val aggregated = IndividualNonce.aggregate(nonces.map { it.second }).right!! - val session = Session.create( - aggregatedNonce = aggregated, - signerIds = signerIds.map { it.toUInt() }, - signerPublicShares = signerIds.map { publicShares[it] }, - nParticipants = participants, - threshold = threshold, - tweakCache = cache, - message = message, - ) - val partials = signerIds.mapIndexed { position, id -> - session.sign(nonces[position].first, dkg[id].secretShare!!, id.toUInt()).right!!.also { - assertTrue(session.verify(it, nonces[position].second, publicShares[id], position), "signer $id's partial signature") - } - } - return Signed(session.aggregateSigs(partials).right!!, aggregated) - } - - private fun witnessed(tx: Transaction, signatures: List): Transaction = - signatures.foldIndexed(tx) { input, partial, signature -> partial.updateWitness(input, Script.witnessKeyPathPay2tr(signature)) } - - private fun assertSpends(tx: Transaction) = - tx.correctlySpends(funding.txOut.mapIndexed { i, out -> OutPoint(funding, i.toLong()) to out }.toMap(), ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) - - @Test - fun `a quorum of the ceremony's shares spends the group's coins`() { - val signed = derivations.mapIndexed { input, derived -> signInput(sighash(spend, input), derived.cache, seed = input + 1) } - - signed.forEachIndexed { input, it -> - assertTrue(Crypto.verifySignatureSchnorr(sighash(spend, input), it.signature, derivations[input].outputKey)) - } - assertSpends(witnessed(spend, signed.map { it.signature })) - } - - @Test - fun `any quorum will do`() { - val signed = derivations.mapIndexed { input, derived -> - signInput(sighash(spend, input), derived.cache, seed = input + 1, signerIds = listOf(1, 2)) - } - - assertSpends(witnessed(spend, signed.map { it.signature })) - } - - @Test - fun `each input is its own instance, with its own nonce`() { - val signed = derivations.mapIndexed { input, derived -> signInput(sighash(spend, input), derived.cache, seed = input + 1) } - - // Every assertion above still passes if two inputs share a nonce. What - // sharing costs is each signer's share, to anyone who sees both partials. - assertNotEquals(signed[0].aggregatedNonce, signed[1].aggregatedNonce) - assertNotEquals(sighash(spend, 0), sighash(spend, 1), "and the two messages differ, so one nonce would be two equations") - } - - @Test - fun `the wrong cache signs for a key the coins are not at`() { - val wrongCaches = mapOf( - "the other input's" to second.cache, - "the bare threshold key's" to TweakCache.create(thresholdPublicKey), - "the account key's, without the tail or the key-path tweak" to account.cache, - ) - - wrongCaches.forEach { (name, cache) -> - val signatures = listOf(signInput(sighash(spend, 0), cache, seed = 1).signature, signInput(sighash(spend, 1), second.cache, seed = 2).signature) - assertFails("$name cache") { assertSpends(witnessed(spend, signatures)) } - } - } - - @Test - fun `a sighash over a lie about an amount does not spend`() { - // BIP341 commits every spent amount into every sighash. That is what lets a - // signer trust a PSBT's amounts without fetching the transactions: a - // proposer who lies gets a signature the network rejects, not a bigger fee. - val lied = listOf(spentOutputs[0].copy(amount = Satoshi(600_000)), spentOutputs[1]) - val signatures = derivations.mapIndexed { input, derived -> signInput(sighash(spend, input, lied), derived.cache, seed = input + 1).signature } - - assertFails { assertSpends(witnessed(spend, signatures)) } - } -} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/GuardianDerivationTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/GuardianDerivationTest.kt deleted file mode 100644 index 6aaa1e1c..00000000 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/GuardianDerivationTest.kt +++ /dev/null @@ -1,267 +0,0 @@ -package mobi.giza.compose.managers - -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.Descriptor -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.Script -import fr.acinq.bitcoin.ScriptTree -import fr.acinq.secp256k1.Hex -import kotlin.test.Test -import mobi.giza.compose.nostr.subgroup.tags.GuardianTag -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertNotEquals -import kotlin.test.assertNull -import kotlin.test.assertTrue - -/** - * The guardian keys, pinned and walked. - * - * The pinned vector freezes the two tags and the order of every input, so a - * change to either fails here rather than moving every leaf a certificate has - * already granted. The rest is the one property everything else rests on: the - * key a descendant derives from its grant and the key an ancestor's cache signs - * as are the same point, at every depth and both parities. - */ -class GuardianDerivationTest { - /** A threshold key nobody needs the secret of: the test is about public derivation. */ - private fun thresholdKey(seed: Int): String = - PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))).publicKey().toString() - - private val rootKey = thresholdKey(0x600d) - private val middleKey = thresholdKey(0xbeef) - private val childKey = thresholdKey(0xcafe) - - private val rootRoom = SharedKeyDerivation.marmotGroupId(rootKey) - private val middleRoom = SharedKeyDerivation.marmotGroupId(middleKey) - private val childRoom = SharedKeyDerivation.marmotGroupId(childKey) - - /** root → middle → child, as the certificates would carry them. */ - private val middleGrant = GuardianDerivation.grant(rootKey, rootRoom, inherited = emptyList(), childChatRoomId = middleRoom) - private val childGrant = GuardianDerivation.grant(middleKey, middleRoom, inherited = middleGrant, childChatRoomId = childRoom) - - @Test - fun `the guardian root and the child index are pinned`() { - // Frozen. A failure here is not a test to update: every certificate - // already signed grants keys under these, and changing them moves every - // leaf in every guarded address. - val root = GuardianDerivation.root(rootKey) - assertEquals(PINNED_ROOT_KEY, root.publicKey.toString()) - assertEquals(PINNED_ROOT_CHAIN_CODE, root.chainCode.toHex()) - assertEquals(PINNED_CHILD_INDEX, GuardianDerivation.childIndex(middleRoom)) - assertEquals( - PINNED_LEAF, - GuardianDerivation.leafKey(childGrant[1], Chain.Mainnet, account = 0, change = 0, index = 7).value.toHex() - ) - } - - @Test - fun `a child index is unhardened and case-blind`() { - val index = GuardianDerivation.childIndex(childRoom) - assertTrue(index in 0L..0x7FFFFFFFL) - assertEquals(index, GuardianDerivation.childIndex(childRoom.uppercase())) - assertFailsWith { GuardianDerivation.childIndex("abcd") } - } - - @Test - fun `a grant is the parent's root and its own grant, each one step further`() { - assertEquals(listOf(rootRoom), middleGrant.map { it.chatRoomId }) - assertEquals(listOf(middleRoom, rootRoom), childGrant.map { it.chatRoomId }) - - val rootOfRoot = GuardianDerivation.root(rootKey).extendedPublicKey - val rootOfMiddle = GuardianDerivation.root(middleKey).extendedPublicKey - val middleIndex = GuardianDerivation.childIndex(middleRoom) - val childIndex = GuardianDerivation.childIndex(childRoom) - - assertEquals(rootOfMiddle.derivePublicKey(childIndex).publicKey, childGrant[0].publicKey) - assertEquals( - rootOfRoot.derivePublicKey(middleIndex).derivePublicKey(childIndex).publicKey, - childGrant[1].publicKey, - "the root's key in the grandchild is R_root / i(M) / i(C)" - ) - assertEquals(GuardianDerivation.DEFAULT_DELAY, childGrant[1].delay) - } - - @Test - fun `an ancestor's cache signs as the leaf its descendant derives, at every depth`() { - val parities = mutableSetOf() - - (1..8).forEach { seed -> - val parent = thresholdKey(seed) - val parentRoom = SharedKeyDerivation.marmotGroupId(parent) - val grandparent = thresholdKey(seed + 100) - val grandparentRoom = SharedKeyDerivation.marmotGroupId(grandparent) - - val parentGrant = GuardianDerivation.grant(grandparent, grandparentRoom, emptyList(), parentRoom) - val grant = GuardianDerivation.grant(parent, parentRoom, parentGrant, childRoom) - - listOf(Chain.Mainnet, Chain.Regtest).forEach { chain -> - (0L..2L).forEach { index -> - listOf(parent to parentRoom, grandparent to grandparentRoom).forEachIndexed { position, (key, room) -> - val lineage = GuardianDerivation.lineage(grant, childRoom, room)!! - val signing = GuardianDerivation.signingCache(key, lineage, chain, account = 0, change = 1, index = index) - val derived = GuardianDerivation.leafKey(grant[position], chain, account = 0, change = 1, index = index) - assertEquals(derived, signing.leafKey) - assertEquals(derived, signing.cache.tweakedPublicKey) - parities += grant[position].extendedPublicKey - .derivePublicKey(listOf(GuardianDerivation.networkIndex(chain), 0L, 1L, index)) - .publicKey.isEven() - } - } - } - } - - assertEquals(setOf(true, false), parities, "the sweep has to cover both parities of a leaf key") - } - - @Test - fun `the lineage runs from the ancestor's child down to the descendant`() { - val a1 = "11".repeat(32) - val a2 = "22".repeat(32) - val a3 = "33".repeat(32) - val c = "cc".repeat(32) - val grant = listOf(a1, a2, a3).map { GuardianDerivation.Guardian(it, middleGrant[0].publicKey, middleGrant[0].chainCode) } - - assertEquals(listOf(c), GuardianDerivation.lineage(grant, c, a1)) - assertEquals(listOf(a2, a1, c), GuardianDerivation.lineage(grant, c, a3)) - assertNull(GuardianDerivation.lineage(grant, c, "44".repeat(32))) - } - - @Test - fun `no two places share a leaf`() { - val siblingRoom = SharedKeyDerivation.marmotGroupId(thresholdKey(0xd00d)) - val sibling = GuardianDerivation.grant(middleKey, middleRoom, middleGrant, siblingRoom) - - fun leaf(guardian: GuardianDerivation.Guardian, chain: Chain = Chain.Mainnet, account: Long = 0) = - GuardianDerivation.leafKey(guardian, chain, account, change = 0, index = 0) - - val leaves = listOf( - leaf(childGrant[0]), - leaf(childGrant[1]), - leaf(sibling[0]), - leaf(sibling[1]), - leaf(middleGrant[0]), - leaf(childGrant[1], Chain.Regtest), - leaf(childGrant[1], account = 1), - ) - assertEquals(leaves.size, leaves.toSet().size, "siblings, a parent and its child, networks and accounts all differ") - - val room = SharedKeyDerivation.derive(rootKey).publicKey - assertTrue(leaves.none { it == room }, "no leaf is a room key") - } - - @Test - fun `a leaf is and_v(v_pk, older 12) and 36 bytes`() { - val key = GuardianDerivation.leafKey(childGrant[0], Chain.Mainnet, 0, 0, 0) - val script = Script.write(GuardianDerivation.leafScript(key, GuardianDerivation.DEFAULT_DELAY)) - - assertEquals(36, script.size) - assertEquals("20" + key.value.toHex() + "ad5cb2", Hex.encode(script)) - // Past sixteen the lock is a number push rather than an opcode. - assertEquals("02e803", Hex.encode(Script.write(GuardianDerivation.leafScript(key, 1000).subList(2, 3)))) - assertFailsWith { GuardianDerivation.leafScript(key, 0) } - } - - /** - * Where a script number changes length, byte for byte. A lock pushed any - * other way is not minimal, and a leaf with a non-minimal push is a coin - * nobody can spend through it. docs/guardian-delay.md. - */ - @Test - fun `a delay is pushed minimally at every edge of its encoding`() { - val key = GuardianDerivation.leafKey(childGrant[0], Chain.Mainnet, 0, 0, 0) - val encodings = mapOf( - 6L to ("56" to 36), - 16L to ("60" to 36), - 17L to ("0111" to 37), - 127L to ("017f" to 37), - 128L to ("028000" to 38), - 32_767L to ("02ff7f" to 38), - 32_768L to ("03008000" to 39), - 65_535L to ("03ffff00" to 39), - ) - encodings.forEach { (delay, expected) -> - val (lock, size) = expected - val script = Script.write(GuardianDerivation.leafScript(key, delay)) - assertEquals("20" + key.value.toHex() + "ad" + lock + "b2", Hex.encode(script), "a delay of $delay") - assertEquals(size, script.size, "a delay of $delay") - } - } - - @Test - fun `a delay outside 6 to 65535 is refused everywhere it could enter`() { - val key = GuardianDerivation.leafKey(childGrant[0], Chain.Mainnet, 0, 0, 0) - listOf(5L, 65_536L).forEach { delay -> - assertFailsWith("leafScript at $delay") { GuardianDerivation.leafScript(key, delay) } - assertFailsWith("grant at $delay") { - GuardianDerivation.grant(middleKey, middleRoom, middleGrant, childRoom, delay = delay) - } - val tag = GuardianTag.assemble(childGrant[0].copy(delay = delay)) - assertNull(GuardianTag.parse(tag), "a tag at $delay reads") - } - assertEquals(childGrant[0].copy(delay = 6), GuardianTag.parse(GuardianTag.assemble(childGrant[0].copy(delay = 6)))) - assertEquals(childGrant[0].copy(delay = 65_535), GuardianTag.parse(GuardianTag.assemble(childGrant[0].copy(delay = 65_535)))) - } - - @Test - fun `a parent chooses its own leaf's delay, and an inherited key keeps the one its ancestor chose`() { - val rootChose = GuardianDerivation.grant(rootKey, rootRoom, emptyList(), middleRoom, delay = 26_280) - val middleChose = GuardianDerivation.grant(middleKey, middleRoom, rootChose, childRoom, delay = 144) - - assertEquals(listOf(144L, 26_280L), middleChose.map { it.delay }) - // Only the delay moved: the keys are the default grant's. - assertEquals(childGrant.map { it.publicKey }, middleChose.map { it.publicKey }) - assertEquals(GuardianDerivation.DEFAULT_DELAY, GuardianDerivation.grant(rootKey, rootRoom, emptyList(), middleRoom).single().delay) - } - - @Test - fun `the longest delay is a descriptor bitcoin-kmp can checksum`() { - val longest = GuardianDerivation.grant(middleKey, middleRoom, middleGrant, childRoom, delay = GuardianDerivation.MAX_DELAY) - val tree = GuardianDerivation.descriptorTree(longest, Chain.Mainnet, account = 0, change = 0) - - assertTrue("older(65535)" in tree, tree) - assertTrue("older(12)" in tree, "the root's inherited leaf keeps its own") - assertEquals(8, Descriptor.checksum("tr(${longest[0].encoded(Chain.Mainnet)}/0/*,$tree)").length) - } - - @Test - fun `the tree is a caterpillar, nearest first`() { - val leaves = (0..2).map { ScriptTree.Leaf(ByteVector(byteArrayOf(it.toByte())), Script.TAPROOT_LEAF_TAPSCRIPT) } - - assertEquals(leaves[0], GuardianDerivation.tree(leaves.take(1))) - assertEquals(ScriptTree.Branch(leaves[0], ScriptTree.Branch(leaves[1], leaves[2])), GuardianDerivation.tree(leaves)) - - // The control block grows by one hash per level: the parent's is the shortest. - val internalKey = GuardianDerivation.leafKey(childGrant[0], Chain.Mainnet, 0, 0, 0) - val tree = GuardianDerivation.tree(leaves) - assertEquals(65, Script.ControlBlock.build(internalKey, tree, leaves[0]).size()) - assertEquals(97, Script.ControlBlock.build(internalKey, tree, leaves[2]).size()) - } - - @Test - fun `the descriptor tree is the same caterpillar, ranged`() { - val tree = GuardianDerivation.descriptorTree(childGrant, Chain.Mainnet, account = 0, change = 0) - val parent = childGrant[0].encoded(Chain.Mainnet) - val root = childGrant[1].encoded(Chain.Mainnet) - - assertEquals("{and_v(v:pk($parent/0/0/0/*),older(12)),and_v(v:pk($root/0/0/0/*),older(12))}", tree) - assertTrue(childGrant[0].encoded(Chain.Signet).startsWith("tpub")) - // A descriptor with this tree in it is one bitcoin-kmp can checksum. - assertEquals(8, Descriptor.checksum("tr(${parent}/0/*,$tree)").length) - assertNotEquals(tree, GuardianDerivation.descriptorTree(childGrant, Chain.Mainnet, account = 0, change = 1)) - } - - /** - * Checked against an independent implementation -- HMAC-SHA512, SHA-256 and - * point arithmetic written out in plain Python -- before they were pinned, so - * they are BIP32 and the doc's formulas rather than this code's own output. - */ - private companion object { - const val PINNED_ROOT_KEY = "02437ef22d50eb95d81d3344b49d4872b23881fbd46f4c658fabfe5f7753db84e9" - const val PINNED_ROOT_CHAIN_CODE = "089593979b6055ff3b34dd2bc378160405108766f34c4804a37cf909a1246530" - const val PINNED_CHILD_INDEX = 977297025L - const val PINNED_LEAF = "ae5078c25c84b630c7ac199cdf86fb3f32b36c677f63415d3405222623359927" - } -} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/GuardianSpendRoundTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/GuardianSpendRoundTest.kt deleted file mode 100644 index 83495e94..00000000 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/GuardianSpendRoundTest.kt +++ /dev/null @@ -1,264 +0,0 @@ -package mobi.giza.compose.managers - -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.ByteVector64 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.Crypto -import fr.acinq.bitcoin.OutPoint -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.PublicKey -import fr.acinq.bitcoin.Satoshi -import fr.acinq.bitcoin.Script -import fr.acinq.bitcoin.ScriptFlags -import fr.acinq.bitcoin.ScriptTree -import fr.acinq.bitcoin.ScriptWitness -import fr.acinq.bitcoin.SigHash -import fr.acinq.bitcoin.Transaction -import fr.acinq.bitcoin.TxId -import fr.acinq.bitcoin.TxIn -import fr.acinq.bitcoin.TxOut -import fr.acinq.bitcoin.crypto.dkg.chill.ChillDKG -import fr.acinq.bitcoin.crypto.dkg.chill.ParticipantFinalizeResult -import fr.acinq.bitcoin.crypto.frost.IndividualNonce -import fr.acinq.bitcoin.crypto.frost.SecretNonce -import fr.acinq.bitcoin.crypto.frost.Session -import fr.acinq.bitcoin.crypto.frost.TweakCache -import fr.acinq.secp256k1.Hex -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFails -import kotlin.test.assertTrue - -/** - * An ancestor group spending a descendant's coin through its guardian leaf, - * against real ChillDKG and real FROST, with no database and no manager. - * - * The counterpart of `GroupWalletSpendRoundTest` for the script path, and judged - * the same way: by `correctlySpends`, the script interpreter, which is the only - * check that asks what the network will -- including whether the coin has sat - * long enough for the leaf's relative lock. - * - * The ceremony is the ancestor's. The descendants' keys are anybody's, since - * nothing here signs as them: what is under test is that the key a descendant - * derives from its certificate's grant is the key the ancestor's shares sign as. - */ -class GuardianSpendRoundTest { - private val participants = 3 - private val threshold = 2 - - /** The ancestor's ceremony, as in `GroupWalletSpendRoundTest`. */ - private val dkg: List = run { - val hostSecretKeys = (1..participants).map { PrivateKey(ByteVector32(ByteArray(32) { i -> (it * 5 + i).toByte() })) } - val hostPublicKeys = hostSecretKeys.map { ChillDKG.hostPublicKey(it) } - val step1 = hostSecretKeys.mapIndexed { i, key -> - ChillDKG.participantStep1(key, hostPublicKeys, threshold, ByteVector32(ByteArray(32) { (i + 3).toByte() })) - } - val coordinator1 = ChillDKG.coordinatorStep1(step1.map { it.message }, hostPublicKeys, threshold) - val step2 = hostSecretKeys.mapIndexed { i, key -> - ChillDKG.participantStep2(key, step1[i].state, coordinator1.message, ByteVector32(ByteArray(32) { (i + 17).toByte() })) - } - val certificate = ChillDKG.coordinatorFinalize(coordinator1.state, step2.map { it.certEqSignature }, threshold).certificate - (0 until participants).map { i -> ChillDKG.participantFinalize(step2[i].state, certificate, participants, threshold) } - .onEach { assertTrue(it.fault.isOk, "the ceremony has to succeed for the rest to mean anything") } - } - - private val ancestorKey: PublicKey = dkg[0].thresholdPublicKey!! - private val publicShares: List = dkg[0].publicShares - private val ancestorRoom = SharedKeyDerivation.marmotGroupId(ancestorKey.toString()) - - private fun someKey(seed: Int): String = - PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))).publicKey().toString() - - private val chain = Chain.Regtest - - /** A guarded address of [childKey]'s wallet, under [grant]: its internal key, its tree, and its script. */ - private class Address(val internalKey: fr.acinq.bitcoin.XonlyPublicKey, val leaves: List, val tree: ScriptTree) { - val pubkeyScript: ByteVector get() = ByteVector(Script.write(Script.pay2tr(internalKey, tree))) - } - - private fun address(childKey: String, grant: List, change: Long = 0, index: Long = 0): Address { - val account = GroupWalletDerivation.account(childKey, chain) - val internalKey = account.extendedPublicKey.derivePublicKey(change).derivePublicKey(index).publicKey.xOnly() - val leaves = GuardianDerivation.leaves(grant, chain, 0, change, index) - return Address(internalKey, leaves, GuardianDerivation.tree(leaves)) - } - - private fun funding(address: Address) = Transaction( - version = 2, - txIn = listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 0x24 })), 0), ByteVector.empty, 0xffffffffL)), - txOut = listOf(TxOut(Satoshi(50_000), address.pubkeyScript)), - lockTime = 0, - ) - - private fun spend(funding: Transaction, sequence: Long = GuardianDerivation.DEFAULT_DELAY) = Transaction( - version = 2, - txIn = listOf(TxIn(OutPoint(funding, 0), ByteVector.empty, sequence)), - txOut = listOf(TxOut(Satoshi(49_000), Script.pay2wpkh(PrivateKey(ByteVector32(ByteArray(32) { 9 })).publicKey()))), - lockTime = 0, - ) - - /** One FROST instance over [message] with [cache], by signers 0 and 2. */ - private fun sign(message: ByteVector32, cache: TweakCache): ByteVector64 { - val signerIds = listOf(0, 2) - val nonces = signerIds.map { id -> - SecretNonce.generate( - sessionRandom = ByteVector32(ByteArray(32) { (id + 40).toByte() }), - secretShare = dkg[id].secretShare!!, - publicShare = publicShares[id], - tweakedThresholdPublicKey = cache.tweakedPublicKey, - message = message, - extraInput = null, - ) - } - val session = Session.create( - aggregatedNonce = IndividualNonce.aggregate(nonces.map { it.second }).right!!, - signerIds = signerIds.map { it.toUInt() }, - signerPublicShares = signerIds.map { publicShares[it] }, - nParticipants = participants, - threshold = threshold, - tweakCache = cache, - message = message, - ) - val partials = signerIds.mapIndexed { position, id -> - session.sign(nonces[position].first, dkg[id].secretShare!!, id.toUInt()).right!!.also { - assertTrue(session.verify(it, nonces[position].second, publicShares[id], position), "signer $id's partial signature") - } - } - return session.aggregateSigs(partials).right!! - } - - /** The ancestor signs [leaf] of [address] in [tx] with [cache], and the witness goes on. */ - private fun guardianSpend(tx: Transaction, funding: Transaction, address: Address, leaf: ScriptTree.Leaf, cache: TweakCache): Transaction { - val sighash = tx.hashForSigningTaprootScriptPath(0, funding.txOut, SigHash.SIGHASH_DEFAULT, leaf.hash()) - val signature = sign(sighash, cache) - return tx.updateWitness(0, Script.witnessScriptPathPay2tr(address.internalKey, leaf, ScriptWitness(listOf(signature)), address.tree)) - } - - private fun assertSpends(tx: Transaction, funding: Transaction) = - tx.correctlySpends(mapOf(OutPoint(funding, 0) to funding.txOut[0]), ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) - - @Test - fun `a parent's quorum spends its child's coin through its leaf`() { - val child = someKey(0xc1) - val childRoom = SharedKeyDerivation.marmotGroupId(child) - val grant = GuardianDerivation.grant(ancestorKey.toString(), ancestorRoom, emptyList(), childRoom) - val address = address(child, grant) - val funding = funding(address) - - val signing = GuardianDerivation.signingCache(ancestorKey.toString(), listOf(childRoom), chain, 0, 0, 0) - val signed = guardianSpend(spend(funding), funding, address, address.leaves[0], signing.cache) - - assertEquals(1, address.leaves.size) - assertEquals(33, signed.txIn[0].witness.stack.last().size(), "a tree of one leaf has a bare control block") - assertSpends(signed, funding) - } - - @Test - fun `a grandparent's quorum spends its grandchild's coin from the bottom of the tree`() { - val middle = someKey(0xb1) - val middleRoom = SharedKeyDerivation.marmotGroupId(middle) - val child = someKey(0xc2) - val childRoom = SharedKeyDerivation.marmotGroupId(child) - - val middleGrant = GuardianDerivation.grant(ancestorKey.toString(), ancestorRoom, emptyList(), middleRoom) - val grant = GuardianDerivation.grant(middle, middleRoom, middleGrant, childRoom) - val address = address(child, grant, change = 1, index = 3) - val funding = funding(address) - - val lineage = GuardianDerivation.lineage(grant, childRoom, ancestorRoom)!! - assertEquals(listOf(middleRoom, childRoom), lineage) - val signing = GuardianDerivation.signingCache(ancestorKey.toString(), lineage, chain, 0, 1, 3) - val signed = guardianSpend(spend(funding), funding, address, address.leaves[1], signing.cache) - - assertEquals(65, signed.txIn[0].witness.stack.last().size(), "the root's leaf is one level down") - assertSpends(signed, funding) - } - - @Test - fun `the coin has to have sat for 12 blocks`() { - val child = someKey(0xc3) - val childRoom = SharedKeyDerivation.marmotGroupId(child) - val grant = GuardianDerivation.grant(ancestorKey.toString(), ancestorRoom, emptyList(), childRoom) - val address = address(child, grant) - val funding = funding(address) - val cache = GuardianDerivation.signingCache(ancestorKey.toString(), listOf(childRoom), chain, 0, 0, 0).cache - - assertSpends(guardianSpend(spend(funding, sequence = 12), funding, address, address.leaves[0], cache), funding) - assertFails("eleven blocks") { - assertSpends(guardianSpend(spend(funding, sequence = 11), funding, address, address.leaves[0], cache), funding) - } - assertFails("no relative lock at all") { - assertSpends(guardianSpend(spend(funding, sequence = 0xfffffffdL), funding, address, address.leaves[0], cache), funding) - } - } - - /** - * A chosen delay, at every edge of its encoding: the script interpreter takes - * the spend at exactly that many blocks and not one fewer. Where an encoding - * mistake would be caught before a coin could be lost to it. - * docs/guardian-delay.md, Phase 2. - */ - @Test - fun `a chosen delay holds at exactly its own number of blocks`() { - val child = someKey(0xc6) - val childRoom = SharedKeyDerivation.marmotGroupId(child) - val cache = GuardianDerivation.signingCache(ancestorKey.toString(), listOf(childRoom), chain, 0, 0, 0).cache - - listOf(6L, 16L, 17L, 127L, 128L, 32_767L, 32_768L, 65_535L).forEach { delay -> - val grant = GuardianDerivation.grant(ancestorKey.toString(), ancestorRoom, emptyList(), childRoom, delay = delay) - val address = address(child, grant) - val funding = funding(address) - - assertSpends(guardianSpend(spend(funding, sequence = delay), funding, address, address.leaves[0], cache), funding) - assertFails("one block short of $delay") { - assertSpends(guardianSpend(spend(funding, sequence = delay - 1), funding, address, address.leaves[0], cache), funding) - } - } - } - - @Test - fun `the wrong cache signs for a key the leaf does not name`() { - val child = someKey(0xc4) - val childRoom = SharedKeyDerivation.marmotGroupId(child) - val sibling = SharedKeyDerivation.marmotGroupId(someKey(0xc5)) - val grant = GuardianDerivation.grant(ancestorKey.toString(), ancestorRoom, emptyList(), childRoom) - val address = address(child, grant) - val funding = funding(address) - - val wrongCaches = mapOf( - "the room key's" to SharedKeyDerivation.derive(ancestorKey.toString()).cache, - "the guardian root's" to GuardianDerivation.root(ancestorKey.toString()).cache, - "a sibling's leaf" to GuardianDerivation.signingCache(ancestorKey.toString(), listOf(sibling), chain, 0, 0, 0).cache, - "the next address's leaf" to GuardianDerivation.signingCache(ancestorKey.toString(), listOf(childRoom), chain, 0, 0, 1).cache, - "the wallet's own key" to GroupWalletDerivation.account(ancestorKey.toString(), chain).cache, - ) - - wrongCaches.forEach { (name, cache) -> - assertFails("$name cache") { - assertSpends(guardianSpend(spend(funding), funding, address, address.leaves[0], cache), funding) - } - } - } - - @Test - fun `a guardian signature is over the leaf it names`() { - // Sign the parent's leaf and present it as the grandparent's: the leaf hash - // is in the sighash, so a signature cannot be moved between leaves. - val middle = someKey(0xb2) - val middleRoom = SharedKeyDerivation.marmotGroupId(middle) - val child = someKey(0xc6) - val childRoom = SharedKeyDerivation.marmotGroupId(child) - val grant = GuardianDerivation.grant(middle, middleRoom, GuardianDerivation.grant(ancestorKey.toString(), ancestorRoom, emptyList(), middleRoom), childRoom) - val address = address(child, grant) - val funding = funding(address) - val tx = spend(funding) - val cache = GuardianDerivation.signingCache(ancestorKey.toString(), listOf(middleRoom, childRoom), chain, 0, 0, 0).cache - - val overParentLeaf = sign(tx.hashForSigningTaprootScriptPath(0, funding.txOut, SigHash.SIGHASH_DEFAULT, address.leaves[0].hash()), cache) - val moved = tx.updateWitness(0, Script.witnessScriptPathPay2tr(address.internalKey, address.leaves[1], ScriptWitness(listOf(overParentLeaf)), address.tree)) - - assertTrue(!Crypto.verifySignatureSchnorr(tx.hashForSigningTaprootScriptPath(0, funding.txOut, SigHash.SIGHASH_DEFAULT, address.leaves[1].hash()), overParentLeaf, GuardianDerivation.leafKey(grant[1], chain, 0, 0, 0))) - assertFails { assertSpends(moved, funding) } - } -} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/RetiredKindsTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/RetiredKindsTest.kt index abd9a62c..79be143b 100644 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/RetiredKindsTest.kt +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/RetiredKindsTest.kt @@ -18,7 +18,7 @@ import kotlin.test.assertTrue class RetiredKindsTest { private val live: Map> = mapOf( "the key ceremony" to DkgRitualEvents.ALL, - // Less the transaction proposal, which FROST still routes so that it can decline it. + // Less the transaction proposal, which FROST routes only so that it can decline it out loud. "event signing" to FrostSigningEvents.ALL - RetiredKinds.TRANSACTION_PROPOSAL, "the chronicle" to setOf(ChronicleEvent.KIND, ChronicleRequestEvent.KIND), "a key state" to setOf(GroupKeyStateEvent.KIND), diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/chronicle/ChronicleEventTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/chronicle/ChronicleEventTest.kt index f40aa650..3079018f 100644 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/chronicle/ChronicleEventTest.kt +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/chronicle/ChronicleEventTest.kt @@ -14,7 +14,7 @@ import mobi.giza.compose.nostr.chronicle.tags.ChronicleRecipientTag import mobi.giza.compose.nostr.frost.FrostSigningEvents import mobi.giza.compose.nostr.frost.GroupKeyStateEvent import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent +import mobi.giza.compose.nostr.RetiredKinds import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent import com.vitorpamplona.quartz.nip65RelayList.AdvertisedRelayListEvent @@ -185,10 +185,10 @@ class ChronicleEventTest { assertEquals(3, TEST_KINDS.all.size) assertFalse(TEST_KINDS.isEmpty()) - // Group-signed, with an arm in applyInnerEvent, and still refused: being - // signed is not what earns a kind its place, being on the list is. - assertFalse(TEST_KINDS.isChroniclable(GroupWalletStatementEvent.KIND)) - assertNull(TEST_KINDS.applyRank(GroupWalletStatementEvent.KIND)) + // A Bennu group wallet's statement, which a group signs, and still refused: + // being signed is not what earns a kind its place, being on the list is. + assertFalse(TEST_KINDS.isChroniclable(RetiredKinds.WALLET.first)) + assertNull(TEST_KINDS.applyRank(RetiredKinds.WALLET.first)) // And the empty list admits nothing at all. assertTrue(ChronicleKinds.NONE.isEmpty()) diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/subgroup/SubgroupBirthCertificateEventTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/subgroup/SubgroupBirthCertificateEventTest.kt index fd080e60..f22ccb7e 100644 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/subgroup/SubgroupBirthCertificateEventTest.kt +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/subgroup/SubgroupBirthCertificateEventTest.kt @@ -4,23 +4,20 @@ import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.crypto.frost.IndividualNonce +import fr.acinq.bitcoin.crypto.frost.SecretNonce +import fr.acinq.bitcoin.crypto.frost.Session import fr.acinq.bitcoin.ByteVector32 import fr.acinq.bitcoin.PrivateKey import fr.acinq.bitcoin.crypto.frost.Frost -import fr.acinq.bitcoin.crypto.frost.IndividualNonce import fr.acinq.bitcoin.crypto.frost.KeyMaterial -import fr.acinq.bitcoin.crypto.frost.SecretNonce -import fr.acinq.bitcoin.crypto.frost.Session import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue import mobi.giza.compose.extensions.toHex -import mobi.giza.compose.managers.GuardianDerivation import mobi.giza.compose.managers.SharedKeyDerivation -import mobi.giza.compose.nostr.subgroup.tags.GuardianTag -import mobi.giza.compose.nostr.subgroup.tags.WalletPolicyTag /** * What a birth certificate is allowed to convince a member of. @@ -344,19 +341,32 @@ class SubgroupBirthCertificateEventTest { } /** - * A certificate as the app produces one: the caller's fields under the - * parent room's key, with the id hashed over them and the group's own - * signature on it. - * - * [author] decides whose room the event claims to be from and [signer] whose - * quorum actually signs, so the two can be pulled apart -- which is the only - * way to test that both are checked. [signature] replaces the real one - * outright, for the cases where what arrives is not a signature at all. + * A Bennu parent's certificate can carry guardian keys and a wallet policy, which + * Giza neither writes nor reads. They are not part of what a certificate + * certifies, so one carrying them -- even ones that make no sense -- is still + * the parent's word that the child is its child. docs/giza-wallet-removal.md. */ @Test - fun `guardian keys ride on a certificate without touching what it certifies`() { - val parentKey = parentMaterial.thresholdPublicKey.value.toHex() - val guardians = GuardianDerivation.grant(parentKey, parentChatRoomId, emptyList(), subgroupChatRoomId) + fun `a certificate carrying wallet tags still certifies`() { + val plain = SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = subgroupChatRoomId, + parentChatRoomId = parentChatRoomId, + thresholdPublicKey = childKey, + adminPublicKeys = admins, + name = name, + path = path, + ) + listOf( + arrayOf(arrayOf("wallet", "guarded"), arrayOf("guardian", "02".padEnd(66, '0'), "12")), + arrayOf(arrayOf("wallet", "unguarded")), + arrayOf(arrayOf("wallet", "maybe")), + ).forEach { extra -> + assertTrue(SubgroupBirthCertificateEvent.certifies(certificate(tags = plain + extra), subgroupChatRoomId, parentChatRoomId)) + } + } + + @Test + fun `a certificate is proposed with no wallet tags`() { val tags = SubgroupBirthCertificateEvent.assembleTags( subgroupChatRoomId = subgroupChatRoomId, parentChatRoomId = parentChatRoomId, @@ -364,87 +374,10 @@ class SubgroupBirthCertificateEventTest { adminPublicKeys = admins, name = name, path = path, - guardians = guardians, ) - - assertTrue(SubgroupBirthCertificateEvent.certifies(certificate(tags = tags), subgroupChatRoomId, parentChatRoomId)) - assertEquals(guardians, SubgroupBirthCertificateEvent.parseGuardians(tags)) - assertEquals(emptyList(), SubgroupBirthCertificateEvent.parseGuardians(certificate().tags)) - - // One unreadable entry makes the list unreadable, rather than shorter. - val broken = tags.map { if (it[0] == GuardianTag.TAG_NAME) it.copyOf().also { tag -> tag[2] = "04" + tag[2].drop(2) } else it } - assertNull(SubgroupBirthCertificateEvent.parseGuardians(broken.toTypedArray())) + assertTrue(tags.none { it[0] == "wallet" || it[0] == "guardian" }) } - @Test - fun `a guarded certificate carries its keys and reads as guarded`() { - val tags = policyTags(SubgroupWalletPolicy.GUARDED, guardians = grant()) - - assertEquals(WalletPolicyReading.Decided(SubgroupWalletPolicy.GUARDED), SubgroupBirthCertificateEvent.parseWalletPolicy(tags)) - assertEquals(grant(), SubgroupBirthCertificateEvent.parseGuardians(tags)) - } - - @Test - fun `an unguarded certificate carries no keys and reads as unguarded`() { - val tags = policyTags(SubgroupWalletPolicy.UNGUARDED, guardians = emptyList()) - - assertEquals(WalletPolicyReading.Decided(SubgroupWalletPolicy.UNGUARDED), SubgroupBirthCertificateEvent.parseWalletPolicy(tags)) - assertEquals(emptyList(), SubgroupBirthCertificateEvent.parseGuardians(tags)) - } - - @Test - fun `a certificate from before policies reads as undecided, with keys or without`() { - assertEquals(WalletPolicyReading.Undecided, SubgroupBirthCertificateEvent.parseWalletPolicy(certificate().tags)) - assertEquals(WalletPolicyReading.Undecided, SubgroupBirthCertificateEvent.parseWalletPolicy(policyTags(null, guardians = grant()))) - } - - @Test - fun `a policy that contradicts its keys, or does not read, reads as nothing`() { - // Each of these must not fall back to undecided: that would hand the - // child the choice its parent took away. - val contradictions = mapOf( - "guarded with no keys" to policyTags(SubgroupWalletPolicy.GUARDED, guardians = emptyList()), - "unguarded with keys" to policyTags(SubgroupWalletPolicy.UNGUARDED, guardians = grant()), - "two policies" to policyTags(SubgroupWalletPolicy.UNGUARDED, guardians = emptyList()) + WalletPolicyTag.assemble(SubgroupWalletPolicy.UNGUARDED), - "an unknown policy" to policyTags(null, guardians = emptyList()) + arrayOf(WalletPolicyTag.TAG_NAME, "maybe"), - "an empty policy" to policyTags(null, guardians = emptyList()) + arrayOf(WalletPolicyTag.TAG_NAME), - ) - - contradictions.forEach { (what, tags) -> - assertNull(SubgroupBirthCertificateEvent.parseWalletPolicy(tags), "a certificate with $what was read") - } - } - - @Test - fun `a policy does not touch what a certificate certifies`() { - // Lineage stays six questions. A certificate whose policy reads as nothing - // is still the parent's word that the child is its child. - listOf( - policyTags(SubgroupWalletPolicy.GUARDED, guardians = grant()), - policyTags(SubgroupWalletPolicy.UNGUARDED, guardians = emptyList()), - policyTags(SubgroupWalletPolicy.GUARDED, guardians = emptyList()), - ).forEach { tags -> - assertTrue(SubgroupBirthCertificateEvent.certifies(certificate(tags = tags), subgroupChatRoomId, parentChatRoomId)) - } - } - - private fun grant(): List = - GuardianDerivation.grant(parentMaterial.thresholdPublicKey.value.toHex(), parentChatRoomId, emptyList(), subgroupChatRoomId) - - private fun policyTags( - policy: SubgroupWalletPolicy?, - guardians: List, - ): Array> = SubgroupBirthCertificateEvent.assembleTags( - subgroupChatRoomId = subgroupChatRoomId, - parentChatRoomId = parentChatRoomId, - thresholdPublicKey = childKey, - adminPublicKeys = admins, - name = name, - path = path, - guardians = guardians, - walletPolicy = policy, - ) - private fun certificate( content: String = subgroupChatRoomId, tags: Array> = SubgroupBirthCertificateEvent.assembleTags( diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/wallet/GroupWalletStatementEventTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/wallet/GroupWalletStatementEventTest.kt deleted file mode 100644 index 12789fa9..00000000 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/wallet/GroupWalletStatementEventTest.kt +++ /dev/null @@ -1,275 +0,0 @@ -package mobi.giza.compose.nostr.wallet - -import mobi.giza.compose.nostr.subgroup.WalletPolicyReading -import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy -import mobi.giza.compose.database.model.GroupSignedEvent -import mobi.giza.compose.managers.GroupWalletDerivation -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.GuardianTag -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 -import kotlin.test.assertTrue - -/** - * A wallet statement, read and believed. - * - * The statement is a record that the group agreed, not a source of keys, so most - * of what is here is refusals: a statement is only a wallet when the room signed - * it *and* the room's threshold key rederives every value it carries. - */ -class GroupWalletStatementEventTest { - private fun key(seed: Int): String = - PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))).publicKey().toString() - - private val thresholdKey = key(0x1c0ffee) - private val otherThresholdKey = key(0xdecaf) - - /** - * The room, as a key whose secret the test holds -- `GroupSignedEvent.verifies` - * asks only that the room's id signed it, and a real FROST signature over the - * same id is `GroupWalletSpendRoundTest`'s business. - */ - private val roomKey = PrivateKey(ByteVector32(Hex.decode("07".repeat(32)))) - private val roomId = roomKey.publicKey().xOnly().value.toString() - - private fun signed(tags: Array>, content: String, createdAt: Long = 1_700_000_000, by: PrivateKey = roomKey): GroupSignedEvent { - val pubKey = by.publicKey().xOnly().value.toString() - val id = EventHasher.hashId(pubKey, createdAt, GroupWalletStatementEvent.KIND, tags, content) - val sig = Crypto.signSchnorr(ByteVector32(id), by, null).toString() - return GroupSignedEvent.fromEvent( - Event(id, pubKey, createdAt, GroupWalletStatementEvent.KIND, tags, content, sig), - chatRoomId = roomId, - ) - } - - private fun statement(account: GroupWalletDerivation.Account, createdAt: Long = 1_700_000_000): GroupSignedEvent { - val template = GroupWalletStatementEvent.template(account, createdAt = createdAt) - return signed(template.tags, template.content, createdAt) - } - - private val mainnet = GroupWalletDerivation.account(thresholdKey, Chain.Mainnet) - - @Test - fun `a statement reads back as what was written`() { - val template = GroupWalletStatementEvent.template(mainnet) - val reading = assertNotNull(GroupWalletStatementEvent.read(template.tags, template.content)) - - assertEquals(Chain.Mainnet, reading.chain) - assertEquals(0L, reading.account) - assertEquals(mainnet.xpub, reading.xpub) - assertEquals(mainnet.receiveDescriptor, reading.receiveDescriptor) - assertEquals(mainnet.changeDescriptor, reading.changeDescriptor) - assertEquals(mainnet, reading.verifiedAgainst(thresholdKey)) - } - - @Test - fun `the room's statement opens the room's wallet`() { - val wallet = assertNotNull(GroupWallet.of(statement(mainnet), thresholdKey)) - - assertEquals(mainnet, wallet.account) - assertEquals(Chain.Mainnet, wallet.chain) - } - - @Test - fun `a statement another key rederives is not this room's wallet`() { - // Signed by the room, every field well formed -- and naming the xpub of a - // different group. Whoever signed it, it is not a wallet this room's key holds. - val foreign = GroupWalletDerivation.account(otherThresholdKey, Chain.Mainnet) - - assertNull(GroupWallet.of(statement(foreign), thresholdKey)) - } - - @Test - fun `an xpub edited after the fact is refused`() { - val template = GroupWalletStatementEvent.template(mainnet) - val other = GroupWalletDerivation.account(thresholdKey, Chain.Mainnet, account = 1) - - assertNull(GroupWallet.of(signed(template.tags, other.xpub), thresholdKey)) - } - - @Test - fun `a statement the room did not sign is a member's, not the group's`() { - val template = GroupWalletStatementEvent.template(mainnet) - val member = PrivateKey(ByteVector32(Hex.decode("09".repeat(32)))) - - assertNull(GroupWallet.of(signed(template.tags, template.content, by = member), thresholdKey)) - } - - @Test - fun `a d tag that disagrees with the fields is not read`() { - val template = GroupWalletStatementEvent.template(mainnet) - val tags = template.tags.map { if (it[0] == "d") arrayOf("d", "regtest:0") else it }.toTypedArray() - - assertNull(GroupWalletStatementEvent.read(tags, template.content)) - } - - @Test - fun `the newest statement for the asked network wins, and another network's is not it`() { - val regtest = GroupWalletDerivation.account(thresholdKey, Chain.Regtest) - val older = statement(mainnet, createdAt = 1_700_000_000) - val newer = statement(mainnet, createdAt = 1_700_000_100) - - val wallet = assertNotNull( - GroupWallet.newestAmong(listOf(newer, statement(regtest), older), thresholdKey, Chain.Mainnet) - ) - assertEquals(newer.id, wallet.signedEvent.id) - assertNull(GroupWallet.newestAmong(listOf(older, newer), thresholdKey, Chain.Signet)) - } - - // ---- A guarded statement --------------------------------------------- - - /** - * The parent, as a key whose secret the test holds: `certifies` asks only - * that the room the certificate names as parent signed it. - */ - private val parentKey = PrivateKey(ByteVector32(Hex.decode("0b".repeat(32)))) - private val parentRoomId = parentKey.publicKey().xOnly().value.toString() - private val childRoomId = SharedKeyDerivation.marmotGroupId(thresholdKey) - private val grant = GuardianDerivation.grant(key(0x9a4e47), parentRoomId, emptyList(), childRoomId) - - private fun certificate(guardians: List = grant, childKey: String = thresholdKey): Event { - val tags = SubgroupBirthCertificateEvent.assembleTags( - subgroupChatRoomId = SharedKeyDerivation.marmotGroupId(childKey), - parentChatRoomId = parentRoomId, - thresholdPublicKey = childKey, - adminPublicKeys = listOf("a".repeat(64)), - name = "Translation team", - guardians = guardians, - ) - val content = SharedKeyDerivation.marmotGroupId(childKey) - val id = EventHasher.hashId(parentRoomId, 1_700_000_000, SubgroupBirthCertificateEvent.KIND, tags, content) - val sig = Crypto.signSchnorr(ByteVector32(id), parentKey, null).toString() - return Event(id, parentRoomId, 1_700_000_000, SubgroupBirthCertificateEvent.KIND, tags, content, sig) - } - - private val guarded = GroupWalletDerivation.account(thresholdKey, Chain.Mainnet, guardians = grant) - - private fun guardedStatement( - account: GroupWalletDerivation.Account = guarded, - certificate: Event = certificate(), - createdAt: Long = 1_700_000_000, - ): GroupSignedEvent { - val template = GroupWalletStatementEvent.template(account, certificate, createdAt) - return signed(template.tags, template.content, createdAt) - } - - @Test - fun `a guarded statement reads back as the guarded account, tree and all`() { - val wallet = assertNotNull(GroupWallet.of(guardedStatement(), thresholdKey)) - - assertEquals(guarded, wallet.account) - assertEquals(grant, wallet.account.guardians) - assertTrue(wallet.account.receiveDescriptor.contains("and_v(v:pk("), wallet.account.receiveDescriptor) - // Same internal key as the plain account, different address: only the tree differs. - val plainAddress = GroupWalletDerivation.derive(mainnet, 0, 0) - val guardedAddress = GroupWalletDerivation.derive(guarded, 0, 0) - assertEquals(plainAddress.internalKey, guardedAddress.internalKey) - assertTrue(plainAddress.address(Chain.Mainnet) != guardedAddress.address(Chain.Mainnet)) - assertTrue(guardedAddress.address(Chain.Mainnet).startsWith("bc1p")) - assertEquals(guardedAddress.outputKey, guardedAddress.cache.tweakedPublicKey, "the cache signs the key path of the guarded address") - } - - @Test - fun `guardians the certificate does not grant open nothing`() { - val stranger = GuardianDerivation.grant(key(0x5), parentRoomId, emptyList(), childRoomId) - val wrongGuardians = GroupWalletDerivation.account(thresholdKey, Chain.Mainnet, guardians = stranger) - - assertNull(GroupWallet.of(guardedStatement(account = wrongGuardians), thresholdKey), "guardians the parent never granted") - assertNull(GroupWallet.of(guardedStatement(certificate = certificate(childKey = otherThresholdKey)), thresholdKey), "a certificate for another child") - } - - @Test - fun `a guarded statement with its guardians stripped is no wallet at all`() { - // What a client that predates guardians sees: descriptors with a tree it - // does not build. It refuses rather than hand out plain addresses under - // the guarded account's name. - val template = GroupWalletStatementEvent.template(guarded, certificate()) - val stripped = template.tags.filterNot { it[0] == GuardianTag.TAG_NAME }.toTypedArray() - - assertNull(GroupWallet.of(signed(stripped, template.content), thresholdKey)) - } - - @Test - fun `an account opened guarded stays guarded, under its first guardians`() { - val firstGuarded = guardedStatement(createdAt = 1_700_000_000) - val laterPlain = statement(mainnet, createdAt = 1_700_000_200) - val laterOtherGuardians = run { - // The parent re-certified with other keys; a later statement adopting - // them would move every address, so it is ignored. - val other = GuardianDerivation.grant(key(0x77), parentRoomId, emptyList(), childRoomId) - guardedStatement( - account = GroupWalletDerivation.account(thresholdKey, Chain.Mainnet, guardians = other), - certificate = certificate(other), - createdAt = 1_700_000_300, - ) - } - - val wallet = assertNotNull(GroupWallet.newestAmong(listOf(laterPlain, firstGuarded, laterOtherGuardians), thresholdKey, Chain.Mainnet)) - assertEquals(firstGuarded.id, wallet.signedEvent.id) - assertEquals(laterPlain.id, GroupWallet.newestAmong(listOf(laterPlain), thresholdKey, Chain.Mainnet)?.signedEvent?.id) - } - - // ---- the parent's decision: docs/subgroup-wallet-policy.md ------------- - - private val decidedGuarded = WalletPolicyReading.Decided(SubgroupWalletPolicy.GUARDED) - private val decidedUnguarded = WalletPolicyReading.Decided(SubgroupWalletPolicy.UNGUARDED) - - @Test - fun `under a guarded policy a plain statement is no wallet, even alone`() { - // Stronger than rule 1: an older client's plain wallet opens nothing, - // so no device derives its addresses or watches its coins. - val plain = statement(mainnet) - - assertNull(GroupWallet.newestAmong(listOf(plain), thresholdKey, Chain.Mainnet, policy = decidedGuarded)) - - val guarded = guardedStatement(createdAt = 1_700_000_100) - assertEquals( - guarded.id, - GroupWallet.newestAmong(listOf(plain, guarded), thresholdKey, Chain.Mainnet, policy = decidedGuarded)?.signedEvent?.id, - ) - } - - @Test - fun `under an unguarded policy a guarded statement is no wallet`() { - val plain = statement(mainnet, createdAt = 1_700_000_000) - val guarded = guardedStatement(createdAt = 1_700_000_100) - - assertEquals( - plain.id, - GroupWallet.newestAmong(listOf(plain, guarded), thresholdKey, Chain.Mainnet, policy = decidedUnguarded)?.signedEvent?.id, - "rule 1 would have picked the guarded one; the parent ruled it out", - ) - } - - @Test - fun `an undecided room reads exactly as before policies`() { - val plain = statement(mainnet, createdAt = 1_700_000_200) - val guarded = guardedStatement(createdAt = 1_700_000_000) - - listOf(WalletPolicyReading.Undecided, null).forEach { policy -> - assertEquals( - guarded.id, - GroupWallet.newestAmong(listOf(plain, guarded), thresholdKey, Chain.Mainnet, policy = policy)?.signedEvent?.id, - ) - assertEquals(plain.id, GroupWallet.newestAmong(listOf(plain), thresholdKey, Chain.Mainnet, policy = policy)?.signedEvent?.id) - } - } - - @Test - fun `every network name round trips`() { - listOf(Chain.Mainnet, Chain.Testnet3, Chain.Testnet4, Chain.Signet, Chain.Regtest).forEach { - assertEquals(it, GroupWalletStatementEvent.chainNamed(GroupWalletStatementEvent.chainName(it))) - } - } -} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/BlockDurationTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/BlockDurationTest.kt deleted file mode 100644 index cefe857f..00000000 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/BlockDurationTest.kt +++ /dev/null @@ -1,68 +0,0 @@ -package mobi.giza.compose.text - -import mobi.giza.compose.managers.GuardianDerivation -import mobi.giza.compose.text.BlockDuration.Approximate -import mobi.giza.compose.text.BlockDuration.Unit.DAYS -import mobi.giza.compose.text.BlockDuration.Unit.HOURS -import mobi.giza.compose.text.BlockDuration.Unit.MINUTES -import mobi.giza.compose.text.BlockDuration.Unit.MONTHS -import mobi.giza.compose.text.BlockDuration.Unit.YEARS -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertTrue - -/** - * How a guardian's delay is said in time -- `docs/guardian-delay.md`, D5. The - * table is the plan's, row for row, so the words a member reads are the words - * the plan argued for. - */ -class BlockDurationTest { - @Test - fun `every row of the plan's table`() { - val table = mapOf( - 6L to Approximate(1, HOURS), - 12L to Approximate(2, HOURS), - 100L to Approximate(17, HOURS), - 144L to Approximate(1, DAYS), - 216L to Approximate(36, HOURS), - 1_008L to Approximate(7, DAYS), - 4_320L to Approximate(1, MONTHS), - 13_140L to Approximate(3, MONTHS), - 26_280L to Approximate(6, MONTHS), - 52_560L to Approximate(1, YEARS), - 65_535L to Approximate(15, MONTHS), - ) - table.forEach { (blocks, expected) -> assertEquals(expected, BlockDuration.approximate(blocks), "$blocks blocks") } - } - - @Test - fun `exactly one of a unit is a five percent window either side`() { - // A day is 144 blocks: 137 is 95.1% of it and 151 is 104.9%. - assertEquals(Approximate(1, DAYS), BlockDuration.approximate(137)) - assertEquals(Approximate(1, DAYS), BlockDuration.approximate(151)) - assertEquals(Approximate(23, HOURS), BlockDuration.approximate(136)) - assertEquals(Approximate(25, HOURS), BlockDuration.approximate(152)) - } - - @Test - fun `under an hour is minutes`() { - assertEquals(Approximate(10, MINUTES), BlockDuration.approximate(1)) - assertEquals(Approximate(50, MINUTES), BlockDuration.approximate(5)) - } - - @Test - fun `nothing a leaf can carry comes out as zero or past a year`() { - GuardianDerivation.DELAY_RANGE.forEach { blocks -> - val approximate = BlockDuration.approximate(blocks) - assertTrue(approximate.count >= 1, "$blocks blocks came out as $approximate") - assertTrue(approximate.unit != YEARS || approximate.count == 1, "$blocks blocks came out as $approximate") - } - } - - @Test - fun `a block count is grouped in thousands`() { - assertEquals("6", 6L.groupedBlocks()) - assertEquals("1,008", 1_008L.groupedBlocks()) - assertEquals("65,535", 65_535L.groupedBlocks()) - } -} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt index 54c2f9a7..24920847 100644 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedEventTest.kt @@ -2,8 +2,6 @@ package mobi.giza.compose.text import fr.acinq.bitcoin.PrivateKey import fr.acinq.bitcoin.ByteVector32 -import mobi.giza.compose.managers.GuardianDerivation -import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent @@ -32,38 +30,32 @@ class ProposedEventTest { } @Test - fun `a birth certificate says what it decides about the child's wallet, either way`() { + fun `a birth certificate says who and what, and nothing of a wallet`() { val parent = "1".repeat(64) val child = "2".repeat(64) val key = PrivateKey(ByteVector32("01".repeat(32))).publicKey().toHex() - fun certificate(policy: SubgroupWalletPolicy?, guarded: Boolean) = event( - SubgroupBirthCertificateEvent.KIND, - tags = SubgroupBirthCertificateEvent.assembleTags( - subgroupChatRoomId = child, - parentChatRoomId = parent, - thresholdPublicKey = key, - adminPublicKeys = listOf("a".repeat(64)), - name = "#Translation", - guardians = if (guarded) GuardianDerivation.grant(key, parent, emptyList(), child) else emptyList(), - walletPolicy = policy, - ), + val tags = SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = child, + parentChatRoomId = parent, + thresholdPublicKey = key, + adminPublicKeys = listOf("a".repeat(64)), + name = "#Translation", ) + val expected = "#Translation · run by 1 members" + assertEquals(expected, ProposedEvent.summarize(event(SubgroupBirthCertificateEvent.KIND, tags = tags)).detail) + // A Bennu parent's wallet tags change nothing it says: a certificate that + // carries them is declined before it is ever shown. + assertEquals( + expected, + ProposedEvent.summarize(event(SubgroupBirthCertificateEvent.KIND, tags = tags + arrayOf(arrayOf("wallet", "guarded")))).detail, + ) + } - assertEquals( - "#Translation · run by 1 members · this group can spend from its wallet · this group after 12 blocks, about 2 hours · its wallet must be guarded", - ProposedEvent.summarize(certificate(SubgroupWalletPolicy.GUARDED, guarded = true)).detail, - ) - // Not left to an absent line: a signer approving this is taking the - // subgroup's wallet out of every group's reach above it. - assertEquals( - "#Translation · run by 1 members · its wallet will not be guarded", - ProposedEvent.summarize(certificate(SubgroupWalletPolicy.UNGUARDED, guarded = false)).detail, - ) - assertEquals( - "#Translation · run by 1 members · this group can spend from its wallet · this group after 12 blocks, about 2 hours", - ProposedEvent.summarize(certificate(null, guarded = true)).detail, - "an older certificate decides nothing, and says nothing about it", - ) + @Test + fun `a wallet's kind is said as one, not as a number`() { + listOf(30331, 30334, 30337, 30355, 30363).forEach { kind -> + assertEquals(ProposedEvent.WALLET, ProposedEvent.summarize(event(kind, tags = arrayOf()))) + } } @Test diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedSpendTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedSpendTest.kt deleted file mode 100644 index f80d5ce9..00000000 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/text/ProposedSpendTest.kt +++ /dev/null @@ -1,73 +0,0 @@ -package mobi.giza.compose.text - -import mobi.giza.compose.managers.GroupWalletDerivation -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.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.assertIs - -/** - * A spend with change, said the way the room's proposal list and the wallet's - * spend rows say it: the payment, never the payment and the change together. - * The change is the group paying itself, and a line that added it in would - * tell every member the group sent more than it did. - */ -class ProposedSpendTest { - private val account = GroupWalletDerivation.account( - PrivateKey(ByteVector32(Hex.decode("1c0ffee".padStart(64, '0')))).publicKey().toString(), - Chain.Regtest, - ) - private val destination = "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080" - - private val state: GroupWalletState = run { - val receive = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, 0) - val change = GroupWalletDerivation.derive(account, GroupWalletDerivation.CHANGE, 0) - val funding = Transaction( - 2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 1 })), 0), ByteVector.empty, 0xffffffffL)), - listOf(TxOut(Satoshi(100_000), receive.pubkeyScript)), 0, - ) - val meta = WalletState.AddressMeta.Derived(0) - GroupWalletState( - account, - WalletState(mapOf(receive.address(Chain.Regtest) to WalletState.AddressState(meta, true, listOf(WalletState.Utxo(funding.txid, 0, 100, funding, meta))))), - WalletState(mapOf(change.address(Chain.Regtest) to WalletState.AddressState(WalletState.AddressMeta.Derived(0), false, emptyList()))), - tipHeight = 110, - ) - } - - @Test - fun `a spend with change is described by its payment`() { - val built = assertIs( - GroupSpendBuilder.send(state, destination, Satoshi(30_000), 4, emptySet()) - ) - val spend = assertIs(GroupSpend.check(built.psbt, account)).checked - - assertEquals(Satoshi(30_000), spend.amountSent, "what the transcript lines report") - assertEquals( - ProposedEvent.Summary("Spend from the group's wallet", "Send 30,000 sats to $destination"), - ProposedSpend.summarize(spend, Chain.Regtest), - ) - } - - @Test - fun `a send-all is described by everything less the fee`() { - val built = assertIs(GroupSpendBuilder.sendAll(state, destination, 4, emptySet())) - val spend = assertIs(GroupSpend.check(built.psbt, account)).checked - - assertEquals("Send ${(Satoshi(100_000) - spend.fee).grouped()} sats to $destination", ProposedSpend.summarize(spend, Chain.Regtest).detail) - } -} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/wallet/GroupSpendBuilderTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/wallet/GroupSpendBuilderTest.kt deleted file mode 100644 index 5de52534..00000000 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/wallet/GroupSpendBuilderTest.kt +++ /dev/null @@ -1,193 +0,0 @@ -package mobi.giza.compose.wallet - -import mobi.giza.compose.managers.GroupWalletDerivation -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.OutPoint -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.Satoshi -import fr.acinq.bitcoin.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.assertIs -import kotlin.test.assertNull -import kotlin.test.assertTrue - -/** - * The spends a member can build. Every one that is built is also put through - * [GroupSpend.check], because a builder that produced spends the other members - * refuse would be a builder that wastes a quorum every time. - */ -class GroupSpendBuilderTest { - private val account = GroupWalletDerivation.account( - PrivateKey(ByteVector32(Hex.decode("1c0ffee".padStart(64, '0')))).publicKey().toString(), - Chain.Regtest, - ) - private val destination = "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080" - private val feerate = 5L - - private fun coin(index: Int, sats: Long, height: Long = 100): Pair { - val derived = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, index.toLong()) - val tx = Transaction( - 2, - listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { index.toByte() })), 0), ByteVector.empty, 0xffffffffL)), - listOf(TxOut(Satoshi(sats), derived.pubkeyScript)), - 0, - ) - val meta = WalletState.AddressMeta.Derived(index) - return derived.address(Chain.Regtest) to WalletState.AddressState( - meta, alreadyUsed = true, utxos = listOf(WalletState.Utxo(tx.txid, 0, height, tx, meta)), - ) - } - - /** [coins] on the receive branch, and [changeWindow] unused change addresses watched -- none, before Electrum has answered. */ - private fun state(vararg coins: Pair, changeWindow: Int = 1): GroupWalletState { - val change = WalletState((0 until changeWindow).associate { index -> - GroupWalletDerivation.derive(account, GroupWalletDerivation.CHANGE, index.toLong()).address(Chain.Regtest) to - WalletState.AddressState(WalletState.AddressMeta.Derived(index), 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 `send all spends every confirmed coin to one output`() { - val result = GroupSpendBuilder.sendAll(state(coin(0, 60_000), coin(1, 40_000)), destination, feerate, emptySet()) - val spend = checked(result) - - assertEquals(2, spend.inputs.size) - assertEquals(1, spend.outputs.size) - assertEquals(Satoshi(100_000), spend.amountSent + spend.fee) - assertEquals(feerate, spend.feeratePerVbyte, "the fee is exact before signing") - } - - @Test - fun `an unconfirmed coin and a reserved one are left alone`() { - val reservedCoin = coin(2, 30_000) - val reserved = setOf(reservedCoin.second.utxos.single().outPoint) - - val spend = checked( - GroupSpendBuilder.sendAll(state(coin(0, 60_000), coin(1, 40_000, height = 0), reservedCoin), destination, feerate, reserved) - ) - - assertEquals(1, spend.inputs.size) - assertEquals(0L, spend.inputs.single().derivation.index) - } - - @Test - fun `an amount is paid largest coin first, with change the other members will recognise`() { - val result = GroupSpendBuilder.send(state(coin(0, 20_000), coin(1, 60_000)), destination, Satoshi(30_000), feerate, emptySet()) - val built = assertIs(result) - val spend = checked(result) - - assertEquals(listOf(1L), spend.inputs.map { it.derivation.index }, "the 60,000 coin alone covers it") - val change = spend.outputs.single { it.isChange } - assertEquals(GroupWalletDerivation.CHANGE, change.change!!.change) - assertEquals(built.change, change.txOut.amount) - assertEquals(Satoshi(30_000), spend.amountSent) - assertEquals(Satoshi(0), built.absorbed, "with change, the fee is the feerate's and nothing more") - } - - @Test - fun `change goes past the addresses open spends already pay to`() { - val result = GroupSpendBuilder.send( - state(coin(0, 60_000), changeWindow = 3), destination, Satoshi(30_000), feerate, emptySet(), reservedChange = setOf(0L), - ) - val built = assertIs(result) - - assertEquals(1L, checked(result).outputs.single { it.isChange }.change!!.index) - assertEquals(setOf(1L), GroupSpend.claimedChangeIndices(built.psbt, account), "and the spend after it reads index 1 as held") - } - - @Test - fun `with every watched change address held, a spend with change waits`() { - val wallet = state(coin(0, 60_000), changeWindow = 2) - - assertIs( - GroupSpendBuilder.send(wallet, destination, Satoshi(30_000), feerate, emptySet(), reservedChange = setOf(0L, 1L)) - ) - assertIs( - GroupSpendBuilder.sendAll(wallet, destination, feerate, emptySet()), "send-all has no change to place" - ) - } - - @Test - fun `before the change branch has answered, the builder is finding change rather than empty-handed`() { - val wallet = state(coin(0, 60_000), changeWindow = 0) - - assertIs(GroupSpendBuilder.send(wallet, destination, Satoshi(30_000), feerate, emptySet())) - assertIs( - GroupSpendBuilder.send(state(changeWindow = 0), destination, Satoshi(30_000), feerate, emptySet()), - "no coins is no coins, whatever change is doing", - ) - } - - @Test - fun `change that would be dust goes to fees instead`() { - val result = GroupSpendBuilder.send(state(coin(0, 30_800)), destination, Satoshi(30_000), feerate, emptySet()) - val spend = checked(result) - - assertTrue(spend.outputs.none { it.isChange }) - assertEquals(Satoshi(800), spend.fee) - val atTheFeerate = Satoshi(feerate * ((spend.weight + 3) / 4)) - val absorbed = assertIs(result).absorbed - assertTrue(absorbed.sat > 0) - assertEquals(spend.fee, atTheFeerate + absorbed, "what the screen says went to the fee is all that did") - } - - @Test - fun `what cannot be built says why`() { - val wallet = state(coin(0, 10_000)) - - assertIs(GroupSpendBuilder.send(wallet, destination, Satoshi(50_000), feerate, emptySet())) - assertIs(GroupSpendBuilder.sendAll(wallet, "not an address", feerate, emptySet())) - assertIs(GroupSpendBuilder.send(wallet, destination, Satoshi(100), feerate, emptySet())) - assertIs(GroupSpendBuilder.sendAll(state(), destination, feerate, emptySet())) - // A mainnet address on a regtest wallet is not an address it can pay. - assertNull((GroupSpendBuilder.sendAll(wallet, "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4", feerate, emptySet()) as? GroupSpendBuilder.Result.Built)) - } - - @Test - fun `a bump pays more from the change, and the other members accept it`() { - val first = checked(GroupSpendBuilder.send(state(coin(0, 60_000)), destination, Satoshi(30_000), feerate, emptySet())) - - val bumped = checked(GroupSpendBuilder.bump(first, feerate * 2)) - - assertEquals(first.tx.txIn.map { it.outPoint }, bumped.tx.txIn.map { it.outPoint }, "the same coins") - assertEquals(first.amountSent, bumped.amountSent, "the payment is untouched") - assertEquals(feerate * 2, bumped.feeratePerVbyte) - assertEquals(first.fee + first.outputs.single { it.isChange }.txOut.amount, - bumped.fee + bumped.outputs.single { it.isChange }.txOut.amount, "the extra came out of the change") - } - - @Test - fun `a send-all bump comes out of the one payment, and a bump has to be higher`() { - val first = checked(GroupSpendBuilder.sendAll(state(coin(0, 60_000)), destination, feerate, emptySet())) - - val bumped = checked(GroupSpendBuilder.bump(first, feerate * 3)) - assertEquals(Satoshi(60_000), bumped.amountSent + bumped.fee) - - assertIs(GroupSpendBuilder.bump(first, feerate)) - } - - @Test - fun `the mainnet cap refuses a spend over it, and test networks have none`() { - val built = GroupSpendBuilder.sendAll(state(coin(0, 300_000)), destination, feerate, emptySet()) - - assertIs(GroupSpendBuilder.capped(built, GroupWalletRollout.capFor(Chain.Mainnet))) - assertIs(GroupSpendBuilder.capped(built, GroupWalletRollout.capFor(Chain.Regtest))) - assertIs( - GroupSpendBuilder.capped(GroupSpendBuilder.sendAll(state(coin(0, 50_000)), destination, feerate, emptySet()), GroupWalletRollout.capFor(Chain.Mainnet)) - ) - } -} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/wallet/GroupSpendFingerprintTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/wallet/GroupSpendFingerprintTest.kt deleted file mode 100644 index b65182f2..00000000 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/wallet/GroupSpendFingerprintTest.kt +++ /dev/null @@ -1,61 +0,0 @@ -package mobi.giza.compose.wallet - -import mobi.giza.compose.managers.GroupWalletDerivation -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.OutPoint -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.Satoshi -import fr.acinq.bitcoin.Script -import fr.acinq.bitcoin.Transaction -import fr.acinq.bitcoin.TxId -import fr.acinq.bitcoin.TxIn -import fr.acinq.bitcoin.TxOut -import fr.acinq.secp256k1.Hex -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertIs -import kotlin.test.assertTrue - -/** - * A spend checked the way every member but the proposer checks it: after the - * PSBT has been through the wire. - * - * Half of all accounts have a fingerprint with its top bit set, and bitcoin-kmp - * reads a taproot derivation's fingerprint back from a serialised PSBT as a - * signed int. Compared as written, every such wallet's spends were refused by - * every member who did not build them. - */ -class GroupSpendFingerprintTest { - /** The first account, counting up from a fixed seed, whose fingerprint has its top bit set. */ - private val account: GroupWalletDerivation.Account = generateSequence(1) { it + 1 } - .map { seed -> - val key = PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))).publicKey().toString() - GroupWalletDerivation.account(key, Chain.Regtest) - } - .first { it.fingerprint >= 0x80000000L } - - @Test - fun `a spend from a wallet with a high fingerprint checks out after the wire`() { - val coin = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, 0) - val change = GroupWalletDerivation.derive(account, GroupWalletDerivation.CHANGE, 0) - val funding = Transaction( - 2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 0x51 })), 0), ByteVector.empty, 0xffffffffL)), - listOf(TxOut(Satoshi(50_000), coin.pubkeyScript)), 0, - ) - val elsewhere = ByteVector(Script.write(Script.pay2wpkh(PrivateKey(ByteVector32(ByteArray(32) { 9 })).publicKey()))) - val tx = Transaction( - 2, listOf(TxIn(OutPoint(funding, 0), ByteVector.empty, GroupSpend.MAX_SEQUENCE)), - listOf(TxOut(Satoshi(30_000), elsewhere), TxOut(Satoshi(19_000), change.pubkeyScript)), 0, - ) - val proposed = GroupSpend.psbtOf(tx, listOf(funding.txOut[0] to coin), mapOf(1 to change), account) - - assertTrue(account.fingerprint >= 0x80000000L) - val received = GroupSpend.decode(GroupSpend.encode(proposed))!! - - val checked = assertIs(GroupSpend.check(received, account)).checked - assertEquals(listOf(false, true), checked.outputs.map { it.isChange }) - assertEquals(setOf(0L), GroupSpend.claimedChangeIndices(received, account)) - } -} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/wallet/GroupSpendFundingTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/wallet/GroupSpendFundingTest.kt deleted file mode 100644 index 197f135d..00000000 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/wallet/GroupSpendFundingTest.kt +++ /dev/null @@ -1,127 +0,0 @@ -package mobi.giza.compose.wallet - -import mobi.giza.compose.managers.GroupWalletDerivation -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.OutPoint -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.Satoshi -import fr.acinq.bitcoin.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.assertIs -import kotlin.test.assertNull -import kotlin.test.assertTrue - -/** - * A spend that funds a descendant's wallet: the payment carries its place under - * the descendant's account, and that claim has to survive the wire and never - * be taken for change. See `docs/guarded-wallet-funding.md`, Phase 2. - */ -class GroupSpendFundingTest { - private fun accountFrom(seed: Int): GroupWalletDerivation.Account = GroupWalletDerivation.account( - PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))).publicKey().toString(), - Chain.Regtest, - ) - - private val account = accountFrom(0x1c0ffee) - - /** The first descendant account, counting up, whose fingerprint has its top bit set: the one the wire reads back signed. */ - private val descendant: GroupWalletDerivation.Account = generateSequence(1) { it + 1 } - .map { accountFrom(it) } - .first { it.fingerprint >= 0x80000000L } - - private val funding = GroupSpendBuilder.Destination.Funding( - descendant, GroupWalletDerivation.derive(descendant, GroupWalletDerivation.RECEIVE, 7), - ) - private val typed = "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080" - private val feerate = 5L - - 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.toByte() })), 0), ByteVector.empty, 0xffffffffL)), - listOf(TxOut(Satoshi(sats), derived.pubkeyScript)), - 0, - ) - val meta = WalletState.AddressMeta.Derived(index) - return derived.address(Chain.Regtest) 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.Regtest) to - WalletState.AddressState(WalletState.AddressMeta.Derived(0), false, emptyList()) - )) - return GroupWalletState(account, WalletState(coins.toMap()), change, tipHeight = 110) - } - - @Test - fun `a funding's claim survives the wire for a high fingerprint`() { - val built = assertIs( - GroupSpendBuilder.send(state(coin(0, 60_000)), funding, Satoshi(30_000), feerate, emptySet()) - ) - assertEquals(funding, built.funded) - assertEquals(funding.derived.pubkeyScript, built.psbt.global.tx.txOut[0].publicKeyScript) - - assertTrue(descendant.fingerprint >= 0x80000000L) - val received = GroupSpend.decode(GroupSpend.encode(built.psbt))!! - assertEquals(setOf(7L), GroupSpend.claimedFundingIndices(received, descendant)) - assertEquals(setOf(0L), GroupSpend.claimedChangeIndices(received, account), "the change is still the room's own") - assertEquals(emptySet(), GroupSpend.claimedFundingIndices(received, account), "the room's own account funds nothing") - } - - @Test - fun `a funding is a payment, not change`() { - val built = assertIs( - GroupSpendBuilder.send(state(coin(0, 60_000)), funding, Satoshi(30_000), feerate, emptySet()) - ) - val received = GroupSpend.decode(GroupSpend.encode(built.psbt))!! - - val checked = assertIs(GroupSpend.check(received, account)).checked - assertEquals(listOf(false, true), checked.outputs.map { it.isChange }) - assertEquals(Satoshi(30_000), checked.amountSent) - } - - @Test - fun `sending everything can fund too`() { - val built = assertIs( - GroupSpendBuilder.sendAll(state(coin(0, 60_000), coin(1, 40_000)), funding, feerate, emptySet()) - ) - assertEquals(funding, built.funded) - assertEquals(setOf(7L), GroupSpend.claimedFundingIndices(built.psbt, descendant)) - assertIs(GroupSpend.check(built.psbt, account)) - } - - @Test - fun `a send to a typed address claims nothing about its payment`() { - val built = assertIs( - GroupSpendBuilder.send(state(coin(0, 60_000)), typed, Satoshi(30_000), feerate, emptySet()) - ) - assertNull(built.funded) - assertTrue(built.psbt.outputs[0].taprootDerivationPaths.isEmpty()) - assertEquals(1, built.psbt.outputs[1].taprootDerivationPaths.size, "change is described as it always was") - } - - @Test - fun `a wallet on another network is not one to fund`() { - val elsewhere = GroupWalletDerivation.account( - PrivateKey(ByteVector32(Hex.decode("decaf".padStart(64, '0')))).publicKey().toString(), - Chain.Signet, - ) - val across = GroupSpendBuilder.Destination.Funding(elsewhere, GroupWalletDerivation.derive(elsewhere, GroupWalletDerivation.RECEIVE, 0)) - assertEquals( - GroupSpendBuilder.Result.NotAnAddress, - GroupSpendBuilder.send(state(coin(0, 60_000)), across, Satoshi(30_000), feerate, emptySet()), - ) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/dao/GroupTransactionDaoJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/dao/GroupTransactionDaoJvmTest.kt deleted file mode 100644 index ec57ba02..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/dao/GroupTransactionDaoJvmTest.kt +++ /dev/null @@ -1,152 +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.ChatRoom -import mobi.giza.compose.database.model.FrostSigningItem -import mobi.giza.compose.database.model.FrostSigningSession -import mobi.giza.compose.database.model.GroupTransaction -import mobi.giza.compose.database.model.NostrEvent -import mobi.giza.compose.database.model.Profile -import mobi.giza.compose.database.model.types.FrostSigningSubject -import com.vitorpamplona.quartz.nip01Core.core.toHexKey -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.assertNotNull -import kotlin.test.assertNull -import kotlin.time.Instant - -/** - * A spend from the group's wallet, as the database holds it: a signing session - * whose subject is a transaction, one item per input, and the transaction row - * beside it. - * - * The write-once property is the one worth pinning. The PSBT is what every - * item's sighash was computed from, so a second write at acceptance -- a - * redelivered proposal, or a different one under the same session id -- must - * leave the first in place. - */ -class GroupTransactionDaoJvmTest { - private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) - - @AfterTest - fun closeDb() = db.close() - - private val user = KeyPair().pubKey.toHexKey() - private val room = "11".repeat(32) - - private suspend fun seedRoom() { - val nostrEventId = "c".repeat(64) - db.nostrEventDao().upsert(NostrEvent(id = nostrEventId, pubKey = user, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) - db.profileDao().upsert(Profile(publicKey = user, userName = "user", nostrEventId = nostrEventId)) - db.chatRoomDao().upsert(ChatRoom(id = room, userPublicKey = user, subject = null, description = null, mlsGroupState = null)) - } - - private suspend fun spend(id: String, inputs: Int = 2): FrostSigningSession { - val session = FrostSigningSession( - id = id, - chatRoomId = room, - coordinatorPublicKey = user, - userPublicKey = user, - dkgSessionId = "dkg-1", - threshold = 2, - participantCount = 3, - signerId = 0, - subject = FrostSigningSubject.TRANSACTION, - createdAt = Instant.fromEpochSeconds(1_000), - ) - db.frostSigningSessionDao().upsert(session) - db.frostSigningSessionDao().upsertItems( - (0 until inputs).map { input -> - FrostSigningItem( - sessionId = id, - itemIndex = input, - unsignedEventJson = """{"change":0,"index":$input}""", - eventId = input.toString().repeat(64).take(64), - nonceRandom = "${input + 1}".repeat(64).take(64), - inputIndex = input, - ) - } - ) - return session - } - - private fun transaction(sessionId: String, psbt: String = "cHNidP8=", txid: String = "ab".repeat(32)) = GroupTransaction( - frostSigningSessionId = sessionId, - chatRoomId = room, - chain = "regtest", - account = 0, - psbt = psbt, - txid = txid, - createdAt = Instant.fromEpochSeconds(1_000), - ) - - @Test - fun `a transaction session reads back as one, with an item per input`() = runBlocking { - seedRoom() - spend("spend-1") - - val session = assertNotNull(db.frostSigningSessionDao().getSessionById("spend-1")) - assertEquals(FrostSigningSubject.TRANSACTION, session.subject) - - val items = db.frostSigningSessionDao().getItems("spend-1") - assertEquals(listOf(0, 1), items.map { it.inputIndex }) - assertEquals("""{"change":0,"index":1}""", items[1].payload) - assertEquals(items[1].eventId, items[1].message) - } - - @Test - fun `an event session written without a subject is an event session`() = runBlocking { - seedRoom() - db.frostSigningSessionDao().upsert( - FrostSigningSession( - id = "events-1", chatRoomId = room, coordinatorPublicKey = user, userPublicKey = user, - dkgSessionId = "dkg-1", threshold = 2, participantCount = 3, signerId = 0, - ) - ) - - assertEquals(FrostSigningSubject.EVENTS, db.frostSigningSessionDao().getSessionById("events-1")?.subject) - } - - @Test - fun `the proposed psbt is written once`() = runBlocking { - seedRoom() - spend("spend-1") - - db.groupTransactionDao().insertIfAbsent(transaction("spend-1", psbt = "first")) - db.groupTransactionDao().insertIfAbsent(transaction("spend-1", psbt = "second")) - - assertEquals("first", db.groupTransactionDao().getBySessionId("spend-1")?.psbt) - } - - @Test - fun `later writes fill the row in`() = runBlocking { - seedRoom() - spend("spend-1") - db.groupTransactionDao().insertIfAbsent(transaction("spend-1")) - - val signed = db.groupTransactionDao().getBySessionId("spend-1")!! - .copy(signedTransaction = "02000000", broadcastAt = Instant.fromEpochSeconds(2_000)) - db.groupTransactionDao().upsert(signed) - - assertEquals(signed, db.groupTransactionDao().getBySessionId("spend-1")) - assertEquals(listOf(signed), db.groupTransactionDao().getByChatRoomId(room)) - } - - @Test - fun `a room's transactions go with it`() = runBlocking { - seedRoom() - spend("spend-1") - db.groupTransactionDao().insertIfAbsent(transaction("spend-1")) - - // @Delete matches on the primary key, so the row as it was seeded is enough. - db.chatRoomDao().delete(ChatRoom(id = room, userPublicKey = user, subject = null, description = null, mlsGroupState = null)) - - assertNull(db.groupTransactionDao().getBySessionId("spend-1")) - assertEquals(emptyList(), db.frostSigningSessionDao().getItems("spend-1")) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/model/ProtocolKindDispatchJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/model/ProtocolKindDispatchJvmTest.kt index ff0afa5b..c50d384f 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/model/ProtocolKindDispatchJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/database/model/ProtocolKindDispatchJvmTest.kt @@ -193,4 +193,22 @@ class ProtocolKindDispatchJvmTest { assertTrue(line?.messageType != "unsupported", "kind $kind is a wallet's, not an unknown kind") } } + + /** + * What announces a Bennu wallet -- a group wallet, a member's guarded wallet, a + * Lightning wallet -- is one line saying Giza takes no part. Nothing else of a + * wallet is a line at all. + */ + @Test + fun `a wallet announcement is one line saying Giza takes no part`(): Unit = runBlocking { + RetiredKinds.ANNOUNCEMENTS.forEach { kind -> + val (_, line) = arrive(kind, content = """{"wallet":"w"}""") + assertEquals(ChatMessage.TYPE_WALLET_NOT_TAKEN_PART_IN, line?.messageType, "kind $kind") + assertTrue(line!!.messageType in ChatMessage.GROUP_IDENTITY_TYPES, "a system line, not a bubble") + } + (RetiredKinds.WALLET + RetiredKinds.GROUP_LIGHTNING - RetiredKinds.ANNOUNCEMENTS - RetiredKinds.TRANSACTION_PROPOSAL).forEach { kind -> + val (_, line) = arrive(kind, content = """{"wallet":"w"}""") + assertEquals(null, line, "kind $kind is no line") + } + } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ChronicleAssemblyJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ChronicleAssemblyJvmTest.kt index 13b3f197..42dc01f7 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ChronicleAssemblyJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ChronicleAssemblyJvmTest.kt @@ -35,7 +35,7 @@ import mobi.giza.compose.extensions.toHex import mobi.giza.compose.nostr.chronicle.ChronicleEvent import mobi.giza.compose.nostr.chronicle.TEST_KINDS import mobi.giza.compose.nostr.frost.GroupKeyStateEvent -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent +import mobi.giza.compose.nostr.RetiredKinds /** * Assembling a room's chronicle out of what a device actually holds. @@ -441,7 +441,7 @@ class ChronicleAssemblyJvmTest { fun `a signed kind off the list is left behind`() = runBlocking { seedSignedWork() - record(signed(template(GroupWalletStatementEvent.KIND, 1_700_000_080L, "{}"))) + record(signed(template(RetiredKinds.WALLET.first, 1_700_000_080L, "{}"))) assertEquals(TEST_KINDS.all, chronicledPayloads().map { it.kind }.toSet()) } 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 c16cdb19..174a809c 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupFixtures.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupFixtures.kt @@ -18,7 +18,6 @@ import mobi.giza.compose.database.model.NostrEvent import mobi.giza.compose.database.model.Profile import mobi.giza.compose.extensions.toHex import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent -import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray @@ -65,37 +64,6 @@ internal object GroupFixtures { return Event(id = id, pubKey = pubKey, createdAt = createdAt, kind = kind, tags = tags, content = content, sig = signature(material, id)) } - /** - * [parent]'s certificate for [child], granting [guardians] under [policy] -- - * the grant is the caller's, so a test can hand over a wrong one. - */ - fun birthCertificate( - parent: KeyMaterial, - child: KeyMaterial, - guardians: List, - policy: SubgroupWalletPolicy? = if (guardians.isEmpty()) SubgroupWalletPolicy.UNGUARDED else SubgroupWalletPolicy.GUARDED, - admins: List = listOf("a".repeat(64)), - name: String = "#Child", - ): Event = signedAsRoom( - material = parent, - kind = SubgroupBirthCertificateEvent.KIND, - tags = SubgroupBirthCertificateEvent.assembleTags( - subgroupChatRoomId = roomOf(child), - parentChatRoomId = roomOf(parent), - thresholdPublicKey = thresholdKeyOf(child), - adminPublicKeys = admins, - name = name, - path = path, - guardians = guardians, - walletPolicy = policy, - ), - content = roomOf(child), - ) - - /** [parent]'s guarded certificate for [child], with exactly the grant a parent with no parent makes. */ - fun guardedCertificate(parent: KeyMaterial, child: KeyMaterial): Event = - birthCertificate(parent, child, GuardianDerivation.grant(thresholdKeyOf(parent), roomOf(parent), emptyList(), roomOf(child))) - /** [material]'s verified key state on this device, carrying [certificate] when it is somebody's subgroup. */ suspend fun fileKeyState(db: GizaDatabase, material: KeyMaterial, certificate: Event? = null) { seedRoom(db, roomOf(material)) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/SubgroupCeremonyInParentRoomTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/SubgroupCeremonyInParentRoomTest.kt index 76952591..6532fae2 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/SubgroupCeremonyInParentRoomTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/SubgroupCeremonyInParentRoomTest.kt @@ -1,6 +1,7 @@ package mobi.giza.compose.managers -import mobi.giza.compose.nostr.subgroup.tags.GuardianDelayTag +import mobi.giza.compose.database.model.isGuardedSubgroup + import androidx.room3.Room import com.vitorpamplona.quartz.marmot.mip01Groups.MarmotGroupData import com.vitorpamplona.quartz.marmot.mls.crypto.Ed25519 @@ -36,9 +37,6 @@ import mobi.giza.compose.database.model.types.DkgRitualStage import mobi.giza.compose.extensions.toHex import mobi.giza.compose.nostr.Relays import mobi.giza.compose.nostr.dkg.DkgRitualEvents -import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy -import mobi.giza.compose.nostr.subgroup.tags.WalletPolicyTag -import mobi.giza.compose.database.model.subgroupWalletPolicy /** * A subgroup's key ceremony, held in the room of the group making it. @@ -117,8 +115,6 @@ class SubgroupCeremonyInParentRoomTest { private suspend fun openCeremony( room: LocalChatRoom, - walletPolicy: SubgroupWalletPolicy? = null, - guardianDelay: Long? = null, ) = ChillDkgRitualManager.proposeRitual( database = parent, localChatRoom = room, @@ -128,8 +124,6 @@ class SubgroupCeremonyInParentRoomTest { parentChatRoomId = parentRoomId, participantPublicKeys = admins, subject = "Translation", - walletPolicy = walletPolicy, - guardianDelay = guardianDelay ) private suspend fun innerEvents(database: GizaDatabase) = database.marmotInnerEventDao() @@ -232,194 +226,51 @@ class SubgroupCeremonyInParentRoomTest { } } + /** Giza's ceremony carries no wallet tag at all. docs/giza-wallet-removal.md. */ + @Test + fun `a subgroup's ceremony carries no wallet tag`(): Unit = runBlocking { + openCeremony(parentRoom()) + + innerEvents(parent).forEach { + assertNull(DkgRitualEvents.parseWalletPolicy(it.tags), "kind ${it.kind} carries a wallet tag") + assertTrue(it.tags.none { tag -> tag.firstOrNull() == "guardian_delay" }, "kind ${it.kind} carries a delay") + } + } + /** - * The coordinator's choice of wallet policy reaches every admin before they - * join -- docs/subgroup-wallet-policy.md, Phase 2. It is what the join screen - * shows and what the certificate is later proposed under, so it has to be on - * every admin's session, not only the coordinator's. + * A Bennu coordinator's subgroup ceremony for a guarded wallet. Its certificate + * has to be guarded, which Giza declines to sign, so Giza does not join it: the + * proposal is filed with what it said, the join screen says why, and approving + * publishes nothing (W5). */ @Test - fun `the wallet policy travels on the proposal and lands on every admin's session`(): Unit = runBlocking { + fun `a guarded subgroup's ceremony is filed and not joined`(): Unit = runBlocking { val room = parentRoom() - val session = openCeremony(room, SubgroupWalletPolicy.GUARDED) - assertEquals(SubgroupWalletPolicy.GUARDED, session.subgroupWalletPolicy) - - val proposal = assertNotNull( - innerEvents(parent).firstOrNull { it.kind == DkgRitualEvents.PROPOSAL } - ) - assertEquals( - WalletPolicyTag.Result.Present(SubgroupWalletPolicy.GUARDED), - DkgRitualEvents.parseWalletPolicy(proposal.tags), - ) - innerEvents(parent).filterNot { it.kind == DkgRitualEvents.PROPOSAL }.forEach { - assertEquals(WalletPolicyTag.Result.Absent, DkgRitualEvents.parseWalletPolicy(it.tags), "kind ${it.kind} repeats the policy") - } + val session = openCeremony(room) + val proposal = assertNotNull(innerEvents(parent).firstOrNull { it.kind == DkgRitualEvents.PROPOSAL }).asEvent() + val guarded = Event(proposal.id, proposal.pubKey, proposal.createdAt, proposal.kind, proposal.tags + arrayOf(arrayOf("wallet", "guarded")), proposal.content, proposal.sig) + val theirRoom = receiverRoom() ChillDkgRitualManager.processRitualPayload( database = receiver, - localChatRoom = receiverRoom(), - innerEvent = proposal.asEvent(), - userPublicKey = alice, - nostrPrivateKey = aliceKeys.privKey!! - ) - assertEquals( - SubgroupWalletPolicy.GUARDED, - receiver.dkgSessionDao().getSessionById(session.id)?.subgroupWalletPolicy, - ) - } - - /** docs/guardian-delay.md, Phase 4: the delay travels as the policy does, one field further. */ - @Test - fun `the guardian delay travels on the proposal and lands on every admin's session`(): Unit = runBlocking { - val session = openCeremony(parentRoom(), SubgroupWalletPolicy.GUARDED, guardianDelay = 4_320) - assertEquals(4_320L, session.guardianDelay) - - val proposal = assertNotNull(innerEvents(parent).firstOrNull { it.kind == DkgRitualEvents.PROPOSAL }) - assertEquals(GuardianDelayTag.Result.Present(4_320), DkgRitualEvents.parseGuardianDelay(proposal.tags)) - innerEvents(parent).filterNot { it.kind == DkgRitualEvents.PROPOSAL }.forEach { - assertEquals(GuardianDelayTag.Result.Absent, DkgRitualEvents.parseGuardianDelay(it.tags), "kind ${it.kind} repeats the delay") - } - - ChillDkgRitualManager.processRitualPayload( - database = receiver, - localChatRoom = receiverRoom(), - innerEvent = proposal.asEvent(), - userPublicKey = alice, - nostrPrivateKey = aliceKeys.privKey!! - ) - assertEquals(4_320L, receiver.dkgSessionDao().getSessionById(session.id)?.guardianDelay) - } - - @Test - fun `a guarded proposal with no delay files none`(): Unit = runBlocking { - val session = openCeremony(parentRoom(), SubgroupWalletPolicy.GUARDED) - val proposal = assertNotNull(innerEvents(parent).firstOrNull { it.kind == DkgRitualEvents.PROPOSAL }) - ChillDkgRitualManager.processRitualPayload( - database = receiver, - localChatRoom = receiverRoom(), - innerEvent = proposal.asEvent(), - userPublicKey = alice, - nostrPrivateKey = aliceKeys.privKey!! - ) - val joined = assertNotNull(receiver.dkgSessionDao().getSessionById(session.id)) - assertNull(joined.guardianDelay, "certified later at the default") - } - - @Test - fun `a proposal whose delay is out of range, unreadable, or unguarded is dropped`(): Unit = runBlocking { - val receiving = receiverRoom() - val cases = mapOf( - "five blocks" to (SubgroupWalletPolicy.GUARDED to arrayOf(GuardianDelayTag.TAG_NAME, "5")), - "a word" to (SubgroupWalletPolicy.GUARDED to arrayOf(GuardianDelayTag.TAG_NAME, "twelve")), - "an unguarded subgroup" to (SubgroupWalletPolicy.UNGUARDED to arrayOf(GuardianDelayTag.TAG_NAME, "144")), - ) - cases.entries.forEachIndexed { index, (name, case) -> - val (policy, delayTag) = case - val sessionId = "a${index}".padEnd(64, '0') - val proposal = Event( - id = "b${index}".padEnd(64, '0'), - pubKey = user, - createdAt = 1, - kind = DkgRitualEvents.PROPOSAL, - tags = admins.map { arrayOf("p", it) }.toTypedArray() + - DkgRitualEvents.assembleTags( - sessionId = sessionId, - threshold = quorum, - parentChatRoomId = parentRoomId, - subject = "Translation", - walletPolicy = policy, - ) + arrayOf(delayTag), - content = "", - sig = "" - ) - ChillDkgRitualManager.processRitualPayload( - database = receiver, - localChatRoom = receiving, - innerEvent = proposal, - userPublicKey = alice, - nostrPrivateKey = aliceKeys.privKey!! - ) - assertNull(receiver.dkgSessionDao().getSessionById(sessionId), "a proposal with $name was joined") - } - } - - @Test - fun `only a guarded subgroup's ceremony can carry a delay, and only one in range`(): Unit = runBlocking { - val room = parentRoom() - listOf(SubgroupWalletPolicy.UNGUARDED to 144L, SubgroupWalletPolicy.GUARDED to 5L, SubgroupWalletPolicy.GUARDED to 65_536L) - .forEach { (policy, delay) -> - assertTrue(runCatching { openCeremony(room, policy, guardianDelay = delay) }.isFailure, "$policy at $delay") - } - assertTrue(innerEvents(parent).isEmpty(), "and nothing goes out") - } - - @Test - fun `a subgroup proposal from a build before policies carries none`(): Unit = runBlocking { - val session = openCeremony(parentRoom()) - assertNull(session.walletPolicy) - - val proposal = assertNotNull( - innerEvents(parent).firstOrNull { it.kind == DkgRitualEvents.PROPOSAL } - ) - ChillDkgRitualManager.processRitualPayload( - database = receiver, - localChatRoom = receiverRoom(), - innerEvent = proposal.asEvent(), - userPublicKey = alice, - nostrPrivateKey = aliceKeys.privKey!! - ) - val joined = assertNotNull(receiver.dkgSessionDao().getSessionById(session.id)) - assertNull(joined.walletPolicy, "joined, with nothing to show at the gate") - } - - @Test - fun `a proposal whose wallet policy does not read is dropped`(): Unit = runBlocking { - val proposal = Event( - id = "cc".repeat(32), - pubKey = user, - createdAt = 1, - kind = DkgRitualEvents.PROPOSAL, - tags = admins.map { arrayOf("p", it) }.toTypedArray() + - DkgRitualEvents.assembleTags( - sessionId = "ab".repeat(32), - threshold = quorum, - parentChatRoomId = parentRoomId, - subject = "Translation", - ) + arrayOf(arrayOf(WalletPolicyTag.TAG_NAME, "maybe")), - content = "", - sig = "" - ) - - ChillDkgRitualManager.processRitualPayload( - database = receiver, - localChatRoom = receiverRoom(), - innerEvent = proposal, + localChatRoom = theirRoom, + innerEvent = guarded, userPublicKey = alice, nostrPrivateKey = aliceKeys.privKey!! ) - assertNull( - receiver.dkgSessionDao().getSessionById("ab".repeat(32)), - "an admin is not enrolled in a ceremony whose policy they could not be shown", + val filed = assertNotNull(receiver.dkgSessionDao().getSessionById(session.id)) + assertEquals("guarded", filed.walletPolicy) + assertTrue(filed.isGuardedSubgroup) + + ChillDkgRitualManager.approve( + database = receiver, + localChatRoom = theirRoom, + sessionId = filed.id, + step = DkgApprovalStep.HOST_KEY, + nostrPrivateKey = aliceKeys.privKey!! ) - } - - @Test - fun `only a subgroup's ceremony can carry a wallet policy`(): Unit = runBlocking { - val refused = runCatching { - ChillDkgRitualManager.proposeRitual( - database = parent, - localChatRoom = parentRoom(), - userPublicKey = user, - nostrPrivateKey = coordinator.privKey!!, - threshold = quorum, - participantPublicKeys = admins, - walletPolicy = SubgroupWalletPolicy.UNGUARDED, - ) - } - - assertTrue(refused.isFailure) - assertTrue(innerEvents(parent).isEmpty(), "and nothing goes out") + assertTrue(innerEvents(receiver).isEmpty(), "nothing goes out: Giza does not join it") } /** diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/SubgroupManagerJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/SubgroupManagerJvmTest.kt index f6cd1a01..ccb9cf24 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/SubgroupManagerJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/SubgroupManagerJvmTest.kt @@ -1,7 +1,5 @@ package mobi.giza.compose.managers -import mobi.giza.compose.nostr.subgroup.WalletPolicyReading -import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy import androidx.room3.Room import com.vitorpamplona.quartz.marmot.mip01Groups.MarmotGroupData import com.vitorpamplona.quartz.marmot.mls.crypto.Ed25519 @@ -133,30 +131,6 @@ class SubgroupManagerJvmTest { assertNull(subgroup.keyState) } - @Test - fun `a listed child carries what its parent decided about its wallet`(): Unit = runBlocking { - seedRoom(parentRoomId) - record( - certificate( - tags = SubgroupBirthCertificateEvent.assembleTags( - subgroupChatRoomId = childRoomId, - parentChatRoomId = parentRoomId, - thresholdPublicKey = childMaterial.thresholdPublicKey.value.toHex(), - adminPublicKeys = listOf(user, alice, bob), - name = "Translation team", - path = path, - walletPolicy = SubgroupWalletPolicy.UNGUARDED, - ) - ) - ) - record(certificate(subgroupMaterial = siblingMaterial)) - - val subgroups = SubgroupManager.subgroupsOf(db, parentRoomId).associateBy { it.chatRoomId } - - assertEquals(WalletPolicyReading.Decided(SubgroupWalletPolicy.UNGUARDED), subgroups.getValue(childRoomId).walletPolicy) - assertEquals(WalletPolicyReading.Undecided, subgroups.getValue(siblingRoomId).walletPolicy, "a certificate from before policies") - } - @Test fun `a child whose room this device holds reports it`(): Unit = runBlocking { seedRoom(parentRoomId) @@ -523,19 +497,14 @@ class SubgroupManagerJvmTest { // ---- no wallet: docs/giza-wallet-removal.md, Phase 1 ------------------ - /** The parent made a subgroup of a grandparent, under [policy]. */ - private suspend fun parentIs(policy: SubgroupWalletPolicy?) { - val grandparentRoomId = roomOf(strangerMaterial) - val inherited = if (policy == SubgroupWalletPolicy.UNGUARDED) { - emptyList() - } else { - GuardianDerivation.grant(strangerMaterial.thresholdPublicKey.value.toHex(), grandparentRoomId, emptyList(), parentRoomId) - } - fileParentage(inherited, policy) + /** The parent made a subgroup of a grandparent, whose Bennu certificate carries [policy]. */ + private suspend fun parentIs(policy: String?) { + fileParentage(policy?.let { arrayOf(arrayOf("wallet", it)) } ?: emptyArray()) } - private fun ceremonyUnder(policy: SubgroupWalletPolicy?) = - completedChildCeremony().copy(walletPolicy = policy?.tagValue) + /** A ceremony a Bennu coordinator proposed under [policy], as the proposal's `wallet` tag said. */ + private fun ceremonyUnder(policy: String?) = + completedChildCeremony().copy(walletPolicy = policy) private fun walletTagsOf(certificate: Event) = certificate.tags.filter { it.firstOrNull() == "wallet" || it.firstOrNull() == "guardian" || it.firstOrNull() == "guardian_delay" } @@ -548,14 +517,14 @@ class SubgroupManagerJvmTest { @Test fun `a ceremony an older build proposed as guarded is still certified plain`(): Unit = runBlocking { - val proposed = proposedCertificate(parentWith(listOf(alice, bob)), ceremonyUnder(SubgroupWalletPolicy.GUARDED)) + val proposed = proposedCertificate(parentWith(listOf(alice, bob)), ceremonyUnder("guarded")) assertEquals(emptyList(), walletTagsOf(proposed)) } @Test fun `under an unguarded parent a subgroup is certified plain`(): Unit = runBlocking { val parentRoom = parentWith(listOf(alice, bob)) - parentIs(SubgroupWalletPolicy.UNGUARDED) + parentIs("unguarded") val proposed = proposedCertificate(parentRoom, ceremonyUnder(null)) assertEquals(emptyList(), walletTagsOf(proposed)) @@ -565,7 +534,7 @@ class SubgroupManagerJvmTest { @Test fun `under a guarded parent nothing is proposed`(): Unit = runBlocking { val parentRoom = parentWith(listOf(alice, bob)) - parentIs(SubgroupWalletPolicy.GUARDED) + parentIs("guarded") val refused = runCatching { proposedCertificate(parentRoom, ceremonyUnder(null)) } @@ -594,13 +563,10 @@ class SubgroupManagerJvmTest { /** * The parent's own key state, naming a grandparent through a certificate - * that grants [guardians]. Filed as `stateFrom` would leave it; nothing here - * re-checks the certificate, which is what having passed `stateFrom` means. + * carrying [extraTags] -- a Bennu parent's wallet tags. Filed as `stateFrom` + * would leave it; nothing here re-checks the certificate. */ - private suspend fun fileParentage( - guardians: List, - walletPolicy: SubgroupWalletPolicy? = null, - ) { + private suspend fun fileParentage(extraTags: Array> = emptyArray()) { val grandparentRoomId = roomOf(strangerMaterial) val tags = SubgroupBirthCertificateEvent.assembleTags( subgroupChatRoomId = parentRoomId, @@ -609,9 +575,7 @@ class SubgroupManagerJvmTest { adminPublicKeys = listOf(user, alice, bob), name = "Ekklesia", path = path, - guardians = guardians, - walletPolicy = walletPolicy, - ) + ) + extraTags val parentCertificate = certificate(subgroupMaterial = parentMaterial, tags = tags, author = strangerMaterial) db.groupKeyStateDao().upsert( GroupKeyState( diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/WalletDeclineJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/WalletDeclineJvmTest.kt index b5675e9e..25097108 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/WalletDeclineJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/WalletDeclineJvmTest.kt @@ -33,6 +33,8 @@ import mobi.giza.compose.extensions.toHex import mobi.giza.compose.nostr.dkg.DkgRitualEvents import mobi.giza.compose.nostr.frost.FrostSigningEvents import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import mobi.giza.compose.nostr.RetiredKinds +import mobi.giza.compose.nostr.frost.GroupKeyStateEvent /** * Giza declines what is a wallet's to sign, out loud (docs/giza-wallet-removal.md, @@ -205,6 +207,45 @@ class WalletDeclineJvmTest { ) } + @Test + fun `a transaction proposal is filed declined without being read`() = runBlocking { + openDevice(bob) + FrostSigningManager.processSigningPayload( + database = db, + localChatRoom = room, + innerEvent = Event( + id = "spend".padEnd(64, '0'), + pubKey = alice, + createdAt = Clock.System.now().epochSeconds, + kind = RetiredKinds.TRANSACTION_PROPOSAL, + tags = FrostSigningEvents.assembleTags(sessionId = "t".repeat(64), dkgSessionId = ceremonyId) + + arrayOf(arrayOf("chain", "mainnet"), arrayOf("account", "0")), + content = "cHNidP8=", + sig = "" + ), + userPublicKey = bob + ) + + assertEquals(FrostSigningSubject.TRANSACTION, db.frostSigningSessionDao().getSessionById("t".repeat(64))?.subject) + assertDeclinedAsWallet("t".repeat(64)) + } + + @Test + fun `a key state carrying a guarded certificate is declined`() = runBlocking { + val certificate = Event( + id = "c".repeat(64), + pubKey = "d".repeat(64), + createdAt = 1_700_000_000, + kind = SubgroupBirthCertificateEvent.KIND, + tags = arrayOf(arrayOf("d", roomId), arrayOf("wallet", "guarded")), + content = roomId, + sig = "e".repeat(128) + ) + assertDeclinedAsWallet( + proposalReachesBob(GroupKeyStateEvent.KIND, tags = arrayOf(arrayOf("birth_certificate", certificate.toJson()))) + ) + } + @Test fun `an ordinary event is still put to the member`() = runBlocking { val sessionId = proposalReachesBob(kind = 1, content = "Something for the group to say") diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/StringCatalogueJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/StringCatalogueJvmTest.kt index 4e2bf289..704ea057 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/StringCatalogueJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/StringCatalogueJvmTest.kt @@ -8,9 +8,6 @@ import mobi.giza.compose.resources.something_went_wrong import mobi.giza.compose.resources.recovered_of_still_unreadable import mobi.giza.compose.resources.sent_a_private_message_to import org.jetbrains.compose.resources.getString -import org.jetbrains.compose.resources.getPluralString -import mobi.giza.compose.resources.about_n_hours -import mobi.giza.compose.resources.n_blocks import kotlin.test.Test import kotlin.test.assertEquals @@ -77,14 +74,4 @@ class StringCatalogueJvmTest { getString(Res.string.recovered_of_still_unreadable, "3", "12", "9", ""), ) } - - @Test - fun `a plural picks its form by the count, and substitutes it`() = runBlocking { - // The catalogue's first plurals, for a guardian's delay. A plain - // `%1$d hours` reads "about 1 hours", and no audit catches that. - assertEquals("about 1 hour", getPluralString(Res.plurals.about_n_hours, 1, 1)) - assertEquals("about 36 hours", getPluralString(Res.plurals.about_n_hours, 36, 36)) - assertEquals("1 block", getPluralString(Res.plurals.n_blocks, 1, "1")) - assertEquals("65,535 blocks", getPluralString(Res.plurals.n_blocks, 65_535, "65,535")) - } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupSendScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupSendScreenJvmTest.kt deleted file mode 100644 index 11a98d22..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupSendScreenJvmTest.kt +++ /dev/null @@ -1,219 +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 androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.ui.Modifier -import androidx.compose.ui.semantics.SemanticsProperties -import androidx.compose.ui.test.ComposeUiTest -import androidx.compose.ui.test.ExperimentalTestApi -import androidx.compose.ui.test.SemanticsMatcher -import androidx.compose.ui.test.assert -import androidx.compose.ui.test.assertIsDisplayed -import androidx.compose.ui.test.assertIsEnabled -import androidx.compose.ui.test.assertIsNotEnabled -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import androidx.compose.ui.test.performTextInput -import androidx.compose.ui.test.runDesktopComposeUiTest -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.ui.view.state.FundingTarget -import com.vitorpamplona.quartz.nip01Core.core.Event -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.widgets.ProvideSnackbarHost -import mobi.giza.compose.ui.theme.GizaTheme -import mobi.giza.compose.ui.view.state.GroupSendUIState -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.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.time.Instant - -/** - * The send form, typed into: an amount is read back as the preview will say - * it, a problem with the amount is said on the amount field, and - * send-everything puts the field away without forgetting what was in it. - */ -@OptIn(ExperimentalTestApi::class) -class GroupSendScreenJvmTest { - private val chatRoomId = "d4c3b2a1".repeat(8) - private val regtestAddress = "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080" - private val mainnetAddress = "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4" - - private val isError = SemanticsMatcher.keyIsDefined(SemanticsProperties.Error) - - @Test - fun `an amount is read back grouped, and the spend it builds can be proposed`() = render(Chain.Regtest) { - fill(regtestAddress, amount = "40000") - - onNodeWithText("40,000").assertIsDisplayed() - onNodeWithText("Sends 40,000 sats", substring = true).assertIsDisplayed() - onNodeWithText("come back to the group as change", substring = true).assertIsDisplayed() - onNodeWithText("Ask the group to send").assertIsEnabled() - } - - @Test - fun `how much can be spent is said under the amount`() = render(Chain.Regtest) { - onNodeWithText("100,000 sats confirmed and free to spend").assertIsDisplayed() - onNodeWithText("While the wallet is new", substring = true).assertDoesNotExist() - } - - @Test - fun `a decimal is refused on the amount field, and nothing can be proposed`() = render(Chain.Regtest) { - fill(regtestAddress, amount = "0.5") - - onNodeWithText("Sats are whole numbers", substring = true).assertIsDisplayed() - onNodeWithText("Amount in sats").assert(isError) - onNodeWithText("Sends", substring = true).assertDoesNotExist() - onNodeWithText("Ask the group to send").assertIsNotEnabled() - } - - @Test - fun `send everything puts the amount away, and turning it off finds it again`() = render(Chain.Regtest) { - fill(regtestAddress, amount = "40000") - - onNodeWithText("Send everything").performClick() - onNodeWithText("Amount in sats").assertDoesNotExist() - onNodeWithText("come back to the group as change", substring = true).assertDoesNotExist() - - onNodeWithText("Send everything").performClick() - onNodeWithText("40,000").assertIsDisplayed() - onNodeWithText("Sends 40,000 sats", substring = true).assertIsDisplayed() - } - - @Test - fun `on mainnet the cap is said before it is hit, and on the field when it is`() = render(Chain.Mainnet) { - val cap = "While the wallet is new, a spend on mainnet can send at most 100,000 sats." - onNodeWithText(cap).assertIsDisplayed() - - fill(mainnetAddress, amount = "150000") - - onNodeWithText(cap).assertIsDisplayed() - onNodeWithText("Amount in sats").assert(isError) - onNodeWithText("Ask the group to send").assertIsNotEnabled() - } - - @Test - fun `funding a guarded wallet names it, shows where it pays, and takes no address`() = render(Chain.Regtest, funded = true) { - onNodeWithText("Fund Savings's guarded wallet").assertIsDisplayed() - onNodeWithText("Savings's guarded wallet").assertIsDisplayed() - onNodeWithText("Address").assertDoesNotExist() - onNodeWithText("Address 2").assertIsDisplayed() - // This group's own leaf's delay in the funded wallet, in blocks alone on regtest. - onNodeWithText("This group can spend these coins again once they have waited 12 blocks.").assertIsDisplayed() - - onNodeWithText("Fee rate in sats per byte").performTextInput("4") - onNodeWithText("Amount in sats").performTextInput("40000") - onNodeWithText("Sends 40,000 sats to Savings's guarded wallet", substring = true).assertIsDisplayed() - onNodeWithText("Ask the group to send").assertIsEnabled() - } - - private fun funding(chain: Chain): FundingTarget { - val descendantRoomId = "c".repeat(64) - // Guarded by this room, at the default delay, as a verified statement would be. - val descendant = GroupWalletDerivation.account( - PrivateKey(ByteVector32(Hex.decode("decaf".padStart(64, '0')))).publicKey().toString(), chain, - guardians = GuardianDerivation.grant(PrivateKey(ByteVector32(Hex.decode("a11ce".padStart(64, '0')))).publicKey().toString(), chatRoomId, emptyList(), descendantRoomId), - ) - 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", "Savings")), "", ""), - lineage = listOf(descendantRoomId), - ) - val receive = (0 until 10).associate { index -> - GroupWalletDerivation.derive(descendant, GroupWalletDerivation.RECEIVE, index.toLong()).address(chain) to - WalletState.AddressState(WalletState.AddressMeta.Derived(index), alreadyUsed = false, utxos = emptyList()) - } - return FundingTarget(guarded, GroupWalletState(descendant, WalletState(receive), WalletState.empty, tipHeight = 110)) - } - - private fun ComposeUiTest.fill(address: String, amount: String) { - onNodeWithText("Address").performTextInput(address) - onNodeWithText("Fee rate in sats per byte").performTextInput("4") - onNodeWithText("Amount in sats").performTextInput(amount) - } - - private fun ready(chain: Chain): GroupSendUIState.Ready { - val account = GroupWalletDerivation.account( - PrivateKey(ByteVector32(Hex.decode("1c0ffee".padStart(64, '0')))).publicKey().toString(), chain, - ) - val wallet = GroupWallet( - GroupSignedEvent( - id = "e".repeat(64), chatRoomId = chatRoomId, publicKey = chatRoomId, kind = GroupWalletStatementEvent.KIND, - tags = GroupWalletStatementEvent.template(account).tags, content = account.xpub, signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000), - ), - account, - ) - val receive = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, 0) - val change = GroupWalletDerivation.derive(account, GroupWalletDerivation.CHANGE, 0) - val funding = Transaction( - 2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 1 })), 0), ByteVector.empty, 0xffffffffL)), - listOf(TxOut(Satoshi(if (chain.isMainnet()) 300_000 else 100_000), receive.pubkeyScript)), 0, - ) - val meta = WalletState.AddressMeta.Derived(0) - val walletState = GroupWalletState( - account, - WalletState(mapOf(receive.address(chain) to WalletState.AddressState(meta, true, listOf(WalletState.Utxo(funding.txid, 0, 100, funding, meta))))), - WalletState(mapOf(change.address(chain) to WalletState.AddressState(WalletState.AddressMeta.Derived(0), false, emptyList()))), - tipHeight = 110, - ) - val room = LocalChatRoom( - chatRoom = ChatRoom( - id = chatRoomId, userPublicKey = "a".repeat(64), subject = "Treasury", description = null, - initialGiftWrapPayloadId = "p", mlsGroupState = "state", - ) - ) - return GroupSendUIState.Ready(room, wallet, walletState, reserved = emptySet()) - } - - private fun render(chain: Chain, funded: Boolean = false, assertions: ComposeUiTest.() -> Unit) = - runDesktopComposeUiTest(width = 400, height = 1200) { - setContent { - GizaTheme { - ProvideSnackbarHost { - Box(modifier = Modifier.fillMaxSize()) { - GroupSendScreen( - activeUserPublicKey = "a".repeat(64), - chatRoomId = chatRoomId, - chain = chain, - initialGroupSendUIState = ready(chain).let { if (funded) it.copy(funding = funding(chain)) else it }, - 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())), - onNavigateToRouteAndPopUpInclusive = {}, - onNavigateBack = {}, - ) - } - } - } - } - - assertions() - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/CreateSharedKeyViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/CreateSharedKeyViewModelJvmTest.kt index d4493d0d..f8a6bb39 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/CreateSharedKeyViewModelJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/CreateSharedKeyViewModelJvmTest.kt @@ -1,6 +1,5 @@ package mobi.giza.compose.ui.view.model -import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy import androidx.datastore.preferences.core.PreferenceDataStoreFactory import com.vitorpamplona.quartz.nip01Core.core.HexKey import fr.acinq.bitcoin.ByteVector32 @@ -118,8 +117,6 @@ class CreateSharedKeyViewModelJvmTest { parentChatRoomId: HexKey?, participantPublicKeys: Set?, subject: String?, - walletPolicy: SubgroupWalletPolicy?, - guardianDelay: Long? ): DkgSession? { proposed += threshold return session("new".padEnd(64, '0'), DkgRitualStage.COLLECTING_HOST_KEYS) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/GroupSendViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/GroupSendViewModelJvmTest.kt deleted file mode 100644 index 39576cd0..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/GroupSendViewModelJvmTest.kt +++ /dev/null @@ -1,372 +0,0 @@ -package mobi.giza.compose.ui.view.model - -import mobi.giza.compose.wallet.GroupOnchainWallets -import mobi.giza.compose.wallet.FakeElectrum -import kotlinx.coroutines.cancel -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.CoroutineScope -import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd -import mobi.giza.compose.database.model.ChatRoom -import mobi.giza.compose.database.model.FrostSigningSession -import mobi.giza.compose.database.model.GroupSignedEvent -import mobi.giza.compose.database.model.GroupTransaction -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.flowOf -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.managers.GroupWalletDerivation -import mobi.giza.compose.managers.GuardianManager -import mobi.giza.compose.ui.view.state.FundingTarget -import com.vitorpamplona.quartz.nip01Core.core.Event -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.text.SatsInput -import mobi.giza.compose.ui.view.state.GroupSendUIState -import mobi.giza.compose.wallet.GroupSpend -import mobi.giza.compose.wallet.GroupSpendBuilder -import mobi.giza.compose.wallet.GroupWalletState -import mobi.giza.compose.wallet.GroupWalletRollout -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.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.bitcoin.psbt.Psbt -import fr.acinq.lightning.blockchain.electrum.WalletState -import fr.acinq.secp256k1.Hex -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 -import kotlin.test.assertNotNull -import kotlin.test.assertNull -import kotlin.time.Instant - -/** - * The send form: what it previews is what it proposes, and it is not offered to - * a device that cannot both sign and see the coins. - */ -@OptIn(ExperimentalCoroutinesApi::class) -class GroupSendViewModelJvmTest { - @BeforeTest - fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher()) - - /** A chain with nothing on it: what is under test here is the form, not the coins. */ - private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) - private val wallets = GroupOnchainWallets(FakeElectrum(), scope) - - @AfterTest - fun tearDown() { - scope.cancel() - Dispatchers.resetMain() - } - - private val chatRoomId = "d4c3b2a1".repeat(8) - private val localChatRoom = LocalChatRoom( - chatRoom = ChatRoom(id = chatRoomId, userPublicKey = "a".repeat(64), subject = "Treasury", description = null, initialGiftWrapPayloadId = "p", mlsGroupState = "state") - ) - private fun accountOn(chain: Chain): GroupWalletDerivation.Account = GroupWalletDerivation.account( - PrivateKey(ByteVector32(Hex.decode("1c0ffee".padStart(64, '0')))).publicKey().toString(), chain, - ) - private val account: GroupWalletDerivation.Account = accountOn(Chain.Regtest) - private val wallet = GroupWallet( - GroupSignedEvent( - id = "e".repeat(64), chatRoomId = chatRoomId, publicKey = chatRoomId, kind = GroupWalletStatementEvent.KIND, - tags = GroupWalletStatementEvent.template(account).tags, content = account.xpub, signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000), - ), - account, - ) - - /** One confirmed coin of [sats] under [account], and one unused change address. */ - private fun walletStateOf(account: GroupWalletDerivation.Account, sats: Long): GroupWalletState { - val chain = account.chain - val derived = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, 0) - val tx = Transaction(2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 1 })), 0), ByteVector.empty, 0xffffffffL)), listOf(TxOut(Satoshi(sats), derived.pubkeyScript)), 0) - val meta = WalletState.AddressMeta.Derived(0) - val change = GroupWalletDerivation.derive(account, GroupWalletDerivation.CHANGE, 0) - return GroupWalletState( - account, - WalletState(mapOf(derived.address(chain) to WalletState.AddressState(meta, true, listOf(WalletState.Utxo(tx.txid, 0, 100, tx, meta))))), - WalletState(mapOf(change.address(chain) to WalletState.AddressState(WalletState.AddressMeta.Derived(0), false, emptyList()))), - tipHeight = 110, - ) - } - - private val walletState: GroupWalletState = walletStateOf(account, 100_000) - - private class RecordingSigning : FrostSigningRepository by FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY { - var proposed: Psbt? = null - override suspend fun proposeSpend(localChatRoom: LocalChatRoom, userPublicKey: HexKey, psbt: Psbt, chain: Chain): FrostSigningSession? { - proposed = psbt - return null - } - } - - private fun viewModel( - initial: GroupSendUIState, - chat: ChatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - signing: FrostSigningRepository = RecordingSigning(), - chain: Chain = Chain.Regtest, - ) = GroupSendViewModel("a".repeat(64), chatRoomId, chain, initial, chat, signing, wallets = wallets) - - @Test - fun `a member with no share is not offered the form`() { - val chat = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { - override suspend fun getChatRoomByIdentifier(identifier: String) = localChatRoom - override suspend fun canSign(chatRoomId: String) = false - override suspend fun groupWallet(chatRoomId: String, chain: Chain) = wallet - } - val model = viewModel(GroupSendUIState.Loading, chat).apply { initiate() } - - runBlocking { withTimeout(5_000) { while (model.groupSendUIState == GroupSendUIState.Loading) delay(10) } } - assertEquals(GroupSendUIState.Unavailable, model.groupSendUIState) - } - - @Test - fun `the preview waits for the form, and what it builds is what is proposed`() { - val signing = RecordingSigning() - val model = viewModel(GroupSendUIState.Ready(localChatRoom, wallet, walletState, reserved = emptySet()), signing = signing) - - assertNull(model.preview(), "nothing to build before an address and a feerate") - - model.addressField.setTextAndPlaceCursorAtEnd("bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080") - model.feerateField.setTextAndPlaceCursorAtEnd("4") - model.amountField.setTextAndPlaceCursorAtEnd("40,000") - val built = assertIs(model.preview()) - assertEquals(Satoshi(40_000), built.amount) - assertEquals(Satoshi(100_000), built.amount + built.fee + assertNotNull(built.change), "the rest comes back") - - model.propose(onSuccess = {}, onFailure = {}) - runBlocking { withTimeout(5_000) { while (signing.proposed == null) delay(10) } } - assertEquals(built.psbt, signing.proposed) - assertIs(GroupSpend.check(signing.proposed!!, account), "the other members would accept it") - } - - @Test - fun `a decimal amount is refused, never sent ten times over`() { - val model = viewModel(GroupSendUIState.Ready(localChatRoom, wallet, walletState, reserved = emptySet())) - model.addressField.setTextAndPlaceCursorAtEnd("bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080") - model.feerateField.setTextAndPlaceCursorAtEnd("4") - model.amountField.setTextAndPlaceCursorAtEnd("21000.5") - - assertEquals(SatsInput.NotWhole, model.amount()) - assertEquals(GroupSpendBuilder.Result.InvalidAmount(SatsInput.NotWhole), model.preview()) - } - - @Test - fun `on mainnet the cap holds an amount, as it holds sending everything`() { - val mainnet = accountOn(Chain.Mainnet) - val model = viewModel( - GroupSendUIState.Ready(localChatRoom, wallet, walletStateOf(mainnet, 300_000), reserved = emptySet()), - chain = Chain.Mainnet, - ) - model.addressField.setTextAndPlaceCursorAtEnd("bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4") - model.feerateField.setTextAndPlaceCursorAtEnd("4") - - model.amountField.setTextAndPlaceCursorAtEnd("150,000") - assertEquals(GroupSpendBuilder.Result.OverCap(GroupWalletRollout.MAINNET_CAP), model.preview()) - - model.amountField.setTextAndPlaceCursorAtEnd("100,000") - val built = assertIs(model.preview(), "the cap itself is allowed") - assertNotNull(built.change) - assertIs(GroupSpend.check(built.psbt, mainnet)) - } - - /** The room's spends as the database would report them, and what they hold, set by the test. */ - private class Reserving : FrostSigningRepository by FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY { - val transactions = MutableStateFlow>(emptyList()) - @Volatile var heldCoins: Set = emptySet() - @Volatile var heldChange: Set = emptySet() - @Volatile var heldFunding: Set = emptySet() - override fun observeGroupTransactions(chatRoomId: String): Flow> = transactions - override suspend fun reservedOutPoints(chatRoomId: String): Set = heldCoins - override suspend fun reservedChangeIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set = heldChange - override suspend fun reservedFundingIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set = heldFunding - } - - /** Two confirmed coins, 60,000 and 40,000 sats, on the first two receive addresses. */ - private val twoCoins: GroupWalletState = run { - val coins = listOf(60_000L, 40_000L).mapIndexed { index, sats -> - 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) - derived.address(Chain.Regtest) to WalletState.AddressState(meta, true, listOf(WalletState.Utxo(tx.txid, 0, 100, tx, meta))) - }.toMap() - walletState.copy(receive = WalletState(coins)) - } - - private fun eventually(read: () -> T?): T = - runBlocking { withTimeout(5_000) { var value = read(); while (value == null) { delay(10); value = read() }; value } } - - @Test - fun `a spend proposed while the form is open takes its coins out of what the form will send`() { - val signing = Reserving() - val ready = GroupSendUIState.Ready(localChatRoom, wallet, walletState = null, reserved = emptySet()) - val model = viewModel(ready, signing = signing) - model.follow(ready, flowOf(twoCoins)) - model.addressField.setTextAndPlaceCursorAtEnd("bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080") - model.feerateField.setTextAndPlaceCursorAtEnd("4") - model.sendEverything.value = true - - val before = eventually { model.preview() as? GroupSpendBuilder.Result.Built } - assertEquals(Satoshi(100_000), before.amount + before.fee, "both coins, before anybody holds one") - - // Another member's proposal arrives: it holds the 60,000 coin and change index 0. - val bigCoin = twoCoins.utxos.single { it.amount == Satoshi(60_000) }.utxo.outPoint - signing.heldCoins = setOf(bigCoin) - signing.heldChange = setOf(0L) - signing.transactions.value = listOf( - GroupTransaction(frostSigningSessionId = "theirs", chatRoomId = chatRoomId, chain = "regtest", account = 0, psbt = "", txid = "t".repeat(64)) - ) - - val following = eventually { (model.groupSendUIState as GroupSendUIState.Ready).takeIf { it.reserved.isNotEmpty() } } - assertEquals(setOf(bigCoin), following.reserved) - assertEquals(setOf(0L), following.reservedChange) - assertEquals(twoCoins, following.walletState, "the coins are kept while the reservations change") - - val after = assertIs(model.preview()) - assertEquals(Satoshi(40_000), after.amount + after.fee, "only the coin nobody holds, without the form being opened again") - assertEquals(Satoshi(40_000), model.spendable()) - } - - @Test - fun `send everything ignores the amount`() { - val model = viewModel(GroupSendUIState.Ready(localChatRoom, wallet, walletState, reserved = emptySet())) - model.addressField.setTextAndPlaceCursorAtEnd("bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080") - model.feerateField.setTextAndPlaceCursorAtEnd("4") - model.sendEverything.value = true - - val built = assertIs(model.preview()) - assertEquals(Satoshi(100_000), built.amount + built.fee) - assertNull(built.change) - } - - // ---- Funding a descendant's guarded wallet --------------------------------- - - private val descendantRoomId = "c".repeat(64) - private val descendant: GroupWalletDerivation.Account = GroupWalletDerivation.account( - PrivateKey(ByteVector32(Hex.decode("decaf".padStart(64, '0')))).publicKey().toString(), Chain.Regtest, - ) - private 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", "Savings")), "", ""), - lineage = listOf(descendantRoomId), - ) - - /** The descendant's receive branch as Electrum reports it: its first ten addresses watched, [paid] of them used. */ - private fun descendantState(paid: Set = emptySet()): GroupWalletState { - val receive = (0 until 10).associate { index -> - GroupWalletDerivation.derive(descendant, GroupWalletDerivation.RECEIVE, index.toLong()).address(Chain.Regtest) to - WalletState.AddressState(WalletState.AddressMeta.Derived(index), alreadyUsed = index in paid, utxos = emptyList()) - } - return GroupWalletState(descendant, WalletState(receive), WalletState.empty, tipHeight = 110) - } - - private fun fundingForm(signing: FrostSigningRepository, fundingState: Flow): GroupSendViewModel { - val ready = GroupSendUIState.Ready(localChatRoom, wallet, walletState = null, reserved = emptySet(), funding = FundingTarget(guarded, walletState = null)) - return viewModel(ready, signing = signing).apply { - follow(ready, flowOf(walletState), fundingState) - feerateField.setTextAndPlaceCursorAtEnd("4") - amountField.setTextAndPlaceCursorAtEnd("30,000") - } - } - - @Test - fun `a funding pays two past the descendant's current address, and says so in the PSBT`() { - val signing = RecordingSigning() - val model = fundingForm(signing, flowOf(descendantState())) - - val built = eventually { model.preview() as? GroupSpendBuilder.Result.Built } - assertEquals(2L, built.funded?.derived?.index) - assertEquals(GroupWalletDerivation.derive(descendant, GroupWalletDerivation.RECEIVE, 2).pubkeyScript, built.psbt.global.tx.txOut[0].publicKeyScript) - assertEquals(setOf(2L), GroupSpend.claimedFundingIndices(built.psbt, descendant)) - - // The address field plays no part: whatever is typed there, the funding goes where it goes. - model.addressField.setTextAndPlaceCursorAtEnd("bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080") - assertEquals(built.psbt, assertIs(model.preview()).psbt) - - model.propose(onSuccess = {}, onFailure = {}) - runBlocking { withTimeout(5_000) { while (signing.proposed == null) delay(10) } } - assertEquals(built.psbt, signing.proposed, "proposed as the room's own spend") - } - - @Test - fun `an open funding moves the next one on`() { - val signing = Reserving() - val model = fundingForm(signing, flowOf(descendantState())) - assertEquals(2L, eventually { (model.preview() as? GroupSpendBuilder.Result.Built)?.funded }.derived.index) - - signing.heldFunding = setOf(2L) - signing.transactions.value = listOf( - GroupTransaction(frostSigningSessionId = "theirs", chatRoomId = chatRoomId, chain = "regtest", account = 0, psbt = "", txid = "t".repeat(64)) - ) - assertEquals(3L, eventually { (model.preview() as? GroupSpendBuilder.Result.Built)?.funded?.takeIf { it.derived.index != 2L } }.derived.index) - } - - @Test - fun `a payment to the address while the form is open moves it on`() { - val chain = MutableStateFlow(descendantState()) - val model = fundingForm(RecordingSigning(), chain) - assertEquals(2L, eventually { (model.preview() as? GroupSpendBuilder.Result.Built)?.funded }.derived.index) - - chain.value = descendantState(paid = setOf(2)) - assertEquals(3L, eventually { (model.preview() as? GroupSpendBuilder.Result.Built)?.funded?.takeIf { it.derived.index != 2L } }.derived.index) - } - - @Test - fun `nothing is built while the descendant's addresses are not known, or every one is held`() { - val waiting = fundingForm(RecordingSigning(), flowOf(null)) - val state = eventually { (waiting.groupSendUIState as GroupSendUIState.Ready).takeIf { it.walletState != null } } - assertNull(waiting.preview()) - assertEquals(false, state.funding?.allHeld) - - val signing = Reserving().apply { heldFunding = (2L until 10L).toSet() } - val full = fundingForm(signing, flowOf(descendantState())) - val held = eventually { (full.groupSendUIState as GroupSendUIState.Ready).takeIf { it.funding?.walletState != null } } - assertEquals(true, held.funding?.allHeld) - assertNull(full.preview()) - } - - @Test - fun `a route naming a source and a destination is not opened, nor one funding a wallet the room does not hold`() { - var asked = 0 - val chat = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { - override suspend fun getChatRoomByIdentifier(identifier: String) = localChatRoom - override suspend fun canSign(chatRoomId: String) = true - override suspend fun groupWallet(chatRoomId: String, chain: Chain) = wallet - override suspend fun guardedWallets(chatRoomId: String): List { asked++; return emptyList() } - } - val both = GroupSendViewModel("a".repeat(64), chatRoomId, Chain.Regtest, GroupSendUIState.Loading, chat, RecordingSigning(), wallets = wallets, - guardedChatRoomId = descendantRoomId, fundChatRoomId = descendantRoomId).apply { initiate() } - runBlocking { withTimeout(5_000) { while (both.groupSendUIState == GroupSendUIState.Loading) delay(10) } } - assertEquals(GroupSendUIState.Unavailable, both.groupSendUIState) - assertEquals(0, asked, "refused before either wallet is looked for") - - val unknown = GroupSendViewModel("a".repeat(64), chatRoomId, Chain.Regtest, GroupSendUIState.Loading, chat, RecordingSigning(), wallets = wallets, - fundChatRoomId = descendantRoomId).apply { initiate() } - runBlocking { withTimeout(5_000) { while (unknown.groupSendUIState == GroupSendUIState.Loading) delay(10) } } - assertEquals(GroupSendUIState.Unavailable, unknown.groupSendUIState) - assertEquals(1, asked) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/GroupWalletAddressesViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/GroupWalletAddressesViewModelJvmTest.kt deleted file mode 100644 index 174160ec..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/GroupWalletAddressesViewModelJvmTest.kt +++ /dev/null @@ -1,149 +0,0 @@ -package mobi.giza.compose.ui.view.model - -import mobi.giza.compose.database.model.GroupSignedEvent -import mobi.giza.compose.managers.GroupWalletDerivation -import mobi.giza.compose.nostr.wallet.GroupWallet -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import mobi.giza.compose.repository.ChatRepository -import mobi.giza.compose.ui.view.state.GroupWalletAddressesUIState -import mobi.giza.compose.wallet.FakeElectrum -import mobi.giza.compose.wallet.GroupAddress -import mobi.giza.compose.wallet.GroupOnchainWallets -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.Satoshi -import fr.acinq.secp256k1.Hex -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.cancel -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 -import kotlin.test.assertNull -import kotlin.time.Instant - -/** Which of its states the address list is in, and that it follows the chain while it is open. */ -@OptIn(ExperimentalCoroutinesApi::class) -class GroupWalletAddressesViewModelJvmTest { - private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) - - @BeforeTest - fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher()) - - @AfterTest - fun tearDown() { - scope.cancel() - Dispatchers.resetMain() - } - - private val chatRoomId = "d4c3b2a1".repeat(8) - - private val account = GroupWalletDerivation.account( - PrivateKey(ByteVector32(Hex.decode("1c0ffee".padStart(64, '0')))).publicKey().toString(), - Chain.Regtest, - ) - - private val wallet = GroupWallet( - signedEvent = GroupSignedEvent( - id = "e".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = GroupWalletStatementEvent.KIND, - tags = GroupWalletStatementEvent.template(account).tags, - content = account.xpub, - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000), - ), - account = account, - ) - - private fun repository(opened: GroupWallet?) = - object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { - override suspend fun groupWallet(chatRoomId: String, chain: Chain): GroupWallet? = opened - } - - private fun viewModel(opened: GroupWallet?, wallets: GroupOnchainWallets = GroupOnchainWallets(FakeElectrum(), scope)) = - GroupWalletAddressesViewModel( - chatRoomId = chatRoomId, - chain = Chain.Regtest, - initialUIState = GroupWalletAddressesUIState.Loading, - chatRepository = repository(opened), - wallets = wallets, - ).apply { initiate() } - - private fun GroupWalletAddressesViewModel.until(predicate: (GroupWalletAddressesUIState) -> Boolean): GroupWalletAddressesUIState = - runBlocking { - withTimeout(10_000) { - while (!predicate(uiState)) delay(10) - uiState - } - } - - private fun receive(index: Long) = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, index) - - @Test - fun `a room with no wallet has no addresses to list`() { - assertIs(viewModel(opened = null).until { it != GroupWalletAddressesUIState.Loading }) - } - - @Test - fun `the list follows a payment while the screen is open`() { - val electrum = FakeElectrum() - val addresses = viewModel(opened = wallet, wallets = GroupOnchainWallets(electrum, scope)) - - addresses.until { (it as? GroupWalletAddressesUIState.Loaded)?.receive != null } - runBlocking { electrum.pay(receive(0).pubkeyScript, Satoshi(25_000)) } - - val state = addresses.until { loaded -> - (loaded as? GroupWalletAddressesUIState.Loaded)?.receive?.any { it.status == GroupAddress.Status.USED } == true - } - val current = assertIs(state).receive!!.single { it.status == GroupAddress.Status.CURRENT } - assertEquals(1L, current.derivation.index) - } - - private fun GroupWalletAddressesViewModel.untilListed(index: Long, status: GroupAddress.Status) = until { loaded -> - (loaded as? GroupWalletAddressesUIState.Loaded)?.receive?.any { it.derivation.index == index && it.status == status } == true - } - - @Test - fun `the sheet closes once when the address it shows is paid`() { - val electrum = FakeElectrum() - val addresses = viewModel(opened = wallet, wallets = GroupOnchainWallets(electrum, scope)) - addresses.untilListed(1L, GroupAddress.Status.NEXT) - - var paid = 0 - addresses.show(1L) { paid++ } - runBlocking { electrum.pay(receive(1).pubkeyScript, Satoshi(25_000)) } - addresses.untilListed(1L, GroupAddress.Status.USED) - runBlocking { withTimeout(10_000) { while (addresses.shown != null) delay(10) } } - - assertNull(addresses.shown) - assertEquals(1, paid) - } - - @Test - fun `the sheet stays open when some other address is paid`() { - val electrum = FakeElectrum() - val addresses = viewModel(opened = wallet, wallets = GroupOnchainWallets(electrum, scope)) - addresses.untilListed(1L, GroupAddress.Status.NEXT) - - var paid = 0 - addresses.show(1L) { paid++ } - runBlocking { electrum.pay(receive(0).pubkeyScript, Satoshi(25_000)) } - addresses.untilListed(1L, GroupAddress.Status.CURRENT) - - assertEquals(1L, addresses.shown, "the address it shows became the current one, which is still unused") - assertEquals(0, paid) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/GroupWalletViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/GroupWalletViewModelJvmTest.kt deleted file mode 100644 index a933b0d0..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/GroupWalletViewModelJvmTest.kt +++ /dev/null @@ -1,376 +0,0 @@ -package mobi.giza.compose.ui.view.model - -import mobi.giza.compose.wallet.GroupOnchainWallets -import mobi.giza.compose.wallet.FakeElectrum -import kotlinx.coroutines.cancel -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.CoroutineScope -import kotlin.test.assertTrue -import mobi.giza.compose.nostr.subgroup.WalletPolicyReading -import mobi.giza.compose.nostr.subgroup.SubgroupWalletPolicy -import mobi.giza.compose.database.model.ChatRoom -import mobi.giza.compose.database.model.FrostSigningSession -import mobi.giza.compose.database.model.GroupSignedEvent -import mobi.giza.compose.database.model.intermdiate.LocalChatRoom -import mobi.giza.compose.managers.GroupWalletDerivation -import mobi.giza.compose.nostr.wallet.GroupWallet -import mobi.giza.compose.nostr.wallet.GroupWalletStatementEvent -import mobi.giza.compose.repository.ChatRepository -import mobi.giza.compose.repository.FrostSigningRepository -import mobi.giza.compose.ui.view.state.GroupWalletUIState -import mobi.giza.compose.ui.view.state.SpendStatus -import mobi.giza.compose.wallet.GroupWalletRollout -import mobi.giza.compose.database.model.types.FrostSigningStage -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.core.Kind -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.secp256k1.Hex -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.time.Instant - -/** - * What the wallet screen's view model decides: which of its states a room is in, - * and what it asks the group to sign when a member opens a wallet. - */ -@OptIn(ExperimentalCoroutinesApi::class) -class GroupWalletViewModelJvmTest { - @BeforeTest - fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher()) - - /** A chain with nothing on it: the wallet screen's rules, not its coins. */ - private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) - - @AfterTest - fun tearDown() { - scope.cancel() - Dispatchers.resetMain() - } - - private val chatRoomId = "d4c3b2a1".repeat(8) - private val me = "a".repeat(64) - - private val localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = chatRoomId, - userPublicKey = me, - subject = "Treasury", - description = null, - initialGiftWrapPayloadId = "payload", - mlsGroupState = "state", - ) - ) - - private val account = GroupWalletDerivation.account( - PrivateKey(ByteVector32(Hex.decode("1c0ffee".padStart(64, '0')))).publicKey().toString(), - Chain.Mainnet, - ) - - /** The repository's answer is the thing under test's input; the statement's own checks are `GroupWalletStatementEventTest`'s. */ - private val wallet = GroupWallet( - signedEvent = GroupSignedEvent( - id = "e".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = GroupWalletStatementEvent.KIND, - tags = GroupWalletStatementEvent.template(account).tags, - content = account.xpub, - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000), - ), - account = account, - ) - - private fun repository(opened: GroupWallet?, canSign: Boolean = true, hasKey: Boolean = true) = - object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { - override suspend fun getChatRoomByIdentifier(identifier: String): LocalChatRoom? = localChatRoom - override suspend fun canSign(chatRoomId: String): Boolean = canSign - override suspend fun groupWallet(chatRoomId: String, chain: Chain): GroupWallet? = opened - override suspend fun groupWalletAccount(chatRoomId: String, chain: Chain): GroupWalletDerivation.Account? = - account.takeIf { hasKey } - } - - private class RecordingSigning : FrostSigningRepository by FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY { - var proposed: Triple>, String>? = null - - override suspend fun proposeSigning( - localChatRoom: LocalChatRoom, - userPublicKey: HexKey, - kind: Kind, - tags: Array>, - content: String, - ): FrostSigningSession? { - proposed = Triple(kind, tags, content) - return null - } - } - - private fun viewModel(chat: ChatRepository, signing: FrostSigningRepository = RecordingSigning(), chain: Chain = Chain.Mainnet) = - GroupWalletViewModel( - activeUserPublicKey = me, - chatRoomId = chatRoomId, - chain = chain, - initialGroupWalletUIState = GroupWalletUIState.Loading, - chatRepository = chat, - frostSigningRepository = signing, - wallets = GroupOnchainWallets(FakeElectrum(), scope), - ) - - private fun GroupWalletViewModel.settled(): GroupWalletUIState = runBlocking { - withTimeout(5_000) { - while (groupWalletUIState == GroupWalletUIState.Loading) delay(10) - groupWalletUIState - } - } - - @Test - fun `a group that has not opened a wallet is offered the account it would open`() { - val state = assertIs(viewModel(repository(opened = null)).apply { initiate() }.settled()) - - assertEquals(account, state.account) - assertEquals(true, state.canSign) - } - - @Test - fun `a room with no key has nothing to open`() { - val state = assertIs( - viewModel(repository(opened = null, hasKey = false)).apply { initiate() }.settled() - ) - - assertNull(state.account) - } - - @Test - fun `an open wallet is shown`() { - val state = assertIs(viewModel(repository(opened = wallet)).apply { initiate() }.settled()) - - assertEquals(wallet, state.wallet) - } - - @Test - fun `opening a wallet proposes the statement for the account, and nothing else`() { - val signing = RecordingSigning() - val model = viewModel(repository(opened = null), signing).apply { initiate() } - model.settled() - - var failed = false - model.openWallet(onSuccess = {}, onFailure = { failed = true }) - runBlocking { withTimeout(5_000) { while (signing.proposed == null || model.isActionPending.value) delay(10) } } - - val (kind, tags, content) = assertNotNull(signing.proposed) - assertEquals(GroupWalletStatementEvent.KIND, kind) - assertEquals(account.xpub, content) - assertEquals(account, GroupWalletStatementEvent.read(tags, content)?.verifiedAgainst( - PrivateKey(ByteVector32(Hex.decode("1c0ffee".padStart(64, '0')))).publicKey().toString() - )) - runBlocking { withTimeout(5_000) { while (!failed) delay(10) } } - } - - // ---- a guarded wallet --------------------------------------------------- - - /** What the repository would hand a subgroup whose certificate grants it guardians; the checks behind it are `GroupWalletStatementEventTest`'s. */ - private val certificate = com.vitorpamplona.quartz.nip01Core.core.Event( - "c".repeat(64), "b".repeat(64), 1_700_000_000, 30329, emptyArray(), chatRoomId, "f".repeat(128) - ) - private val guardians = mobi.giza.compose.managers.GuardianDerivation.grant( - PrivateKey(ByteVector32(Hex.decode("9a4e47".padStart(64, '0')))).publicKey().toString(), - "b".repeat(64), emptyList(), chatRoomId, - ) - - private fun guardedRepository( - chain: Chain, - policy: WalletPolicyReading? = WalletPolicyReading.Undecided, - ) = object : ChatRepository by repository(opened = null) { - override suspend fun walletPolicyOf(chatRoomId: String): WalletPolicyReading? = policy - - override suspend fun groupWalletGuardedOpening(chatRoomId: String, chain: Chain) = - mobi.giza.compose.managers.GroupWalletManager.GuardedOpening( - GroupWalletDerivation.account( - PrivateKey(ByteVector32(Hex.decode("1c0ffee".padStart(64, '0')))).publicKey().toString(), - chain, guardians = guardians, - ), - certificate, - ) - } - - @Test - fun `a subgroup is offered a guarded wallet on a test network and on mainnet`() { - val regtest = assertIs( - viewModel(guardedRepository(Chain.Regtest), chain = Chain.Regtest).apply { initiate() }.settled() - ) - assertEquals(guardians, regtest.guarded?.account?.guardians) - - // Mainnet follows GroupWalletRollout.GUARDIANS_ON_MAINNET, which is on. - val mainnet = assertIs( - viewModel(guardedRepository(Chain.Mainnet)).apply { initiate() }.settled() - ) - assertEquals(GroupWalletRollout.GUARDIANS_ON_MAINNET, mainnet.guarded != null) - assertEquals(guardians, mainnet.guarded?.account?.guardians) - } - - @Test - fun `opening a guarded wallet proposes a statement naming the guardians and carrying the certificate`() { - val signing = RecordingSigning() - val model = viewModel(guardedRepository(Chain.Regtest), signing, chain = Chain.Regtest).apply { initiate() } - model.settled() - - model.openWallet(guarded = true, onSuccess = {}, onFailure = {}) - runBlocking { withTimeout(5_000) { while (signing.proposed == null || model.isActionPending.value) delay(10) } } - - val (_, tags, content) = assertNotNull(signing.proposed) - val reading = assertNotNull(GroupWalletStatementEvent.read(tags, content)) - assertEquals(guardians, reading.guardians) - assertEquals(certificate.id, reading.certificate?.id) - } - - // ---- the parent's decision: docs/subgroup-wallet-policy.md ------------- - - @Test - fun `a subgroup whose parent decided guarded is offered the guarded wallet alone`() { - val state = assertIs( - viewModel(guardedRepository(Chain.Regtest, WalletPolicyReading.Decided(SubgroupWalletPolicy.GUARDED)), chain = Chain.Regtest) - .apply { initiate() }.settled() - ) - - assertNotNull(state.guarded) - assertFalse(state.offersPlain) - } - - @Test - fun `a subgroup whose parent decided unguarded is offered the plain wallet alone`() { - val state = assertIs( - viewModel(guardedRepository(Chain.Regtest, WalletPolicyReading.Decided(SubgroupWalletPolicy.UNGUARDED)), chain = Chain.Regtest) - .apply { initiate() }.settled() - ) - - assertNull(state.guarded) - assertTrue(state.offersPlain) - assertEquals(account, state.account) - } - - @Test - fun `an undecided subgroup is offered both, and a root group the plain one`() { - val undecided = assertIs( - viewModel(guardedRepository(Chain.Regtest), chain = Chain.Regtest).apply { initiate() }.settled() - ) - assertNotNull(undecided.guarded) - assertTrue(undecided.offersPlain) - - val root = assertIs(viewModel(repository(opened = null)).apply { initiate() }.settled()) - assertNull(root.guarded) - assertTrue(root.offersPlain) - } - - @Test - fun `each guardian is named by the room this device holds for it`() { - val state = assertIs( - viewModel(guardedRepository(Chain.Regtest), chain = Chain.Regtest).apply { initiate() }.settled() - ) - - // The fixture's repository answers every room id with the one room. - assertEquals(mapOf(guardians.single().chatRoomId to localChatRoom.chatRoom.subject!!), state.guardianNames) - } - - @Test - fun `a plain wallet is never proposed under a parent that decided guarded`() { - val signing = RecordingSigning() - val model = viewModel( - guardedRepository(Chain.Regtest, WalletPolicyReading.Decided(SubgroupWalletPolicy.GUARDED)), signing, chain = Chain.Regtest - ).apply { initiate() } - model.settled() - - model.openWallet(guarded = false, onSuccess = {}, onFailure = {}) - runBlocking { delay(200) } - - assertNull(signing.proposed) - assertFalse(model.isActionPending.value) - } - - // ---- spends ------------------------------------------------------------ - - private val coinTx = fr.acinq.bitcoin.Transaction( - 2, listOf(fr.acinq.bitcoin.TxIn(fr.acinq.bitcoin.OutPoint(fr.acinq.bitcoin.TxId(ByteVector32(ByteArray(32) { 1 })), 0), fr.acinq.bitcoin.ByteVector.empty, 0xffffffffL)), - listOf(fr.acinq.bitcoin.TxOut(fr.acinq.bitcoin.Satoshi(60_000), GroupWalletDerivation.derive(account, 0, 0).pubkeyScript)), 0, - ) - - private val spend: mobi.giza.compose.wallet.GroupSpend.Checked = run { - val first = GroupWalletDerivation.derive(account, 0, 0) - val change = GroupWalletDerivation.derive(account, 1, 0) - val tx = fr.acinq.bitcoin.Transaction( - 2, listOf(fr.acinq.bitcoin.TxIn(fr.acinq.bitcoin.OutPoint(coinTx, 0), fr.acinq.bitcoin.ByteVector.empty, 0xfffffffdL)), - listOf( - fr.acinq.bitcoin.TxOut(fr.acinq.bitcoin.Satoshi(30_000), fr.acinq.bitcoin.ByteVector("0014" + "00".repeat(20))), - fr.acinq.bitcoin.TxOut(fr.acinq.bitcoin.Satoshi(29_000), change.pubkeyScript), - ), 0, - ) - val psbt = mobi.giza.compose.wallet.GroupSpend.psbtOf(tx, listOf(coinTx.txOut[0] to first), mapOf(1 to change), account) - (mobi.giza.compose.wallet.GroupSpend.check(psbt, account) as mobi.giza.compose.wallet.GroupSpend.Result.Ok).checked - } - - private val signedRow = mobi.giza.compose.database.model.GroupTransaction( - frostSigningSessionId = "spend-1", chatRoomId = chatRoomId, chain = "mainnet", account = 0, - psbt = mobi.giza.compose.wallet.GroupSpend.encode(spend.psbt), txid = spend.tx.txid.toString(), signedTransaction = "00", - ) - - private inner class SpendingRepository : FrostSigningRepository by FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY { - var proposed: fr.acinq.bitcoin.psbt.Psbt? = null - override fun observeGroupTransactions(chatRoomId: String) = kotlinx.coroutines.flow.flowOf(listOf(signedRow)) - override suspend fun checkedSpend(sessionId: String) = spend - override suspend fun getSessionById(sessionId: String): FrostSigningSession? = null - override suspend fun proposeSpend(localChatRoom: LocalChatRoom, userPublicKey: HexKey, psbt: fr.acinq.bitcoin.psbt.Psbt, chain: Chain): FrostSigningSession? { - proposed = psbt - return null - } - } - - @Test - fun `the room's spends are listed, and a bump asks for twice the feerate on the same coins`() { - val signing = SpendingRepository() - val model = viewModel(repository(opened = wallet), signing).apply { initiate() } - - val loaded = runBlocking { - withTimeout(5_000) { - while ((model.groupWalletUIState as? GroupWalletUIState.Loaded)?.spends.isNullOrEmpty()) delay(10) - model.groupWalletUIState as GroupWalletUIState.Loaded - } - } - val row = loaded.spends.single() - assertEquals(mobi.giza.compose.ui.view.state.SpendStatus.SIGNED, row.status) - assertEquals(true, row.canBump) - - model.bumpFee("spend-1", onSuccess = {}, onFailure = {}) - runBlocking { withTimeout(5_000) { while (signing.proposed == null) delay(10) } } - - val bumped = (mobi.giza.compose.wallet.GroupSpend.check(signing.proposed!!, account) as mobi.giza.compose.wallet.GroupSpend.Result.Ok).checked - assertEquals(spend.tx.txIn.map { it.outPoint }, bumped.tx.txIn.map { it.outPoint }) - assertEquals(spend.feeratePerVbyte * 2, bumped.feeratePerVbyte) - } - - @Test - fun `a spend's status is the session's until it is signed, and the chain's after`() { - val unsigned = signedRow.copy(signedTransaction = null) - - assertEquals(SpendStatus.WAITING_FOR_SIGNATURES, SpendStatus.of(FrostSigningStage.COLLECTING_NONCES, unsigned)) - assertEquals(SpendStatus.ABANDONED, SpendStatus.of(FrostSigningStage.FAILED, unsigned)) - assertEquals(SpendStatus.SIGNED, SpendStatus.of(FrostSigningStage.COMPLETE, signedRow)) - assertEquals(SpendStatus.SENT, SpendStatus.of(FrostSigningStage.COMPLETE, signedRow.copy(seenAt = Instant.fromEpochSeconds(1)))) - assertEquals(SpendStatus.CONFIRMED, SpendStatus.of(FrostSigningStage.COMPLETE, signedRow.copy(seenAt = Instant.fromEpochSeconds(1), confirmedAt = Instant.fromEpochSeconds(2)))) - assertEquals(SpendStatus.REPLACED, SpendStatus.of(FrostSigningStage.COMPLETE, signedRow.copy(replacedByTxid = "ab".repeat(32)))) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/FakeElectrum.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/FakeElectrum.kt deleted file mode 100644 index 20e67eee..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/FakeElectrum.kt +++ /dev/null @@ -1,103 +0,0 @@ -package mobi.giza.compose.wallet - -import fr.acinq.bitcoin.Block -import fr.acinq.bitcoin.BlockHeader -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Crypto -import fr.acinq.bitcoin.OutPoint -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.ElectrumConnectionStatus -import fr.acinq.lightning.blockchain.electrum.ElectrumSubscriptionResponse -import fr.acinq.lightning.blockchain.electrum.GetMerkleResponse -import fr.acinq.lightning.blockchain.electrum.HeaderSubscriptionResponse -import fr.acinq.lightning.blockchain.electrum.IElectrumClient -import fr.acinq.lightning.blockchain.electrum.ScriptHashSubscriptionResponse -import fr.acinq.lightning.blockchain.electrum.TransactionHistoryItem -import fr.acinq.lightning.blockchain.electrum.UnspentItem -import fr.acinq.lightning.blockchain.fee.FeeratePerKw -import kotlinx.coroutines.flow.MutableSharedFlow -import kotlinx.coroutines.flow.MutableStateFlow - -/** - * A chain that only exists in a test. - * - * `IElectrumClient` is small and documented never to throw, so a fake of it is - * a few maps: what each script has been paid, what of it is unspent, and the - * transactions that paid it. - */ -internal class FakeElectrum : IElectrumClient { - val unspents = mutableMapOf>() - val txs = mutableMapOf() - val subscribed = mutableSetOf() - override val notifications = MutableSharedFlow(extraBufferCapacity = 64) - override val connectionStatus = MutableStateFlow(ElectrumConnectionStatus.Closed(null)) - - /** How many transactions have touched each script: Electrum's status is over the history, not the unspents. */ - private val history = mutableMapOf() - - /** The transactions that touched each script, in order: what `get_history` answers. */ - private val historyTxs = mutableMapOf>() - - private fun status(scriptHash: ByteVector32): String? = history[scriptHash]?.let { "used:$it" } - - /** Pays [script] in a fresh transaction, confirmed at [height] (0 for the mempool), and tells the wallet. */ - suspend fun pay(script: ByteVector, amount: Satoshi, height: Long = 100) { - val tx = Transaction( - version = 2, - txIn = listOf(TxIn(OutPoint(TxId(ByteVector32(Crypto.sha256(script.toByteArray() + txs.size.toByte()))), 0), ByteVector.empty, 0xffffffffL)), - txOut = listOf(TxOut(amount, script)), - lockTime = 0, - ) - txs[tx.txid] = tx - val hash = scriptHash(script) - unspents[hash] = unspents[hash].orEmpty() + UnspentItem(tx.txid, 0, amount.sat, height) - history[hash] = (history[hash] ?: 0) + 1 - historyTxs[hash] = historyTxs[hash].orEmpty() + tx.txid - notifications.emit(ScriptHashSubscriptionResponse(hash, status(hash))) - } - - /** Spends everything [script] holds: its unspents go, its history stays. */ - suspend fun spend(script: ByteVector) { - val hash = scriptHash(script) - unspents.remove(hash) - history[hash] = (history[hash] ?: 0) + 1 - notifications.emit(ScriptHashSubscriptionResponse(hash, status(hash))) - } - - /** The transaction paying [script] most recently, as [pay] made it. */ - fun fundingOf(script: ByteVector): Transaction = txs.getValue(historyTxs.getValue(scriptHash(script)).last()) - - /** Spends what [script] holds with [tx] itself, which joins its history as a real spend would. */ - suspend fun spendWith(script: ByteVector, tx: Transaction) { - val hash = scriptHash(script) - txs[tx.txid] = tx - historyTxs[hash] = historyTxs[hash].orEmpty() + tx.txid - spend(script) - } - - override suspend fun startScriptHashSubscription(scriptHash: ByteVector32): ScriptHashSubscriptionResponse { - subscribed += scriptHash - return ScriptHashSubscriptionResponse(scriptHash, status(scriptHash)) - } - - override suspend fun getScriptHashUnspents(scriptHash: ByteVector32): List = unspents[scriptHash].orEmpty() - override suspend fun getTx(txId: TxId): Transaction? = txs[txId] - override suspend fun getHeader(blockHeight: Int): BlockHeader? = null - override suspend fun getHeaders(startHeight: Int, count: Int): List = emptyList() - override suspend fun getMerkle(txId: TxId, blockHeight: Int, contextOpt: Transaction?): GetMerkleResponse? = null - override suspend fun getScriptHashHistory(scriptHash: ByteVector32): List = - historyTxs[scriptHash].orEmpty().map { TransactionHistoryItem(100, it) } - override suspend fun broadcastTransaction(tx: Transaction): TxId = tx.txid - override suspend fun estimateFees(confirmations: Int): FeeratePerKw? = null - override suspend fun startHeaderSubscription() = HeaderSubscriptionResponse(0, Block.RegtestGenesisBlock.header) - - companion object { - /** Electrum's script hash: sha256 of the script, byte-reversed. */ - fun scriptHash(script: ByteVector): ByteVector32 = ByteVector32(Crypto.sha256(script.toByteArray()).reversedArray()) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/GroupChainClientsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/GroupChainClientsJvmTest.kt deleted file mode 100644 index 9fe2f660..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/GroupChainClientsJvmTest.kt +++ /dev/null @@ -1,94 +0,0 @@ -package mobi.giza.compose.wallet - -import fr.acinq.bitcoin.Block -import fr.acinq.bitcoin.Chain -import fr.acinq.lightning.blockchain.electrum.ElectrumConnectionStatus -import fr.acinq.lightning.blockchain.electrum.ServerVersionResponse -import fr.acinq.lightning.io.TcpSocket -import fr.acinq.lightning.utils.ServerAddress -import fr.acinq.phoenix.data.ElectrumConfig -import fr.acinq.phoenix.managers.global.NetworkState -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertSame -import kotlin.test.assertTrue -import kotlin.time.Duration -import kotlin.time.Duration.Companion.seconds -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.test.StandardTestDispatcher -import kotlinx.coroutines.test.advanceTimeBy -import kotlinx.coroutines.test.runCurrent -import kotlinx.coroutines.test.runTest - -/** - * One Electrum connection per network: the node's own is used as it is, any other is made once, on - * first use, and closed with the identity. - */ -class GroupChainClientsJvmTest { - @Test - fun `the node's network uses the node's client and connects nothing`() = runBlocking { - val node = FakeElectrum() - val made = mutableListOf() - val clients = GroupChainClients(Chain.Mainnet, node) { chain -> made += chain; GroupChainClients.Connection(FakeElectrum()) {} } - assertSame(node, clients.clientFor(Chain.Mainnet)) - assertEquals(emptyList(), made) - } - - @Test - fun `another network gets one connection of its own, reused, and closed on stop`() = runBlocking { - val node = FakeElectrum() - val made = mutableListOf() - var closed = 0 - val clients = GroupChainClients(Chain.Mainnet, node) { chain -> made += chain; GroupChainClients.Connection(FakeElectrum()) { closed++ } } - val first = clients.clientFor(Chain.Testnet3) - assertSame(first, clients.clientFor(Chain.Testnet3)) - assertEquals(listOf(Chain.Testnet3), made) - clients.stop() - assertEquals(1, closed) - // A wallet asked for after a stop -- a profile switched back -- connects again. - clients.clientFor(Chain.Testnet3) - assertEquals(listOf(Chain.Testnet3, Chain.Testnet3), made) - } - - /** A link that only records where the loop sends it. */ - private class RecordingLink : ElectrumLink { - override val client = FakeElectrum() - val servers = mutableListOf() - var stopped = false - override suspend fun connect(server: ServerAddress, timeout: Duration) { - servers += server - client.connectionStatus.value = ElectrumConnectionStatus.Connected(ServerVersionResponse("fake", "1.4"), 0, Block.RegtestGenesisBlock.header) - } - override fun disconnect() { client.connectionStatus.value = ElectrumConnectionStatus.Closed(null) } - override fun stop() { stopped = true } - } - - @Test - fun `another network's connection is the identity's own loop, so it keeps to Tor`() = runTest { - val onion = ServerAddress("testnetexample.onion", 50001, TcpSocket.TLS.DISABLED) - val clearnet = ServerAddress("testnet.example", 50002, TcpSocket.TLS.TRUSTED_CERTIFICATES()) - val asked = mutableListOf>() - val link = RecordingLink() - val node = FakeElectrum() - val clients = GroupChainClients.forNode(Chain.Mainnet, node) { chain -> - StandaloneElectrum( - chain = chain, - networkState = MutableStateFlow(NetworkState.Available), - isTorEnabled = MutableStateFlow(true), - customServer = MutableStateFlow(null), - link = link, - randomServer = { c, tor -> asked += c to tor; if (tor) onion else clearnet }, - context = StandardTestDispatcher(testScheduler), - ) - } - assertSame(node, clients.clientFor(Chain.Mainnet), "the node's own network is the node's client") - assertSame(link.client, clients.clientFor(Chain.Testnet3)) - advanceTimeBy(1.seconds) - runCurrent() - assertEquals(listOf>(Chain.Testnet3 to true), asked.toList()) - assertEquals(listOf(onion), link.servers, "with Tor on, the testnet3 connection goes to an onion server") - clients.stop() - assertTrue(link.stopped, "stopping the identity's clients stops the standalone one") - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/GroupOnchainWalletJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/GroupOnchainWalletJvmTest.kt deleted file mode 100644 index 6c81783d..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/GroupOnchainWalletJvmTest.kt +++ /dev/null @@ -1,321 +0,0 @@ -package mobi.giza.compose.wallet - -import mobi.giza.compose.managers.GroupWalletDerivation -import fr.acinq.bitcoin.Block -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.Satoshi -import fr.acinq.lightning.blockchain.electrum.HeaderSubscriptionResponse -import fr.acinq.lightning.blockchain.electrum.WalletState -import fr.acinq.secp256k1.Hex -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.cancel -import kotlinx.coroutines.flow.first -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.withTimeout -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertNull -import kotlin.test.assertTrue - -/** - * The group's wallet watching a chain that only exists in [FakeElectrum]. - */ -class GroupOnchainWalletJvmTest { - private fun key(seed: Int): String = - PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))).publicKey().toString() - - private val account = GroupWalletDerivation.account(key(0x1c0ffee), Chain.Regtest) - private fun receive(index: Long) = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, index) - private fun change(index: Long) = GroupWalletDerivation.derive(account, GroupWalletDerivation.CHANGE, index) - - private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) - - @AfterTest - fun tearDown() = scope.cancel() - - private fun eventually(block: suspend () -> T): T = runBlocking { withTimeout(10_000) { block() } } - - @Test - fun `being paid moves the receive address on`() { - val electrum = FakeElectrum() - val wallet = GroupOnchainWallet(account, electrum, scope) - - eventually { wallet.state.first { it.receiveAddress == receive(0).address(Chain.Regtest) } } - eventually { electrum.pay(receive(0).pubkeyScript, Satoshi(25_000)) } - - val paid = eventually { wallet.state.first { it.receiveAddress == receive(1).address(Chain.Regtest) } } - assertEquals(Satoshi(25_000), paid.confirmedBalance) - assertEquals(receive(0), paid.utxos.single().derivation) - } - - @Test - fun `change is the group's money and is not handed out to be paid`() { - val electrum = FakeElectrum() - val wallet = GroupOnchainWallet(account, electrum, scope) - - eventually { wallet.state.first { it.nextChangeIndex() == 0L } } - eventually { electrum.pay(change(0).pubkeyScript, Satoshi(7_000), height = 0) } - - val state = eventually { wallet.state.first { it.nextChangeIndex() == 1L && it.receiveAddress != null } } - assertEquals(Satoshi(7_000), state.pendingBalance, "in the mempool, so pending") - assertEquals(Satoshi(0), state.confirmedBalance) - assertEquals(receive(0).address(Chain.Regtest), state.receiveAddress, "a change address is never offered for receiving") - assertEquals(change(0), state.derivationOf(change(0).pubkeyScript)) - } - - @Test - fun `two groups on one client see only their own coins`() { - val electrum = FakeElectrum() - val other = GroupWalletDerivation.account(key(0xdecaf), Chain.Regtest) - val ours = GroupOnchainWallet(account, electrum, scope) - val theirs = GroupOnchainWallet(other, electrum, scope) - - eventually { ours.state.first { it.receiveAddress != null } } - eventually { theirs.state.first { it.receiveAddress != null } } - eventually { electrum.pay(GroupWalletDerivation.derive(other, 0, 0).pubkeyScript, Satoshi(50_000)) } - - eventually { theirs.state.first { it.confirmedBalance == Satoshi(50_000) } } - val state = eventually { ours.state.first { it.receiveAddress != null } } - assertTrue(state.utxos.isEmpty()) - assertNull(state.derivationOf(GroupWalletDerivation.derive(other, 0, 0).pubkeyScript), "another group's address is not ours to vouch for") - } - - @Test - fun `confirmations follow the tip`() { - val electrum = FakeElectrum() - val wallet = GroupOnchainWallet(account, electrum, scope) - - eventually { wallet.state.first { it.receiveAddress != null } } - eventually { electrum.pay(receive(0).pubkeyScript, Satoshi(25_000), height = 100) } - eventually { electrum.notifications.emit(HeaderSubscriptionResponse(105, Block.RegtestGenesisBlock.header)) } - - val state = eventually { wallet.state.first { it.tipHeight == 105 && it.utxos.isNotEmpty() } } - assertEquals(6, state.confirmations(state.utxos.single())) - } - - @Test - fun `the receive branch is watched past the first unused address`() { - val electrum = FakeElectrum() - GroupOnchainWallet(account, electrum, scope).let { wallet -> - eventually { wallet.state.first { it.receive.addresses.size == GroupOnchainWallet.RECEIVE_LOOKAHEAD.toInt() } } - } - assertTrue(FakeElectrum.scriptHash(receive(9).pubkeyScript) in electrum.subscribed) - } - - @Test - fun `every change address an open spend can be given is one the wallet watches`() { - val electrum = FakeElectrum() - val wallet = GroupOnchainWallet(account, electrum, scope) - val lookAhead = GroupOnchainWallet.CHANGE_LOOKAHEAD.toLong() - - val state = eventually { wallet.state.first { it.change.addresses.size == lookAhead.toInt() } } - assertTrue(FakeElectrum.scriptHash(change(lookAhead - 1).pubkeyScript) in electrum.subscribed) - - // Each open spend holds the next; the one after the last has nowhere watched to go. - val held = (0 until lookAhead).toSet() - assertEquals(lookAhead - 1, state.nextChangeIndex(held - (lookAhead - 1))) - assertEquals(null, state.nextChangeIndex(held)) - } - - private fun GroupWalletState.listed(): List>? = - receiveAddresses?.map { it.derivation.index to it.status } - - @Test - fun `a fresh wallet lists the current address and the two after it`() { - val wallet = GroupOnchainWallet(account, FakeElectrum(), scope) - - val state = eventually { wallet.state.first { it.receiveAddresses != null } } - assertEquals( - listOf(2L to GroupAddress.Status.NEXT, 1L to GroupAddress.Status.NEXT, 0L to GroupAddress.Status.CURRENT), - state.listed(), - ) - assertEquals(state.receiveAddress, state.receiveAddresses!!.last().address, "the current row is the address the wallet screen shows") - } - - @Test - fun `a paid address stays in the list and the list moves on with it`() { - val electrum = FakeElectrum() - val wallet = GroupOnchainWallet(account, electrum, scope) - - eventually { wallet.state.first { it.receiveAddresses != null } } - eventually { electrum.pay(receive(0).pubkeyScript, Satoshi(25_000)) } - - val state = eventually { wallet.state.first { it.receiveAddress == receive(1).address(Chain.Regtest) } } - assertEquals( - listOf( - 3L to GroupAddress.Status.NEXT, - 2L to GroupAddress.Status.NEXT, - 1L to GroupAddress.Status.CURRENT, - 0L to GroupAddress.Status.USED, - ), - state.listed(), - ) - assertEquals(Satoshi(25_000), state.receiveAddresses!!.last().balance) - } - - @Test - fun `a paid address that has been spent from is still used`() { - val electrum = FakeElectrum() - val wallet = GroupOnchainWallet(account, electrum, scope) - - eventually { wallet.state.first { it.receiveAddresses != null } } - eventually { electrum.pay(receive(0).pubkeyScript, Satoshi(25_000)) } - eventually { wallet.state.first { it.receiveAddress == receive(1).address(Chain.Regtest) } } - eventually { electrum.spend(receive(0).pubkeyScript) } - - val state = eventually { wallet.state.first { it.utxos.isEmpty() && it.receiveAddresses != null } } - val spent = state.receiveAddresses!!.single { it.derivation.index == 0L } - assertEquals(GroupAddress.Status.USED, spent.status) - assertEquals(Satoshi(0), spent.balance) - assertEquals(receive(1).address(Chain.Regtest), state.receiveAddress, "an emptied address is not handed out again") - } - - @Test - fun `a payment past the current address is listed however far up it is`() { - val electrum = FakeElectrum() - val wallet = GroupOnchainWallet(account, electrum, scope) - - eventually { wallet.state.first { it.receiveAddresses != null } } - eventually { electrum.pay(receive(6).pubkeyScript, Satoshi(10_000)) } - - val state = eventually { wallet.state.first { it.receiveAddresses?.any { it.status == GroupAddress.Status.USED } == true } } - assertEquals( - listOf(6L to GroupAddress.Status.USED) + - (5L downTo 1L).map { it to GroupAddress.Status.NEXT } + - listOf(0L to GroupAddress.Status.CURRENT), - state.listed(), - "the lowest unused address is still the current one", - ) - } - - @Test - fun `every listed address is one the wallet watches`() { - val electrum = FakeElectrum() - val wallet = GroupOnchainWallet(account, electrum, scope) - - eventually { wallet.state.first { it.receiveAddresses != null } } - eventually { electrum.pay(receive(0).pubkeyScript, Satoshi(1_000)) } - eventually { electrum.pay(receive(1).pubkeyScript, Satoshi(1_000)) } - - val state = eventually { wallet.state.first { it.receiveAddress == receive(2).address(Chain.Regtest) } } - val watched = state.receive.addresses.keys - state.receiveAddresses!!.forEach { assertTrue(it.address in watched, "${it.derivation.index} is listed but not watched") } - } - - @Test - fun `change addresses are never listed for receiving`() { - val electrum = FakeElectrum() - val wallet = GroupOnchainWallet(account, electrum, scope) - - eventually { wallet.state.first { it.nextChangeIndex() == 0L } } - eventually { electrum.pay(change(0).pubkeyScript, Satoshi(7_000)) } - - val state = eventually { wallet.state.first { it.nextChangeIndex() == 1L && it.receiveAddresses != null } } - assertTrue(state.receiveAddresses!!.none { it.address == change(0).address(Chain.Regtest) }) - assertTrue(state.receiveAddresses!!.all { it.derivation.change == GroupWalletDerivation.RECEIVE }) - } - - @Test - fun `a wallet that has never sent lists no change addresses`() { - val wallet = GroupOnchainWallet(account, FakeElectrum(), scope) - - val state = eventually { wallet.state.first { it.changeAddresses != null } } - assertEquals(emptyList(), state.changeAddresses, "unused change is never offered, not even as the next one") - } - - @Test - fun `used change addresses are listed and the receive list is untouched`() { - val electrum = FakeElectrum() - val wallet = GroupOnchainWallet(account, electrum, scope) - - val before = eventually { wallet.state.first { it.receiveAddresses != null && it.changeAddresses != null } } - eventually { electrum.pay(change(0).pubkeyScript, Satoshi(7_000)) } - - val state = eventually { wallet.state.first { it.changeAddresses?.isNotEmpty() == true } } - val used = state.changeAddresses!!.single() - assertEquals(change(0), used.derivation) - assertEquals(GroupAddress.Status.USED, used.status) - assertEquals(Satoshi(7_000), used.balance) - assertEquals(before.listed(), state.listed()) - } - - @Test - fun `a fresh wallet is funded two past the current address`() { - val wallet = GroupOnchainWallet(account, FakeElectrum(), scope) - - val state = eventually { wallet.state.first { it.receive.addresses.size == GroupOnchainWallet.RECEIVE_LOOKAHEAD.toInt() } } - val funding = state.fundingAddress()!! - assertEquals(receive(2), funding.derivation) - assertEquals(receive(2).address(Chain.Regtest), funding.address) - assertEquals(GroupAddress.Status.NEXT, funding.status) - } - - @Test - fun `an open funding holds its address and the window ends where the watching does`() { - val wallet = GroupOnchainWallet(account, FakeElectrum(), scope) - val lookAhead = GroupOnchainWallet.RECEIVE_LOOKAHEAD.toLong() - - val state = eventually { wallet.state.first { it.receive.addresses.size == lookAhead.toInt() } } - assertEquals(receive(3), state.fundingAddress(setOf(2L))!!.derivation) - val held = (GroupOnchainWallet.ADDRESSES_AHEAD.toLong() until lookAhead).toSet() - assertEquals(receive(lookAhead - 1), state.fundingAddress(held - (lookAhead - 1))!!.derivation) - assertNull(state.fundingAddress(held), "past the last watched address the child would not see the payment") - } - - @Test - fun `being paid moves the funding address on`() { - val electrum = FakeElectrum() - val wallet = GroupOnchainWallet(account, electrum, scope) - - eventually { wallet.state.first { it.receiveAddress != null } } - eventually { electrum.pay(receive(0).pubkeyScript, Satoshi(25_000)) } - - val state = eventually { wallet.state.first { it.receiveAddress == receive(1).address(Chain.Regtest) } } - assertEquals(receive(3), state.fundingAddress()!!.derivation) - } - - @Test - fun `a paid address above the current one is never funded`() { - val electrum = FakeElectrum() - val wallet = GroupOnchainWallet(account, electrum, scope) - - eventually { wallet.state.first { it.receiveAddress != null } } - eventually { electrum.pay(receive(4).pubkeyScript, Satoshi(10_000)) } - - val state = eventually { wallet.state.first { it.receiveAddresses?.any { it.status == GroupAddress.Status.USED } == true } } - assertEquals(receive(0).address(Chain.Regtest), state.receiveAddress) - assertEquals(receive(2), state.fundingAddress()!!.derivation) - assertEquals(receive(3), state.fundingAddress(setOf(2L))!!.derivation) - assertEquals(receive(5), state.fundingAddress(setOf(2L, 3L))!!.derivation) - } - - @Test - fun `no funding address before Electrum has answered`() { - val state = GroupWalletState(account, WalletState.empty, WalletState.empty, tipHeight = null) - assertNull(state.fundingAddress()) - } - - @Test - fun `every funding address is one the wallet watches`() { - val electrum = FakeElectrum() - val wallet = GroupOnchainWallet(account, electrum, scope) - - eventually { wallet.state.first { it.receiveAddress != null } } - eventually { electrum.pay(receive(0).pubkeyScript, Satoshi(1_000)) } - - val state = eventually { wallet.state.first { it.receiveAddress == receive(1).address(Chain.Regtest) } } - val watched = state.receive.addresses.keys - var reserved = emptySet() - while (true) { - val funding = state.fundingAddress(reserved) ?: break - assertTrue(funding.address in watched, "${funding.derivation.index} is funded but not watched") - reserved = reserved + funding.derivation.index - } - assertEquals(GroupOnchainWallet.RECEIVE_LOOKAHEAD.toInt() - GroupOnchainWallet.ADDRESSES_AHEAD, reserved.size) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/GroupTransactionWatcherJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/GroupTransactionWatcherJvmTest.kt deleted file mode 100644 index fab9fc3e..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/GroupTransactionWatcherJvmTest.kt +++ /dev/null @@ -1,271 +0,0 @@ -package mobi.giza.compose.wallet - -import androidx.room3.Room -import mobi.giza.compose.database.GizaDatabase -import mobi.giza.compose.database.builder.getRoomDatabase -import mobi.giza.compose.database.model.ChatMessage -import mobi.giza.compose.database.model.ChatRoom -import mobi.giza.compose.database.model.FrostSigningSession -import mobi.giza.compose.database.model.GroupTransaction -import mobi.giza.compose.database.model.NostrEvent -import mobi.giza.compose.database.model.Profile -import mobi.giza.compose.database.model.types.FrostSigningStage -import mobi.giza.compose.database.model.types.FrostSigningSubject -import com.vitorpamplona.quartz.nip01Core.core.toHexKey -import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair -import fr.acinq.bitcoin.Block -import fr.acinq.bitcoin.BlockHeader -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.OutPoint -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.bitcoin.psbt.Psbt -import fr.acinq.lightning.blockchain.electrum.ElectrumConnectionStatus -import fr.acinq.lightning.blockchain.electrum.ElectrumSubscriptionResponse -import fr.acinq.lightning.blockchain.electrum.GetMerkleResponse -import fr.acinq.lightning.blockchain.electrum.HeaderSubscriptionResponse -import fr.acinq.lightning.blockchain.electrum.IElectrumClient -import fr.acinq.lightning.blockchain.electrum.ScriptHashSubscriptionResponse -import fr.acinq.lightning.blockchain.electrum.TransactionHistoryItem -import fr.acinq.lightning.blockchain.electrum.UnspentItem -import fr.acinq.lightning.blockchain.fee.FeeratePerKw -import fr.acinq.secp256k1.Hex -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.flow.MutableSharedFlow -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.runBlocking -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertNotNull -import kotlin.test.assertNull -import kotlin.test.assertTrue -import kotlin.time.Duration.Companion.minutes -import kotlin.time.Instant - -/** - * What happens to a signed spend after the group signed it: it is sent, sent - * again while nobody has seen it, and -- once it confirms -- settles every other - * spend of the same coins. - */ -class GroupTransactionWatcherJvmTest { - private class FakeElectrum : IElectrumClient { - val broadcasts = mutableListOf() - /** Confirmations by txid; absent is "Electrum has not heard of it". */ - val confirmations = mutableMapOf() - /** What each script hash still holds, has seen, and the transactions behind both. */ - val unspents = mutableMapOf>() - val histories = mutableMapOf>() - val txs = mutableMapOf() - - override val notifications = MutableSharedFlow() - override val connectionStatus: StateFlow = MutableStateFlow(ElectrumConnectionStatus.Closed(null)) - override suspend fun broadcastTransaction(tx: Transaction): TxId = tx.txid.also { broadcasts += it } - override suspend fun getConfirmations(tx: Transaction): Int? = confirmations[tx.txid] - override suspend fun getTx(txId: TxId): Transaction? = txs[txId] - override suspend fun getHeader(blockHeight: Int): BlockHeader? = null - override suspend fun getHeaders(startHeight: Int, count: Int): List = emptyList() - override suspend fun getMerkle(txId: TxId, blockHeight: Int, contextOpt: Transaction?): GetMerkleResponse? = null - override suspend fun getScriptHashHistory(scriptHash: ByteVector32): List = histories[scriptHash].orEmpty() - override suspend fun getScriptHashUnspents(scriptHash: ByteVector32): List = unspents[scriptHash].orEmpty() - override suspend fun estimateFees(confirmations: Int): FeeratePerKw? = null - override suspend fun startScriptHashSubscription(scriptHash: ByteVector32) = ScriptHashSubscriptionResponse(scriptHash, null) - override suspend fun startHeaderSubscription() = HeaderSubscriptionResponse(0, Block.RegtestGenesisBlock.header) - } - - private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) - private val electrum = FakeElectrum() - private var clock = Instant.fromEpochSeconds(1_700_000_000) - private val watcher = GroupTransactionWatcher(db, electrum, CoroutineScope(Dispatchers.Default), now = { clock }) - - @AfterTest - fun close() = db.close() - - private val user = KeyPair().pubKey.toHexKey() - private val room = "11".repeat(32) - - /** The coin every spend below wants. */ - private val coin = OutPoint(TxId(ByteVector32(ByteArray(32) { 3 })), 0) - - private fun spending(vararg coins: OutPoint, pay: Long) = Transaction( - 2, coins.map { TxIn(it, ByteVector.empty, 0xfffffffdL) }, listOf(TxOut(Satoshi(pay), ByteVector("0014" + "00".repeat(20)))), 0, - ) - - private suspend fun seed() { - val eventId = "c".repeat(64) - db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = user, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) - db.profileDao().upsert(Profile(publicKey = user, userName = "user", nostrEventId = eventId)) - db.chatRoomDao().upsert(ChatRoom(id = room, userPublicKey = user, subject = null, description = null, mlsGroupState = "00")) - } - - private suspend fun spend(id: String, tx: Transaction, stage: FrostSigningStage, signed: Boolean, chain: String = "regtest") { - db.frostSigningSessionDao().upsert( - FrostSigningSession( - id = id, chatRoomId = room, coordinatorPublicKey = user, userPublicKey = user, dkgSessionId = "dkg", - threshold = 2, participantCount = 3, signerId = 0, stage = stage, subject = FrostSigningSubject.TRANSACTION, - ) - ) - db.groupTransactionDao().insertIfAbsent( - GroupTransaction( - frostSigningSessionId = id, chatRoomId = room, chain = chain, account = 0, - psbt = GroupSpend.encode(Psbt(tx)), txid = tx.txid.toString(), - signedTransaction = if (signed) Hex.encode(Transaction.write(tx)) else null, - ) - ) - } - - @Test - fun `each spend goes out on its own network's connection`() = runBlocking { - // A group with wallets on two networks: the node's, and the test network a Lightning wallet is - // tried on. Each signed spend must reach the network it spends on, and only that one. - seed() - val testnet = FakeElectrum() - val clients = GroupChainClients(fr.acinq.bitcoin.Chain.Regtest, electrum) { GroupChainClients.Connection(testnet) {} } - val watcher = GroupTransactionWatcher(db, clients, CoroutineScope(Dispatchers.Default), now = { clock }) - val onNode = spending(coin, pay = 9_000) - val onTestnet = spending(OutPoint(TxId(ByteVector32(ByteArray(32) { 4 })), 0), pay = 8_000) - spend("a", onNode, FrostSigningStage.COMPLETE, signed = true) - spend("b", onTestnet, FrostSigningStage.COMPLETE, signed = true, chain = "testnet3") - watcher.pass() - assertEquals(listOf(onNode.txid), electrum.broadcasts) - assertEquals(listOf(onTestnet.txid), testnet.broadcasts) - } - - @Test - fun `a spend on a network nobody named is left alone`() = runBlocking { - seed() - spend("a", spending(coin, pay = 9_000), FrostSigningStage.COMPLETE, signed = true, chain = "litecoin") - watcher.pass() - assertTrue(electrum.broadcasts.isEmpty()) - } - - @Test - fun `a signed spend is sent, and sent again while nobody has seen it`() = runBlocking { - seed() - val tx = spending(coin, pay = 9_000) - spend("a", tx, FrostSigningStage.COMPLETE, signed = true) - - watcher.pass() - watcher.pass() - assertEquals(listOf(tx.txid), electrum.broadcasts, "not again inside the interval") - - clock += 11.minutes - watcher.pass() - assertEquals(2, electrum.broadcasts.size, "sent again once the interval has passed, still unseen") - - electrum.confirmations[tx.txid] = 0 - watcher.pass() - val seen = assertNotNull(db.groupTransactionDao().getBySessionId("a")) - assertNotNull(seen.seenAt, "in the mempool is seen") - assertNull(seen.confirmedAt) - - clock += 11.minutes - watcher.pass() - assertEquals(2, electrum.broadcasts.size, "a seen transaction is not sent again") - } - - @Test - fun `a confirmation settles every other spend of the same coins`() = runBlocking { - seed() - val winner = spending(coin, pay = 9_000) - spend("winner", winner, FrostSigningStage.COMPLETE, signed = true) - // A bump of the same coins, signed but beaten to the block. - val replaced = spending(coin, pay = 8_000) - spend("replaced", replaced, FrostSigningStage.COMPLETE, signed = true) - // A third spend of the coin, still collecting signatures. - spend("collecting", spending(coin, OutPoint(TxId(ByteVector32(ByteArray(32) { 4 })), 0), pay = 15_000), FrostSigningStage.COLLECTING_NONCES, signed = false) - // And one of some other coin, which none of this touches. - spend("unrelated", spending(OutPoint(TxId(ByteVector32(ByteArray(32) { 5 })), 1), pay = 1_000), FrostSigningStage.COLLECTING_NONCES, signed = false) - - electrum.confirmations[winner.txid] = 1 - watcher.pass() - - assertNotNull(db.groupTransactionDao().getBySessionId("winner")?.confirmedAt) - assertEquals(winner.txid.toString(), db.groupTransactionDao().getBySessionId("replaced")?.replacedByTxid) - assertEquals(FrostSigningStage.COMPLETE, db.frostSigningSessionDao().getSessionById("replaced")?.stage, "a signed spend is not reported as failed") - db.frostSigningSessionDao().getSessionById("collecting")!!.let { - assertEquals(FrostSigningStage.FAILED, it.stage) - assertEquals("Spent by another transaction", it.failureReason) - } - assertEquals(FrostSigningStage.COLLECTING_NONCES, db.frostSigningSessionDao().getSessionById("unrelated")?.stage) - - // Once, however many passes see it. - watcher.pass() - val lines = db.chatMessageDao().getChatMessagesByChatRoomId(room) - .filter { it.chatMessage.messageType == ChatMessage.TYPE_GROUP_TRANSACTION_CONFIRMED } - assertEquals(1, lines.size) - assertTrue(db.groupTransactionDao().getUnsettled().isEmpty(), "neither signed spend is still on its way") - } - - // ---- Coins another room's transaction took ------------------------------ - - /** The script the guarded coin sits at, and its Electrum script hash. */ - private val coinScript = ByteVector("5120" + "ab".repeat(32)) - private val coinHash = ByteVector32(fr.acinq.bitcoin.Crypto.sha256(coinScript.toByteArray()).reversedArray()) - - /** A signed spend of [coin] whose PSBT names the output it spends, as every real proposal's does. */ - private suspend fun signedSpendOfCoin(id: String, tx: Transaction) { - db.frostSigningSessionDao().upsert( - FrostSigningSession( - id = id, chatRoomId = room, coordinatorPublicKey = user, userPublicKey = user, dkgSessionId = "dkg", - threshold = 2, participantCount = 3, signerId = 0, stage = FrostSigningStage.COMPLETE, subject = FrostSigningSubject.TRANSACTION, - ) - ) - val psbt = Psbt(tx).updateWitnessInput(coin, TxOut(Satoshi(10_000), coinScript)).right!! - db.groupTransactionDao().insertIfAbsent( - GroupTransaction( - frostSigningSessionId = id, chatRoomId = room, chain = "regtest", account = 0, - psbt = GroupSpend.encode(psbt), txid = tx.txid.toString(), signedTransaction = Hex.encode(Transaction.write(tx)), - ) - ) - } - - /** Somebody else -- a guardian, or the guarded group itself -- spends [coin], at [height] (0 for the mempool). */ - private fun takenElsewhere(height: Int): Transaction { - val theirs = spending(coin, pay = 7_000).copy(txOut = listOf(TxOut(Satoshi(7_000), ByteVector("0014" + "11".repeat(20))))) - electrum.txs[theirs.txid] = theirs - electrum.histories[coinHash] = listOf(TransactionHistoryItem(90, coin.txid), TransactionHistoryItem(height, theirs.txid)) - return theirs - } - - @Test - fun `a spend whose coin another transaction took is replaced once that transaction confirms`(): Unit = runBlocking { - seed() - val ours = spending(coin, pay = 9_000) - signedSpendOfCoin("ours", ours) - // Another of this room's spends of the same coin, still collecting. - spend("collecting", spending(coin, OutPoint(TxId(ByteVector32(ByteArray(32) { 6 })), 0), pay = 12_000), FrostSigningStage.COLLECTING_NONCES, signed = false) - - val theirs = takenElsewhere(height = 101) - watcher.pass() - - assertEquals(theirs.txid.toString(), db.groupTransactionDao().getBySessionId("ours")?.replacedByTxid) - assertEquals(FrostSigningStage.COMPLETE, db.frostSigningSessionDao().getSessionById("ours")?.stage, "it was signed, and stays so") - assertEquals(FrostSigningStage.FAILED, db.frostSigningSessionDao().getSessionById("collecting")?.stage) - assertTrue(db.groupTransactionDao().getUnsettled().isEmpty(), "nothing is left being sent again every ten minutes") - } - - @Test - fun `a coin taken only in the mempool, or not taken at all, settles nothing`(): Unit = runBlocking { - seed() - signedSpendOfCoin("ours", spending(coin, pay = 9_000)) - - // Still unspent where it sits. - electrum.unspents[coinHash] = listOf(UnspentItem(coin.txid, coin.index.toInt(), 10_000, 90)) - electrum.histories[coinHash] = listOf(TransactionHistoryItem(90, coin.txid)) - watcher.pass() - assertNull(db.groupTransactionDao().getBySessionId("ours")?.replacedByTxid) - - // Spent by something unconfirmed: ours may yet be the one that confirms. - electrum.unspents.remove(coinHash) - takenElsewhere(height = 0) - watcher.pass() - assertNull(db.groupTransactionDao().getBySessionId("ours")?.replacedByTxid) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/GuardianSpendNoticeJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/GuardianSpendNoticeJvmTest.kt deleted file mode 100644 index b149ec67..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/GuardianSpendNoticeJvmTest.kt +++ /dev/null @@ -1,91 +0,0 @@ -package mobi.giza.compose.wallet - -import mobi.giza.compose.managers.GroupWalletDerivation -import mobi.giza.compose.managers.GuardianDerivation -import mobi.giza.compose.managers.GuardianManager -import mobi.giza.compose.managers.SharedKeyDerivation -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.OutPoint -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.Satoshi -import fr.acinq.bitcoin.Script -import fr.acinq.bitcoin.ScriptWitness -import fr.acinq.bitcoin.Transaction -import fr.acinq.bitcoin.TxIn -import fr.acinq.bitcoin.TxOut -import fr.acinq.lightning.blockchain.electrum.WalletState -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.cancel -import kotlinx.coroutines.runBlocking -import kotlin.test.AfterTest -import kotlin.test.Test -import kotlin.test.assertEquals - -/** - * A guarded wallet reading its own history for spends its guardians made -- - * the child's only notice of one, since nobody in its room signed it. - * - * The witnesses here are the right shape and carry no valid signature: what is - * under test is which leaf a spend used, which the chain records whether or not - * anybody checks the signature again. `GuardianSigningJvmTest` spends for real. - */ -class GuardianSpendNoticeJvmTest { - private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) - - @AfterTest - fun stop() = scope.cancel() - - private fun key(seed: Int): String = PrivateKey(ByteVector32(ByteArray(32) { seed.toByte() })).publicKey().toString() - - private val chain = Chain.Regtest - private val parentRoom = SharedKeyDerivation.marmotGroupId(key(1)) - private val childKey = key(2) - private val childRoom = SharedKeyDerivation.marmotGroupId(childKey) - private val grant = GuardianDerivation.grant(key(1), parentRoom, emptyList(), childRoom) - private val account = GroupWalletDerivation.account(childKey, chain, guardians = grant) - private val coin = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, 0) - private val elsewhere = ByteVector(Script.write(Script.pay2wpkh(PrivateKey(ByteVector32(ByteArray(32) { 9 })).publicKey()))) - - /** The wallet after its one coin has been spent: the address used, nothing left on it. */ - private val spentState = GroupWalletState( - account, - WalletState(mapOf(coin.address(chain) to WalletState.AddressState(WalletState.AddressMeta.Derived(0), alreadyUsed = true, utxos = emptyList()))), - WalletState(emptyMap()), - tipHeight = 200, - ) - - private fun spending(funding: Transaction, witness: ScriptWitness) = Transaction( - 2, listOf(TxIn(OutPoint(funding, 0), ByteVector.empty, GuardianDerivation.DEFAULT_DELAY, witness)), - listOf(TxOut(Satoshi(49_000), elsewhere)), 0, - ) - - @Test - fun `a spend through the parent's leaf is read off the address's history`(): Unit = runBlocking { - val electrum = FakeElectrum() - electrum.pay(coin.pubkeyScript, Satoshi(50_000)) - val funding = electrum.fundingOf(coin.pubkeyScript) - val leaf = GuardianDerivation.leaves(grant, chain, 0, coin.change, coin.index)[0] - val taken = spending(funding, Script.witnessScriptPathPay2tr(coin.internalKey, leaf, ScriptWitness(listOf(ByteVector(ByteArray(64)))), coin.tree!!)) - electrum.spendWith(coin.pubkeyScript, taken) - - val wallets = GroupOnchainWallets(electrum, scope) - assertEquals( - listOf(GuardianManager.Taken(taken.txid, grant[0], Satoshi(50_000))), - wallets.guardianSpends(spentState), - ) - } - - @Test - fun `the group's own key-path spend names no guardian`(): Unit = runBlocking { - val electrum = FakeElectrum() - electrum.pay(coin.pubkeyScript, Satoshi(50_000)) - val own = spending(electrum.fundingOf(coin.pubkeyScript), Script.witnessKeyPathPay2tr(fr.acinq.bitcoin.ByteVector64.Zeroes)) - electrum.spendWith(coin.pubkeyScript, own) - - assertEquals(emptyList(), GroupOnchainWallets(electrum, scope).guardianSpends(spentState)) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/IdentityElectrumJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/IdentityElectrumJvmTest.kt deleted file mode 100644 index eb88a769..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/IdentityElectrumJvmTest.kt +++ /dev/null @@ -1,137 +0,0 @@ -package mobi.giza.compose.wallet - -import androidx.datastore.preferences.core.PreferenceDataStoreFactory -import mobi.giza.compose.identity.Identity -import mobi.giza.compose.identity.IdentityKind -import mobi.giza.compose.identity.toWalletId -import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.byteVector32 -import fr.acinq.lightning.utils.ServerAddress -import fr.acinq.phoenix.managers.global.NetworkState -import fr.acinq.phoenix.managers.nostrPublicKeyHex -import fr.acinq.phoenix.utils.preferences.InternalPrefs -import fr.acinq.phoenix.utils.preferences.UserPrefs -import kotlinx.coroutines.flow.flowOf -import okio.Path.Companion.toPath -import org.junit.Rule -import org.junit.rules.TemporaryFolder -import kotlin.random.Random -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertNotSame -import kotlin.test.assertNull -import kotlin.test.assertSame -import kotlin.test.assertTrue -import kotlin.time.Duration - -/** - * Which client each kind of identity watches on, and that a switch never leaves - * the last profile's connection open (D1 of `docs/standalone-electrum.md`). - */ -class IdentityElectrumJvmTest { - @get:Rule - val temporaryFolder = TemporaryFolder() - - /** Never connects: the network is down. What is under test is which client is made, and when it is stopped. */ - private class IdleLink : ElectrumLink { - override val client = FakeElectrum() - var stopped = false - override suspend fun connect(server: ServerAddress, timeout: Duration) {} - override fun disconnect() {} - override fun stop() { - stopped = true - } - } - - private val made = mutableListOf>() - - /** For each client made, whether every one made before it had been stopped by then. */ - private val earlierStopped = mutableListOf() - - private val identityElectrum = IdentityElectrum { identity -> - earlierStopped += made.all { it.second.stopped } - val link = IdleLink() - made += identity to link - StandaloneElectrum( - chain = Chain.Regtest, - networkState = flowOf(NetworkState.NotAvailable), - isTorEnabled = flowOf(false), - customServer = flowOf(null), - link = link, - ) - } - - private fun prefsStore() = PreferenceDataStoreFactory.createWithPath { - temporaryFolder.newFolder().resolve("prefs.preferences_pb").path.toPath() - } - - private fun key() = PrivateKey(Random.nextBytes(32).byteVector32()) - - private fun signing(kind: IdentityKind, key: PrivateKey = key()) = Identity.signing( - id = key.publicKey().xOnly().toWalletId(), - kind = kind, - nostrPrivateKey = key, - userPrefs = UserPrefs(prefsStore()), - internalPrefs = InternalPrefs(prefsStore()), - business = null, - ) - - private fun readOnly(key: PrivateKey = key()) = Identity.readOnly( - id = key.publicKey().xOnly().toWalletId(), - nostrPublicKey = key.nostrPublicKeyHex(), - userPrefs = UserPrefs(prefsStore()), - internalPrefs = InternalPrefs(prefsStore()), - ) - - @Test - fun `a profile with a node watches on the node's client, and no other is made`() { - val node = FakeElectrum() - val client = identityElectrum.clientFor(signing(IdentityKind.Mnemonic), nodeClient = node) - assertSame(node, client) - assertEquals(emptyList(), made) - } - - @Test - fun `an nsec profile and an npub profile each get a client of their own`() { - val nsec = signing(IdentityKind.NostrSecret) - val nsecClient = identityElectrum.clientFor(nsec) - assertSame(made.single { it.first == nsec }.second.client, nsecClient) - - val npub = readOnly() - val npubClient = identityElectrum.clientFor(npub) - assertSame(made.single { it.first == npub }.second.client, npubClient) - } - - @Test - fun `the same identity asked again keeps its client`() { - val nsec = signing(IdentityKind.NostrSecret) - val first = identityElectrum.clientFor(nsec) - assertSame(first, identityElectrum.clientFor(nsec)) - assertEquals(1, made.size) - } - - @Test - fun `switching from one nsec to another stops the first before the second is made`() { - val firstClient = identityElectrum.clientFor(signing(IdentityKind.NostrSecret)) - val secondClient = identityElectrum.clientFor(signing(IdentityKind.NostrSecret)) - - assertEquals(listOf(true, true), earlierStopped) - assertNotSame(firstClient, secondClient) - assertEquals(listOf(true, false), made.map { it.second.stopped }) - } - - @Test - fun `switching to a profile with a node stops the standalone client`() { - identityElectrum.clientFor(signing(IdentityKind.NostrSecret)) - identityElectrum.clientFor(signing(IdentityKind.Mnemonic), nodeClient = FakeElectrum()) - assertTrue(made.single().second.stopped) - } - - @Test - fun `no identity has no client, and the last one is stopped`() { - identityElectrum.clientFor(signing(IdentityKind.NostrSecret)) - assertNull(identityElectrum.clientFor(null)) - assertTrue(made.single().second.stopped) - } -} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/StandaloneElectrumJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/StandaloneElectrumJvmTest.kt deleted file mode 100644 index b7624509..00000000 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/wallet/StandaloneElectrumJvmTest.kt +++ /dev/null @@ -1,180 +0,0 @@ -package mobi.giza.compose.wallet - -import fr.acinq.bitcoin.Block -import fr.acinq.bitcoin.Chain -import fr.acinq.lightning.blockchain.electrum.ElectrumConnectionStatus -import fr.acinq.lightning.blockchain.electrum.ServerVersionResponse -import fr.acinq.lightning.io.TcpSocket -import fr.acinq.lightning.utils.ServerAddress -import fr.acinq.phoenix.data.ElectrumConfig -import fr.acinq.phoenix.managers.global.NetworkState -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.test.StandardTestDispatcher -import kotlinx.coroutines.test.TestScope -import kotlinx.coroutines.test.advanceTimeBy -import kotlinx.coroutines.test.runCurrent -import kotlinx.coroutines.test.runTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertTrue -import kotlin.time.Duration -import kotlin.time.Duration.Companion.seconds - -/** - * The connection loop of a profile with no node, against a link whose connection - * status the test moves. No socket is opened: the loop's job is to decide when to - * connect and to where, and that is all it is asked here. - */ -class StandaloneElectrumJvmTest { - private class FakeLink : ElectrumLink { - override val client = FakeElectrum() - val attempts = mutableListOf>() - var succeeds = true - var stopped = false - - override suspend fun connect(server: ServerAddress, timeout: Duration) { - attempts += server to timeout - client.connectionStatus.value = ElectrumConnectionStatus.Connecting(server) - client.connectionStatus.value = if (succeeds) { - ElectrumConnectionStatus.Connected(ServerVersionResponse("fake", "1.4"), 0, Block.RegtestGenesisBlock.header) - } else { - // A fresh exception each time, as the real client makes: two closes in a - // row are then two values, not one the StateFlow swallows. - ElectrumConnectionStatus.Closed(TcpSocket.IOException.ConnectionRefused()) - } - } - - /** The server hanging up, as the client's listen job reports it. */ - fun drop() { - client.connectionStatus.value = ElectrumConnectionStatus.Closed(TcpSocket.IOException.ConnectionRefused()) - } - - override fun disconnect() { - client.connectionStatus.value = ElectrumConnectionStatus.Closed(null) - } - - override fun stop() { - stopped = true - } - } - - private val random = ServerAddress("random.example", 50002, TcpSocket.TLS.TRUSTED_CERTIFICATES()) - private val onion = ServerAddress("onionaddressexample.onion", 50001, TcpSocket.TLS.DISABLED) - private val custom = ElectrumConfig.Custom.create(ServerAddress("mine.example", 50002, TcpSocket.TLS.TRUSTED_CERTIFICATES()), requireOnionIfTorEnabled = true) - - private val network = MutableStateFlow(NetworkState.Available) - private val tor = MutableStateFlow(false) - private val customServer = MutableStateFlow(null) - private val link = FakeLink() - - private fun TestScope.electrum() = StandaloneElectrum( - chain = Chain.Testnet3, - networkState = network, - isTorEnabled = tor, - customServer = customServer, - link = link, - randomServer = { _, torIsEnabled -> if (torIsEnabled) onion else random }, - context = StandardTestDispatcher(testScheduler), - ) - - @Test - fun `with no custom server, a random one for the network is used`() = runTest { - val electrum = electrum().also { it.start() } - advanceTimeBy(1.seconds) - assertEquals(listOf(random), link.attempts.map { it.first }) - electrum.stop() - } - - @Test - fun `a custom server is used when one is set, and setting one reconnects`() = runTest { - val electrum = electrum().also { it.start() } - advanceTimeBy(1.seconds) - customServer.value = custom - advanceTimeBy(1.seconds) - assertEquals(listOf(random, custom.server), link.attempts.map { it.first }) - electrum.stop() - } - - @Test - fun `a closed connection is retried after a pause that grows, and a connection resets it`() = runTest { - link.succeeds = false - val electrum = electrum().also { it.start() } - // 0.1 + 0.25 + 0.5 + 1 seconds: four attempts, the fifth two seconds off. - advanceTimeBy(1.9.seconds) - // And the handshake is given longer once three have failed. - assertEquals(listOf(4.seconds, 4.seconds, 4.seconds, 7.seconds), link.attempts.map { it.second }) - - link.succeeds = true - advanceTimeBy(2.seconds) - assertEquals(5, link.attempts.size) - - // Connected, so the count starts again: the next drop is retried after a tenth of a second. - link.drop() - advanceTimeBy(0.2.seconds) - assertEquals(6, link.attempts.size) - electrum.stop() - } - - @Test - fun `losing the network disconnects, and getting it back connects`() = runTest { - val electrum = electrum().also { it.start() } - advanceTimeBy(1.seconds) - network.value = NetworkState.NotAvailable - advanceTimeBy(30.seconds) - assertEquals(1, link.attempts.size) - assertTrue(link.client.connectionStatus.value is ElectrumConnectionStatus.Closed) - - network.value = NetworkState.Available - advanceTimeBy(1.seconds) - assertEquals(2, link.attempts.size) - electrum.stop() - } - - @Test - fun `with Tor on, a clearnet custom server that must be an onion is never connected to`() = runTest { - tor.value = true - customServer.value = custom - val electrum = electrum().also { it.start() } - advanceTimeBy(30.seconds) - assertEquals(emptyList(), link.attempts) - electrum.stop() - } - - @Test - fun `with Tor on and no custom server, only an onion server is tried`() = runTest { - tor.value = true - val electrum = electrum().also { it.start() } - advanceTimeBy(1.seconds) - assertEquals(listOf(onion), link.attempts.map { it.first }) - assertEquals(20.seconds, link.attempts.single().second) - electrum.stop() - } - - @Test - fun `a network with no servers is not connected to, and does not crash`() = runTest { - val electrum = StandaloneElectrum( - chain = Chain.Signet, - networkState = network, - isTorEnabled = tor, - customServer = customServer, - link = link, - context = StandardTestDispatcher(testScheduler), - ).also { it.start() } - advanceTimeBy(30.seconds) - assertEquals(emptyList(), link.attempts) - electrum.stop() - } - - @Test - fun `after stop nothing is retried, and the client is stopped`() = runTest { - link.succeeds = false - val electrum = electrum().also { it.start() } - advanceTimeBy(0.5.seconds) - val before = link.attempts.size - electrum.stop() - advanceTimeBy(60.seconds) - runCurrent() - assertEquals(before, link.attempts.size) - assertTrue(link.stopped) - } -} diff --git a/docs/giza-wallet-removal.md b/docs/giza-wallet-removal.md index 5ec1ecbc..be0eb1c2 100644 --- a/docs/giza-wallet-removal.md +++ b/docs/giza-wallet-removal.md @@ -22,7 +22,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 | -| 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 +| 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) | +| 4 | built: the on-chain wallet, its guardians and the subgroup wallet policy, together. `wallet/` (Electrum included), `nostr/wallet/`, the policy and guardian tags, `GroupWalletDerivation`, `GroupWalletManager`, `GuardianDerivation`, `GuardianManager`, `ProposedSpend`, three screens with their view models, states and routes, and FROST's spend half. Every 30332 is filed declined without being read. Certificates and ceremonies carry no wallet tag, and a guarded subgroup's ceremony is filed and not joined (W5). The last `bennu/` derivation tag is gone from the code, and with it the last wallet pins. `jvmTest` 1,148 run, 0 failed | 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. @@ -49,6 +50,10 @@ Where the build chose differently from the phases as written: | 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 | +| `FrostSigningSubject` keeps only `EVENTS` | it keeps `TRANSACTION` and `SWEEP`, which now mean *a Bennu peer's, declined on arrival*: a 30332 is still filed as a session, so `advance` can publish the decline, and the subject is what says it is a wallet's. `FrostSigningEvents.TRANSACTION_PROPOSAL` stays in `ALL` for the same reason, and `RetiredKindsTest` says why | +| `DkgSession.walletPolicy` and `guardianDelay` are dropped in Phase 5 | only `guardianDelay`. `walletPolicy` stays as the `wallet` tag a Bennu ceremony carried, raw, because the join screen reads it to say why Giza does not join a guarded subgroup's ceremony | +| `SubgroupManager.refuseKeyState` goes with the policy | it stays, as `WalletRefusal` over the certificate a key state carries; and `WalletRefusal` reads that certificate too, so such a key state is declined out loud rather than dropped | +| the `GroupKeyStateManager` gate goes | and nothing replaces it: a certificate's wallet tags decide nothing on a Giza device, so a key state is kept as it came, whatever they say | | 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