Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 66 additions & 14 deletions app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -64,18 +64,34 @@ class WatchOnlyAccountRepo @Inject constructor(
}
val currentWalletAccountCount: Flow<Int> = currentWalletAccounts.map { it.size }

suspend fun prepareUnsignedClaim(authUrl: String, name: String): PreparedWatchOnlyAccountClaim =
/**
* Prepares the claim for a Paykit server approval. With [reuseAccountId] the claim shares that active account
* of the current wallet again instead of reserving a new one; the user picks it when re-approving a server.
*/
suspend fun prepareUnsignedClaim(
authUrl: String,
name: String,
reuseAccountId: String? = null,
): PreparedWatchOnlyAccountClaim =
withContext(bgDispatcher) {
lifecycleCoordinator.withLock {
val normalizedName = normalizeName(name)
val walletIndex = lightningService.currentWalletIndex
val fingerprint = requestFingerprint(authUrl)
val current = store.load()
current.firstOrNull {
it.walletIndex == walletIndex &&
it.requestFingerprint == fingerprint &&
it.setupState != WatchOnlyAccountSetupState.Active
}?.let { existing ->
val incomplete = current.incompleteSetup(walletIndex, fingerprint)
if (reuseAccountId != null && incomplete == null) {
Comment thread
ovitrif marked this conversation as resolved.
Resolved
Comment thread
ovitrif marked this conversation as resolved.
Resolved
val reused = current.firstOrNull {
it.id == reuseAccountId &&
it.walletIndex == walletIndex &&
it.setupState == WatchOnlyAccountSetupState.Active
} ?: throw WatchOnlyAccountError.AuthorizationAccountMissing()
return@withLock PreparedWatchOnlyAccountClaim(
account = reused,
payload = WatchOnlyAccountClaimCodec.encode(reused, xpubSerializer::serialize),
)
Comment thread
ovitrif marked this conversation as resolved.
Resolved
}
val normalizedName = normalizeName(name)
incomplete?.let { existing ->
val refreshed = existing.copy(name = normalizedName)
if (refreshed != existing) {
store.save(current.map { if (it.id == existing.id) refreshed else it })
Expand Down Expand Up @@ -200,18 +216,43 @@ class WatchOnlyAccountRepo @Inject constructor(
val account = current.firstOrNull { it.id == id } ?: return@withLock
if (account.setupState != WatchOnlyAccountSetupState.Active) return@withLock
if (account.isTrackingEnabled == enabled) return@withLock
saveTracking(current, account, enabled)
}
}

setAccountTracking(account, enabled)
val saveResult = runSuspendCatching {
store.save(current.map { if (it.id == id) it.copy(isTrackingEnabled = enabled) else it })
}
saveResult.onFailure {
runSuspendCatching { setAccountTracking(account, enabled = !enabled) }
/** Tracks a reused account before its claim is sent, failing when it is no longer active on this wallet. */
suspend fun trackReusedAccount(id: String) = withContext(NonCancellable) {
lifecycleCoordinator.withLock {
val current = store.load()
val account = current.firstOrNull {
it.id == id &&
it.walletIndex == lightningService.currentWalletIndex &&
it.setupState == WatchOnlyAccountSetupState.Active
} ?: throw WatchOnlyAccountError.AuthorizationAccountMissing()
// The store can say tracked while the node lost the account, so the node is always asked to track it.
if (account.isTrackingEnabled) {
setAccountTracking(account, enabled = true)
} else {
saveTracking(current, account, enabled = true)
}
saveResult.getOrThrow()
}
}

private suspend fun saveTracking(
current: List<WatchOnlyAccountRecord>,
account: WatchOnlyAccountRecord,
enabled: Boolean,
) {
setAccountTracking(account, enabled)
val saveResult = runSuspendCatching {
store.save(current.map { if (it.id == account.id) it.copy(isTrackingEnabled = enabled) else it })
}
saveResult.onFailure {
runSuspendCatching { setAccountTracking(account, enabled = !enabled) }
}
saveResult.getOrThrow()
}

suspend fun restore(
accounts: List<WatchOnlyAccountRecord>?,
allocationState: WatchOnlyAccountAllocationState? = null,
Expand Down Expand Up @@ -297,6 +338,17 @@ class WatchOnlyAccountRepo @Inject constructor(
}
}

/** Whether this request already has an account whose setup has not finished; approving it resumes that account. */
suspend fun hasIncompleteSetup(authUrl: String): Boolean = withContext(bgDispatcher) {
store.load().incompleteSetup(lightningService.currentWalletIndex, requestFingerprint(authUrl)) != null
}

private fun List<WatchOnlyAccountRecord>.incompleteSetup(walletIndex: Int, fingerprint: String) = firstOrNull {
it.walletIndex == walletIndex &&
it.requestFingerprint == fingerprint &&
it.setupState != WatchOnlyAccountSetupState.Active
}

private fun normalizeName(name: String): String {
val normalized = name.trim()
if (normalized.isEmpty() || normalized.length > MAX_NAME_LENGTH) {
Expand Down
139 changes: 128 additions & 11 deletions app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalSheet.kt
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.selected
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
Expand All @@ -52,6 +54,9 @@ import to.bitkit.models.PubkyAuthClaim
import to.bitkit.models.PubkyAuthClaim.Item
import to.bitkit.models.PubkyAuthPermission
import to.bitkit.models.PubkyProfile
import to.bitkit.models.WATCH_ONLY_ACCOUNT_NATIVE_SEGWIT_ADDRESS_TYPE
import to.bitkit.models.WatchOnlyAccountRecord
import to.bitkit.models.WatchOnlyAccountSetupState
import to.bitkit.ui.appViewModel
import to.bitkit.ui.components.AuthCheckView
import to.bitkit.ui.components.BiometricsView
Expand All @@ -71,6 +76,8 @@ import to.bitkit.ui.components.SecondaryButton
import to.bitkit.ui.components.SheetSize
import to.bitkit.ui.components.Text13Up
import to.bitkit.ui.components.VerticalSpacer
import to.bitkit.ui.components.settings.SettingsButtonRow
import to.bitkit.ui.components.settings.SettingsButtonValue
import to.bitkit.ui.scaffold.SheetTopBar
import to.bitkit.ui.settingsViewModel
import to.bitkit.ui.shared.modifiers.sheetHeight
Expand Down Expand Up @@ -106,9 +113,11 @@ fun PubkyAuthApprovalSheet(
onApproveWatchOnly = {
if (uiState.authUrl == authUrl) viewModel.approveWatchOnlyConsent(authUrl)
},
onBackToWatchOnly = {
if (uiState.authUrl == authUrl) viewModel.returnToWatchOnlyConsent(authUrl)
onBack = {
if (uiState.authUrl == authUrl) viewModel.returnToPreviousStep(authUrl)
},
onSelectAccount = { viewModel.selectAccount(authUrl, it) },
onConfirmAccount = { viewModel.confirmAccountChoice(authUrl) },
onRetryUsdt = { viewModel.loadUsdtAddress(authUrl) },
onShareUsdt = viewModel::setShareUsdt,
onCancel = { viewModel.dismiss() },
Expand Down Expand Up @@ -222,18 +231,20 @@ private fun Content(
isCurrentRequest: Boolean,
onAuthorize: () -> Unit,
onApproveWatchOnly: () -> Unit,
onBackToWatchOnly: () -> Unit,
onBack: () -> Unit,
onCancel: () -> Unit,
onDismiss: () -> Unit,
onRetryUsdt: () -> Unit = {},
onShareUsdt: (Boolean) -> Unit = {},
onSelectAccount: (String?) -> Unit = {},
onConfirmAccount: () -> Unit = {},
) {
val approvalState = if (isCurrentRequest) uiState.state else ApprovalState.Loading
val headerTitle = approvalHeaderTitle(approvalState)
val onBack = approvalBackAction(
val onBackAction = approvalBackAction(
approvalState = approvalState,
showsReceivingDetails = uiState.showsReceivingDetails,
onBackToWatchOnly = onBackToWatchOnly,
onBack = onBack,
onCancel = onCancel,
onDismiss = onDismiss,
)
Expand All @@ -247,7 +258,7 @@ private fun Content(
) {
SheetTopBar(
titleText = headerTitle,
onBack = onBack,
onBack = onBackAction,
titleStyle = if (approvalState == ApprovalState.WatchOnlyConsent) {
AppTextStyles.Subtitle.copy(letterSpacing = 0.sp, lineHeight = 22.sp)
} else {
Expand All @@ -264,6 +275,12 @@ private fun Content(
onApprove = onApproveWatchOnly,
onCancel = onCancel,
)
ApprovalState.ChooseAccount -> ChooseAccountContent(
uiState = uiState,
onSelect = onSelectAccount,
onContinue = onConfirmAccount,
onCancel = onCancel,
)
ApprovalState.Authorize -> AuthorizeContent(
uiState = uiState,
onAuthorize = onAuthorize,
Expand All @@ -283,18 +300,20 @@ private fun Content(
@Composable
private fun approvalHeaderTitle(approvalState: ApprovalState): String = when (approvalState) {
ApprovalState.WatchOnlyConsent -> stringResource(R.string.profile__auth_approval_watch_only_intro_nav_title)
ApprovalState.ChooseAccount -> stringResource(R.string.profile__auth_approval_account_nav_title)
ApprovalState.Success -> stringResource(R.string.profile__auth_approval_success)
else -> stringResource(R.string.profile__auth_approval_title)
}

private fun approvalBackAction(
approvalState: ApprovalState,
showsReceivingDetails: Boolean,
onBackToWatchOnly: () -> Unit,
onBack: () -> Unit,
onCancel: () -> Unit,
onDismiss: () -> Unit,
): (() -> Unit)? = when (approvalState) {
ApprovalState.Authorize if showsReceivingDetails -> onBackToWatchOnly
ApprovalState.ChooseAccount -> onBack
ApprovalState.Authorize if showsReceivingDetails -> onBack
ApprovalState.Authorize, ApprovalState.Authenticating, ApprovalState.Authorizing -> onCancel
ApprovalState.Success -> onDismiss
else -> null
Expand Down Expand Up @@ -369,6 +388,64 @@ private fun ColumnScope.WatchOnlyConsentContent(
VerticalSpacer(16.dp)
}

@Composable
private fun ColumnScope.ChooseAccountContent(
uiState: PubkyAuthApprovalUiState,
onSelect: (String?) -> Unit,
onContinue: () -> Unit,
onCancel: () -> Unit,
) {
Column(
modifier = Modifier
.weight(1f)
.verticalScroll(rememberScrollState())
.testTag("PubkyAuthChooseAccount")
) {
VerticalSpacer(8.dp)
BodyM(
text = stringResource(R.string.profile__auth_approval_account_description),
color = Colors.White64,
letterSpacing = 0.sp,
)
VerticalSpacer(16.dp)
uiState.existingAccounts.forEach { account ->
SettingsButtonRow(
title = account.name,
subtitle = account.derivationPath,
value = SettingsButtonValue.BooleanValue(uiState.selectedAccountId == account.id),
onClick = { onSelect(account.id) },
modifier = Modifier
.semantics { selected = uiState.selectedAccountId == account.id }
.testTag("PubkyAuthAccount_${account.accountIndex}")
)
}
SettingsButtonRow(
title = stringResource(R.string.profile__auth_approval_account_new),
value = SettingsButtonValue.BooleanValue(uiState.selectedAccountId == null),
onClick = { onSelect(null) },
modifier = Modifier
.semantics { selected = uiState.selectedAccountId == null }
.testTag("PubkyAuthAccountNew")
)
}
VerticalSpacer(32.dp)
Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {
SecondaryButton(
text = stringResource(R.string.common__cancel),
onClick = onCancel,
textStyle = AppTextStyles.BodySSB.copy(letterSpacing = 0.sp),
modifier = Modifier.weight(1f).testTag("PubkyAuthAccountCancel")
)
PrimaryButton(
text = stringResource(R.string.common__continue),
onClick = onContinue,
textStyle = AppTextStyles.BodySSB.copy(letterSpacing = 0.sp),
modifier = Modifier.weight(1f).testTag("PubkyAuthAccountContinue")
)
}
VerticalSpacer(16.dp)
}

@Composable
private fun UsdtSharingChoice(
uiState: PubkyAuthApprovalUiState,
Expand Down Expand Up @@ -833,14 +910,54 @@ private fun WatchOnlyConsentPreview() {
isCurrentRequest = true,
onAuthorize = {},
onApproveWatchOnly = {},
onBackToWatchOnly = {},
onBack = {},
onCancel = {},
onDismiss = {},
)
}
}
}

@Preview(showSystemUi = true)
@Composable
private fun ChooseAccountPreview() {
AppThemeSurface {
BottomSheetPreview {
Content(
uiState = PubkyAuthApprovalUiState(
state = ApprovalState.ChooseAccount,
serviceName = "paykit",
bitkitClaim = PubkyAuthClaim(Item.PAYKIT_ACCESS_V1, Item.WATCH_ONLY_ACCOUNT_V1),
existingAccounts = persistentListOf(
previewAccount(id = "1", accountIndex = 1, name = "paykit server"),
previewAccount(id = "2", accountIndex = 2, name = "shop server"),
),
selectedAccountId = "1",
),
isCurrentRequest = true,
onAuthorize = {},
onApproveWatchOnly = {},
onBack = {},
onCancel = {},
onDismiss = {},
)
}
}
}

private fun previewAccount(id: String, accountIndex: Int, name: String) = WatchOnlyAccountRecord(
id = id,
walletIndex = 0,
accountIndex = accountIndex,
addressType = WATCH_ONLY_ACCOUNT_NATIVE_SEGWIT_ADDRESS_TYPE,
xpub = "",
requestFingerprint = "",
createdAt = 0,
name = name,
isTrackingEnabled = true,
setupState = WatchOnlyAccountSetupState.Active,
)

@Preview(showSystemUi = true)
@Composable
private fun AuthorizePreview() {
Expand Down Expand Up @@ -868,7 +985,7 @@ private fun AuthorizePreview() {
isCurrentRequest = true,
onAuthorize = {},
onApproveWatchOnly = {},
onBackToWatchOnly = {},
onBack = {},
onCancel = {},
onDismiss = {},
)
Expand All @@ -890,7 +1007,7 @@ private fun SuccessPreview() {
isCurrentRequest = true,
onAuthorize = {},
onApproveWatchOnly = {},
onBackToWatchOnly = {},
onBack = {},
onCancel = {},
onDismiss = {},
)
Expand Down
Loading
Loading