diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml
index 706392b2..6fe92099 100644
--- a/composeApp/src/commonMain/composeResources/values/strings.xml
+++ b/composeApp/src/commonMain/composeResources/values/strings.xml
@@ -639,6 +639,10 @@
This group's guardian keys can't be read by this version of the app.
Guarded wallets for members aren't offered on this network yet.
This profile has no wallet of its own to watch the chain with, so it couldn't see its own coins.
+ %1$s would refuse this request: it was asked before the group said it guards members' wallets. Asking again makes a new one.
+ %1$s has changed its delay since you asked. Asking again makes a new request at the new delay.
+ %1$s has stopped guarding members' wallets, so this request won't be signed. You can discard it.
+ %1$s would refuse this request. Asking again makes a new one.
This group doesn't guard members' wallets.
This group has stopped guarding members' wallets.
You have no guarded wallets.
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseMemberWalletRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseMemberWalletRepository.kt
index 69285390..15ea4877 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseMemberWalletRepository.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseMemberWalletRepository.kt
@@ -77,10 +77,11 @@ class DatabaseMemberWalletRepository(
null
}
- override suspend fun askAgain(walletId: String) {
+ override suspend fun askAgain(walletId: String): String {
val wallet = database.memberWalletDao().getById(walletId) ?: throw IllegalStateException("No key for $walletId here")
check(wallet.ownerPublicKey == activeIdentity.value?.nostrPublicKey) { "Not this profile's wallet" }
- MemberWalletManager.askAgain(database, wallet)
+ val key = activeIdentity.value?.nostrPrivateKey ?: throw IllegalStateException("This profile cannot sign")
+ return MemberWalletManager.askAgain(database, wallet, key).walletId
}
override suspend fun discard(walletId: String) {
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletManager.kt
index b1c45090..58b09314 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletManager.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletManager.kt
@@ -274,13 +274,31 @@ object MemberWalletManager {
}
/**
- * Asks again with the request [wallet] was asked with, unchanged -- for a
- * request no signer put to the group, or one the group did not sign.
+ * Asks again -- for a request no signer put to the group, or one the group
+ * did not sign. With the request [wallet] was asked with, unchanged, when
+ * the group would still accept it; otherwise with a new one under the
+ * group's newest policy and a new key, as the member [memberPrivateKey]
+ * holds, and the old key discarded: no address of it was ever offered.
+ * `docs/member-wallet-delay.md`, Phase 5.
+ *
+ * Returns the wallet now asked for -- [wallet] itself, or its replacement.
+ *
+ * @throws IllegalStateException when a new request is needed and this group
+ * cannot be asked now, with the [Refusal]
*/
- suspend fun askAgain(database: BennuDatabase, wallet: MemberWallet) {
+ suspend fun askAgain(database: BennuDatabase, wallet: MemberWallet, memberPrivateKey: PrivateKey): MemberWallet {
val request = Event.fromJsonOrNull(wallet.requestJson) ?: throw IllegalStateException("The stored request does not read")
- send(database, wallet.guardingChatRoomId, request)
- sponsorIfSigner(database, wallet.guardingChatRoomId, wallet.ownerPublicKey, request)
+ if (judgePolicy(database, wallet.guardingChatRoomId, request) is PolicyJudgement.At) {
+ send(database, wallet.guardingChatRoomId, request)
+ sponsorIfSigner(database, wallet.guardingChatRoomId, wallet.ownerPublicKey, request)
+ return wallet
+ }
+
+ val chain = MemberWalletRequestEvent.read(request)?.chain ?: throw IllegalStateException("The stored request does not read")
+ val replacement = request(database, wallet.guardingChatRoomId, memberPrivateKey, chain, wallet.label)
+ discard(database, wallet.walletId)
+ logger.i("Asked ${wallet.guardingChatRoomId} again for a new wallet in place of ${wallet.walletId.take(8)}")
+ return replacement
}
/**
@@ -348,6 +366,12 @@ object MemberWalletManager {
val isMember: Boolean,
/** The stored key's row, for a wallet whose key is here. Never handed to a screen. */
internal val stored: MemberWallet?,
+ /**
+ * Why the group would refuse this wallet's request as it stands, for one
+ * not yet guarded -- [judgePolicy] -- or null when it would not. Asking
+ * again then makes a new request. `docs/member-wallet-delay.md`.
+ */
+ val refusedBecause: Why? = null,
) {
val isCertified: Boolean get() = state == WalletState.OPEN || state == WalletState.WATCH_ONLY
}
@@ -376,6 +400,10 @@ object MemberWalletManager {
else -> WalletState.ASKED
}
row(database, wallet.walletId, wallet.guardingChatRoomId, wallet.label, verified.account, state, ownerPublicKey, wallet)
+ .let { row ->
+ if (row.isCertified) row
+ else row.copy(refusedBecause = (judgePolicy(database, wallet.guardingChatRoomId, request) as? PolicyJudgement.Refused)?.why)
+ }
}
val elsewhere = certified.values
.filter { cert -> stored.none { it.walletId == cert.walletId } }
@@ -552,6 +580,9 @@ object MemberWalletManager {
* The group's own wallet policy decides only which keys the grant carries.
* It never refuses a member's wallet: an unguarded group guards its members
* with its own key alone. `docs/member-guarded-wallets.md`, Phase 7.
+ *
+ * The group's *member-wallet* policy decides whether it guards one at all,
+ * and the delay on its own leaf: [judgePolicy], `docs/member-wallet-delay.md`.
*/
suspend fun refuseCertificate(
database: BennuDatabase,
@@ -566,11 +597,76 @@ object MemberWalletManager {
.any { it.participantPublicKey.equals(verified.memberPublicKey, ignoreCase = true) }
if (!member) return "was asked by somebody who is not a member"
- val expected = runCatching { SubgroupManager.grantFor(database, chatRoomId, thresholdPublicKey, verified.walletId) }.getOrNull()
+ val delay = when (val judged = judgePolicy(database, chatRoomId, verified.request)) {
+ is PolicyJudgement.Refused -> return judged.reason
+ is PolicyJudgement.At -> judged.delay
+ }
+
+ val expected = runCatching { SubgroupManager.grantFor(database, chatRoomId, thresholdPublicKey, verified.walletId, delay) }.getOrNull()
?: return "grants keys this device cannot check"
return if (verified.account.guardians == expected) null else "grants guardian keys this group does not"
}
+ /** What a signer makes of the policy a request was built under: the delay to judge it at, or why not. */
+ sealed interface PolicyJudgement {
+ data class At(val delay: Long) : PolicyJudgement
+ data class Refused(val reason: String, val why: Why) : PolicyJudgement
+ }
+
+ /** Why a request's policy will not do, said as a reason the member's screen can name. */
+ enum class Why {
+ /** Built before policies, or under none: the group never said it guards members' wallets. */
+ NO_POLICY,
+
+ /** It carries a policy, but not an open one the group signed. */
+ NOT_THE_GROUPS,
+
+ /** The group has a newer delay; the request was built under an older one. */
+ DELAY_CHANGED,
+
+ /** The group has since stopped guarding members' wallets. */
+ CLOSED,
+ }
+
+ /**
+ * The delay [chatRoomId]'s own leaf must have in the wallet [request] asks
+ * for, or why the request cannot be signed -- `docs/member-wallet-delay.md`,
+ * D6. `held` is this device's newest policy, `carried` the one the request
+ * was built under:
+ *
+ * - carried, an open policy the group signed, and nothing held newer: at
+ * its delay. Newer than what this device holds is fine -- the group
+ * signed it, and this device missed it;
+ * - carried, but a newer open one held: stale, *asked under a delay the
+ * group has since changed*;
+ * - carried, but a newer closed one held: stale, *the group has stopped*;
+ * - carried and not an open policy the group signed: refused;
+ * - none carried: refused. A request from before policies never asked for
+ * the delay the group chose, or of a group that chose to guard members.
+ *
+ * Read from the request, not the certificate, so the member's screen and a
+ * sponsor's device can ask it before there is a certificate to check.
+ */
+ suspend fun judgePolicy(database: BennuDatabase, chatRoomId: String, request: Event): PolicyJudgement {
+ val reading = MemberWalletRequestEvent.read(request)
+ ?: return PolicyJudgement.Refused("is not a request this group could have been asked", Why.NOT_THE_GROUPS)
+ val carried = reading.policy
+ ?: return PolicyJudgement.Refused("does not say the group guards members' wallets", Why.NO_POLICY)
+ val open = MemberWalletPolicyEvent.verify(carried, chatRoomId) as? MemberWalletPolicyEvent.Policy.Open
+ ?: return PolicyJudgement.Refused("carries a policy this group did not sign open", Why.NOT_THE_GROUPS)
+
+ val held = policyFor(database, chatRoomId)
+ if (held != null && MemberWalletPolicyEvent.ORDER.compare(held, open) > 0) {
+ return when (held) {
+ is MemberWalletPolicyEvent.Policy.Open ->
+ PolicyJudgement.Refused("was asked under a delay the group has since changed", Why.DELAY_CHANGED)
+ is MemberWalletPolicyEvent.Policy.Closed ->
+ PolicyJudgement.Refused("was asked of a group that has since stopped guarding members' wallets", Why.CLOSED)
+ }
+ }
+ return PolicyJudgement.At(open.delay)
+ }
+
/**
* Puts [request] to [groupRoom]'s quorum, as [userPublicKey]: a signing
* session over the certificate the request determines, which this device's
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/MemberWalletRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/MemberWalletRepository.kt
index 318c874e..573db498 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/MemberWalletRepository.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/MemberWalletRepository.kt
@@ -47,7 +47,8 @@ interface MemberWalletRepository {
suspend fun walletOf(ownerPublicKey: HexKey, walletId: String): MemberWalletManager.MemberWalletRow?
/** Asks the group again, with the request the wallet was first asked with. */
- suspend fun askAgain(walletId: String)
+ /** Asks again for [walletId]; returns the wallet now asked for, a new one when the old request would be refused. */
+ suspend fun askAgain(walletId: String): String
/** Forgets a wallet's key -- refused once a group guards it. */
suspend fun discard(walletId: String)
@@ -88,7 +89,7 @@ interface MemberWalletRepository {
throw UnsupportedOperationException("no repository")
override suspend fun walletsOf(ownerPublicKey: HexKey): List = emptyList()
override suspend fun walletOf(ownerPublicKey: HexKey, walletId: String): MemberWalletManager.MemberWalletRow? = null
- override suspend fun askAgain(walletId: String) = Unit
+ override suspend fun askAgain(walletId: String): String = walletId
override suspend fun discard(walletId: String) = Unit
override suspend fun exportKey(walletId: String): Pair? = null
override suspend fun roomName(chatRoomId: String): String? = null
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletScreen.kt
index fe23a852..58bb4f6a 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletScreen.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletScreen.kt
@@ -1,5 +1,10 @@
package com.machankura.bennu.compose.ui.composable
+import com.machankura.bennu.compose.managers.MemberWalletManager
+import bennu.composeapp.generated.resources.s_has_stopped_guarding_members_wallets_discard
+import bennu.composeapp.generated.resources.s_has_changed_its_delay_since_you_asked
+import bennu.composeapp.generated.resources.s_would_refuse_this_request_asked_before
+import bennu.composeapp.generated.resources.s_would_refuse_this_request
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
@@ -199,13 +204,35 @@ fun MemberWalletScreen(
)
)
}
- if (wallet.state != WalletState.SIGNING) {
+ // Why the group would refuse the request as it stands, said
+ // before the button that fixes it. docs/member-wallet-delay.md.
+ wallet.refusedBecause?.let { why ->
+ item {
+ Text(
+ stringResource(
+ when (why) {
+ MemberWalletManager.Why.NO_POLICY -> Res.string.s_would_refuse_this_request_asked_before
+ MemberWalletManager.Why.DELAY_CHANGED -> Res.string.s_has_changed_its_delay_since_you_asked
+ MemberWalletManager.Why.CLOSED -> Res.string.s_has_stopped_guarding_members_wallets_discard
+ MemberWalletManager.Why.NOT_THE_GROUPS -> Res.string.s_would_refuse_this_request
+ },
+ group,
+ ),
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ }
+ // A closed group takes no new request, so asking again
+ // could only fail; discarding is what is left.
+ if (wallet.state != WalletState.SIGNING && wallet.refusedBecause != MemberWalletManager.Why.CLOSED) {
item {
OutlinedButton(
onClick = { viewModel.askAgain(onAsked = {}, onFailure = { notify(couldNotAskAgain) }) },
enabled = !viewModel.isActionPending.value,
) { Text(stringResource(Res.string.ask_again)) }
}
+ }
+ if (wallet.state != WalletState.SIGNING) {
item {
TextButton(onClick = { confirmingDiscard = true }, enabled = !viewModel.isActionPending.value) {
Text(stringResource(Res.string.discard))
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletViewModel.kt
index 0241d2ca..dbf2b8c0 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletViewModel.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletViewModel.kt
@@ -35,13 +35,21 @@ import kotlinx.coroutines.withContext
*/
class MemberWalletViewModel(
private val ownerPublicKey: HexKey,
- val walletId: String,
+ walletId: String,
initialUIState: MemberWalletUIState,
private val memberWalletRepository: MemberWalletRepository,
private val wallets: GroupOnchainWallets?,
) : ViewModel() {
private val logger = Logger.withTag(TAG)
+ /**
+ * The wallet on screen. Moves when asking again had to make a new request
+ * under the group's newest policy, with a new key, in place of this one --
+ * `docs/member-wallet-delay.md`, Phase 5.
+ */
+ var walletId: String = walletId
+ private set
+
var uiState: MemberWalletUIState by mutableStateOf(initialUIState)
private set
@@ -107,7 +115,7 @@ class MemberWalletViewModel(
}
fun askAgain(onAsked: () -> Unit, onFailure: () -> Unit) = act(onAsked, onFailure) {
- memberWalletRepository.askAgain(walletId)
+ walletId = memberWalletRepository.askAgain(walletId)
initiate()
}
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletPolicyJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletPolicyJvmTest.kt
index 95e53d1a..36122691 100644
--- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletPolicyJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletPolicyJvmTest.kt
@@ -1,5 +1,6 @@
package com.machankura.bennu.compose.managers
+import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent
import kotlin.test.assertTrue
import kotlin.test.assertNotNull
import kotlin.test.assertFailsWith
@@ -135,4 +136,92 @@ class MemberWalletPolicyJvmTest {
// A request from before policies still reads: old certificates embed one.
assertNotNull(MemberWalletRequestEvent.verified(build(null)))
}
+
+ // ---- Phase 5: every signer checks it -----------------------------------
+
+ /** This device as a signer of the group, which the member is in. */
+ private suspend fun asSigner() {
+ GroupFixtures.signingRoom(db, group, members = listOf(memberPublicKey))
+ GroupFixtures.fileKeyState(db, group, GroupFixtures.guardedCertificate(parent, group))
+ }
+
+ /** What the signer is asked to sign: the certificate for a request built at [delay] under [carried]. */
+ private fun proposedUnder(carried: Event?, delay: Long): Event {
+ val walletKey = MemberWalletDerivation.generate()
+ val walletId = MemberWalletDerivation.walletId(walletKey.publicKey())
+ val parentsGrant = GuardianDerivation.grant(thresholdKeyOf(parent), roomOf(parent), emptyList(), groupRoom)
+ val guardians = GuardianDerivation.grant(thresholdKeyOf(group), groupRoom, parentsGrant, walletId, delay)
+ val account = MemberWalletDerivation.account(walletKey.publicKey(), chain, guardians)
+ val request = MemberWalletRequestEvent.build(member, groupRoom, walletKey, account, label = null, createdAt = 1_700_000_500, policy = carried)
+ val template = MemberWalletCertificateEvent.template(request)
+ return Event(MemberWalletManager.certificateIdFor(groupRoom, request), groupRoom, template.createdAt, template.kind, template.tags, template.content, "")
+ }
+
+ private suspend fun refusal(certificate: Event) =
+ MemberWalletManager.refuseCertificate(db, groupRoom, thresholdKeyOf(group), certificate)
+
+ @Test
+ fun `a signer judges a request by the policy it carries, unless it holds a newer one`(): Unit = runBlocking {
+ asSigner()
+ val older = 1_700_000_000L
+ val carried = memberWalletPolicy(group, 4_320, createdAt = older + 100)
+
+ // Held none: a signer that missed the opening is told what it missed.
+ assertNull(refusal(proposedUnder(carried, 4_320)))
+ // The leaf has to have the carried delay, as every reader checks.
+ assertEquals("is not a certificate this group could have been asked for", refusal(proposedUnder(carried, 12)))
+
+ // An older closing the group has since reversed is no reason to refuse.
+ filePolicy(db, group, memberWalletPolicy(group, null, createdAt = older))
+ assertNull(refusal(proposedUnder(carried, 4_320)))
+
+ // A newer delay held: the request is stale.
+ filePolicy(db, group, memberWalletPolicy(group, 144, createdAt = older + 200))
+ assertEquals("was asked under a delay the group has since changed", refusal(proposedUnder(carried, 4_320)))
+
+ // A newer closing held: the group has stopped.
+ filePolicy(db, group, memberWalletPolicy(group, null, createdAt = older + 300))
+ assertEquals("was asked of a group that has since stopped guarding members' wallets", refusal(proposedUnder(carried, 4_320)))
+ }
+
+ @Test
+ fun `a request built under no policy, or under a closed one, is refused`(): Unit = runBlocking {
+ asSigner()
+ filePolicy(db, group, memberWalletPolicy(group, 12))
+
+ assertEquals("does not say the group guards members' wallets", refusal(proposedUnder(null, 12)))
+ assertNotNull(refusal(proposedUnder(memberWalletPolicy(group, null), 12)), "a closed policy opens nothing")
+ assertNotNull(refusal(proposedUnder(memberWalletPolicy(stranger, 12), 12)), "nor does another group's")
+ }
+
+ @Test
+ fun `a stale request says why, and asking again makes a new one at the new delay`(): Unit = runBlocking {
+ asMember()
+ filePolicy(db, group, memberWalletPolicy(group, 12, createdAt = 1_700_000_000))
+ val asked = MemberWalletManager.request(db, groupRoom, member, chain, label = "Savings")
+ assertNull(MemberWalletManager.walletsOf(db, memberPublicKey).single().refusedBecause)
+
+ filePolicy(db, group, memberWalletPolicy(group, 144, createdAt = 1_700_000_100))
+ assertEquals(MemberWalletManager.Why.DELAY_CHANGED, MemberWalletManager.walletsOf(db, memberPublicKey).single().refusedBecause)
+
+ val replacement = MemberWalletManager.askAgain(db, db.memberWalletDao().getById(asked.walletId)!!, member)
+ assertTrue(replacement.walletId != asked.walletId, "a new key")
+ assertNull(db.memberWalletDao().getById(asked.walletId), "the old key, never offered, is gone")
+ assertEquals("Savings", replacement.label)
+ val rebuilt = assertNotNull(MemberWalletRequestEvent.verified(Event.fromJson(replacement.requestJson)))
+ assertEquals(144L, rebuilt.reading.guardians.first().delay)
+ assertNull(MemberWalletManager.walletsOf(db, memberPublicKey).single().refusedBecause)
+ }
+
+ @Test
+ fun `a request to a group that has since closed can only be discarded`(): Unit = runBlocking {
+ asMember()
+ filePolicy(db, group, memberWalletPolicy(group, 12, createdAt = 1_700_000_000))
+ val asked = MemberWalletManager.request(db, groupRoom, member, chain, label = null)
+ filePolicy(db, group, memberWalletPolicy(group, null, createdAt = 1_700_000_100))
+
+ assertEquals(MemberWalletManager.Why.CLOSED, MemberWalletManager.walletsOf(db, memberPublicKey).single().refusedBecause)
+ assertFailsWith { MemberWalletManager.askAgain(db, db.memberWalletDao().getById(asked.walletId)!!, member) }
+ assertNotNull(db.memberWalletDao().getById(asked.walletId), "a refused ask leaves the old key for the member to discard")
+ }
}
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletSigningJvmTest.kt
index 0a0391ca..b0bbcb47 100644
--- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletSigningJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletSigningJvmTest.kt
@@ -79,6 +79,9 @@ class MemberWalletSigningJvmTest {
account = MemberWalletDerivation.account(walletPrivateKey.publicKey(), chain, guardians),
label = "Savings",
createdAt = 1_700_000_000,
+ // Built under the group's open policy, as a member's device builds
+ // it -- the one groupRoomHere() files. docs/member-wallet-delay.md.
+ policy = GroupFixtures.memberWalletPolicy(group, GuardianDerivation.DEFAULT_DELAY, createdAt = 1_600_000_000).takeIf { asking == groupRoom },
)
/** The certificate [request] asks for, as a session would carry it -- unsigned, authored by the room. */