From 74ec7a40d9f2dedc9bb5b3741eb550790ed6ee81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Sena?= Date: Fri, 6 Nov 2026 12:55:10 -0300 Subject: [PATCH 01/11] Merge pull request #1798 from synonymdev/fix/pubky-own-queue fix: run pubky work on its own service queue (cherry picked from commit ebe9bc09850704d1e96a2bb1697fd5d5a664fd1a) --- .../main/java/to/bitkit/async/ServiceQueue.kt | 2 +- .../java/to/bitkit/services/PubkyService.kt | 62 +++++++++---------- .../bitkit/services/PaykitSdkServiceTest.kt | 2 +- .../to/bitkit/services/PubkyServiceTest.kt | 30 ++++++++- changelog.d/next/1798.fixed.md | 1 + 5 files changed, 62 insertions(+), 35 deletions(-) create mode 100644 changelog.d/next/1798.fixed.md diff --git a/app/src/main/java/to/bitkit/async/ServiceQueue.kt b/app/src/main/java/to/bitkit/async/ServiceQueue.kt index d81323687b..0d2a6a01dc 100644 --- a/app/src/main/java/to/bitkit/async/ServiceQueue.kt +++ b/app/src/main/java/to/bitkit/async/ServiceQueue.kt @@ -13,7 +13,7 @@ import java.util.concurrent.ThreadFactory import kotlin.coroutines.CoroutineContext enum class ServiceQueue { - LDK, CORE, FOREX, LOG, MIGRATION; + LDK, CORE, PUBKY, FOREX, LOG, MIGRATION; private val scope by lazy { CoroutineScope(newSingleThreadDispatcher(name) + SupervisorJob()) } diff --git a/app/src/main/java/to/bitkit/services/PubkyService.kt b/app/src/main/java/to/bitkit/services/PubkyService.kt index e9105a40c9..413fb3c90c 100644 --- a/app/src/main/java/to/bitkit/services/PubkyService.kt +++ b/app/src/main/java/to/bitkit/services/PubkyService.kt @@ -29,11 +29,11 @@ class PubkyService @Inject constructor( internal val AUTHORIZATION_TIMEOUT = 30.seconds } - suspend fun initialize() = ServiceQueue.CORE.background { + suspend fun initialize() = ServiceQueue.PUBKY.background { paykitSdkService.initialize() } - suspend fun initializeAndImportSession(secret: String): Result = ServiceQueue.CORE.background { + suspend fun initializeAndImportSession(secret: String): Result = ServiceQueue.PUBKY.background { paykitSdkService.initializeAndImportSession(secret).map { it.publicKey } } @@ -42,27 +42,27 @@ class PubkyService @Inject constructor( // region Session management - suspend fun importSession(secret: String): String = ServiceQueue.CORE.background { + suspend fun importSession(secret: String): String = ServiceQueue.PUBKY.background { paykitSdkService.importSession(secret).publicKey } - suspend fun currentPublicKey(): String? = ServiceQueue.CORE.background { + suspend fun currentPublicKey(): String? = ServiceQueue.PUBKY.background { paykitSdkService.currentPublicKey() } - suspend fun signOut() = ServiceQueue.CORE.background { + suspend fun signOut() = ServiceQueue.PUBKY.background { paykitSdkService.signOut() } - suspend fun forgetSessionAccess() = ServiceQueue.CORE.background { + suspend fun forgetSessionAccess() = ServiceQueue.PUBKY.background { paykitSdkService.forgetSessionAccess() } - suspend fun clearSessionAccess() = ServiceQueue.CORE.background { + suspend fun clearSessionAccess() = ServiceQueue.PUBKY.background { paykitSdkService.clearSessionAccess() } - suspend fun removeBitkitPaymentEndpoints() = ServiceQueue.CORE.background { + suspend fun removeBitkitPaymentEndpoints() = ServiceQueue.PUBKY.background { val endpointError = runSuspendCatching { val report = paykitSdkService.syncPublicEndpoints(emptyList()) if (report.failed.isNotEmpty()) throw AppError("Failed to remove Paykit payment endpoints") @@ -79,11 +79,11 @@ class PubkyService @Inject constructor( // region Key derivation - suspend fun deriveSecretKey(mnemonic: String): String = ServiceQueue.CORE.background { + suspend fun deriveSecretKey(mnemonic: String): String = ServiceQueue.PUBKY.background { PaykitSdkService.deriveSecretKey(mnemonic) } - suspend fun publicKeyFromSecret(secretKeyHex: String): String = ServiceQueue.CORE.background { + suspend fun publicKeyFromSecret(secretKeyHex: String): String = ServiceQueue.PUBKY.background { PaykitSdkService.publicKeyFromSecret(secretKeyHex) } @@ -92,7 +92,7 @@ class PubkyService @Inject constructor( // region Homeserver auth suspend fun signUp(secretKeyHex: String, homeserverZ32: String, signupCode: String?): Unit = - ServiceQueue.CORE.background { + ServiceQueue.PUBKY.background { paykitSdkService.signUp(secretKeyHex, homeserverZ32, signupCode) Unit } @@ -102,20 +102,20 @@ class PubkyService @Inject constructor( homeserverZ32: String, signupCode: String?, ): PubkySessionBootstrapResult = - ServiceQueue.CORE.background { + ServiceQueue.PUBKY.background { paykitSdkService.registerIdentity(secretKeyHex, homeserverZ32, signupCode) } - suspend fun activateRegisteredIdentity(result: PubkySessionBootstrapResult) = ServiceQueue.CORE.background { + suspend fun activateRegisteredIdentity(result: PubkySessionBootstrapResult) = ServiceQueue.PUBKY.background { paykitSdkService.activateRegisteredIdentity(result) } - suspend fun signIn(secretKeyHex: String): Unit = ServiceQueue.CORE.background { + suspend fun signIn(secretKeyHex: String): Unit = ServiceQueue.PUBKY.background { paykitSdkService.signIn(secretKeyHex) Unit } - suspend fun hasIdentityRecord(publicKey: String): Boolean = ServiceQueue.CORE.background { + suspend fun hasIdentityRecord(publicKey: String): Boolean = ServiceQueue.PUBKY.background { paykitSdkService.hasIdentityRecord(publicKey) } @@ -123,12 +123,12 @@ class PubkyService @Inject constructor( // region Auth approval - suspend fun parseAuthUrl(url: String) = ServiceQueue.CORE.background { + suspend fun parseAuthUrl(url: String) = ServiceQueue.PUBKY.background { PaykitSdkService.parseAuthUrl(url) } suspend fun validateSignupRequest(authorizationUrl: String?, homeserverPublicKey: String): Unit = - ServiceQueue.CORE.background { + ServiceQueue.PUBKY.background { authorizationUrl?.let { parseLegacyPubkyAuthUrl(it) } PaykitPublicKeys.normalize(homeserverPublicKey) Unit @@ -139,7 +139,7 @@ class PubkyService @Inject constructor( expectedCapabilities: String, approvedClientId: String, secretKeyHex: String, - ) = ServiceQueue.CORE.background { + ) = ServiceQueue.PUBKY.background { paykitSdkService.republishIdentityIfNeeded(publicKeyFromSecret(secretKeyHex)) paykitSdkService.approveAuth(authUrl, expectedCapabilities, approvedClientId, secretKeyHex) } @@ -148,7 +148,7 @@ class PubkyService @Inject constructor( authUrl: String, secretKeyHex: String, timeout: Duration = AUTHORIZATION_TIMEOUT, - ) = ServiceQueue.CORE.background { + ) = ServiceQueue.PUBKY.background { paykitSdkService.republishIdentityIfNeeded(publicKeyFromSecret(secretKeyHex)) withTimeoutOrNull(timeout) { approvePubkyAuth(authUrl, secretKeyHex) @@ -161,7 +161,7 @@ class PubkyService @Inject constructor( approvedClientId: String, secretKeyHex: String, claim: PubkyAuthCompanionClaim, - ) = ServiceQueue.CORE.background { + ) = ServiceQueue.PUBKY.background { paykitSdkService.republishIdentityIfNeeded(publicKeyFromSecret(secretKeyHex)) paykitSdkService.approveAuthWithCompanionClaim( authUrl = authUrl, @@ -191,7 +191,7 @@ class PubkyService @Inject constructor( publicKeys: List, expectedIdentity: String, isStillCurrent: () -> Boolean, - ): List = ServiceQueue.CORE.background(ServiceQueue.CORE.queueContext.minusKey(Job)) { + ): List = ServiceQueue.PUBKY.background(ServiceQueue.PUBKY.queueContext.minusKey(Job)) { paykitSdkService.importShopContacts(publicKeys, expectedIdentity, isStillCurrent) } @@ -199,15 +199,15 @@ class PubkyService @Inject constructor( // region Profile & contacts - suspend fun publishPaykitProfile(profile: PaykitProfile) = ServiceQueue.CORE.background { + suspend fun publishPaykitProfile(profile: PaykitProfile) = ServiceQueue.PUBKY.background { paykitSdkService.publishPaykitProfile(profile) } - suspend fun uploadProfileAvatar(bytes: ByteArray, contentType: String): String = ServiceQueue.CORE.background { + suspend fun uploadProfileAvatar(bytes: ByteArray, contentType: String): String = ServiceQueue.PUBKY.background { paykitSdkService.uploadProfileAvatar(bytes, contentType) } - suspend fun deletePaykitProfile() = ServiceQueue.CORE.background { + suspend fun deletePaykitProfile() = ServiceQueue.PUBKY.background { paykitSdkService.deletePaykitProfile() } @@ -215,11 +215,11 @@ class PubkyService @Inject constructor( paykitSdkService.fetchPubkyFollows(publicKey) } - suspend fun contactRecords(): List = ServiceQueue.CORE.background { + suspend fun contactRecords(): List = ServiceQueue.PUBKY.background { paykitSdkService.contactRecords() } - suspend fun observedContactRecords(expectedIdentity: String): List = ServiceQueue.CORE.background { + suspend fun observedContactRecords(expectedIdentity: String): List = ServiceQueue.PUBKY.background { paykitSdkService.observeState(expectedIdentity).contacts } @@ -229,7 +229,7 @@ class PubkyService @Inject constructor( restorePrivateConnection: Boolean = false, expectedIdentity: String? = null, isStillCurrent: (() -> Boolean)? = null, - ): ContactRecord = ServiceQueue.CORE.background { + ): ContactRecord = ServiceQueue.PUBKY.background { paykitSdkService.saveContact( publicKey, label, @@ -243,15 +243,15 @@ class PubkyService @Inject constructor( updates: List, expectedIdentity: String? = null, isStillCurrent: (() -> Boolean)? = null, - ): List = ServiceQueue.CORE.background { + ): List = ServiceQueue.PUBKY.background { paykitSdkService.saveContacts(updates, expectedIdentity, isStillCurrent) } - suspend fun removeContact(publicKey: String): ContactRecord? = ServiceQueue.CORE.background { + suspend fun removeContact(publicKey: String): ContactRecord? = ServiceQueue.PUBKY.background { paykitSdkService.removeContact(publicKey) } - suspend fun removeContacts(publicKeys: List): List = ServiceQueue.CORE.background { + suspend fun removeContacts(publicKeys: List): List = ServiceQueue.PUBKY.background { paykitSdkService.removeContacts(publicKeys) } @@ -266,7 +266,7 @@ class PubkyService @Inject constructor( // endregion private suspend fun cancellablePublicRead(block: suspend CoroutineScope.() -> T): T = - ServiceQueue.CORE.background(ServiceQueue.CORE.queueContext.minusKey(Job), block) + ServiceQueue.PUBKY.background(ServiceQueue.PUBKY.queueContext.minusKey(Job), block) } class PubkyRingAuthTimeoutError : AppError("Ring authorization timed out") diff --git a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt index 2c3cc12ac6..a228d3193c 100644 --- a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt @@ -393,7 +393,7 @@ class PaykitSdkServiceTest { service.setPaymentSubmissionActive(true) val caller = launch { wrapper.importShopContacts(listOf(RING_PUBKY), RING_PUBKY) { true } } runCurrent() - ServiceQueue.CORE.background { } + ServiceQueue.PUBKY.background { } caller.cancel() service.setPaymentSubmissionActive(false) caller.join() diff --git a/app/src/test/java/to/bitkit/services/PubkyServiceTest.kt b/app/src/test/java/to/bitkit/services/PubkyServiceTest.kt index 38320d75e4..a2dc689d09 100644 --- a/app/src/test/java/to/bitkit/services/PubkyServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/PubkyServiceTest.kt @@ -21,6 +21,9 @@ import to.bitkit.async.ServiceQueue import to.bitkit.ext.runSuspendCatching import to.bitkit.test.BaseUnitTest import to.bitkit.utils.AppError +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import kotlin.concurrent.thread import kotlin.coroutines.Continuation import kotlin.coroutines.intrinsics.startCoroutineUninterceptedOrReturn import kotlin.test.assertEquals @@ -31,6 +34,29 @@ import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.seconds class PubkyServiceTest : BaseUnitTest() { + @Test + fun `paykit initialization does not hold the core queue`() = test { + val paykit = mock() + val sut = PubkyService(paykit) + val entered = CountDownLatch(1) + val release = CountDownLatch(1) + whenever(paykit.initialize()).doSuspendableAnswer { + entered.countDown() + release.await() + } + val initializing = launch { sut.initialize() } + try { + assertTrue(entered.await(5, TimeUnit.SECONDS)) + val coreReady = CountDownLatch(1) + thread { ServiceQueue.CORE.blocking { coreReady.countDown() } } + + assertTrue(coreReady.await(5, TimeUnit.SECONDS)) + } finally { + release.countDown() + } + initializing.join() + } + @Test fun `public cleanup reconciles disabled capabilities even after endpoint removal fails`() = test { for (failure in listOf(null, "endpoints", "registry")) { @@ -96,7 +122,7 @@ class PubkyServiceTest : BaseUnitTest() { @Test fun `relay timeout cancels the queued call and allows another approval`() = test { - ServiceQueue.CORE.background { + ServiceQueue.PUBKY.background { val binding = Class.forName("com.synonym.bitkitcore.Bitkitcore_androidKt") val approve = binding.getMethod( "approvePubkyAuth", @@ -131,7 +157,7 @@ class PubkyServiceTest : BaseUnitTest() { @Test fun `relay cancellation propagates without becoming a timeout failure`() = test { - ServiceQueue.CORE.background { + ServiceQueue.PUBKY.background { val binding = Class.forName("com.synonym.bitkitcore.Bitkitcore_androidKt") val approve = binding.getMethod( "approvePubkyAuth", diff --git a/changelog.d/next/1798.fixed.md b/changelog.d/next/1798.fixed.md new file mode 100644 index 0000000000..6f2612265b --- /dev/null +++ b/changelog.d/next/1798.fixed.md @@ -0,0 +1 @@ +Fixed an occasional app freeze on launch while Pubky contacts start up. From 067c6b3b6d0b8160b74266bb83fe1157625ebfae Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 17:24:25 +0100 Subject: [PATCH 02/11] Merge pull request #1803 from synonymdev/chore/paykit-rc6 fix: adopt paykit 0.1.1-rc6 (cherry picked from commit 816f08ed7bfc9774d15ec1bb8e5f37bf13479b26) --- .../java/to/bitkit/ext/PaykitExceptionExt.kt | 12 ++ .../to/bitkit/models/PaykitUsdtStateBackup.kt | 5 +- .../repositories/PaykitAllowanceExecutor.kt | 16 +++ .../repositories/PaykitPaymentProofRepo.kt | 75 ++++++++++++ .../repositories/PaykitPaymentRequestRepo.kt | 21 +++- .../repositories/PaykitUsdtPaymentRepo.kt | 65 +++++------ .../to/bitkit/services/PaykitSdkService.kt | 26 +++++ .../paymentrequests/PaymentRequestsScreen.kt | 1 + .../bitkit/ui/utils/PubkyAuthErrorMessage.kt | 4 + .../java/to/bitkit/viewmodels/AppViewModel.kt | 12 +- app/src/main/res/values-ar/strings.xml | 3 + app/src/main/res/values-b+es+419/strings.xml | 3 + app/src/main/res/values-ca/strings.xml | 3 + app/src/main/res/values-cs/strings.xml | 3 + app/src/main/res/values-de/strings.xml | 3 + app/src/main/res/values-el/strings.xml | 3 + app/src/main/res/values-es-rES/strings.xml | 3 + app/src/main/res/values-es/strings.xml | 3 + app/src/main/res/values-fr/strings.xml | 3 + app/src/main/res/values-it/strings.xml | 3 + app/src/main/res/values-nl/strings.xml | 3 + app/src/main/res/values-pl/strings.xml | 3 + app/src/main/res/values-pt-rBR/strings.xml | 3 + app/src/main/res/values-pt/strings.xml | 3 + app/src/main/res/values-ru/strings.xml | 3 + app/src/main/res/values/strings.xml | 3 + .../models/PaykitPaymentStateBackupTest.kt | 17 ++- .../PaykitAllowanceExecutorTest.kt | 37 ++++++ .../repositories/PaykitIssuerInteropTest.kt | 2 + .../PaykitPaymentProofRepoTest.kt | 57 ++++++++- ...aykitPaymentRequestRepoSubscriptionTest.kt | 25 ++++ .../PaykitPaymentRequestRepoTest.kt | 30 +++++ .../repositories/PaykitUsdtPaymentRepoTest.kt | 110 +++++++++++++++--- .../repositories/PrivatePaykitRepoTest.kt | 2 + .../to/bitkit/repositories/PubkyRepoTest.kt | 38 ++++++ .../bitkit/services/PaykitSdkServiceTest.kt | 15 ++- .../ui/utils/PubkyAuthErrorMessageTest.kt | 26 +++++ .../viewmodels/AppViewModelSendFlowTest.kt | 27 +++++ changelog.d/next/1803.fixed.md | 1 + gradle/libs.versions.toml | 2 +- journeys/payment-requests/README.md | 4 + .../request-note-too-long.xml | 18 +++ journeys/pubky-auth/README.md | 7 +- .../pubky-auth/grant-signup-rejected-code.xml | 17 +++ 44 files changed, 650 insertions(+), 70 deletions(-) create mode 100644 changelog.d/next/1803.fixed.md create mode 100644 journeys/payment-requests/request-note-too-long.xml create mode 100644 journeys/pubky-auth/grant-signup-rejected-code.xml diff --git a/app/src/main/java/to/bitkit/ext/PaykitExceptionExt.kt b/app/src/main/java/to/bitkit/ext/PaykitExceptionExt.kt index 42133dc7c5..b445a55c2c 100644 --- a/app/src/main/java/to/bitkit/ext/PaykitExceptionExt.kt +++ b/app/src/main/java/to/bitkit/ext/PaykitExceptionExt.kt @@ -2,6 +2,12 @@ package to.bitkit.ext import com.synonym.paykit.PaykitException +/** Protocol error code for an outbound Private Application Message larger than one pubky-noise message. */ +private const val MESSAGE_TOO_LARGE_CODE = "message_too_large" + +/** Identity error code for a signup code the homeserver refused during sign-up. */ +private const val SIGNUP_CODE_REJECTED_CODE = "signup_code_rejected" + fun Throwable.isPaykitIdentityError(): Boolean = generateSequence(this) { it.cause }.any { it is PaykitException.Identity } @@ -13,3 +19,9 @@ fun Throwable.isPaykitTemporarilyUnavailable(): Boolean = it is PaykitException.ConcurrentUpdate || it is PaykitException.SharedStateBusy || it is PaykitException.Transport } + +fun Throwable.isPaykitMessageTooLarge(): Boolean = + generateSequence(this) { it.cause }.any { it is PaykitException.Protocol && it.code == MESSAGE_TOO_LARGE_CODE } + +fun Throwable.isPaykitSignupCodeRejected(): Boolean = + generateSequence(this) { it.cause }.any { it is PaykitException.Identity && it.code == SIGNUP_CODE_REJECTED_CODE } diff --git a/app/src/main/java/to/bitkit/models/PaykitUsdtStateBackup.kt b/app/src/main/java/to/bitkit/models/PaykitUsdtStateBackup.kt index 03e4a1c3ae..3b9df92bf9 100644 --- a/app/src/main/java/to/bitkit/models/PaykitUsdtStateBackup.kt +++ b/app/src/main/java/to/bitkit/models/PaykitUsdtStateBackup.kt @@ -23,16 +23,17 @@ data class PaykitUsdtStateBackup( val receivedAtMillis: Long, val underpaid: Boolean, val afterExpiry: Boolean, + val beforeRequest: Boolean = false, ) { constructor(value: PaykitUsdtReceipt) : this( value.wallet, value.identity, value.requestId, value.paymentId, value.proofEventId, value.verified, value.transferId, value.amount.atomic, value.receivedAtMillis, - value.underpaid, value.afterExpiry, + value.underpaid, value.afterExpiry, value.beforeRequest, ) fun restored() = PaykitUsdtReceipt( wallet, identity, requestId, paymentId, proofEventId, verified, transferId, - PaykitAmount(PaykitAsset.USDT, amountAtomic), receivedAtMillis, underpaid, afterExpiry, + PaykitAmount(PaykitAsset.USDT, amountAtomic), receivedAtMillis, underpaid, afterExpiry, beforeRequest, ) } } diff --git a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt index 1c72fe4bae..585050ad98 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt @@ -677,6 +677,22 @@ class PaykitAllowanceExecutor @Inject constructor( Logger.info("Kept an incoming request manual: the payee offers no Lightning invoice", context = TAG) return PaykitAllowanceAutoPayResult.MANUAL } + // Measured before the acceptance, so a proof that can never be delivered is never accepted on the payee's side. + val proofFits = runSuspendCatching { + paykitSdkService.requirePaymentProofFits( + paymentReference = request.paymentReference, + paymentAppId = payment.appId, + paymentEndpointIdentifier = payment.endpoint.methodId.rawValue, + kind = PaykitPaymentProofKind.Lightning, + billingPeriod = request.billingPeriod, + conversionQuoteId = null, + allowanceId = candidate.allowanceId, + ) + }.isSuccess + if (!proofFits) { + Logger.info("Kept an incoming request manual: its payment proof would not fit one message", context = TAG) + return PaykitAllowanceAutoPayResult.MANUAL + } if (!admits(activation)) { Logger.info("Kept an incoming request manual: allowances turned off before acceptance", context = TAG) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt index a07a0520e6..5576a7dfe5 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt @@ -1,5 +1,6 @@ package to.bitkit.repositories +import com.synonym.bitkitcore.UsdtPaymentProof import com.synonym.paykit.BillingPeriod import com.synonym.paykit.PaymentProofRecord import com.synonym.paykit.PaymentRequestLifecycleState @@ -41,6 +42,7 @@ import to.bitkit.ext.toHex import to.bitkit.models.HwFundingSignedTx import to.bitkit.models.PaykitPaymentStateBackup import to.bitkit.models.PaykitRequestPayment +import to.bitkit.models.PaykitUsdt import to.bitkit.models.PubkyPublicKeyFormat import to.bitkit.models.WalletScope import to.bitkit.services.PaykitSdkOperationLock @@ -203,6 +205,15 @@ class PaykitPaymentProofRepo @Inject constructor( ) { throw PaykitPaymentRequestError.RequestUnavailable } + paykitSdkService.requirePaymentProofFits( + paymentReference = request.paymentReference, + paymentAppId = paymentAppId, + paymentEndpointIdentifier = paymentEndpointIdentifier, + kind = kind, + billingPeriod = request.billingPeriod, + conversionQuoteId = paymentTerms?.quoteId, + allowanceId = allowanceId, + ) val read = paykitSdkService.readPaymentRequests(request.counterparty) val identityStatus = read.identityStatus val identity = identityStatus?.publicKey?.let(PubkyPublicKeyFormat::normalized) @@ -1684,6 +1695,70 @@ private fun proofJson(kind: PaykitPaymentProofKind, data: String): String { }.toString() } +/** Hex length of the 32-byte preimage or transaction id a Bitcoin proof carries. */ +private const val BITCOIN_PROOF_DATA_LENGTH = 64 + +/** Hex digits of a 32-byte ERC-20 transaction hash after its `0x` prefix. */ +private const val USDT_TRANSACTION_HASH_DIGITS = 64 + +/** Hex digits of a 65-byte EIP-712 signature after its `0x` prefix. */ +private const val USDT_SIGNATURE_DIGITS = 130 + +/** The largest uint256 receipt log index, the longest one the SDK accepts in an ERC-20 proof. */ +internal const val USDT_MAX_RECEIPT_LOG_INDEX = + "115792089237316195423570985008687907853269984665640564039457584007913129639935" + +/** The longest proof Bitkit submits for this kind, so a measured proof is never shorter than the one sent. */ +internal fun PaykitPaymentProofKind.longestProofJson(): String = when (this) { + PaykitPaymentProofKind.Usdt -> Json.encodeToString( + PaykitUsdtProof.serializer(), + PaykitUsdtProof( + UsdtPaymentProof( + chainId = PaykitUsdt.CHAIN_ID, + transactionHash = "0x" + "0".repeat(USDT_TRANSACTION_HASH_DIGITS), + receiptLogIndex = USDT_MAX_RECEIPT_LOG_INDEX, + signature = "0x" + "0".repeat(USDT_SIGNATURE_DIGITS), + ), + ), + ) + PaykitPaymentProofKind.Lightning, PaykitPaymentProofKind.Onchain -> + proofJson(this, "0".repeat(BITCOIN_PROOF_DATA_LENGTH)) +} + +/** Log context for measuring a Payment Proof before payment. */ +private const val PROOF_SIZE_TAG = "PaykitProofSize" + +/** + * Fails with [PaykitPaymentRequestError.RequestUnavailable] when the longest proof of [kind] for these values would + * not fit one Private Application Message, or cannot be measured, so nothing is paid for a proof that could never be + * delivered. + */ +internal fun PaykitSdkService.requirePaymentProofFits( + paymentReference: String, + paymentAppId: String, + paymentEndpointIdentifier: String, + kind: PaykitPaymentProofKind, + billingPeriod: PaykitBillingPeriod?, + conversionQuoteId: String?, + allowanceId: String?, +) { + val length = runCatching { + paymentProofEventLength( + paymentReference = paymentReference, + paymentAppId = paymentAppId, + paymentEndpointIdentifier = paymentEndpointIdentifier, + proofJson = kind.longestProofJson(), + billingPeriod = billingPeriod, + conversionQuoteId = conversionQuoteId, + allowanceId = allowanceId, + ) + }.getOrElse { + Logger.warn("Failed to measure a Paykit payment proof", it, context = PROOF_SIZE_TAG) + throw PaykitPaymentRequestError.RequestUnavailable + } + if (length > PaykitSdkService.MAX_MESSAGE_BYTES.toUInt()) throw PaykitPaymentRequestError.RequestUnavailable +} + private fun String.proofValues(): JsonObject? = runCatching { Json.parseToJsonElement(this).jsonObject }.getOrNull() private fun String.matchesPaymentHash(paymentHash: String): Boolean { diff --git a/app/src/main/java/to/bitkit/repositories/PaykitPaymentRequestRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitPaymentRequestRepo.kt index 4e92b203ae..877c5a0438 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitPaymentRequestRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitPaymentRequestRepo.kt @@ -53,6 +53,7 @@ import to.bitkit.data.SettingsStore import to.bitkit.di.IoDispatcher import to.bitkit.di.SubscriptionClock import to.bitkit.env.Env +import to.bitkit.ext.isPaykitMessageTooLarge import to.bitkit.ext.runSuspendCatching import to.bitkit.flags.PaykitFeatureFlags import to.bitkit.models.PaykitAmount @@ -307,6 +308,7 @@ sealed class PaykitPaymentRequestError(message: String) : AppError(message) { data object RequestExpired : PaykitPaymentRequestError("Payment request has expired") data object OperationInProgress : PaykitPaymentRequestError("Payment request operation is already in progress") data object SubscriptionTooLong : PaykitPaymentRequestError("Subscription proposal exceeds the message size limit") + data object RequestTooLong : PaykitPaymentRequestError("Payment request proposal exceeds the message size limit") } enum class PaykitPaymentRequestRefreshMode { @@ -898,10 +900,11 @@ class PaykitPaymentRequestRepo @Inject constructor( proposalDate ) actionVersion++ - val record = paykitSdkService.proposePaymentRequest( + val record = proposeWithinMessageLimit( counterparty = target.publicKey, proposal = proposal, expectedIdentity = expectedIdentity, + tooLong = PaykitPaymentRequestError.RequestTooLong, ) val reports = processPendingMessages(target.publicKey) @@ -924,6 +927,19 @@ class PaykitPaymentRequestRepo @Inject constructor( } } + private suspend fun proposeWithinMessageLimit( + counterparty: String, + proposal: PaykitPaymentRequestProposalTerms, + expectedIdentity: String, + tooLong: PaykitPaymentRequestError, + ): PaymentRequestRecord = runSuspendCatching { + paykitSdkService.proposePaymentRequest( + counterparty = counterparty, + proposal = proposal, + expectedIdentity = expectedIdentity, + ) + }.getOrElse { throw if (it.isPaykitMessageTooLarge()) tooLong else it } + private fun buildPaymentRequestProposal( draft: PaykitPaymentRequestDraft, endpointIdentifiers: List, @@ -996,10 +1012,11 @@ class PaykitPaymentRequestRepo @Inject constructor( val proposal = buildSubscriptionProposal(draft, name, description, iconUri, endpoints, clock.now()) PaykitSubscriptionProposal.validate(proposal) actionVersion++ - val record = paykitSdkService.proposePaymentRequest( + val record = proposeWithinMessageLimit( counterparty = target.publicKey, proposal = proposal, expectedIdentity = expectedIdentity, + tooLong = PaykitPaymentRequestError.SubscriptionTooLong, ) val reports = processPendingMessages(target.publicKey) val deliveryStatus = if (proposalWasSent(record, reports, generation, expectedIdentity)) { diff --git a/app/src/main/java/to/bitkit/repositories/PaykitUsdtPaymentRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitUsdtPaymentRepo.kt index 2d9e01aaea..78b0c46176 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitUsdtPaymentRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitUsdtPaymentRepo.kt @@ -27,9 +27,6 @@ import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json -import kotlinx.serialization.json.JsonNull -import kotlinx.serialization.json.buildJsonObject -import kotlinx.serialization.json.put import to.bitkit.data.keychain.Keychain import to.bitkit.di.IoDispatcher import to.bitkit.ext.runSuspendCatching @@ -47,6 +44,7 @@ import java.util.UUID import javax.inject.Inject import javax.inject.Singleton import kotlin.time.Clock +import kotlin.time.Duration.Companion.hours import kotlin.time.ExperimentalTime import kotlin.time.Instant @@ -95,8 +93,10 @@ data class PaykitUsdtReceipt( val receivedAtMillis: Long, val underpaid: Boolean, val afterExpiry: Boolean, + /** Paid earlier than the payee recorded its own proposal, so it does not count as paying the request. */ + val beforeRequest: Boolean = false, ) { - val satisfied: Boolean get() = verified && !underpaid && !afterExpiry + val satisfied: Boolean get() = verified && !underpaid && !afterExpiry && !beforeRequest fun matches(request: PaykitPaymentRequest): Boolean = requestId == request.id && proofEventId == request.paymentProofEventId @@ -115,6 +115,12 @@ class PaykitUsdtPaymentRepo @Inject constructor( private val KEY = Keychain.Key.PAYKIT_USDT_PAYMENTS.name private const val TAG = "PaykitUsdtPaymentRepo" + /** + * How far an Arbitrum block timestamp may trail the payee's clock. The sequencer may set timestamps up to a + * day in the past, so a transfer counts as earlier than the request only beyond this margin. + */ + internal val PAYMENT_TIME_TOLERANCE = 24.hours + fun binding( request: PaykitPaymentRequest, identity: String, @@ -138,39 +144,6 @@ class PaykitUsdtPaymentRepo @Inject constructor( conversionQuoteId = quoteId.orEmpty(), ) } - - fun validateProofSize(binding: UsdtPaymentProofBinding) { - val profile = - PaykitUsdtProof( - UsdtPaymentProof("42161", "0x" + "0".repeat(64), "9".repeat(78), "0x" + "0".repeat(130)) - ) - val message = buildJsonObject { - put("version", 1) - put("kind", "paykit.payment_proof") - put("app_id", "bitkit") - put("event_id", UUID.randomUUID().toString()) - put("payment_request_id", binding.paymentRequestId) - put("payment_reference", binding.paymentReference) - put("payment_app_id", binding.paymentAppId) - put("payment_endpoint_identifier", binding.paymentEndpointIdentifier) - put( - "billing_period", - if (binding.periodStartsAt.isEmpty()) { - JsonNull - } else { - buildJsonObject { - put("starts_at", binding.periodStartsAt) - put("ends_at", binding.periodEndsAt) - } - } - ) - if (binding.conversionQuoteId.isNotEmpty()) put("conversion_quote_id", binding.conversionQuoteId) - put("proof", Json.encodeToJsonElement(PaykitUsdtProof.serializer(), profile)) - } - if (message.toString().toByteArray(Charsets.UTF_8).size > PaykitSdkService.MAX_MESSAGE_BYTES) { - throw PaykitPaymentRequestError.RequestUnavailable - } - } } @Serializable @@ -433,7 +406,17 @@ class PaykitUsdtPaymentRepo @Inject constructor( it.billingPeriod?.sdkValue ) } - binding?.let(::validateProofSize) + binding?.let { + sdk.requirePaymentProofFits( + paymentReference = it.paymentReference, + paymentAppId = it.paymentAppId, + paymentEndpointIdentifier = it.paymentEndpointIdentifier, + kind = PaykitPaymentProofKind.Usdt, + billingPeriod = request.billingPeriod, + conversionQuoteId = it.conversionQuoteId.takeIf(String::isNotEmpty), + allowanceId = null, + ) + } val attempt = PaykitUsdtAttempt( quote.id, @@ -665,6 +648,11 @@ class PaykitUsdtPaymentRepo @Inject constructor( updated } + private fun PaymentRequestRecord.isPaidBeforeProposal(paidAt: Instant): Boolean { + val proposedAt = proposalRecordedAt?.let { runCatching { Instant.parse(it) }.getOrNull() } ?: return false + return paidAt < proposedAt - PAYMENT_TIME_TOLERANCE + } + private fun PaykitUsdtAttempt.bindingState() = copy(proof = null, proofQueued = false, paymentStarted = false) private suspend fun reconcileReceipts(reconciliation: Reconciliation) { @@ -742,6 +730,7 @@ class PaykitUsdtPaymentRepo @Inject constructor( receivedAtMillis = receivedAt.toEpochMilliseconds(), underpaid = amount.atomic < terms.amount.atomic, afterExpiry = !terms.isValid(receivedAt), + beforeRequest = record.isPaidBeforeProposal(receivedAt), ) mutex.withLock { if (!isCurrent(reconciliation)) return@withLock diff --git a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt index 314ae4ef7f..4860858a76 100644 --- a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt +++ b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt @@ -83,6 +83,7 @@ import com.synonym.paykit.defaultConfig import com.synonym.paykit.defaultPubkyClientConfig import com.synonym.paykit.parsePubkyAuthUrl import com.synonym.paykit.paykitAuthorizerSessionCapabilities +import com.synonym.paykit.paymentProofEventLen import com.synonym.paykit.pubkyPublicKeyFromSecret import com.synonym.paykit.pubkySecretKeyFromBip39Mnemonic import dagger.hilt.android.qualifiers.ApplicationContext @@ -1297,6 +1298,31 @@ class PaykitSdkService @Inject constructor( } } + /** + * Byte length of the Payment Proof Event Message [submitPaymentProof] would queue for these values. The SDK builds + * it with the code it queues with, so a payer can check it against [MAX_MESSAGE_BYTES] before paying. + */ + fun paymentProofEventLength( + paymentReference: String, + paymentAppId: String, + paymentEndpointIdentifier: String, + proofJson: String, + billingPeriod: PaykitBillingPeriod? = null, + conversionQuoteId: String? = null, + allowanceId: String? = null, + ): UInt = PaymentReference(paymentReference).use { reference -> + PaymentProofSubmission( + billingPeriod = billingPeriod?.sdkValue, + paymentAppId = paymentAppId, + paymentEndpointIdentifier = paymentEndpointIdentifier, + allowanceId = allowanceId, + conversionQuoteId = conversionQuoteId, + proof = PrivateJsonObject(proofJson), + ).use { submission -> + paymentProofEventLen(localAppId = "bitkit", paymentReference = reference, submission = submission) + } + } + suspend fun listAllowances(filter: AllowanceFilter): List { isSetup.await() return operationLock.withLock { diff --git a/app/src/main/java/to/bitkit/ui/screens/paymentrequests/PaymentRequestsScreen.kt b/app/src/main/java/to/bitkit/ui/screens/paymentrequests/PaymentRequestsScreen.kt index c7f57fc0df..ee46ead94f 100644 --- a/app/src/main/java/to/bitkit/ui/screens/paymentrequests/PaymentRequestsScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/paymentrequests/PaymentRequestsScreen.kt @@ -820,6 +820,7 @@ private fun PaymentRequestsPreview() { internal fun paykitUsdtReceiptText(receipt: PaykitUsdtReceipt): String { val label = when { !receipt.verified -> R.string.wallet__payment_request_pending + receipt.beforeRequest -> R.string.wallet__payment_request_before_request receipt.underpaid -> R.string.wallet__payment_request_underpaid receipt.afterExpiry -> R.string.wallet__payment_request_after_expiry else -> R.string.wallet__payment_request_payment_verified diff --git a/app/src/main/java/to/bitkit/ui/utils/PubkyAuthErrorMessage.kt b/app/src/main/java/to/bitkit/ui/utils/PubkyAuthErrorMessage.kt index 252c03ba5e..cd1b15e547 100644 --- a/app/src/main/java/to/bitkit/ui/utils/PubkyAuthErrorMessage.kt +++ b/app/src/main/java/to/bitkit/ui/utils/PubkyAuthErrorMessage.kt @@ -1,7 +1,9 @@ package to.bitkit.ui.utils import android.content.Context +import com.synonym.paykit.PaykitException import to.bitkit.R +import to.bitkit.ext.isPaykitSignupCodeRejected import to.bitkit.models.PubkyAuthRequestError import to.bitkit.repositories.WatchOnlyAccountError import to.bitkit.services.PubkyRingAuthTimeoutError @@ -27,6 +29,8 @@ private fun Throwable.pubkyAuthMessageResource() = when (this) { PubkyAuthRequestError.DuplicateBitkitClaim -> R.string.profile__auth_error_duplicate_claim is PubkyAuthRequestError.UnsupportedBitkitClaim -> R.string.profile__auth_error_unsupported_claim PubkyAuthRequestError.InvalidBitkitClaimCapabilities -> R.string.profile__auth_error_invalid_capabilities + is PaykitException.Identity if isPaykitSignupCodeRejected() -> R.string.profile__auth_error_signup_code_rejected + is PaykitException.Transport -> R.string.pubky_auth__identity_unavailable_desc is WatchOnlyAccountError.AuthorizationAccountMissing -> R.string.watch_only_accounts__setup_not_finished is WatchOnlyAccountError.InvalidAccountName -> R.string.watch_only_accounts__error_invalid_name is WatchOnlyAccountError.InvalidExtendedPublicKey -> R.string.watch_only_accounts__error_invalid_xpub diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 95bcf05879..f0b2010bf1 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -8492,7 +8492,17 @@ class AppViewModel @Inject constructor( ) } } - .onFailure(::toast) + .onFailure { + if (it is PaykitPaymentRequestError.RequestTooLong) { + toast( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.common__error), + description = context.getString(R.string.wallet__payment_request_note_too_long), + ) + } else { + toast(it) + } + } } } diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index c8973f2586..d387d14087 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1287,6 +1287,7 @@ الوصول المطلوب لا يطابق مطالبة Bitkit هذه. رابط تفويض Pubky هذا غير صالح. ينقص هذا التفويض مطالبة Bitkit المطلوبة. + لم يقبل الخادم الرئيسي رمز التسجيل هذا. حاول مرة أخرى أو استخدم رابط تسجيل آخر. لم يستجب مُرحّل التفويض في الوقت المحدد. يرجى المحاولة مرة أخرى. فشل التفويض مطالبة Bitkit هذه غير مدعومة. @@ -1539,6 +1540,7 @@ قبول الدفع بـ مستلم · بعد انتهاء الصلاحية المبلغ + مستلم · قبل الطلب اختر المستلم تجاهل أدخل pubky @@ -1552,6 +1554,7 @@ لم تطابق تفاصيل الدفع الطلب. تم إلغاء الدفع. غير محدد ما الغرض من هذه الدفعة؟ + اختصر الملاحظة وحاول مرة أخرى. طلب أو دفع ادفع لـ %1$s أو اطلب دفعة. اطلب\n<accent>أو ادفع ₿</accent> diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index f62df577aa..0a78867a0c 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1313,6 +1313,7 @@ El acceso solicitado no coincide con esta declaración de Bitkit. Este enlace de autorización de Pubky no es válido. A esta autorización le falta la declaración de Bitkit requerida. + El homeserver no aceptó este código de registro. Inténtelo de nuevo o use otro enlace de registro. El relay de autorización no respondió a tiempo. Inténtelo de nuevo. Falló la autorización Esta declaración de Bitkit no es compatible. @@ -1546,6 +1547,7 @@ Aceptar pago en Recibido · Tras vencer Monto + Recibido · Antes de la solicitud Elegir destinatario Descartar Introduzca un pubky @@ -1559,6 +1561,7 @@ Los datos del pago no coincidieron con la solicitud. Pago cancelado. No especificado ¿Para qué es este pago? + Acorte la nota y vuelva a intentarlo. Solicitar o pagar Pague a %1$s o solicite un pago. Solicitar\n<accent>o pagar ₿</accent> diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index f87eac631f..fdd9acd4a9 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1309,6 +1309,7 @@ L\'accés sol·licitat no coincideix amb aquesta declaració de Bitkit. Aquest enllaç d\'autorització de Pubky no és vàlid. A aquesta autorització li falta la declaració de Bitkit necessària. + El homeserver no ha acceptat aquest codi de registre. Torna-ho a provar o fes servir un altre enllaç de registre. El relé d\'autorització no ha respost a temps. Torna-ho a provar. Ha fallat l\'autorització Aquesta declaració de Bitkit no és compatible. @@ -1543,6 +1544,7 @@ Acceptar pagament en Rebut · Després del venciment Import + Rebut · Abans de la sol·licitud Triar destinatari Descartar Introdueix un pubky @@ -1556,6 +1558,7 @@ Les dades del pagament no coincidien amb la sol·licitud. Pagament cancel·lat. No especificat Per a què és aquest pagament? + Escurça la nota i torna-ho a provar. Sol·licitar o pagar Paga a %1$s o sol·licita un pagament. Sol·licita\n<accent>o paga ₿</accent> diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index a6b2454328..c9211d9c80 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1311,6 +1311,7 @@ Požadovaný přístup neodpovídá tomuto nároku Bitkit. Tento autorizační odkaz Pubky je neplatný. V této autorizaci chybí požadovaný nárok Bitkit. + Homeserver tento registrační kód nepřijal. Zkuste to znovu nebo použijte jiný registrační odkaz. Autorizační relay neodpověděl včas. Zkuste to prosím znovu. Autorizace se nezdařila Tento nárok Bitkit není podporován. @@ -1546,6 +1547,7 @@ Přijmout platbu v Přijato · Po vypršení Částka + Přijato · Před žádostí Vybrat příjemce Odmítnout Zadejte pubky @@ -1559,6 +1561,7 @@ Platební údaje neodpovídaly žádosti. Platba byla zrušena. Neuvedeno Za co je tato platba? + Zkraťte poznámku a zkuste to znovu. Požádat nebo zaplatit Zaplaťte kontaktu %1$s nebo požádejte o platbu. Požádat\n<accent>nebo zaplatit ₿</accent> diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index d8a0d88b77..71aeca5dd2 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1309,6 +1309,7 @@ Der angeforderte Zugriff passt nicht zu diesem Bitkit-Claim. Dieser Pubky-Autorisierungslink ist ungültig. Dieser Autorisierung fehlt der erforderliche Bitkit-Claim. + Der Homeserver hat diesen Registrierungscode nicht akzeptiert. Versuche es erneut oder nutze einen anderen Registrierungslink. Das Autorisierungs-Relay hat nicht rechtzeitig geantwortet. Bitte versuche es erneut. Autorisierung fehlgeschlagen Dieser Bitkit-Claim wird nicht unterstützt. @@ -1545,6 +1546,7 @@ Zahlung akzeptieren in Empfangen · Nach Ablauf Betrag + Empfangen · Vor der Anforderung Empfänger wählen Verwerfen pubky eingeben @@ -1558,6 +1560,7 @@ Die Zahlungsdetails stimmten nicht mit der Anforderung überein. Zahlung abgebrochen. Nicht angegeben Wofür ist diese Zahlung? + Kürze die Notiz und versuche es erneut. Anfordern oder bezahlen Bezahle %1$s oder fordere eine Zahlung an. Anfordern\n<accent>oder ₿ zahlen</accent> diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 5b589e5087..5041fe127c 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1293,6 +1293,7 @@ Η ζητούμενη πρόσβαση δεν αντιστοιχεί σε αυτή τη δήλωση Bitkit. Αυτός ο σύνδεσμος εξουσιοδότησης Pubky δεν είναι έγκυρος. Σε αυτή την εξουσιοδότηση λείπει η απαιτούμενη δήλωση Bitkit. + Ο homeserver δεν δέχτηκε αυτόν τον κωδικό εγγραφής. Δοκίμασε ξανά ή χρησιμοποίησε άλλον σύνδεσμο εγγραφής. Ο αναμεταδότης εξουσιοδότησης δεν απάντησε εγκαίρως. Δοκίμασε ξανά. Η εξουσιοδότηση απέτυχε Αυτή η δήλωση Bitkit δεν υποστηρίζεται. @@ -1540,6 +1541,7 @@ Αποδοχή πληρωμής σε Ελήφθη · Μετά τη λήξη Ποσό + Ελήφθη · Πριν από το αίτημα Επιλογή παραλήπτη Απόρριψη Εισαγωγή pubky @@ -1553,6 +1555,7 @@ Τα στοιχεία πληρωμής δεν αντιστοιχούσαν στο αίτημα. Η πληρωμή ακυρώθηκε. Δεν καθορίστηκε Για τι είναι αυτή η πληρωμή; + Συντόμευσε τη σημείωση και δοκίμασε ξανά. Αίτημα ή πληρωμή Πλήρωσε τον/την %1$s ή ζήτησε πληρωμή. Αίτημα\n<accent>ή πληρωμή ₿</accent> diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 34faa374a7..dcbc58e3c5 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1307,6 +1307,7 @@ El acceso solicitado no coincide con esta reclamación de Bitkit. Este enlace de autorización de Pubky no es válido. A esta autorización le falta la reclamación de Bitkit necesaria. + El servidor principal no ha aceptado este código de registro. Inténtalo de nuevo o usa otro enlace de registro. El relé de autorización no respondió a tiempo. Inténtalo de nuevo. Error de autorización Esta reclamación de Bitkit no es compatible. @@ -1542,6 +1543,7 @@ Aceptar pago en Recibido · Tras caducar Cantidad + Recibido · Antes de la solicitud Elegir destinatario Descartar Introducir pubky @@ -1555,6 +1557,7 @@ Los datos del pago no coinciden con la solicitud. Pago cancelado. Sin especificar ¿Para qué es este pago? + Acorta la nota e inténtalo de nuevo. Solicitar o pagar Paga a %1$s o solicita un pago. Solicitar\n<accent>o pagar ₿</accent> diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index b9c24c4522..33a9bbce01 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1306,6 +1306,7 @@ El acceso solicitado no coincide con esta reclamación de Bitkit. Este enlace de autorización de Pubky no es válido. A esta autorización le falta la reclamación de Bitkit necesaria. + El servidor principal no aceptó este código de registro. Inténtelo de nuevo o use otro enlace de registro. El relé de autorización no respondió a tiempo. Inténtelo de nuevo. Error de autorización Esta reclamación de Bitkit no es compatible. @@ -1542,6 +1543,7 @@ Aceptar pago en Recibido · Tras caducar Cantidad + Recibido · Antes de la solicitud Elegir destinatario Descartar Introducir pubky @@ -1555,6 +1557,7 @@ Los datos del pago no coinciden con la solicitud. Pago cancelado. Sin especificar ¿Para qué es este pago? + Acorte la nota e inténtelo de nuevo. Solicitar o pagar Pague a %1$s o solicite un pago. Solicitar\n<accent>o pagar ₿</accent> diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 504d48a804..fbe36f81bc 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1307,6 +1307,7 @@ L\'accès demandé ne correspond pas à cette déclaration Bitkit. Ce lien d\'autorisation Pubky n\'est pas valide. Il manque à cette autorisation la déclaration Bitkit requise. + Le serveur domestique n\'a pas accepté ce code d\'inscription. Réessayez ou utilisez un autre lien d\'inscription. Le relais d\'autorisation n\'a pas répondu à temps. Veuillez réessayer. Échec de l\'autorisation Cette déclaration Bitkit n\'est pas prise en charge. @@ -1543,6 +1544,7 @@ Accepter le paiement en Reçu · Après expiration Montant + Reçu · Avant la demande Choisir le destinataire Contact Date @@ -1559,6 +1561,7 @@ Non précisé Note À quoi sert ce paiement ? + Raccourcissez la note et réessayez. Demander ou payer Payez %1$s ou demandez un paiement. Demander\n<accent>ou payer ₿</accent> diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index bbe3915683..38a8889d27 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1312,6 +1312,7 @@ L\'accesso richiesto non corrisponde a questa claim Bitkit. Questo link di autorizzazione Pubky non è valido. In questa autorizzazione manca la claim Bitkit richiesta. + L\'homeserver non ha accettato questo codice di registrazione. Riprova o usa un altro link di registrazione. Il relay di autorizzazione non ha risposto in tempo. Riprova. Autorizzazione Non Riuscita Questa claim Bitkit non è supportata. @@ -1545,6 +1546,7 @@ Accetta pagamento in Ricevuto · Dopo la scadenza Importo + Ricevuto · Prima della richiesta Scegli Destinatario Ignora Inserisci pubky @@ -1559,6 +1561,7 @@ Non specificato Nota A cosa serve questo pagamento? + Accorcia la nota e riprova. Richiedi o Paga Paga %1$s o richiedi un pagamento. Richiedi\n<accent>o Paga ₿</accent> diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 9e476721ba..c97f60b562 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1309,6 +1309,7 @@ De gevraagde toegang komt niet overeen met deze Bitkit-claim. Deze Pubky-autorisatielink is ongeldig. Deze autorisatie mist de vereiste Bitkit-claim. + De homeserver heeft deze aanmeldcode niet geaccepteerd. Probeer het opnieuw of gebruik een andere aanmeldlink. De autorisatierelay reageerde niet op tijd. Probeer het opnieuw. Autorisatie mislukt Deze Bitkit-claim wordt niet ondersteund. @@ -1545,6 +1546,7 @@ Betaling accepteren in Ontvangen · Na vervaldatum Bedrag + Ontvangen · Vóór het verzoek Ontvanger kiezen Contact Negeren @@ -1559,6 +1561,7 @@ De betaalgegevens kwamen niet overeen met het verzoek. Betaling geannuleerd. Niet opgegeven Waar is deze betaling voor? + Maak de notitie korter en probeer het opnieuw. Verzoeken of betalen Betaal %1$s of vraag een betaling aan. Verzoek\n<accent>of betaal ₿</accent> diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index db3199891a..21b12d0dfd 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1310,6 +1310,7 @@ Żądany dostęp nie odpowiada temu oświadczeniu Bitkit. Ten link autoryzacji Pubky jest nieprawidłowy. W tej autoryzacji brakuje wymaganego oświadczenia Bitkit. + Serwer domowy nie zaakceptował tego kodu rejestracji. Spróbuj ponownie lub użyj innego linku rejestracyjnego. Przekaźnik autoryzacji nie odpowiedział na czas. Spróbuj ponownie. Autoryzacja nie powiodła się To oświadczenie Bitkit nie jest obsługiwane. @@ -1545,6 +1546,7 @@ Akceptuj płatność w Otrzymano · Po terminie Kwota + Otrzymano · Przed żądaniem Wybierz odbiorcę Odrzuć Wprowadź pubky @@ -1558,6 +1560,7 @@ Dane płatności nie odpowiadają żądaniu. Płatność anulowana. Nie określono Za co jest ta płatność? + Skróć notatkę i spróbuj ponownie. Zażądaj lub zapłać Zapłać %1$s lub zażądaj płatności. Zażądaj\n<accent>lub zapłać ₿</accent> diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 47626cd119..7d3f385814 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1312,6 +1312,7 @@ O acesso solicitado não corresponde a esta declaração da Bitkit. Este link de autorização do Pubky é inválido. Esta autorização não contém a declaração da Bitkit necessária. + O homeserver não aceitou este código de cadastro. Tente novamente ou use outro link de cadastro. O relay de autorização não respondeu a tempo. Tente novamente. Falha na Autorização Esta declaração da Bitkit não é suportada. @@ -1546,6 +1547,7 @@ Aceitar pagamento em Recebido · Após o vencimento Valor + Recebido · Antes da solicitação Escolher Destinatário Dispensar Digite a pubky @@ -1559,6 +1561,7 @@ Os dados de pagamento não corresponderam à solicitação. Pagamento cancelado. Não especificado Para que é este pagamento? + Encurte a nota e tente novamente. Solicitar ou Pagar Pague %1$s ou solicite um pagamento. Solicitar\n<accent>ou Pagar ₿</accent> diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 1fece40c5e..00bc9f16c6 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1286,6 +1286,7 @@ O acesso pedido não corresponde a esta declaração Bitkit. Este link de autorização Pubky é inválido. Falta a esta autorização a declaração Bitkit obrigatória. + O homeserver não aceitou este código de registo. Tente novamente ou use outra ligação de registo. O relay de autorização não respondeu a tempo. Tente novamente. Falha na autorização Esta declaração Bitkit não é suportada. @@ -1540,6 +1541,7 @@ Aceitar pagamento em Recebido · Após expirar Montante + Recebido · Antes do pedido Escolher destinatário Ignorar Introduza o pubky @@ -1553,6 +1555,7 @@ Os dados de pagamento não correspondem ao pedido. Pagamento cancelado. Não especificado Para que é este pagamento? + Encurte a nota e tente novamente. Pedir ou pagar Pague a %1$s ou peça um pagamento. Pedir\n<accent>ou pagar ₿</accent> diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index c59eb8f103..4b2e2fea07 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1327,6 +1327,7 @@ Запрошенный доступ не соответствует этому заявлению Bitkit. Эта ссылка авторизации Pubky недействительна. В этой авторизации отсутствует обязательное заявление Bitkit. + Домашний сервер не принял этот код регистрации. Попробуйте снова или используйте другую ссылку для регистрации. Ретранслятор авторизации не ответил вовремя. Пожалуйста, попробуйте снова. Ошибка Авторизации Это заявление Bitkit не поддерживается. @@ -1560,6 +1561,7 @@ Принимать оплату в Получено · После истечения Сумма + Получено · До запроса Выберите Получателя Отклонить Введите pubky @@ -1573,6 +1575,7 @@ Платёжные данные не совпали с запросом. Платёж отменён. Не указано За что этот платёж? + Сократите заметку и попробуйте снова. Запросить или Оплатить Заплатите %1$s или запросите платёж. Запросить\n<accent>или Оплатить ₿</accent> diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 0581f041af..2e97ca9eb6 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -619,6 +619,7 @@ The requested access does not match this Bitkit claim. This Pubky authorization link is invalid. This authorization is missing its required Bitkit claim. + The homeserver did not accept this signup code. Try again or use another signup link. The authorization relay did not respond in time. Please try again. Authorization Failed This Bitkit claim is not supported. @@ -1413,6 +1414,7 @@ Accept payment in Received · After expiry Amount + Received · Before request Choose Recipient Contact Date @@ -1429,6 +1431,7 @@ Not specified Note What is this payment for? + Shorten the note and try again. Request Or Pay Pay %1$s or request a payment. Or Pay ₿]]> diff --git a/app/src/test/java/to/bitkit/models/PaykitPaymentStateBackupTest.kt b/app/src/test/java/to/bitkit/models/PaykitPaymentStateBackupTest.kt index 57d40557c6..4246506b4d 100644 --- a/app/src/test/java/to/bitkit/models/PaykitPaymentStateBackupTest.kt +++ b/app/src/test/java/to/bitkit/models/PaykitPaymentStateBackupTest.kt @@ -95,9 +95,24 @@ class PaykitPaymentStateBackupTest { assertEquals("2026-10-01T00:00:00.125Z", attempt.billingPeriod?.sdkValue?.startsAt) assertEquals(50_000uL, receipt.amount.atomic) assertEquals(attempt.requestId, receipt.requestId) + assertFalse(receipt.beforeRequest, "A backup written without the flag restores it as unset") val rebuilt = PaykitUsdtStateBackup(listOf(attempt), listOf(PaykitUsdtStateBackup.Receipt(receipt))) val json = Json { encodeDefaults = true } - assertEquals(json.parseToJsonElement(fixture), json.parseToJsonElement(json.encodeToString(rebuilt))) + val expected = fixture.replace("\"afterExpiry\": false", "\"afterExpiry\": false,\n\"beforeRequest\": false") + assertEquals(json.parseToJsonElement(expected), json.parseToJsonElement(json.encodeToString(rebuilt))) + } + + @Test + fun `usdt backup keeps a receipt paid before its request`() { + val backup = Json.decodeFromString(usdtBackupFixture) + val receipt = backup.receipts.single().restored().copy(beforeRequest = true) + + val restored = Json.decodeFromString( + Json.encodeToString(PaykitUsdtStateBackup(backup.attempts, listOf(PaykitUsdtStateBackup.Receipt(receipt)))), + ).receipts.single().restored() + + assertTrue(restored.beforeRequest) + assertFalse(restored.satisfied) } @Test diff --git a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt index d094fd3e70..8838ccaffd 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt @@ -412,6 +412,43 @@ class PaykitAllowanceExecutorTest : BaseUnitTest() { assertEquals(listOf(Stage.SUCCEEDED), sut.localState(identity).journal.map { it.stage }) } + @Test + fun `payment proof is measured with its allowance before the request is accepted`() = test { + val request = fixtures.paymentRequest() + whenever( + sdk.paymentProofEventLength(any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull()) + ).thenReturn(PaykitSdkService.MAX_MESSAGE_BYTES.toUInt()) + + val result = sut.autoPay(request, listOf(fixtures.allowance()), identity) + + assertEquals(PaykitAllowanceAutoPayResult.STARTED, result) + val order = inOrder(sdk, payer) + order.verify(sdk).paymentProofEventLength( + paymentReference = request.paymentReference, + paymentAppId = PAYMENT_APP_ID, + paymentEndpointIdentifier = fixtures.lightningIdentifier, + proofJson = PaykitPaymentProofKind.Lightning.longestProofJson(), + billingPeriod = null, + conversionQuoteId = null, + allowanceId = ALLOWANCE_ID, + ) + order.verify(payer).acceptOnThisInstall(eq(request), any()) + } + + @Test + fun `request whose payment proof would not fit one message stays manual without acceptance`() = test { + whenever( + sdk.paymentProofEventLength(any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull()) + ).thenReturn(PaykitSdkService.MAX_MESSAGE_BYTES.toUInt() + 1u) + + val result = sut.autoPay(fixtures.paymentRequest(), listOf(fixtures.allowance()), identity) + + assertEquals(PaykitAllowanceAutoPayResult.MANUAL, result) + verify(payer, never()).acceptOnThisInstall(any(), any()) + verify(sdk, never()).acceptPaymentRequestAutomatically(any(), any(), any(), any()) + verify(sdk, never()).reserveAutomaticPayment(any(), any(), any()) + } + @Test fun `blocked candidate stays manual without acceptance`() = test { candidates = listOf(candidate(blocked = AllowanceAccountingBlock.SharedRule("amount_outside_range"))) diff --git a/app/src/test/java/to/bitkit/repositories/PaykitIssuerInteropTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitIssuerInteropTest.kt index a5febcda89..3c3ff2d45a 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitIssuerInteropTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitIssuerInteropTest.kt @@ -149,6 +149,8 @@ class PaykitIssuerInteropTest { proposalAppId = "bitkit", payerAppId = null, executionClaimAppId = null, + proposalRecordedAt = null, + acceptanceRecordedAt = null, ) } diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt index c6f146bb78..4ea9a154cb 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt @@ -48,6 +48,7 @@ import org.lightningdevkit.ldknode.PaymentDirection import org.lightningdevkit.ldknode.PaymentKind import org.lightningdevkit.ldknode.PaymentStatus import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.argThat import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.doReturn @@ -156,7 +157,7 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { emptyList() } PaymentRequestRead(status, records) - }.whenever(paykitSdkService).readPaymentRequests(any(), org.mockito.kotlin.anyOrNull()) + }.whenever(paykitSdkService).readPaymentRequests(any(), anyOrNull()) whenever(store.load()).thenAnswer { if (shouldFailNextLoad) { shouldFailNextLoad = false @@ -253,6 +254,58 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { verify(paykitSdkService, never()).processPendingPrivateMessages() } + @Test + fun `lightning proof that fits one message is measured with its largest preimage before payment`() = test { + val request = paymentRequest(MethodId.Bolt11.rawValue) + whenever( + paykitSdkService.paymentProofEventLength(any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull()) + ).thenReturn(PaykitSdkService.MAX_MESSAGE_BYTES.toUInt()) + + paymentProofRepo() + .prepare(request, MethodId.Bolt11.rawValue, "bitkit", PaykitPaymentProofKind.Lightning, allowanceId = "a") + .getOrThrow() + + verify(paykitSdkService).paymentProofEventLength( + paymentReference = request.paymentReference, + paymentAppId = "bitkit", + paymentEndpointIdentifier = MethodId.Bolt11.rawValue, + proofJson = """{"data":"${"0".repeat(64)}","type":"bitcoin-bolt11-preimage"}""", + billingPeriod = request.billingPeriod, + conversionQuoteId = null, + allowanceId = "a", + ) + assertEquals(request.id, storedProofs.single().requestId) + } + + @Test + fun `onchain proof too large for one message fails before payment`() = test { + val request = paymentRequest(MethodId.P2wpkh.rawValue) + whenever( + paykitSdkService.paymentProofEventLength(any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull()) + ).thenReturn(PaykitSdkService.MAX_MESSAGE_BYTES.toUInt() + 1u) + + val result = paymentProofRepo() + .prepare(request, MethodId.P2wpkh.rawValue, "bitkit", PaykitPaymentProofKind.Onchain) + + assertEquals(PaykitPaymentRequestError.RequestUnavailable, result.exceptionOrNull()) + assertTrue(storedProofs.isEmpty()) + verify(paykitSdkService, never()).readPaymentRequests(any(), anyOrNull()) + } + + @Test + fun `proof the sdk cannot measure fails before payment as unavailable`() = test { + val request = paymentRequest(MethodId.Bolt11.rawValue) + whenever( + paykitSdkService.paymentProofEventLength(any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull()) + ).thenAnswer { throw PaykitException.Protocol("protocol_error", "Payment Proof cannot be measured") } + + val result = paymentProofRepo() + .prepare(request, MethodId.Bolt11.rawValue, "bitkit", PaykitPaymentProofKind.Lightning) + + assertEquals(PaykitPaymentRequestError.RequestUnavailable, result.exceptionOrNull()) + assertTrue(storedProofs.isEmpty()) + } + @Test fun `proof snapshot waits for local persistence to finish`() = test { val request = paymentRequest(MethodId.Bolt11.rawValue) @@ -3666,5 +3719,7 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { proposalAppId = "bitkit", payerAppId = null, executionClaimAppId = null, + proposalRecordedAt = null, + acceptanceRecordedAt = null, ) } diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoSubscriptionTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoSubscriptionTest.kt index e51e73d959..29c6e05819 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoSubscriptionTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoSubscriptionTest.kt @@ -9,6 +9,7 @@ import com.synonym.paykit.LinkedPeerRecord import com.synonym.paykit.LinkedPeerState import com.synonym.paykit.OutboundPrivateMessageStatus import com.synonym.paykit.OutboundPrivateSendReport +import com.synonym.paykit.PaykitException import com.synonym.paykit.PaykitStateObservation import com.synonym.paykit.PaymentConversion import com.synonym.paykit.PaymentDeadline @@ -543,6 +544,28 @@ class PaykitPaymentRequestRepoSubscriptionTest : BaseUnitTest(StandardTestDispat verify(paykitSdkService).proposePaymentRequest(any(), any(), eq(LOCAL_IDENTITY)) } + @Test + fun `creator proposal the sdk finds too large reports subscription content that is too long`() = test { + val target = stubSubscriptionProposal() + whenever(paykitSdkService.proposePaymentRequest(any(), any(), eq(LOCAL_IDENTITY))).doSuspendableAnswer { + throw PaykitException.Protocol("message_too_large", "Private Application Message exceeds the limit") + } + + val result = sut.proposeSubscription( + draft = PaykitSubscriptionDraft( + amount = PaykitAmount(PaykitAsset.BTC, 100_000uL), + name = "Monthly support", + description = "Thank you", + frequency = PaykitRecurrenceUnit.Month, + expiresAt = clock.now().plus(60.seconds), + ), + target = target, + savedPublicKeys = listOf(COUNTERPARTY), + ) + + assertEquals(PaykitPaymentRequestError.SubscriptionTooLong, result.exceptionOrNull()) + } + @Test fun `creator proposal publishes real time while the subscription clock offset is on`() = test { val target = stubSubscriptionProposal() @@ -1669,6 +1692,8 @@ class PaykitPaymentRequestRepoSubscriptionTest : BaseUnitTest(StandardTestDispat proposalAppId = "bitkit", payerAppId = null, executionClaimAppId = null, + proposalRecordedAt = null, + acceptanceRecordedAt = null, ) private fun linkedPeer( publicKey: String, diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoTest.kt index 148d9dc9ae..4da1a00f2e 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentRequestRepoTest.kt @@ -2654,6 +2654,34 @@ class PaykitPaymentRequestRepoTest : BaseUnitTest(StandardTestDispatcher()) { activity.checkRefreshAdmission(Priority.Background) } + @Test + fun `proposal too large for one message reports a note that is too long`() = test { + val target = stubProposal(paymentRequestRecord(role = PaymentRequestLocalRole.PAYEE)) + val draft = PaykitPaymentRequestDraft(PaykitAmount(PaykitAsset.BTC, 1uL), "Lunch", clock.now().plus(60.seconds)) + whenever(paykitSdkService.proposePaymentRequest(any(), any(), eq(LOCAL_IDENTITY))).doSuspendableAnswer { + throw PaykitException.Protocol("message_too_large", "Private Application Message exceeds the limit") + } + + val result = sut.propose(draft, target, listOf(COUNTERPARTY)) + + assertSame(PaykitPaymentRequestError.RequestTooLong, result.exceptionOrNull()) + assertFalse(sut.isCreatingRequest.value) + } + + @Test + fun `other proposal protocol errors are reported unchanged`() = test { + val target = stubProposal(paymentRequestRecord(role = PaymentRequestLocalRole.PAYEE)) + val draft = PaykitPaymentRequestDraft(PaykitAmount(PaykitAsset.BTC, 1uL), "Lunch", clock.now().plus(60.seconds)) + val failure = PaykitException.Protocol("protocol_error", "Link is not ready") + whenever(paykitSdkService.proposePaymentRequest(any(), any(), eq(LOCAL_IDENTITY))).doSuspendableAnswer { + throw failure + } + + val result = sut.propose(draft, target, listOf(COUNTERPARTY)) + + assertSame(failure, result.exceptionOrNull()) + } + @Test fun `proposal uses canonical terms and accepts available selected methods`() = test { val target = @@ -3664,6 +3692,8 @@ class PaykitPaymentRequestRepoTest : BaseUnitTest(StandardTestDispatcher()) { proposalAppId = "bitkit", payerAppId = null, executionClaimAppId = null, + proposalRecordedAt = null, + acceptanceRecordedAt = null, ) private fun linkedPeer( diff --git a/app/src/test/java/to/bitkit/repositories/PaykitUsdtPaymentRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitUsdtPaymentRepoTest.kt index e4f2795f08..49f98c7539 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitUsdtPaymentRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitUsdtPaymentRepoTest.kt @@ -64,12 +64,15 @@ import to.bitkit.services.UsdtService import to.bitkit.test.BaseUnitTest import to.bitkit.utils.AppError import to.bitkit.viewmodels.ContactPaymentContext +import java.math.BigInteger import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertTrue import kotlin.time.Clock import kotlin.time.Duration +import kotlin.time.Duration.Companion.hours +import kotlin.time.Duration.Companion.seconds import kotlin.time.ExperimentalTime import kotlin.time.Instant @@ -688,6 +691,7 @@ class PaykitUsdtPaymentRepoTest : BaseUnitTest() { for (invalidReceipt in listOf( receipt.copy(underpaid = true), receipt.copy(afterExpiry = true), + receipt.copy(beforeRequest = true), receipt.copy(verified = false), receipt.copy(proofEventId = "unrelated") )) { @@ -699,6 +703,52 @@ class PaykitUsdtPaymentRepoTest : BaseUnitTest() { } } + @Test + fun `transfer within the timestamp tolerance of the proposal pays the request`() = test { + val paidAt = clock.now() + for (proposedAt in listOf(paidAt - 1.hours, paidAt + PaykitUsdtPaymentRepo.PAYMENT_TIME_TOLERANCE)) { + val record = receivedRequest(proposalRecordedAt = proposedAt.toString()) + whenever(sdk.paymentRequests()).thenReturn(listOf(record)) + stubVerification(Result.success(verifiedPayment(paidAt))) + stored = null + val repo = repo() + + repo.reconcile().getOrThrow() + + val receipt = repo.receipts.value.single() + assertFalse(receipt.beforeRequest) + assertTrue(receipt.satisfied) + } + } + + @Test + fun `transfer earlier than the proposal beyond the tolerance does not pay the request`() = test { + val paidAt = clock.now() + val proposedAt = paidAt + PaykitUsdtPaymentRepo.PAYMENT_TIME_TOLERANCE + 1.seconds + val record = receivedRequest(proposalRecordedAt = proposedAt.toString()) + whenever(sdk.paymentRequests()).thenReturn(listOf(record)) + stubVerification(Result.success(verifiedPayment(paidAt))) + val repo = repo() + + repo.reconcile().getOrThrow() + + val receipt = repo.receipts.value.single() + assertTrue(receipt.verified) + assertTrue(receipt.beforeRequest) + assertFalse(receipt.satisfied) + assertTrue(repo.verifiedReceipts(identity).getOrThrow().isEmpty()) + assertEquals(receipt, PaykitUsdtStateBackup.Receipt(receipt).restored()) + } + + private fun verifiedPayment(paidAt: Instant) = UsdtVerifiedPayment( + "42161:transaction:0", + "transaction:0", + "sender", + address, + 50_000u, + paidAt.epochSeconds.toULong(), + ) + @Test fun `receipt status survives restart and reflects canonical execution and payment deadline`() = test { val record = receivedRequest().let { @@ -740,29 +790,48 @@ class PaykitUsdtPaymentRepoTest : BaseUnitTest() { } @Test - fun `proof envelope includes the application id at the UTF-8 message boundary`() { - val binding = PaykitUsdtPaymentRepo.binding(request, identity, "bitkit", null, null) - // The rc63 envelope and largest ERC-20 receipt proof reserve 692 bytes before the reference. - val exactLimit = binding.copy(paymentReference = "é".repeat(154)) - PaykitUsdtPaymentRepo.validateProofSize(exactLimit) - assertFailsWith { - PaykitUsdtPaymentRepo.validateProofSize( - exactLimit.copy(paymentReference = exactLimit.paymentReference + "x") - ) - } + fun `proof that fits one message is measured by the sdk before the payment is prepared`() = test { + whenever( + sdk.paymentProofEventLength(any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull()) + ).thenReturn(PaykitSdkService.MAX_MESSAGE_BYTES.toUInt()) + + repo().prepare(context(), quote, amount, request.payment(MethodId.UsdtArbitrum, clock.now())).getOrThrow() + + verify(sdk).paymentProofEventLength( + paymentReference = request.paymentReference, + paymentAppId = "bitkit", + paymentEndpointIdentifier = MethodId.UsdtArbitrum.rawValue, + proofJson = PaykitPaymentProofKind.Usdt.longestProofJson(), + billingPeriod = null, + conversionQuoteId = null, + allowanceId = null, + ) + assertTrue(stored != null) } @Test - fun `proof size is bounded before the payment is prepared`() = test { - val binding = PaykitUsdtPaymentRepo.binding(request, identity, "bitkit", null, request.billingPeriod?.sdkValue) - PaykitUsdtPaymentRepo.validateProofSize(binding) - val oversized = context(request.copy(paymentReference = "é".repeat(256))) - assertTrue( - repo().prepare(oversized, quote, amount, request.payment(MethodId.UsdtArbitrum, clock.now())).isFailure - ) + fun `proof too large for one message fails before the payment is prepared`() = test { + whenever( + sdk.paymentProofEventLength(any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull()) + ).thenReturn(PaykitSdkService.MAX_MESSAGE_BYTES.toUInt() + 1u) + + val result = repo().prepare(context(), quote, amount, request.payment(MethodId.UsdtArbitrum, clock.now())) + + assertEquals(PaykitPaymentRequestError.RequestUnavailable, result.exceptionOrNull()) assertEquals(null, stored) } + @Test + fun `longest usdt proof carries the largest receipt log index`() { + val proof = Json.decodeFromString(PaykitPaymentProofKind.Usdt.longestProofJson()) + + assertEquals(PaykitUsdt.CHAIN_ID, proof.chainId) + assertEquals(66, proof.transactionHash.length) + assertEquals(78, proof.receiptLogIndex.length) + assertEquals(BigInteger.ONE.shiftLeft(256) - BigInteger.ONE, BigInteger(proof.receiptLogIndex)) + assertEquals(132, proof.signature.length) + } + @Test fun `invalid evidence does not prevent another request from completing`() = test { val records = listOf(receivedRequest(), receivedRequest("550e8400-e29b-41d4-a716-446655440001")) @@ -785,7 +854,10 @@ class PaykitUsdtPaymentRepoTest : BaseUnitTest() { assertEquals(true, repo.receipts.value.single().satisfied) } - private fun receivedRequest(id: String = request.paymentRequestId): PaymentRequestRecord { + private fun receivedRequest( + id: String = request.paymentRequestId, + proposalRecordedAt: String? = null, + ): PaymentRequestRecord { val json = Json.encodeToString( PaykitUsdtProof(UsdtPaymentProof("42161", "0x" + "a".repeat(64), "0", "0x" + "b".repeat(130))) ) @@ -806,6 +878,8 @@ class PaykitUsdtPaymentRepoTest : BaseUnitTest() { proposalAppId = "bitkit", payerAppId = "bitkit", executionClaimAppId = "bitkit", + proposalRecordedAt = proposalRecordedAt, + acceptanceRecordedAt = null, terms = PaymentRequestTerms( PaymentRequestAmount("0.05", "usd"), reference, diff --git a/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt index a5327b4308..2a45bbc1ba 100644 --- a/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PrivatePaykitRepoTest.kt @@ -4522,6 +4522,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { }, failedToQueue = failedToQueue, failedToDeliver = failedToDeliver, + acknowledged = emptyList(), ) private fun cachedPublishedContact() = PrivatePaykitContactCacheData( @@ -4539,6 +4540,7 @@ class PrivatePaykitRepoTest : BaseUnitTest(StandardTestDispatcher()) { .map { privateListSyncChange(it.counterparty) }, failedToQueue = emptyList(), failedToDeliver = emptyList(), + acknowledged = emptyList(), ) private fun privateListSyncChange( diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index 426aaccb13..9f9cddce72 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -75,6 +75,7 @@ import to.bitkit.data.SettingsStore import to.bitkit.data.keychain.Keychain import to.bitkit.data.sharedpubky.SharedPubkyClient import to.bitkit.data.sharedpubky.SharedPubkyContract +import to.bitkit.ext.isPaykitTemporarilyUnavailable import to.bitkit.ext.runSuspendCatching import to.bitkit.models.PubkyAuthClaim import to.bitkit.models.PubkyAuthClaim.Item @@ -711,6 +712,43 @@ class PubkyRepoTest : BaseUnitTest() { httpClient.close() } + @Test + fun `createIdentity signs in when sign up finds the identity on another homeserver`() = test { + val httpClient = identityHttpClient() + sut = createSut(httpClient) + stubSignupKeys() + whenever(pubkyService.signUp("secret", "test-homeserver", "test-code")).thenAnswer { + throw AppError(PaykitException.Policy("policy_error", "Identity lives on another homeserver")) + } + whenever(pubkyService.signIn("secret")).thenReturn(Unit) + whenever(pubkyService.publishPaykitProfile(any())).thenReturn(mock()) + + val result = sut.createIdentity("Test", "", emptyList(), emptyList(), null) + httpClient.close() + + assertTrue(result.isSuccess) + assertEquals(VALID_SELF_KEY, sut.publicKey.value) + verifyBlocking(pubkyService) { signIn("secret") } + } + + @Test + fun `createIdentity reports a transport failure without signing up again`() = test { + val httpClient = identityHttpClient() + sut = createSut(httpClient) + stubSignupKeys() + val offline = PaykitException.Transport("transport_error", "Homeserver unavailable") + whenever(pubkyService.signUp("secret", "test-homeserver", "test-code")).thenAnswer { throw AppError(offline) } + whenever(pubkyService.signIn("secret")).thenAnswer { throw AppError(offline) } + + val result = sut.createIdentity("Test", "", emptyList(), emptyList(), null) + httpClient.close() + + assertTrue(result.exceptionOrNull()?.isPaykitTemporarilyUnavailable() == true) + assertNull(sut.publicKey.value) + verifyBlocking(pubkyService, times(1)) { signUp(any(), any(), any()) } + verifyBlocking(pubkyService, never()) { publishPaykitProfile(any()) } + } + @Test fun `createIdentity should preserve signup session when pending profile publication fails`() = test { val registeredSession = mock() diff --git a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt index a228d3193c..3ef1927900 100644 --- a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt @@ -225,7 +225,13 @@ class PaykitSdkServiceTest { } "revision" } - val report = PrivatePaymentListDeliveryReport(emptyList(), emptyList(), emptyList(), emptyList()) + val report = PrivatePaymentListDeliveryReport( + emptyList(), + emptyList(), + emptyList(), + emptyList(), + emptyList(), + ) whenever(sdk.syncPrivatePaymentListsWithReservationsAndProcessOutbound(any(), any())).thenReturn(report) val updates = listOf(PrivatePaymentListReservationUpdateInput(RING_PUBKY, listOf(mock()))) val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } @@ -2495,7 +2501,7 @@ class PaykitSdkServiceTest { withdrawal.thenThrow(IllegalStateException("network unavailable")) } else { withdrawal.thenReturn( - PrivatePaymentListDeliveryReport(emptyList(), emptyList(), emptyList(), emptyList()), + PrivatePaymentListDeliveryReport(emptyList(), emptyList(), emptyList(), emptyList(), emptyList()), ) } val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } @@ -3313,7 +3319,7 @@ class PaykitSdkServiceTest { val sdk = mock() val started = CompletableDeferred() val resume = CompletableDeferred() - val report = PrivatePaymentListDeliveryReport(emptyList(), emptyList(), emptyList(), emptyList()) + val report = PrivatePaymentListDeliveryReport(emptyList(), emptyList(), emptyList(), emptyList(), emptyList()) whenever(sdk.linkedPeers()).thenReturn(listOf(contactPeer(LinkedPeerState.LINKED))) whenever(sdk.syncPrivatePaymentListsWithReservationsAndProcessOutbound(any(), any())).doSuspendableAnswer { started.complete(Unit) @@ -3373,7 +3379,7 @@ class PaykitSdkServiceTest { whenever(sdk.paykitAppRegistry(RING_PUBKY)).thenReturn( PaykitAppRegistry(1u, null, listOf(PaykitApp("bitkit", "Bitkit", capabilities)), null, emptyMap()), ) - val report = PrivatePaymentListDeliveryReport(emptyList(), emptyList(), emptyList(), emptyList()) + val report = PrivatePaymentListDeliveryReport(emptyList(), emptyList(), emptyList(), emptyList(), emptyList()) val updates = listOf(RING_PUBKY, other).map { PrivatePaymentListReservationUpdateInput(it, emptyList()) } whenever(sdk.syncPrivatePaymentListsWithReservationsAndProcessOutbound(updates, false)).thenReturn(report) val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } @@ -3420,6 +3426,7 @@ class PaykitSdkServiceTest { emptyList() }, failedToDeliver = emptyList(), + acknowledged = emptyList(), ) } val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } diff --git a/app/src/test/java/to/bitkit/ui/utils/PubkyAuthErrorMessageTest.kt b/app/src/test/java/to/bitkit/ui/utils/PubkyAuthErrorMessageTest.kt index c8c5df8432..c7393e5cfa 100644 --- a/app/src/test/java/to/bitkit/ui/utils/PubkyAuthErrorMessageTest.kt +++ b/app/src/test/java/to/bitkit/ui/utils/PubkyAuthErrorMessageTest.kt @@ -2,6 +2,7 @@ package to.bitkit.ui.utils import android.content.Context import com.synonym.bitkitcore.PubkyException +import com.synonym.paykit.PaykitException import org.junit.Test import org.mockito.kotlin.mock import org.mockito.kotlin.whenever @@ -41,4 +42,29 @@ class PubkyAuthErrorMessageTest : BaseUnitTest() { assertEquals(localizedMessage, AppError(AppError(error)).localizedPubkyAuthMessage(context)) } } + + @Test + fun `refused signup codes and transport failures show their own descriptions`() { + val cases = listOf( + PaykitException.Identity("signup_code_rejected", "sign up") to + R.string.profile__auth_error_signup_code_rejected, + PaykitException.Transport("transport_error", "sign up") to R.string.pubky_auth__identity_unavailable_desc, + ) + cases.forEach { (error, resource) -> + val localizedMessage = "Localized message for $resource" + whenever(context.getString(resource)).thenReturn(localizedMessage) + + assertEquals(localizedMessage, AppError(error).localizedPubkyAuthMessage(context)) + } + } + + @Test + fun `other identity errors keep the localized fallback`() { + val localizedMessage = "Localized unknown error" + whenever(context.getString(R.string.common__error_body)).thenReturn(localizedMessage) + + val error = PaykitException.Identity("identity_error", "sign up") + + assertEquals(localizedMessage, AppError(error).localizedPubkyAuthMessage(context)) + } } diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 89de855cf8..6666d9eb26 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -11333,6 +11333,33 @@ class AppViewModelSendFlowTest : BaseUnitTest() { ) } + @Test + fun `payment request too long to send asks to shorten the note`() = test { + val target = PaykitPaymentRequestTarget("pubkyrecipient") + val draft = PaykitPaymentRequestDraft( + amount = PaykitAmount(PaykitAsset.BTC, 1_000uL), + note = "💜".repeat(256), + expiresAt = Clock.System.now() + 60.seconds, + ) + whenever(context.getString(R.string.common__error)).thenReturn("Error") + whenever(context.getString(R.string.wallet__payment_request_note_too_long)) + .thenReturn("Shorten the note and try again.") + whenever(paykitPaymentRequestRepo.propose(draft, target, emptyList())) + .thenReturn(Result.failure(PaykitPaymentRequestError.RequestTooLong)) + var created = false + + sut.createPaymentRequest(draft, target) { created = true } + runCurrent() + + assertFalse(created) + verify(toastManager).enqueue( + check { + assertEquals(Toast.ToastType.ERROR, it.type) + assertEquals("Shorten the note and try again.", it.description) + } + ) + } + @Test fun `incoming payment request closes when it is no longer pending`() = test { val request = paymentRequest() diff --git a/changelog.d/next/1803.fixed.md b/changelog.d/next/1803.fixed.md new file mode 100644 index 0000000000..23eb778524 --- /dev/null +++ b/changelog.d/next/1803.fixed.md @@ -0,0 +1 @@ +Paykit payment requests now check that a payment proof fits before paying, explain notes that are too long and refused signup codes, and no longer count a USDT transfer sent before its request as payment. diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 9767d1a465..842f1aa85c 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -22,7 +22,7 @@ appcompat = { module = "androidx.appcompat:appcompat", version = "1.7.1" } barcode-scanning = { module = "com.google.mlkit:barcode-scanning", version = "17.3.0" } biometric = { module = "androidx.biometric:biometric", version = "1.4.0-alpha05" } bitkit-core = { module = "com.synonym:bitkit-core-android", version = "0.8.0-rc11" } -paykit = { module = "com.synonym:paykit-android", version = "0.1.1-rc2" } +paykit = { module = "com.synonym:paykit-android", version = "0.1.1-rc6" } bouncycastle-pkix-jdk = { module = "org.bouncycastle:bcpkix-jdk18on", version = "1.83" } bouncycastle-provider-jdk = { module = "org.bouncycastle:bcprov-jdk18on", version = "1.83" } camera-camera2 = { module = "androidx.camera:camera-camera2", version.ref = "camera" } diff --git a/journeys/payment-requests/README.md b/journeys/payment-requests/README.md index 00b162d346..52e26a2c24 100644 --- a/journeys/payment-requests/README.md +++ b/journeys/payment-requests/README.md @@ -37,6 +37,10 @@ The accepted journey uses: Rejected fixture shapes stay in unit tests because Bitkit intentionally does not present requests that fail the contract gate. +`request-note-too-long.xml` checks that a request whose note does not fit one Paykit message is +refused with "Shorten the note and try again." before anything is sent, and sends after the note is +shortened. It uses the same two-instance setup as `request-summary.xml`. + `success-dismissal.xml` matches iOS's journey: after paying a Lightning request, closing success must leave no error toast or duplicate payment; closing a later unpaid request must not send it. Use two linked disposable regtest wallets and observe or record dismissal to catch short-lived toasts. diff --git a/journeys/payment-requests/request-note-too-long.xml b/journeys/payment-requests/request-note-too-long.xml new file mode 100644 index 0000000000..b9808cc522 --- /dev/null +++ b/journeys/payment-requests/request-note-too-long.xml @@ -0,0 +1,18 @@ + + + Verifies that a Payment Request whose note does not fit one Paykit message is refused before anything is sent, with a message asking to shorten the note, and that the same request sends once the note is shortened. Requires two Bitkit instances saved as each other's contacts and linked as identities. See README.md. Paste the long note from the device clipboard rather than typing it, since adb input cannot type emoji. + + + Copy a note of 256 "💜" characters to the requester's clipboard + On the requester, open the payer contact, tap Pay (testTag "ContactPay") and tap Request on the sheet + Enter 1,000 sats on the Payment Request amount screen and tap Continue (testTag "PaymentRequestAmountContinue") + Paste the copied note into the note field (testTag "PaymentRequestNote") + Tap Send (testTag "PaymentRequestSend") + Verify an error toast says "Shorten the note and try again." and the request screen stays open with Send (testTag "PaymentRequestSend") visible + On the payer, verify no new Payment Request appears + On the requester, replace the note with "Coffee" and tap Send (testTag "PaymentRequestSend") + Verify completion (testTag "PaymentRequestSent") is shown + On the payer, verify the Payment Request confirmation screen (testTag "PaymentRequestConfirm") appears with 1,000 sats and For (testTag "PaymentRequestFor") shows "Coffee" + Close the Payment Request confirmation screen without paying + + diff --git a/journeys/pubky-auth/README.md b/journeys/pubky-auth/README.md index 83e54928ff..45dffe13df 100644 --- a/journeys/pubky-auth/README.md +++ b/journeys/pubky-auth/README.md @@ -18,10 +18,13 @@ - `grant-signup.xml` checks consent, cancellation, homeserver registration, and profile setup for a fresh identity. - `grant-signup-existing-identity.xml` checks approval with an existing identity without opening profile setup. +- `grant-signup-rejected-code.xml` checks the message for a signup code the homeserver refuses, and that no identity is created. -Both require a fresh `pubkyauth://signup_grant` URL from a controlled requesting app, a reachable +The first two require a fresh `pubkyauth://signup_grant` URL from a controlled requesting app, a reachable homeserver and authorization relay, and a valid invite when required. The new-identity fixture -uses ordinary app permissions without a Bitkit companion claim. +uses ordinary app permissions without a Bitkit companion claim. The rejected-code journey instead +needs a URL whose signup token that homeserver refuses, such as the token of a link another wallet +already completed. Deliver each grant signup request through the main wallet scanner: copy the complete URL to the device clipboard, tap **Scan**, then **Paste**, and allow clipboard access if prompted. Camera diff --git a/journeys/pubky-auth/grant-signup-rejected-code.xml b/journeys/pubky-auth/grant-signup-rejected-code.xml new file mode 100644 index 0000000000..4a9af76994 --- /dev/null +++ b/journeys/pubky-auth/grant-signup-rejected-code.xml @@ -0,0 +1,17 @@ + + + Verifies that a signup link whose signup code the homeserver refuses shows a specific message, keeps the authorization sheet open for another try, and creates no identity. Precondition: an isolated unlocked wallet with Paykit enabled and no Pubky identity. A controlled requesting app supplies a signup_grant URL for a reachable homeserver and relay whose signup token that homeserver has already used or does not know, for example the token of a signup_grant URL another wallet already completed. The URL requests ordinary app permissions without a Bitkit companion claim. + + + Copy the prepared signup_grant URL with the refused signup token to the device clipboard + Tap the main wallet Scan button (id "Scan") + If camera permission is requested, deny it to use clipboard input + Tap Paste + Allow clipboard access if prompted + Tap Authorize (id "PubkyAuthAuthorize") and complete PIN or biometric approval when enabled + Verify an error toast says "The homeserver did not accept this signup code. Try again or use another signup link." + Verify the authorization sheet is still open with Authorize (id "PubkyAuthAuthorize") enabled + Verify the Create Profile screen (id "CreateProfileSave") is not shown + Close the authorization sheet and verify the wallet still has no Pubky identity + + From d53988716f34f8014302007683d677c861717a96 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 14:31:35 +0100 Subject: [PATCH 03/11] Merge pull request #1801 from synonymdev/feat/pubky-app-profile feat: use the pubky.app profile directly (cherry picked from commit e062e8621b1c8196e0e67aaad6138f8dc92ca76b) --- .../main/java/to/bitkit/data/PubkyStore.kt | 12 +- .../java/to/bitkit/models/PubkyProfile.kt | 12 + .../java/to/bitkit/repositories/PubkyRepo.kt | 576 +++++++++++-- .../to/bitkit/services/PaykitSdkService.kt | 56 +- .../java/to/bitkit/services/PubkyService.kt | 30 +- .../bitkit/ui/components/ProfileEditForm.kt | 44 +- .../ui/screens/profile/CreateProfileScreen.kt | 3 +- .../screens/profile/CreateProfileViewModel.kt | 9 +- .../ui/screens/profile/EditProfileScreen.kt | 5 +- .../screens/profile/EditProfileViewModel.kt | 33 +- .../ui/screens/profile/ProfileViewModel.kt | 2 +- app/src/main/res/values-ar/strings.xml | 4 +- app/src/main/res/values-b+es+419/strings.xml | 4 +- app/src/main/res/values-ca/strings.xml | 4 +- app/src/main/res/values-cs/strings.xml | 4 +- app/src/main/res/values-de/strings.xml | 4 +- app/src/main/res/values-el/strings.xml | 4 +- app/src/main/res/values-es-rES/strings.xml | 4 +- app/src/main/res/values-es/strings.xml | 4 +- app/src/main/res/values-fr/strings.xml | 4 +- app/src/main/res/values-it/strings.xml | 4 +- app/src/main/res/values-nl/strings.xml | 4 +- app/src/main/res/values-pl/strings.xml | 4 +- app/src/main/res/values-pt-rBR/strings.xml | 4 +- app/src/main/res/values-pt/strings.xml | 4 +- app/src/main/res/values-ru/strings.xml | 4 +- app/src/main/res/values/strings.xml | 4 +- .../to/bitkit/repositories/PubkyRepoTest.kt | 766 +++++++++++++++--- .../bitkit/services/PaykitSdkServiceTest.kt | 6 +- .../services/PaykitSdkServiceWipeTest.kt | 2 + .../contacts/ContactSaveSessionChangeTest.kt | 9 + .../profile/EditProfileViewModelTest.kt | 13 +- changelog.d/next/1801.added.md | 1 + gradle/libs.versions.toml | 2 +- journeys/profile/README.md | 2 + journeys/profile/edit-pubky-app-profile.xml | 18 + 36 files changed, 1422 insertions(+), 243 deletions(-) create mode 100644 changelog.d/next/1801.added.md create mode 100644 journeys/profile/edit-pubky-app-profile.xml diff --git a/app/src/main/java/to/bitkit/data/PubkyStore.kt b/app/src/main/java/to/bitkit/data/PubkyStore.kt index 43e27f3409..5460a40af1 100644 --- a/app/src/main/java/to/bitkit/data/PubkyStore.kt +++ b/app/src/main/java/to/bitkit/data/PubkyStore.kt @@ -28,8 +28,14 @@ class PubkyStore @Inject constructor( store.updateData(transform) } + /** Clears the session's data but keeps the migration history, so a profile deleted on pubky.app stays deleted. */ suspend fun reset() { - store.updateData { PubkyStoreData() } + store.updateData { + PubkyStoreData( + pubkyAppProfileOwners = it.pubkyAppProfileOwners, + pubkyAppAvatarPending = it.pubkyAppAvatarPending, + ) + } } } @@ -41,6 +47,10 @@ data class PubkyStoreData( val cachedName: String? = null, val cachedImageUri: String? = null, val contactProfileOverrides: Map = emptyMap(), + /** Identities Bitkit has seen a pubky.app profile for, so a profile deleted there is not moved back from Bitkit. */ + val pubkyAppProfileOwners: Set = emptySet(), + /** Identities whose Bitkit avatar is still to be moved to pubky.app, retried on each profile load. */ + val pubkyAppAvatarPending: Set = emptySet(), ) { fun cachedProfile(): PubkyCachedProfile? = cachedProfileOwner?.let { PubkyCachedProfile(publicKey = it, name = cachedName.orEmpty(), imageUri = cachedImageUri) diff --git a/app/src/main/java/to/bitkit/models/PubkyProfile.kt b/app/src/main/java/to/bitkit/models/PubkyProfile.kt index d5e846c802..214f48a309 100644 --- a/app/src/main/java/to/bitkit/models/PubkyProfile.kt +++ b/app/src/main/java/to/bitkit/models/PubkyProfile.kt @@ -10,6 +10,18 @@ import com.synonym.paykit.PubkyProfile as SdkPubkyProfile private val pubkyProfileJson = Json { ignoreUnknownKeys = true } +/** pubky.app profile name limits from pubky-app-specs. */ +const val PROFILE_NAME_MIN_LENGTH = 3 +const val PROFILE_NAME_MAX_LENGTH = 50 +const val PROFILE_LINKS_MAX_COUNT = 5 + +/** pubky.app counts code points, not UTF-16 chars. */ +fun isValidProfileName(name: String) = name.trim().let { it.codePointCount(0, it.length) } in + PROFILE_NAME_MIN_LENGTH..PROFILE_NAME_MAX_LENGTH + +fun String.takeCodePoints(max: Int) = + if (codePointCount(0, length) <= max) this else substring(0, offsetByCodePoints(0, max)) + @Immutable data class PubkyProfileLink(val label: String, val url: String) diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index 57a3d390dd..725f8307c4 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -6,8 +6,11 @@ import androidx.core.graphics.scale import coil3.ImageLoader import com.synonym.paykit.ContactRecord import com.synonym.paykit.ContactUpdate +import com.synonym.paykit.PaykitException import com.synonym.paykit.ProfileResolution import com.synonym.paykit.PubkyAuthCompanionClaim +import com.synonym.paykit.PubkyProfileSnapshot +import com.synonym.paykit.PubkyProfileUpdate import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.request.post @@ -68,12 +71,15 @@ import to.bitkit.models.PubkyProfileLink import to.bitkit.models.PubkyPublicKeyFormat import to.bitkit.models.PubkySessionBackupKind import to.bitkit.models.PubkySessionBackupV1 +import to.bitkit.models.takeCodePoints import to.bitkit.services.PaykitReadLane import to.bitkit.services.PaykitReadTimeoutError import to.bitkit.services.PubkyService import to.bitkit.utils.AppError import to.bitkit.utils.Logger import java.io.ByteArrayOutputStream +import java.net.URI +import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicLong import javax.inject.Inject import javax.inject.Singleton @@ -83,6 +89,7 @@ import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds import kotlin.time.ExperimentalTime +import com.synonym.paykit.PubkyProfileLink as SdkPubkyProfileLink sealed class PubkyContactError(message: String) : AppError(message) { data object AlreadyExists : PubkyContactError("Contact already exists") @@ -109,6 +116,29 @@ private fun Throwable.isPaykitReadTimeout(): Boolean = data object PubkyAlreadySignedInError : AppError("Already signed in") +/** + * The profile an edit starts from and the pubky.app revision it was read at; null when none exists yet. [tagsUnread] is + * set when the Paykit copy could not be read, so the profile's tags are not the stored ones and a save keeps those. + */ +data class ProfileEditBase(val profile: PubkyProfile?, val revision: String?, val tagsUnread: Boolean = false) + +/** The pubky.app profile changed since Bitkit loaded it, so the save was not applied. */ +class PubkyProfileChangedError(cause: Throwable) : AppError("Profile changed in pubky.app", cause = cause) + +/** The other fields were saved and [base] is where a retry starts from, but the tag change was not. */ +class PubkyProfileTagsNotSavedError(val base: ProfileEditBase, cause: Throwable? = null) : + AppError("Profile tags were not saved", cause = cause) + +private class PubkyProfileNotFoundError : AppError("Profile not found") + +private class SavedProfile(val profile: PubkyProfile, val revision: String, val tagError: Throwable?) + +private class StoredCopy(val tags: List?, val image: String?) + +private class FittedProfile(val name: String, val bio: String, val links: List) + +private class RestoreBase(val publicKey: String, val profile: PubkyProfile, val revision: String?) + /** Whether a Pubky identity is ready to use once restores already under way have finished. */ enum class PubkyIdentityReadiness { /** A session is active. */ @@ -159,6 +189,17 @@ class PubkyRepo @Inject constructor( /** Delay after a deferred restore before another attempt may begin. */ private val DEFERRED_RESTORE_INTERVAL = 5.seconds + + // pubky.app profile limits (pubky-app-specs), applied when moving a Bitkit profile there. + private const val PUBKY_APP_NAME_MAX_LENGTH = 50 + private const val PUBKY_APP_BIO_MAX_LENGTH = 160 + private const val PUBKY_APP_LINKS_MAX_COUNT = 5 + private val ISO_DATE = Regex("""\d{4}-\d{2}-\d{2}""") + private val WEB_SCHEMES = setOf("http", "https", "ws", "wss", "ftp") + private val IPV4 = Regex("""\d{1,3}(\.\d{1,3}){3}""") + private const val PUBKY_APP_LINK_TITLE_MAX_LENGTH = 100 + private const val PUBKY_APP_LINK_URL_MAX_LENGTH = 300 + private const val PUBKY_APP_AVATAR_MAX_BYTES = 5_242_880uL } private val scope = appScope(ioDispatcher, TAG) @@ -184,6 +225,27 @@ class PubkyRepo @Inject constructor( private val adoptedSourceCheckMutex = Mutex() private val adoptionMutex = Mutex() private val profileWriteGeneration = AtomicLong(0L) + + // Held by each own-profile write and by profile deletion, so a deletion waits for the writes under way. The + // deletion moves the generation on, so a load or save that started before or during it writes nothing after. + private val profileWriteMutex = Mutex() + private val profileDeletionGeneration = AtomicLong(0L) + + // Moved on when a save starts and when it ends. A load writes the Paykit copy back only when no save runs and none + // ran since it read the copy, so it never writes back tags a save replaced. + private val profileSaveEpoch = AtomicLong(0L) + private val profileSavesRunning = AtomicInteger(0) + + /** Revision of the loaded pubky.app profile, which a save must still match; null when none exists. */ + @Volatile + private var ownProfileRevision: String? = null + + /** Whether the last profile load could not read the Paykit copy, so the shown tags are not the stored ones. */ + @Volatile + private var tagsUnavailable = false + + @Volatile + private var restoreBase: RestoreBase? = null private val signInGeneration = AtomicLong(0L) private val storedIdentityRevision = AtomicLong(0L) private val readOnlyProfileGeneration = AtomicLong(0L) @@ -802,10 +864,9 @@ class PubkyRepo @Inject constructor( try { runSuspendCatching { withContext(ioDispatcher) { - resolveContactProfile(signIn.publicKey, retry = true).getOrThrow() - ?: throw AppError("Profile not found") + loadOwnProfile(signIn.publicKey) ?: throw PubkyProfileNotFoundError() } - }.onSuccess { loadedProfile -> + }.onSuccess { (loadedProfile, revision) -> var isCurrent = false _profile.update { isCurrent = isCurrentLoad() @@ -815,10 +876,17 @@ class PubkyRepo @Inject constructor( Logger.debug("Skipped stale profile load for '${redacted(signIn.publicKey)}'", context = TAG) return@onSuccess } + ownProfileRevision = revision invalidateReadOnlyProfile() cacheMetadata(loadedProfile, isCurrentLoad) }.onFailure { Logger.error("Failed to load profile", it, context = TAG) + // A profile deleted on pubky.app is set up again rather than left unreachable. + if (it is PubkyProfileNotFoundError && isCurrentLoad()) { + _profile.update { null } + ownProfileRevision = null + settingsStore.setPubkyProfileSetupPending(true) + } } completedProfileSignInGeneration = signIn.generation completedProfileWriteGeneration = writeGeneration @@ -841,7 +909,8 @@ class PubkyRepo @Inject constructor( val secret = keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name) ?: adoptedSecretKeyHex() ?: return@runSuspendCatching null val owner = pubkyService.publicKeyFromSecret(secret).ensurePubkyPrefix() - resolveContactProfile(owner, retry = false).getOrThrow() + pubkyService.fetchPubkyProfileWithRevision(owner) + ?.let { PubkyProfile.fromPubkyProfile(owner, it.profile) } }.onSuccess { loaded -> synchronized(readOnlyProfileLock) { if (isCurrentLoad()) _readOnlyProfile.update { loaded } @@ -855,8 +924,27 @@ class PubkyRepo @Inject constructor( } } - suspend fun fetchRemoteProfile(publicKey: String): Result = - resolveContactProfile(publicKey, retry = true) + suspend fun fetchRemoteProfile(publicKey: String): Result = runSuspendCatching { + withContext(ioDispatcher) { + val prefixedKey = publicKey.ensurePubkyPrefix() + val paykitRead = runSuspendCatching { pubkyService.fetchPaykitProfile(prefixedKey) } + .onFailure { Logger.warn("Failed to read Bitkit profile copy", it, context = TAG) } + val paykitData = paykitRead.getOrNull()?.let { PubkyProfileData.fromPaykitProfile(it.profile) } + // Cleared before the read, so a failed lookup never leaves an earlier visit's base to save against. + restoreBase = null + val snapshot = readRetryingOnce(prefixedKey) { pubkyService.fetchPubkyProfileWithRevision(prefixedKey) } + if (snapshot == null) { + paykitRead.getOrThrow() + return@withContext paykitData?.toPubkyProfile(prefixedKey)?.also { + restoreBase = RestoreBase(prefixedKey, it, revision = null) + } + } + tagsUnavailable = paykitRead.isFailure + PubkyProfile.fromPubkyProfile(prefixedKey, snapshot.profile).copy(tags = paykitData?.tags.orEmpty()).also { + restoreBase = RestoreBase(prefixedKey, it, snapshot.revision) + } + } + } /** * Resolves [publicKey]'s profile once, without retrying, for display only. A null or failed result is not proof @@ -894,8 +982,8 @@ class PubkyRepo @Inject constructor( return@withLock runSuspendCatching { withContext(ioDispatcher) { val publicKey = requireNotNull(_publicKey.value) { "No active Pubky session" } - val imageUrl = publishIdentityProfile(name, bio, links, tags, avatarBytes) - finishIdentityCreation(publicKey, name, bio, links, tags, imageUrl) + val saved = publishIdentityProfile(publicKey, name, bio, links, tags, avatarBytes) + finishIdentityCreation(publicKey, saved) } } } @@ -908,9 +996,9 @@ class PubkyRepo @Inject constructor( val publicKeyZ32 = _publicKey.value ?: createLocalIdentitySession { shouldRevokeSessionOnFailure = true } - val imageUrl = publishIdentityProfile(name, bio, links, tags, avatarBytes) + val saved = publishIdentityProfile(publicKeyZ32, name, bio, links, tags, avatarBytes) shouldRevokeSessionOnFailure = false - finishIdentityCreation(publicKeyZ32, name, bio, links, tags, imageUrl) + finishIdentityCreation(publicKeyZ32, saved) } } if (creationResult.isFailure) revokeIncompleteIdentitySessionIfNeeded(shouldRevokeSessionOnFailure) @@ -954,35 +1042,32 @@ class PubkyRepo @Inject constructor( } private suspend fun publishIdentityProfile( + publicKey: String, name: String, bio: String, links: List, tags: List, avatarBytes: ByteArray?, - ): String? { - val imageUrl = avatarBytes?.let { uploadAvatar(it).getOrNull() } - writeProfile(name, bio, links, tags, imageUrl) - return imageUrl + ): SavedProfile { + // A restore saves against the pubky.app profile its form was filled from; without one it creates the profile. + val restore = restoreBase?.takeIf { it.publicKey == publicKey } + val imageUrl = avatarBytes?.let { uploadAvatar(it, publicKey).getOrNull() } ?: restore?.profile?.imageUrl + val base = restore?.profile?.takeIf { restore.revision != null } + val saved = runSuspendCatching { + writeProfile(publicKey, name, bio, links, tags, imageUrl, base, expectedRevision = restore?.revision) + }.getOrElse { + if (!it.isConcurrentUpdate()) throw it + throw PubkyProfileChangedError(it) + } + restoreBase = null + saved.tagError?.let { Logger.warn("Created profile without its tag change", it, context = TAG) } + return saved } - private suspend fun finishIdentityCreation( - publicKey: String, - name: String, - bio: String, - links: List, - tags: List, - imageUrl: String?, - ): String { - val createdProfile = PubkyProfile( - publicKey = publicKey, - name = name, - bio = bio, - imageUrl = imageUrl, - links = links, - tags = tags, - status = null, - ) + private suspend fun finishIdentityCreation(publicKey: String, saved: SavedProfile): String { + val createdProfile = saved.profile startSignIn(publicKey) + ownProfileRevision = saved.revision setProfile(createdProfile) cacheMetadata(createdProfile) settingsStore.setPubkyProfileSetupPending(false) @@ -1019,41 +1104,67 @@ class PubkyRepo @Inject constructor( return clearedLocalState } - suspend fun uploadAvatar(imageBytes: ByteArray): Result = runSuspendCatching { + suspend fun uploadAvatar(imageBytes: ByteArray, publicKey: String? = null): Result = runSuspendCatching { withContext(ioDispatcher) { requireNotNull(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)) { "No session available" } + val identity = requireNotNull(publicKey ?: _publicKey.value) { "No public key available" } val compressed = compressAvatar(imageBytes) - pubkyService.uploadProfileAvatar(compressed, contentType = "image/jpeg") + withPubkyAppScope { pubkyService.uploadPubkyAppAvatar(compressed, "image/jpeg", identity) } } } + /** The profile and pubky.app revision an edit starts from; its save is checked against that revision. */ + fun profileEditBase() = ProfileEditBase(_profile.value, ownProfileRevision, tagsUnavailable) + + suspend fun saveProfile( + name: String, + bio: String, + links: List, + tags: List, + imageUrl: String?, + ): Result = saveProfile(name, bio, links, tags, imageUrl, profileEditBase()) + suspend fun saveProfile( name: String, bio: String, links: List, tags: List, imageUrl: String?, + editBase: ProfileEditBase, ): Result = runSuspendCatching { withContext(ioDispatcher) { requireNotNull(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)) { "No session available" } - writeProfile(name, bio, links, tags, imageUrl) - val pk = requireNotNull(_publicKey.value) { "No public key available" } - val profile = PubkyProfile( - publicKey = pk, - name = name, - bio = bio, - imageUrl = imageUrl ?: _profile.value?.imageUrl, - links = links, - tags = tags, - status = _profile.value?.status, - ) - setProfile(profile) - cacheMetadata(profile) + val signIn = requireNotNull(currentSignIn()) { "No public key available" } + val pk = signIn.publicKey + val saved = runSuspendCatching { + writeProfile( + pk, + name, + bio, + links, + tags, + imageUrl, + base = editBase.profile.takeIf { editBase.revision != null }, + expectedRevision = editBase.revision, + tagsUnread = editBase.tagsUnread, + ) + }.getOrElse { + if (!it.isConcurrentUpdate()) throw it + ownProfileRevision = null + scope.launch { loadProfile() } + throw PubkyProfileChangedError(it) + } + // A session change while the save ran leaves the new session's profile alone. + if (!isCurrent(signIn)) return@withContext + setProfile(saved.profile) + ownProfileRevision = saved.revision + cacheMetadata(saved.profile) notifyBackupStateChanged() + saved.tagError?.let { throw it } } } @@ -1074,13 +1185,21 @@ class PubkyRepo @Inject constructor( } clearSessionContactProfiles() deleteAllContacts() - runSuspendCatching { - pubkyService.deletePaykitProfile() - }.getOrElse { - if (!it.isMissingPubkyData()) { - throw it + profileWriteMutex.withLock { + profileDeletionGeneration.incrementAndGet() + try { + if (!isRingAdoptedIdentity()) deletePubkyAppProfile() + runSuspendCatching { + pubkyService.deletePaykitProfile() + }.getOrElse { + if (!it.isMissingPubkyData()) { + throw it + } + Logger.info("Continuing sign out, bitkit profile storage already missing", context = TAG) + } + } finally { + profileDeletionGeneration.incrementAndGet() } - Logger.info("Continuing sign out, bitkit profile storage already missing", context = TAG) } profileWriteGeneration.incrementAndGet() } @@ -1088,6 +1207,18 @@ class PubkyRepo @Inject constructor( signOut().getOrThrow() } + private suspend fun deletePubkyAppProfile() { + val publicKey = _publicKey.value ?: return + val known = ownProfileRevision + val revision = known ?: pubkyService.fetchPubkyProfileWithRevision(publicKey)?.revision ?: return + runSuspendCatching { withPubkyAppScope { pubkyService.deletePubkyProfile(revision, publicKey) } }.getOrElse { + if (known == null || !it.isConcurrentUpdate()) throw it + val current = pubkyService.fetchPubkyProfileWithRevision(publicKey)?.revision + if (current != null) withPubkyAppScope { pubkyService.deletePubkyProfile(current, publicKey) } + } + ownProfileRevision = null + } + private suspend fun deleteAllContacts() { val records = runSuspendCatching { pubkyService.contactRecords() @@ -1114,22 +1245,307 @@ class PubkyRepo @Inject constructor( } private suspend fun writeProfile( + publicKey: String, name: String, bio: String, links: List, tags: List, imageUrl: String?, + base: PubkyProfile?, + expectedRevision: String?, + tagsUnread: Boolean = false, + ): SavedProfile { + profileSaveEpoch.incrementAndGet() + profileSavesRunning.incrementAndGet() + try { + return writeProfileOnce(publicKey, name, bio, links, tags, imageUrl, base, expectedRevision, tagsUnread) + } finally { + profileSavesRunning.decrementAndGet() + profileSaveEpoch.incrementAndGet() + } + } + + private suspend fun writeProfileOnce( + publicKey: String, + name: String, + bio: String, + links: List, + tags: List, + imageUrl: String?, + base: PubkyProfile?, + expectedRevision: String?, + tagsUnread: Boolean, + ): SavedProfile { + val generation = profileDeletionGeneration.get() + // Unread when the edit began or now: either way the form's tags are not the stored ones. + val copyUnread = tagsUnread || tagsUnavailable + // A profile written without a base is fitted to pubky.app's limits, as a move is. + val fitted = if (base == null) fitted(name, bio, links) else null + val links = fitted?.links ?: links.map { + PubkyProfileLink( + label = it.label.singleLine(), + url = it.url.toPubkyAppLinkUrl() ?: it.url + ) + } + val bio = fitted?.bio ?: bio.singleLine() + val name = fitted?.name ?: name + // A Bitkit avatar still on Paykit storage is moved by a later load rather than written to pubky.app as is. + val paykitAvatar = imageUrl?.takeIf { it.isPaykitStorage() } + val update = PubkyProfileUpdate( + name = name.singleLine().takeIf { it != base?.name }, + bio = bio.takeIf { base == null || it != base.bio }, + image = when { + paykitAvatar != null -> null + base == null -> imageUrl + imageUrl == base.imageUrl -> null + else -> imageUrl.orEmpty() + }, + links = links.takeIf { base == null || it != base.links } + ?.map { SdkPubkyProfileLink(title = it.label, url = it.url) }, + ) + val snapshot = profileWrite(generation) { + withPubkyAppScope { pubkyService.publishPubkyProfile(update, expectedRevision, publicKey) } + } + ownProfileRevision = snapshot.revision + val baseTags = base?.tags.orEmpty() + val stored = storedCopy(publicKey, copyUnread) + val wasPending = publicKey in pubkyStore.data.first().pubkyAppAvatarPending + // The form could not show an avatar still to move while the copy was unread, so it stays pending. + val keepPending = snapshot.profile.image == null && copyUnread && wasPending + val pendingAvatar = when { + snapshot.profile.image != null -> null + paykitAvatar != null -> paykitAvatar + keepPending -> stored?.image?.takeIf { it.isPaykitStorage() } + else -> null + } + val avatarPending = pendingAvatar != null || keepPending + pubkyStore.update { + val keys = it.pubkyAppAvatarPending + val pending = if (avatarPending) keys + publicKey else keys - publicKey + it.copy(pubkyAppProfileOwners = it.pubkyAppProfileOwners + publicKey, pubkyAppAvatarPending = pending) + } + val keptTags = stored?.let { copy -> copy.tags?.let { it + tags.filterNot { tag -> tag in it } } ?: tags } + val profile = PubkyProfile.fromPubkyProfile(publicKey, snapshot.profile).let { + it.copy(tags = keptTags ?: baseTags, imageUrl = pendingAvatar ?: it.imageUrl) + } + // Tags live only in the Paykit copy, so a changed tag that it does not take is reported. + val copyData = profile.toProfileData().toPaykitProfile() + val copyError = keptTags?.let { + runSuspendCatching { profileWrite(generation) { pubkyService.publishPaykitProfile(copyData, publicKey) } } + .onSuccess { tagsUnavailable = false } + .onFailure { Logger.warn("Failed to update Bitkit profile copy", it, context = TAG) } + .exceptionOrNull() + } + val saved = if (keptTags != null && copyError == null) profile else profile.copy(tags = baseTags) + val tagsLost = (keptTags == null || copyError != null) && tags != baseTags + val tagError = PubkyProfileTagsNotSavedError( + ProfileEditBase(saved, snapshot.revision, tagsUnread = copyUnread), + copyError + ).takeIf { tagsLost } + return SavedProfile(saved, snapshot.revision, tagError) + } + + /** + * What a save keeps from the Paykit copy after the last load could not read it, as the form then lacked its tags + * and the avatar still to move: empty when that load read it, null while it still cannot be read. + */ + private suspend fun storedCopy(publicKey: String, copyUnread: Boolean): StoredCopy? { + if (!copyUnread) return StoredCopy(tags = null, image = null) + val record = runSuspendCatching { pubkyService.fetchPaykitProfile(publicKey) }.getOrElse { return null } + val data = record?.let { PubkyProfileData.fromPaykitProfile(it.profile) } + return StoredCopy(tags = data?.tags.orEmpty(), image = data?.image) + } + + /** [name], [bio] and [links] fitted to pubky.app's limits: one line, cut to length, at most five valid links. */ + private fun fitted(name: String, bio: String, links: List) = FittedProfile( + name = name.singleLine().takeCodePoints(PUBKY_APP_NAME_MAX_LENGTH), + bio = bio.singleLine().takeCodePoints(PUBKY_APP_BIO_MAX_LENGTH), + links = links + .mapNotNull { link -> + val title = link.label.singleLine().takeIf { it.isNotEmpty() } ?: return@mapNotNull null + val url = link.url.toPubkyAppLinkUrl() ?: return@mapNotNull null + PubkyProfileLink(label = title.takeCodePoints(PUBKY_APP_LINK_TITLE_MAX_LENGTH), url = url) + } + .take(PUBKY_APP_LINKS_MAX_COUNT), + ) + + private suspend fun loadOwnProfile(publicKey: String): Pair? { + val generation = profileDeletionGeneration.get() + val saveEpoch = profileSaveEpoch.get() + val paykitRead = runSuspendCatching { pubkyService.fetchPaykitProfile(publicKey) } + .onFailure { Logger.warn("Failed to read Bitkit profile copy", it, context = TAG) } + tagsUnavailable = paykitRead.isFailure + val paykitData = paykitRead.getOrNull()?.let { PubkyProfileData.fromPaykitProfile(it.profile) } + val fetched = readRetryingOnce(publicKey) { pubkyService.fetchPubkyProfileWithRevision(publicKey) } + if (fetched == null) paykitRead.getOrThrow() + val stored = pubkyStore.data.first() + val hadPubkyAppProfile = publicKey in stored.pubkyAppProfileOwners + val migrating = fetched == null && !hadPubkyAppProfile + var snapshot = fetched ?: paykitData?.takeIf { migrating }?.let { migrateToPubkyApp(publicKey, it, generation) } + // While the move cannot finish, the Bitkit profile is shown and the next save creates the pubky.app profile. + snapshot ?: return paykitData?.takeIf { migrating }?.let { it.toPubkyProfile(publicKey) to null } + val pendingAvatar = paykitData?.image?.takeIf { it.isPaykitStorage() } + var retryingAvatar = fetched != null && publicKey in stored.pubkyAppAvatarPending + val avatarMoveSettled = fetched?.profile?.image != null || (paykitRead.isSuccess && pendingAvatar == null) + if (retryingAvatar && avatarMoveSettled) { + // An avatar set on pubky.app meanwhile wins, and only an avatar on Paykit storage is moved. An unread copy + // settles nothing, so the move is retried on a later load. + pubkyStore.update { it.copy(pubkyAppAvatarPending = it.pubkyAppAvatarPending - publicKey) } + } + if (pendingAvatar == null || avatarMoveSettled) retryingAvatar = false + if (retryingAvatar) { + snapshot = moveAvatar(publicKey, checkNotNull(pendingAvatar), snapshot, generation) ?: snapshot + } + if (!hadPubkyAppProfile) { + pubkyStore.update { it.copy(pubkyAppProfileOwners = it.pubkyAppProfileOwners + publicKey) } + } + if (snapshot !== fetched) ownProfileRevision = snapshot.revision + val avatarPending = pendingAvatar != null && snapshot.profile.image == null && (migrating || retryingAvatar) + val profile = PubkyProfile.fromPubkyProfile(publicKey, snapshot.profile).let { + it.copy(tags = paykitData?.tags.orEmpty(), imageUrl = if (avatarPending) pendingAvatar else it.imageUrl) + } + if (!avatarPending && paykitData != null && paykitData != profile.toProfileData()) { + publishPaykitProfileCopy(publicKey, profile, generation, saveEpoch) + } + return profile to snapshot.revision + } + + private suspend fun migrateToPubkyApp( + publicKey: String, + data: PubkyProfileData, + generation: Long, + ): PubkyProfileSnapshot? = + runSuspendCatching { + val fitted = fitted(data.name, data.bio, data.links.map { PubkyProfileLink(it.label, it.url) }) + // An avatar already on pubky.app is kept as is; one on Paykit storage is moved below. + val keptImage = data.image?.takeIf { it.isPubkyAppFile() } + val update = PubkyProfileUpdate( + name = fitted.name, + bio = fitted.bio, + image = keptImage, + links = fitted.links.map { SdkPubkyProfileLink(title = it.label, url = it.url) }, + ) + val image = data.image?.takeIf { it.isPaykitStorage() } + // Recorded before the profile is created without it, so an app stopped before the move still retries it. + // A failed create keeps it too: the create may have landed, and the next load or save handles either case. + if (image != null) { + pubkyStore.update { it.copy(pubkyAppAvatarPending = it.pubkyAppAvatarPending + publicKey) } + } + val snapshot = profileWrite(generation) { + withPubkyAppScope { pubkyService.publishPubkyProfile(update, null, publicKey) } + } + Logger.info("Moved Bitkit profile to pubky.app", context = TAG) + image ?: return@runSuspendCatching snapshot + moveAvatar(publicKey, image, snapshot, generation) ?: snapshot + }.onFailure { Logger.warn("Failed to move Bitkit profile to pubky.app", it, context = TAG) }.getOrNull() + + private suspend fun moveAvatar( + publicKey: String, + uri: String, + snapshot: PubkyProfileSnapshot, + generation: Long, + ): PubkyProfileSnapshot? = runSuspendCatching { + val bytes = pubkyService.fetchFile(uri, PUBKY_APP_AVATAR_MAX_BYTES) + val contentType = when (uri.substringAfterLast('.').lowercase()) { + "png" -> "image/png" + "webp" -> "image/webp" + "gif" -> "image/gif" + else -> "image/jpeg" + } + profileWrite(generation) { + val image = withPubkyAppScope { pubkyService.uploadPubkyAppAvatar(bytes, contentType, publicKey) } + withPubkyAppScope { + pubkyService.publishPubkyProfile( + PubkyProfileUpdate(null, null, image, null), + snapshot.revision, + publicKey + ) + } + } + }.onSuccess { + pubkyStore.update { it.copy(pubkyAppAvatarPending = it.pubkyAppAvatarPending - publicKey) } + }.onFailure { + Logger.warn("Failed to move avatar to pubky.app", it, context = TAG) + pubkyStore.update { it.copy(pubkyAppAvatarPending = it.pubkyAppAvatarPending + publicKey) } + }.getOrNull() + + private fun Throwable.isConcurrentUpdate() = + generateSequence(this) { it.cause }.any { it is PaykitException.ConcurrentUpdate } + + private fun String.singleLine() = map { if (it.isISOControl()) ' ' else it }.joinToString("").trim() + + private fun String.toPubkyAppLinkUrl(): String? { + val value = trim().takeIf { it.isNotEmpty() } ?: return null + val isPhone = value.isPhoneNumber() + if (!isPhone && value.any { it.isWhitespace() }) return null + val url = when { + !isPhone && runCatching { URI(value).scheme }.getOrNull() != null -> value + value.isEmailAddress() -> "mailto:$value" + isPhone -> "tel:" + value.filterNot { it in " -()." } + '.' in value && !value.startsWith('.') -> "https://$value" + else -> return null + } + val parsed = runCatching { URI(url) }.getOrNull() + val valid = url.codePointCount(0, url.length) <= PUBKY_APP_LINK_URL_MAX_LENGTH && + parsed?.scheme != null && parsed.hasValidHost() + return url.takeIf { valid } + } + + /** + * Paykit's URL parser reads a web URL's host that ends in an all-digit label as an IPv4 address (one to four + * numbers, as in `127.1`) and rejects it when it is not one; other schemes keep such hosts as they are. + */ + private fun URI.hasValidHost(): Boolean { + if (scheme?.lowercase() !in WEB_SCHEMES) return true + // java.net.URI leaves the host null when the name is not a valid hostname, so fall back to the authority. + val host = host ?: rawAuthority?.substringAfterLast('@')?.substringBefore(':') ?: return true + if (!host.substringAfterLast('.').all { it.isDigit() }) return true + val numbers = host.split('.').map { it.toLongOrNull() ?: return false } + if (numbers.size !in 1..4) return false + val lastLimit = (1L shl (8 * (5 - numbers.size))) - 1 + return numbers.dropLast(1).all { it <= 255 } && numbers.last() <= lastLimit + } + + private fun String.isEmailAddress(): Boolean { + val parts = split('@') + return parts.size == 2 && parts[0].isNotEmpty() && '.' in parts[1] && '/' !in this + } + + private fun String.isPhoneNumber(): Boolean { + val digits = count { it.isDigit() } + return (startsWith('+') || digits >= 7) && digits >= 5 && all { it in "+0123456789 -()." } && '+' !in drop(1) && + !ISO_DATE.matches(this) && !IPV4.matches(this) + } + + private fun String.isPaykitStorage() = "/pub/paykit/" in this + + private fun String.isPubkyAppFile() = + "/pub/pubky.app/files/" in this && codePointCount(0, length) <= PUBKY_APP_LINK_URL_MAX_LENGTH + + private suspend fun publishPaykitProfileCopy( + publicKey: String, + profile: PubkyProfile, + generation: Long, + saveEpoch: Long, ) { - val data = PubkyProfile( - publicKey = "", - name = name, - bio = bio, - imageUrl = imageUrl, - links = links, - tags = tags, - status = null, - ).toProfileData() - pubkyService.publishPaykitProfile(data.toPaykitProfile()) + runSuspendCatching { + profileWrite(generation) { + // Checked under the write lock, so a save that starts after it writes its copy after this one. + if (profileSavesRunning.get() != 0 || profileSaveEpoch.get() != saveEpoch) return@profileWrite + pubkyService.publishPaykitProfile(profile.toProfileData().toPaykitProfile(), publicKey) + } + }.onFailure { Logger.warn("Failed to update Bitkit profile copy", it, context = TAG) } + } + + /** Runs a write of a load or save that started at [generation], refused once a profile deletion began since. */ + private suspend fun profileWrite(generation: Long, block: suspend () -> T): T = profileWriteMutex.withLock { + check(profileDeletionGeneration.get() == generation) { "The profile was deleted since this write began" } + block() + } + + private suspend fun withPubkyAppScope(block: suspend () -> T): T = runSuspendCatching { block() }.getOrElse { + if (!it.isPaykitIdentityError() || !refreshSessionIfPossible().getOrDefault(false)) throw it + block() } private fun compressAvatar(imageBytes: ByteArray): ByteArray { @@ -1991,30 +2407,23 @@ class PubkyRepo @Inject constructor( withContext(ioDispatcher) { val prefixedKey = publicKey.ensurePubkyPrefix() if (!retry) return@withContext resolveProfileOnce(prefixedKey, lane) - var lastError: Throwable? = null - - repeat(2) { attempt -> - val result = runSuspendCatching { resolveProfileOnce(prefixedKey, lane) } - if (result.isSuccess && (result.getOrNull() != null || attempt == 1)) { - return@withContext result.getOrNull() - } - result.exceptionOrNull()?.let { error -> - lastError = error - } + readRetryingOnce(prefixedKey) { resolveProfileOnce(prefixedKey, lane) } + } + } - if (attempt == 0) { - Logger.warn( - "Retrying contact profile resolution for '${redacted(prefixedKey)}'", - lastError, - context = TAG, - ) - delay(250) - } + private suspend fun readRetryingOnce(publicKey: String, read: suspend () -> T?): T? { + var lastError: Throwable? = null + repeat(2) { attempt -> + val result = runSuspendCatching { read() } + if (result.isSuccess && (result.getOrNull() != null || attempt == 1)) return result.getOrNull() + result.exceptionOrNull()?.let { lastError = it } + if (attempt == 0) { + Logger.warn("Retrying profile read for '${redacted(publicKey)}'", lastError, context = TAG) + delay(250) } - - lastError?.let { throw it } - null } + lastError?.let { throw it } + return null } private suspend fun resolveProfileOnce(prefixedKey: String, lane: PaykitReadLane): PubkyProfile? = @@ -2138,6 +2547,7 @@ class PubkyRepo @Inject constructor( private fun setProfile(profile: PubkyProfile?) { profileWriteGeneration.incrementAndGet() + if (profile == null) ownProfileRevision = null _profile.update { profile } } diff --git a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt index 4860858a76..ba0ed5921a 100644 --- a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt +++ b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt @@ -70,6 +70,8 @@ import com.synonym.paykit.PubkyClientConfig import com.synonym.paykit.PubkyIdentityCapability import com.synonym.paykit.PubkyLocalSecretKey import com.synonym.paykit.PubkyProfile +import com.synonym.paykit.PubkyProfileSnapshot +import com.synonym.paykit.PubkyProfileUpdate import com.synonym.paykit.PubkySessionAccess import com.synonym.paykit.PubkySessionBootstrap import com.synonym.paykit.PubkySessionBootstrapResult @@ -84,6 +86,7 @@ import com.synonym.paykit.defaultPubkyClientConfig import com.synonym.paykit.parsePubkyAuthUrl import com.synonym.paykit.paykitAuthorizerSessionCapabilities import com.synonym.paykit.paymentProofEventLen +import com.synonym.paykit.pubkyAppProfileSessionCapabilities import com.synonym.paykit.pubkyPublicKeyFromSecret import com.synonym.paykit.pubkySecretKeyFromBip39Mnemonic import dagger.hilt.android.qualifiers.ApplicationContext @@ -622,11 +625,12 @@ class PaykitSdkService @Inject constructor( publicRead(PaykitReadLane.Bulk, 5.seconds) { it.fetchPubkyFileBounded(uri, maxBytes) } ?: throw PubkyFileNotFoundError() - suspend fun publishPaykitProfile(profile: PaykitProfile): PaykitProfileRecord { + suspend fun publishPaykitProfile(profile: PaykitProfile, expectedIdentity: String): PaykitProfileRecord { isSetup.await() return operationLock.withLock { withPaykitKey { handle -> val publicKey = requireNotNull(completeSdkCall { handle.identityStatus() }?.publicKey) + requireProfileIdentity(publicKey, expectedIdentity) val current = handle.fetchPaykitProfile(publicKey) completeSdkCall { handle.publishPaykitProfile(profile, current?.revision).also { notifyBackupStateChanged() } @@ -668,6 +672,46 @@ class PaykitSdkService @Inject constructor( suspend fun fetchPubkyProfile(publicKey: String): PubkyProfile? = publicRead { it.fetchPubkyProfile(publicKey) }?.profile + suspend fun fetchPubkyProfileWithRevision(publicKey: String): PubkyProfileSnapshot? = + publicRead { it.fetchPubkyProfileWithRevision(publicKey) } + + suspend fun fetchPaykitProfile(publicKey: String): PaykitProfileRecord? = + publicRead { it.fetchPaykitProfile(publicKey) } + + suspend fun publishPubkyProfile( + update: PubkyProfileUpdate, + expectedRevision: String?, + expectedIdentity: String, + ): PubkyProfileSnapshot { + isSetup.await() + return operationLock.withLock { + requireProfileIdentity(currentIdentity(), expectedIdentity) + completeSdkCall { handle().publishPubkyProfile(update, expectedRevision) } + } + } + + suspend fun deletePubkyProfile(expectedRevision: String, expectedIdentity: String) { + isSetup.await() + operationLock.withLock { + requireProfileIdentity(currentIdentity(), expectedIdentity) + completeSdkCall { handle().deletePubkyProfile(expectedRevision) } + } + } + + suspend fun uploadPubkyAppAvatar(bytes: ByteArray, contentType: String, expectedIdentity: String): String { + isSetup.await() + return operationLock.withLock { + requireProfileIdentity(currentIdentity(), expectedIdentity) + completeSdkCall { handle().uploadPubkyAppAvatar(bytes, contentType) } + } + } + + private suspend fun currentIdentity(): String? = completeSdkCall { handle().identityStatus() }?.publicKey + + private fun requireProfileIdentity(current: String?, expectedIdentity: String) { + if (!PubkyPublicKeyFormat.matches(current, expectedIdentity)) throw PubkyProfileIdentityChangedError() + } + suspend fun fetchPubkyFollows(publicKey: String): List = publicRead { it.fetchPubkyFollows(publicKey, maxEntries = 10_000u) } @@ -885,7 +929,12 @@ class PaykitSdkService @Inject constructor( } } - fun requiredCapabilities(): String = paykitAuthorizerSessionCapabilities() + /** + * Scope for sessions Bitkit creates: Paykit plus the shared pubky.app profile and its avatar. + * Restoring a saved session still checks only the Paykit scope, so sessions from older builds keep working. + */ + fun requiredCapabilities(): String = + "${paykitAuthorizerSessionCapabilities()},${pubkyAppProfileSessionCapabilities()}" suspend fun syncPrivatePaymentListsWithReservations( updates: List, @@ -2264,3 +2313,6 @@ internal fun paykitStorageCallback(code: String, operation: () -> T): T = if (it is PaykitException) throw it throw PaykitException.Storage(code = code, context = "Platform Paykit storage operation failed") } + +/** The signed-in identity changed before a profile write, so it wrote nothing. */ +class PubkyProfileIdentityChangedError : AppError("Pubky identity changed before the profile write") diff --git a/app/src/main/java/to/bitkit/services/PubkyService.kt b/app/src/main/java/to/bitkit/services/PubkyService.kt index 413fb3c90c..1b5264c76e 100644 --- a/app/src/main/java/to/bitkit/services/PubkyService.kt +++ b/app/src/main/java/to/bitkit/services/PubkyService.kt @@ -4,9 +4,12 @@ import com.synonym.bitkitcore.approvePubkyAuth import com.synonym.paykit.ContactRecord import com.synonym.paykit.ContactUpdate import com.synonym.paykit.PaykitProfile +import com.synonym.paykit.PaykitProfileRecord import com.synonym.paykit.PaykitPublicKeys import com.synonym.paykit.ProfileResolution import com.synonym.paykit.PubkyAuthCompanionClaim +import com.synonym.paykit.PubkyProfileSnapshot +import com.synonym.paykit.PubkyProfileUpdate import com.synonym.paykit.PubkySessionBootstrapResult import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job @@ -199,8 +202,8 @@ class PubkyService @Inject constructor( // region Profile & contacts - suspend fun publishPaykitProfile(profile: PaykitProfile) = ServiceQueue.PUBKY.background { - paykitSdkService.publishPaykitProfile(profile) + suspend fun publishPaykitProfile(profile: PaykitProfile, expectedIdentity: String) = ServiceQueue.PUBKY.background { + paykitSdkService.publishPaykitProfile(profile, expectedIdentity) } suspend fun uploadProfileAvatar(bytes: ByteArray, contentType: String): String = ServiceQueue.PUBKY.background { @@ -211,6 +214,29 @@ class PubkyService @Inject constructor( paykitSdkService.deletePaykitProfile() } + suspend fun fetchPubkyProfileWithRevision(publicKey: String): PubkyProfileSnapshot? = cancellablePublicRead { + paykitSdkService.fetchPubkyProfileWithRevision(publicKey) + } + + suspend fun fetchPaykitProfile(publicKey: String): PaykitProfileRecord? = cancellablePublicRead { + paykitSdkService.fetchPaykitProfile(publicKey) + } + + suspend fun publishPubkyProfile( + update: PubkyProfileUpdate, + expectedRevision: String?, + expectedIdentity: String, + ): PubkyProfileSnapshot = ServiceQueue.PUBKY.background { + paykitSdkService.publishPubkyProfile(update, expectedRevision, expectedIdentity) + } + + suspend fun deletePubkyProfile(expectedRevision: String, expectedIdentity: String) = ServiceQueue.PUBKY.background { + paykitSdkService.deletePubkyProfile(expectedRevision, expectedIdentity) + } + + suspend fun uploadPubkyAppAvatar(bytes: ByteArray, contentType: String, expectedIdentity: String): String = + ServiceQueue.PUBKY.background { paykitSdkService.uploadPubkyAppAvatar(bytes, contentType, expectedIdentity) } + suspend fun getContacts(publicKey: String): List = cancellablePublicRead { paykitSdkService.fetchPubkyFollows(publicKey) } diff --git a/app/src/main/java/to/bitkit/ui/components/ProfileEditForm.kt b/app/src/main/java/to/bitkit/ui/components/ProfileEditForm.kt index ba463f8eb7..8d4f534d38 100644 --- a/app/src/main/java/to/bitkit/ui/components/ProfileEditForm.kt +++ b/app/src/main/java/to/bitkit/ui/components/ProfileEditForm.kt @@ -51,6 +51,7 @@ import dev.chrisbanes.haze.rememberHazeState import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import to.bitkit.R +import to.bitkit.models.takeCodePoints import to.bitkit.ui.theme.AppTextFieldDefaults import to.bitkit.ui.theme.AppTextStyles import to.bitkit.ui.theme.AppThemeSurface @@ -81,6 +82,7 @@ fun ProfileEditForm( modifier: Modifier = Modifier, isSaving: Boolean = false, isDeleting: Boolean = false, + maxLinks: Int? = null, avatarContent: @Composable () -> Unit = {}, publicKeyLabel: String? = null, bioPlaceholder: String? = null, @@ -132,7 +134,7 @@ fun ProfileEditForm( TextInput( enabled = !isBusy, value = bio, - onValueChange = { onBioChange(it.take(BIO_MAX_LENGTH)) }, + onValueChange = { onBioChange(it.takeCodePoints(BIO_MAX_LENGTH)) }, placeholder = resolvedBioPlaceholder, minLines = 3, maxLines = 4, @@ -171,25 +173,27 @@ fun ProfileEditForm( ) } } - PrimaryButton( - text = stringResource(R.string.profile__add_link), - enabled = !isBusy, - onClick = { - focusManager.clearFocus(force = true) - keyboardController?.hide() - onAddLink() - }, - size = ButtonSize.Small, - fullWidth = false, - icon = { - Icon( - painter = painterResource(R.drawable.ic_link), - contentDescription = null, - modifier = Modifier.size(16.dp) - ) - }, - modifier = Modifier.testTag("ProfileEditAddLink") - ) + if (maxLinks == null || links.size < maxLinks) { + PrimaryButton( + text = stringResource(R.string.profile__add_link), + enabled = !isBusy, + onClick = { + focusManager.clearFocus(force = true) + keyboardController?.hide() + onAddLink() + }, + size = ButtonSize.Small, + fullWidth = false, + icon = { + Icon( + painter = painterResource(R.drawable.ic_link), + contentDescription = null, + modifier = Modifier.size(16.dp) + ) + }, + modifier = Modifier.testTag("ProfileEditAddLink") + ) + } HorizontalDivider() FieldLabel(text = stringResource(R.string.profile__edit_tags)) { diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/CreateProfileScreen.kt b/app/src/main/java/to/bitkit/ui/screens/profile/CreateProfileScreen.kt index df88a63246..95c1aebf0d 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/CreateProfileScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/CreateProfileScreen.kt @@ -32,6 +32,7 @@ import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import coil3.compose.AsyncImage import to.bitkit.R +import to.bitkit.models.isValidProfileName import to.bitkit.ui.components.BodyM import to.bitkit.ui.components.FillHeight import to.bitkit.ui.components.GradientCircularProgressIndicator @@ -137,7 +138,7 @@ private fun Content( PrimaryButton( text = stringResource(R.string.common__continue), onClick = onSave, - enabled = uiState.name.isNotBlank() && !uiState.isSaving, + enabled = isValidProfileName(uiState.name) && !uiState.isSaving, isLoading = uiState.isSaving, modifier = Modifier.testTag("CreateProfileSave") ) diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/CreateProfileViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/CreateProfileViewModel.kt index 441cd906cd..2daf5d751f 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/CreateProfileViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/CreateProfileViewModel.kt @@ -17,8 +17,11 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import to.bitkit.R +import to.bitkit.models.PROFILE_NAME_MAX_LENGTH import to.bitkit.models.PubkyProfileLink import to.bitkit.models.Toast +import to.bitkit.models.takeCodePoints +import to.bitkit.repositories.PubkyProfileChangedError import to.bitkit.repositories.PubkyRepo import to.bitkit.ui.components.ProfileEditLink import to.bitkit.ui.shared.toast.ToastEventBus @@ -125,7 +128,7 @@ class CreateProfileViewModel @Inject constructor( } fun onNameChange(name: String) { - _uiState.update { it.copy(name = name) } + _uiState.update { it.copy(name = name.takeCodePoints(PROFILE_NAME_MAX_LENGTH)) } } fun onBioChange(bio: String) { @@ -198,11 +201,13 @@ class CreateProfileViewModel @Inject constructor( }.onFailure { Logger.error("Failed to create identity", it, context = TAG) _uiState.update { it.copy(isSaving = false) } + val changed = it is PubkyProfileChangedError ToastEventBus.send( type = Toast.ToastType.ERROR, title = context.getString(R.string.profile__create_error), - description = it.message, + description = if (changed) context.getString(R.string.profile__edit_changed_error) else it.message, ) + if (changed) deriveAndCheckRemote() } } } diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileScreen.kt b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileScreen.kt index 45563016c3..b824b89a96 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileScreen.kt @@ -30,6 +30,8 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import coil3.compose.AsyncImage import kotlinx.collections.immutable.persistentListOf import to.bitkit.R +import to.bitkit.models.PROFILE_LINKS_MAX_COUNT +import to.bitkit.models.isValidProfileName import to.bitkit.ui.components.AddLinkSheet import to.bitkit.ui.components.AddTagSheet import to.bitkit.ui.components.GradientCircularProgressIndicator @@ -166,10 +168,11 @@ private fun Content( onAddTag = onAddTag, onSave = onSave, onCancel = onBackClick, - isSaveEnabled = uiState.name.isNotBlank() && !uiState.isBusy, + isSaveEnabled = isValidProfileName(uiState.name) && !uiState.isBusy, topBar = topBar, isSaving = uiState.isSaving, isDeleting = uiState.isDeleting, + maxLinks = PROFILE_LINKS_MAX_COUNT, avatarContent = { AvatarSection( imageUrl = uiState.imageUrl, diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt index e2628806cf..ad2302f4a4 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt @@ -22,9 +22,14 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import to.bitkit.R import to.bitkit.ext.runSuspendCatching +import to.bitkit.models.PROFILE_NAME_MAX_LENGTH import to.bitkit.models.PubkyProfileLink import to.bitkit.models.Toast +import to.bitkit.models.takeCodePoints import to.bitkit.repositories.PrivatePaykitRepo +import to.bitkit.repositories.ProfileEditBase +import to.bitkit.repositories.PubkyProfileChangedError +import to.bitkit.repositories.PubkyProfileTagsNotSavedError import to.bitkit.repositories.PubkyRepo import to.bitkit.ui.components.ProfileEditLink import to.bitkit.ui.shared.toast.ToastEventBus @@ -41,6 +46,8 @@ class EditProfileViewModel @Inject constructor( private const val TAG = "EditProfileViewModel" } + private var editBase = ProfileEditBase(profile = null, revision = null) + private val _uiState = MutableStateFlow(EditProfileUiState()) val uiState = _uiState.asStateFlow() @@ -54,7 +61,8 @@ class EditProfileViewModel @Inject constructor( private fun loadProfile() { viewModelScope.launch { _uiState.update { it.copy(isLoading = true) } - val profile = pubkyRepo.profile.value + editBase = pubkyRepo.profileEditBase() + val profile = editBase.profile val publicKey = pubkyRepo.publicKey.value.orEmpty() val removal = if (pubkyRepo.isRingAdoptedIdentity()) ProfileRemoval.UNLINK else ProfileRemoval.DELETE if (profile != null) { @@ -78,6 +86,14 @@ class EditProfileViewModel @Inject constructor( } } + private fun reloadAfterExternalEdit() { + viewModelScope.launch { + pubkyRepo.loadProfile() + _uiState.update { it.copy(newAvatarUri = null, newAvatarBytes = null) } + loadProfile() + } + } + fun onAvatarSelected(uri: Uri) { viewModelScope.launch { runCatching { @@ -97,7 +113,7 @@ class EditProfileViewModel @Inject constructor( } fun onNameChange(name: String) { - _uiState.update { it.copy(name = name) } + _uiState.update { it.copy(name = name.takeCodePoints(PROFILE_NAME_MAX_LENGTH)) } } fun onBioChange(bio: String) { @@ -196,6 +212,7 @@ class EditProfileViewModel @Inject constructor( links = state.links.map { PubkyProfileLink(label = it.label, url = it.url) }, tags = state.tags, imageUrl = imageUrl, + editBase = editBase, ).onSuccess { _uiState.update { it.copy(isSaving = false) } ToastEventBus.send( @@ -207,11 +224,15 @@ class EditProfileViewModel @Inject constructor( }.onFailure { Logger.error("Failed to save profile", it, context = TAG) _uiState.update { it.copy(isSaving = false) } + val changed = it is PubkyProfileChangedError ToastEventBus.send( type = Toast.ToastType.ERROR, title = context.getString(R.string.profile__edit_save_error), - description = it.message, + description = it.profileSaveErrorText(context), ) + if (changed) reloadAfterExternalEdit() + // The other fields are on pubky.app, so a retry starts from their revision. + if (it is PubkyProfileTagsNotSavedError) editBase = it.base } } } @@ -355,3 +376,9 @@ sealed interface EditProfileEffect { data object DeleteSuccess : EditProfileEffect data object DisconnectSuccess : EditProfileEffect } + +internal fun Throwable.profileSaveErrorText(context: Context): String? = when (this) { + is PubkyProfileChangedError -> context.getString(R.string.profile__edit_changed_error) + is PubkyProfileTagsNotSavedError -> context.getString(R.string.profile__edit_tags_error) + else -> message +} diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/ProfileViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/ProfileViewModel.kt index 4880ed4375..862871d2b4 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/ProfileViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/ProfileViewModel.kt @@ -246,7 +246,7 @@ class ProfileViewModel @Inject constructor( ToastEventBus.send( type = Toast.ToastType.ERROR, title = context.getString(R.string.profile__edit_save_error), - description = it.message, + description = it.profileSaveErrorText(context), ) } } diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index d387d14087..e188256d43 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1309,13 +1309,15 @@ فشل فصل الملف الشخصي النبذة ملاحظة قصيرة. أخبرنا قليلاً عن نفسك. + تغيّر ملفك الشخصي في pubky.app. حمّل Bitkit أحدث نسخة، لذا أعد إجراء تعديلك. حذف اسمك تعديل الملف الشخصي - يرجى ملاحظة أن معلومات الملف الشخصي مخزنة في ملفات عامة. + هذا هو ملفك الشخصي على pubky.app. إنه عام، والتغييرات التي تجريها هنا تظهر أيضًا على pubky.app. فشل حفظ الملف الشخصي تم حفظ الملف الشخصي العلامات + تعذّر على Bitkit حفظ وسومك. حُفظت تغييراتك الأخرى، لذا حاول حفظ الوسوم مرة أخرى. إلغاء الربط تعذر تحميل ملفك الشخصي. مع ملفك الشخصي المحمول، يمكن لجهات اتصالك الوصول إليك والدفع لك في أي مكان. diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 0a78867a0c..6ce2b14b51 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1335,12 +1335,14 @@ No se pudo desconectar el perfil BIO Nota breve. Cuente un poco sobre usted. + Tu perfil cambió en pubky.app. Bitkit cargó la versión más reciente, así que vuelve a hacer tu cambio. ELIMINAR SU NOMBRE - Tenga en cuenta que la información del perfil se guarda en archivos públicos. + Este es tu perfil de pubky.app. Es público, y los cambios que hagas aquí también se ven en pubky.app. No se pudo guardar el perfil Perfil guardado ETIQUETAS + Bitkit no pudo guardar tus etiquetas. Tus otros cambios se guardaron, así que vuelve a intentar con las etiquetas. DESVINCULAR No se pudo cargar su perfil. Con su perfil portátil, sus contactos pueden encontrarlo y pagarle en cualquier lugar. diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index fdd9acd4a9..2c935e0d26 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1331,12 +1331,14 @@ No s\'ha pogut desconnectar el perfil BIOGRAFIA Nota breu. Explica una mica sobre tu. + El teu perfil ha canviat a pubky.app. Bitkit ha carregat la versió més recent, així que torna a fer la teva edició. ELIMINAR EL TEU NOM - Tingues en compte que la informació del perfil es desa en fitxers públics. + Aquest és el teu perfil de pubky.app. És públic, i els canvis que hi facis aquí també es veuen a pubky.app. No s\'ha pogut desar el perfil Perfil desat ETIQUETES + Bitkit no ha pogut desar les teves etiquetes. Els altres canvis s\'han desat, així que torna a provar amb les etiquetes. DESVINCULAR No s\'ha pogut carregar el teu perfil. Amb el teu perfil portable, els teus contactes et poden trobar i pagar a qualsevol lloc. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index c9211d9c80..1b77a477d3 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1333,12 +1333,14 @@ Profil se nepodařilo odpojit BIO Krátká poznámka. Řekněte něco o sobě. + Tvůj profil se v pubky.app změnil. Bitkit načetl nejnovější verzi, proveď proto úpravu znovu. SMAZAT VAŠE JMÉNO - Upozorňujeme, že informace o profilu jsou uloženy ve veřejných souborech. + Toto je tvůj profil na pubky.app. Je veřejný a změny, které zde provedeš, se zobrazí i na pubky.app. Profil se nepodařilo uložit Profil uložen TAGY + Bitkit nemohl uložit vaše štítky. Ostatní změny byly uloženy, tak zkuste štítky znovu. ZRUŠIT PROPOJENÍ Váš profil nelze načíst. Díky přenosnému profilu vás kontakty mohou kdekoli zastihnout a zaplatit vám. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 71aeca5dd2..6d50016b27 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1331,12 +1331,14 @@ Profil konnte nicht getrennt werden BIO Kurze Notiz. Erzähl ein bisschen über dich. + Dein Profil wurde in pubky.app geändert. Bitkit hat die neueste Version geladen, nimm deine Änderung bitte erneut vor. LÖSCHEN DEIN NAME - Bitte beachte, dass Profilinformationen in öffentlichen Dateien gespeichert werden. + Das ist dein pubky.app-Profil. Es ist öffentlich, und Änderungen, die du hier vornimmst, erscheinen auch auf pubky.app. Profil konnte nicht gespeichert werden Profil gespeichert TAGS + Bitkit konnte deine Tags nicht speichern. Deine anderen Änderungen wurden gespeichert, versuche es mit den Tags erneut. VERKNÜPFUNG AUFHEBEN Dein Profil kann nicht geladen werden. Mit deinem portablen Profil können deine Kontakte dich überall erreichen und bezahlen. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 5041fe127c..d6c8e53eb9 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1315,13 +1315,15 @@ Αποτυχία αποσύνδεσης προφίλ ΒΙΟΓΡΑΦΙΚΟ Σύντομη σημείωση. Πες λίγα λόγια για τον εαυτό σου. + Το προφίλ σου άλλαξε στο pubky.app. Το Bitkit φόρτωσε την πιο πρόσφατη έκδοση, οπότε κάνε ξανά την αλλαγή σου. ΔΙΑΓΡΑΦΗ ΤΟ ΟΝΟΜΑ ΣΟΥ Επεξεργασία προφίλ - Τα στοιχεία του προφίλ αποθηκεύονται σε δημόσια αρχεία. + Αυτό είναι το προφίλ σου στο pubky.app. Είναι δημόσιο, και οι αλλαγές που κάνεις εδώ εμφανίζονται και στο pubky.app. Αποτυχία αποθήκευσης προφίλ Το προφίλ αποθηκεύτηκε ΕΤΙΚΕΤΕΣ + Το Bitkit δεν μπόρεσε να αποθηκεύσει τις ετικέτες σου. Οι άλλες αλλαγές σου αποθηκεύτηκαν, οπότε δοκίμασε ξανά τις ετικέτες. ΑΠΟΣΥΝΔΕΣΗ Δεν ήταν δυνατή η φόρτωση του προφίλ σου. Με το φορητό προφίλ σου, οι επαφές σου μπορούν να σε βρουν και να σε πληρώσουν οπουδήποτε. diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index dcbc58e3c5..3ce949b62a 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1329,12 +1329,14 @@ No se pudo desconectar el perfil BIO Nota breve. Cuenta algo sobre ti. + Tu perfil ha cambiado en pubky.app. Bitkit ha cargado la versión más reciente, así que vuelve a hacer tu cambio. ELIMINAR TU NOMBRE - Ten en cuenta que la información del perfil se guarda en archivos públicos. + Este es tu perfil de pubky.app. Es público, y los cambios que hagas aquí también se ven en pubky.app. No se pudo guardar el perfil Perfil guardado ETIQUETAS + Bitkit no ha podido guardar tus etiquetas. Tus otros cambios se han guardado, así que vuelve a intentarlo con las etiquetas. DESVINCULAR No se pudo cargar tu perfil. Con tu perfil portátil, tus contactos pueden localizarte y pagarte en cualquier lugar. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 33a9bbce01..efe19b0883 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1328,12 +1328,14 @@ No se pudo desconectar el perfil BIO Nota breve. Cuente algo sobre usted. + Tu perfil cambió en pubky.app. Bitkit cargó la versión más reciente, así que vuelve a hacer tu cambio. ELIMINAR SU NOMBRE - Tenga en cuenta que la información del perfil se guarda en archivos públicos. + Este es tu perfil de pubky.app. Es público, y los cambios que hagas aquí también se ven en pubky.app. No se pudo guardar el perfil Perfil guardado ETIQUETAS + Bitkit no pudo guardar tus etiquetas. Tus otros cambios se guardaron, así que vuelve a intentar con las etiquetas. DESVINCULAR No se pudo cargar su perfil. Con su perfil portátil, sus contactos pueden localizarle y pagarle en cualquier lugar. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index fbe36f81bc..0b041379c8 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1329,12 +1329,14 @@ Échec de la déconnexion du profil BIO Courte note. Parlez un peu de vous. + Ton profil a changé sur pubky.app. Bitkit a chargé la version la plus récente, refais donc ta modification. SUPPRIMER VOTRE NOM - Veuillez noter que les informations de profil sont stockées dans des fichiers publics. + Voici ton profil pubky.app. Il est public, et les modifications que tu fais ici apparaissent aussi sur pubky.app. Échec de l\'enregistrement du profil Profil enregistré ÉTIQUETTES + Bitkit n\'a pas pu enregistrer vos étiquettes. Vos autres modifications ont été enregistrées, réessayez pour les étiquettes. DISSOCIER Impossible de charger votre profil. Grâce à votre profil portable, vos contacts peuvent vous joindre et vous payer partout. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 38a8889d27..ec69ef18f3 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1334,12 +1334,14 @@ Impossibile disconnettere il profilo BIO Breve nota. Racconta qualcosa di te. + Il tuo profilo è cambiato su pubky.app. Bitkit ha caricato la versione più recente, quindi ripeti la modifica. ELIMINA IL TUO NOME - Tieni presente che le informazioni del profilo sono salvate in file pubblici. + Questo è il tuo profilo pubky.app. È pubblico e le modifiche che fai qui compaiono anche su pubky.app. Impossibile salvare il profilo Profilo salvato TAG + Bitkit non è riuscito a salvare i tuoi tag. Le altre modifiche sono state salvate, quindi riprova con i tag. SCOLLEGA Impossibile caricare il tuo profilo. Con il tuo profilo portatile i tuoi contatti possono raggiungerti e pagarti ovunque. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index c97f60b562..81e33692c1 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1331,12 +1331,14 @@ Profiel ontkoppelen mislukt BIO Korte notitie. Vertel iets over uzelf. + Je profiel is gewijzigd in pubky.app. Bitkit heeft de nieuwste versie geladen, dus voer je wijziging opnieuw uit. VERWIJDEREN UW NAAM - Let op: profielgegevens worden opgeslagen in openbare bestanden. + Dit is je pubky.app-profiel. Het is openbaar, en wijzigingen die je hier maakt, verschijnen ook op pubky.app. Profiel opslaan mislukt Profiel opgeslagen TAGS + Bitkit kon je tags niet opslaan. Je andere wijzigingen zijn opgeslagen, dus probeer de tags opnieuw. ONTKOPPELEN Kan uw profiel niet laden. Met uw draagbare profiel kunnen uw contacten u overal bereiken en betalen. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 21b12d0dfd..6492c3de36 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1332,12 +1332,14 @@ Nie udało się odłączyć profilu BIO Krótka notatka. Napisz coś o sobie. + Twój profil zmienił się w pubky.app. Bitkit wczytał najnowszą wersję, więc wprowadź zmianę ponownie. USUWANIE TWOJE IMIĘ - Pamiętaj, że dane profilu są przechowywane w publicznych plikach. + To jest Twój profil pubky.app. Jest publiczny, a zmiany wprowadzone tutaj pojawią się też w pubky.app. Nie udało się zapisać profilu Profil zapisany TAGI + Bitkit nie mógł zapisać Twoich tagów. Pozostałe zmiany zostały zapisane, więc spróbuj ponownie z tagami. ODŁĄCZANIE Nie można wczytać Twojego profilu. Dzięki przenośnemu profilowi Twoje kontakty mogą skontaktować się z Tobą i zapłacić Ci w dowolnym miejscu. diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 7d3f385814..abaa3e4831 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1334,12 +1334,14 @@ Falha ao desconectar perfil BIO Nota curta. Conte um pouco sobre você. + Seu perfil mudou no pubky.app. O Bitkit carregou a versão mais recente, então faça sua alteração de novo. EXCLUIR SEU NOME - Observe que as informações do perfil são armazenadas em arquivos públicos. + Este é o seu perfil do pubky.app. Ele é público, e as alterações que você faz aqui também aparecem no pubky.app. Falha ao salvar perfil Perfil salvo TAGS + O Bitkit não conseguiu salvar suas tags. Suas outras alterações foram salvas, então tente as tags novamente. DESVINCULAR Não foi possível carregar seu perfil. Com seu perfil portátil, seus contatos podem encontrar você e pagar você em qualquer lugar. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 00bc9f16c6..57262a74f4 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1308,13 +1308,15 @@ Falha ao desligar o perfil BIOGRAFIA Nota breve. Fale um pouco sobre si. + O teu perfil mudou no pubky.app. A Bitkit carregou a versão mais recente, por isso faz novamente a tua alteração. ELIMINAR O SEU NOME Editar perfil - Tenha em atenção que as informações do perfil são guardadas em ficheiros públicos. + Este é o teu perfil do pubky.app. É público, e as alterações que fazes aqui também aparecem no pubky.app. Falha ao guardar o perfil Perfil guardado ETIQUETAS + O Bitkit não conseguiu guardar as suas etiquetas. As outras alterações foram guardadas, por isso tente as etiquetas novamente. DESASSOCIAR Não foi possível carregar o seu perfil. Com o seu perfil portátil, os seus contactos podem encontrá-lo e pagar-lhe em qualquer lugar. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 4b2e2fea07..614b8a02d9 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1349,12 +1349,14 @@ Не удалось отключить профиль О СЕБЕ Короткая заметка. Расскажите немного о себе. + Ваш профиль изменился в pubky.app. Bitkit загрузил последнюю версию, поэтому внесите изменение снова. УДАЛЕНИЕ ВАШЕ ИМЯ - Обратите внимание: данные профиля хранятся в публичных файлах. + Это ваш профиль pubky.app. Он публичный, и изменения, которые вы вносите здесь, также видны в pubky.app. Не удалось сохранить профиль Профиль сохранён ТЕГИ + Bitkit не удалось сохранить ваши теги. Остальные изменения сохранены, поэтому попробуйте сохранить теги ещё раз. ОТВЯЗКА Не удалось загрузить ваш профиль. С переносимым профилем ваши контакты смогут связаться с вами и заплатить вам где угодно. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 2e97ca9eb6..aaff453bc9 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -642,13 +642,15 @@ Failed to disconnect profile BIO Short note. Tell a bit about yourself. + Your profile changed in pubky.app. Bitkit loaded the latest version, so make your edit again. DELETE YOUR NAME Edit Profile - Please note profile information is stored in public files. + This is your pubky.app profile. It is public, and changes you make here also show on pubky.app. Failed to save profile Profile saved TAGS + Bitkit could not save your tags. Your other changes were saved, so try the tags again. UNLINK Unable to load your profile. With your portable profile your contacts can reach you and pay you anywhere. diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index 9f9cddce72..81352e2b05 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -8,12 +8,15 @@ import com.synonym.paykit.ContactRecord import com.synonym.paykit.ContactUpdate import com.synonym.paykit.PaykitException import com.synonym.paykit.PaykitProfile +import com.synonym.paykit.PaykitProfileRecord import com.synonym.paykit.PaykitSdk import com.synonym.paykit.PaykitStateObservation import com.synonym.paykit.ProfileResolution import com.synonym.paykit.ProfileSource import com.synonym.paykit.PubkyAuthCompanionClaim import com.synonym.paykit.PubkyAuthDetails +import com.synonym.paykit.PubkyProfileSnapshot +import com.synonym.paykit.PubkyProfileUpdate import com.synonym.paykit.PubkySessionBootstrapResult import com.synonym.paykit.PublicationStatus import io.ktor.client.HttpClient @@ -53,6 +56,7 @@ import org.junit.Test import org.mockito.Mockito.clearInvocations import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.atLeastOnce import org.mockito.kotlin.doAnswer import org.mockito.kotlin.doReturn @@ -60,6 +64,7 @@ import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.never +import org.mockito.kotlin.nullableArgumentCaptor import org.mockito.kotlin.reset import org.mockito.kotlin.times import org.mockito.kotlin.verify @@ -81,6 +86,8 @@ import to.bitkit.models.PubkyAuthClaim import to.bitkit.models.PubkyAuthClaim.Item import to.bitkit.models.PubkyAuthRequest import to.bitkit.models.PubkyProfile +import to.bitkit.models.PubkyProfileData +import to.bitkit.models.PubkyProfileDataLink import to.bitkit.models.PubkySessionBackupKind import to.bitkit.models.PubkySessionBackupV1 import to.bitkit.services.PaykitReadLane @@ -92,6 +99,7 @@ import to.bitkit.test.forEachCase import to.bitkit.utils.AppError import kotlin.test.assertEquals import kotlin.test.assertFalse +import kotlin.test.assertIs import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertSame @@ -102,6 +110,7 @@ import kotlin.time.Duration.Companion.seconds import kotlin.time.ExperimentalTime import kotlin.time.Instant import com.synonym.paykit.PubkyProfile as SdkPubkyProfile +import com.synonym.paykit.PubkyProfileLink as SdkPubkyProfileLink @OptIn(ExperimentalCoroutinesApi::class, ExperimentalTime::class) class PubkyRepoTest : BaseUnitTest() { @@ -156,6 +165,20 @@ class PubkyRepoTest : BaseUnitTest() { Unit } whenever(pubkyService.contactRecords()).thenReturn(emptyList()) + whenever(pubkyService.currentPublicKey()).thenReturn(VALID_SELF_KEY) + whenever { pubkyService.publishPubkyProfile(any(), anyOrNull(), any()) }.doSuspendableAnswer { + val update = it.getArgument(0) + createSnapshot( + VALID_SELF_KEY, + SdkPubkyProfile( + name = update.name.orEmpty(), + bio = update.bio, + image = update.image?.ifEmpty { null }, + links = update.links.orEmpty(), + status = null, + ), + ) + } whenever { pubkyService.observedContactRecords(any()) }.doSuspendableAnswer { pubkyService.contactRecords() } whenever { pubkyService.initializeAndImportSession(any()) }.doSuspendableAnswer { runSuspendCatching { pubkyService.importSession(it.getArgument(0)) } @@ -538,7 +561,9 @@ class PubkyRepoTest : BaseUnitTest() { whenever(pubkyService.deriveSecretKey("test mnemonic")).thenReturn("test-secret") whenever(pubkyService.publicKeyFromSecret("test-secret")).thenReturn(VALID_SELF_KEY.removePrefix("pubky")) whenever(pubkyService.signUp("test-secret", "test-homeserver", "test-code")).thenReturn(Unit) - whenever(pubkyService.publishPaykitProfile(any())).thenAnswer { throw TestAppError("Publish failed") } + whenever( + pubkyService.publishPubkyProfile(any(), anyOrNull(), any()) + ).thenAnswer { throw TestAppError("Publish failed") } whenever(pubkyService.signOut()).thenAnswer { throw TestAppError("Server error") } val result = sut.createIdentity( @@ -567,7 +592,7 @@ class PubkyRepoTest : BaseUnitTest() { assertTrue(result.isFailure) assertFalse(profileSetupPending.value) verify(keychain).loadString(Keychain.Key.BIP39_MNEMONIC.name) - verifyBlocking(pubkyService, never()) { publishPaykitProfile(any()) } + verifyBlocking(pubkyService, never()) { publishPubkyProfile(any(), anyOrNull(), any()) } } @Test @@ -577,7 +602,7 @@ class PubkyRepoTest : BaseUnitTest() { profileSetupPending.value = true whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn("local-secret") whenever(pubkyService.publicKeyFromSecret("local-secret")).thenReturn(VALID_SELF_KEY.removePrefix("pubky")) - whenever(pubkyService.publishPaykitProfile(any())).thenReturn(mock()) + whenever(pubkyService.publishPaykitProfile(any(), any())).thenReturn(mock()) val result = sut.createIdentity("Restored", "", emptyList(), emptyList(), null) @@ -604,7 +629,7 @@ class PubkyRepoTest : BaseUnitTest() { verify(keychain, never()).loadString(Keychain.Key.BIP39_MNEMONIC.name) verifyBlocking(pubkyService, never()) { signIn(any()) } verifyBlocking(pubkyService, never()) { signUp(any(), any(), any()) } - verifyBlocking(pubkyService, never()) { publishPaykitProfile(any()) } + verifyBlocking(pubkyService, never()) { publishPubkyProfile(any(), anyOrNull(), any()) } } @Test @@ -612,13 +637,13 @@ class PubkyRepoTest : BaseUnitTest() { whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn("local-secret") whenever(pubkyService.publicKeyFromSecret("local-secret")).thenReturn(VALID_SELF_KEY) whenever(pubkyService.signIn("local-secret")).thenAnswer { throw TestAppError("offline") }.thenReturn(Unit) - whenever(pubkyService.publishPaykitProfile(any())).thenReturn(mock()) + whenever(pubkyService.publishPaykitProfile(any(), any())).thenReturn(mock()) val firstResult = sut.createIdentity("Test", "", emptyList(), emptyList(), null) assertEquals("offline", firstResult.exceptionOrNull()?.message) assertNull(sut.publicKey.value) - verifyBlocking(pubkyService, never()) { publishPaykitProfile(any()) } + verifyBlocking(pubkyService, never()) { publishPubkyProfile(any(), anyOrNull(), any()) } assertTrue(sut.createIdentity("Test", "", emptyList(), emptyList(), null).isSuccess) assertEquals(VALID_SELF_KEY, sut.publicKey.value) @@ -635,9 +660,9 @@ class PubkyRepoTest : BaseUnitTest() { val existingProfile = sut.profile.value whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn("local-secret") whenever(pubkyService.publicKeyFromSecret("local-secret")).thenReturn(VALID_SELF_KEY) - whenever(pubkyService.publishPaykitProfile(any())) + whenever(pubkyService.publishPubkyProfile(any(), anyOrNull(), any())) .thenAnswer { throw TestAppError("offline") } - .thenReturn(mock()) + .thenReturn(createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "Updated"))) val firstResult = sut.createIdentity("Updated", "", emptyList(), emptyList(), null) @@ -667,12 +692,12 @@ class PubkyRepoTest : BaseUnitTest() { } Unit } - whenever(pubkyService.publishPaykitProfile(any())).doSuspendableAnswer { + whenever(pubkyService.publishPubkyProfile(any(), anyOrNull(), any())).doSuspendableAnswer { if (cancelDuringSignIn == false) { operationStarted.complete(Unit) awaitCancellation() } - mock() + createSnapshot(VALID_SELF_KEY, createPubkyProfile()) } for (duringSignIn in listOf(true, false)) { cancelDuringSignIn = duringSignIn @@ -701,7 +726,7 @@ class PubkyRepoTest : BaseUnitTest() { stubSignupKeys() whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenReturn("ring-session") whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn("") - whenever(pubkyService.publishPaykitProfile(any())).thenReturn(mock()) + whenever(pubkyService.publishPaykitProfile(any(), any())).thenReturn(mock()) val result = sut.createIdentity("Test", "", emptyList(), emptyList(), null) @@ -721,7 +746,7 @@ class PubkyRepoTest : BaseUnitTest() { throw AppError(PaykitException.Policy("policy_error", "Identity lives on another homeserver")) } whenever(pubkyService.signIn("secret")).thenReturn(Unit) - whenever(pubkyService.publishPaykitProfile(any())).thenReturn(mock()) + whenever(pubkyService.publishPaykitProfile(any(), any())).thenReturn(mock()) val result = sut.createIdentity("Test", "", emptyList(), emptyList(), null) httpClient.close() @@ -746,7 +771,7 @@ class PubkyRepoTest : BaseUnitTest() { assertTrue(result.exceptionOrNull()?.isPaykitTemporarilyUnavailable() == true) assertNull(sut.publicKey.value) verifyBlocking(pubkyService, times(1)) { signUp(any(), any(), any()) } - verifyBlocking(pubkyService, never()) { publishPaykitProfile(any()) } + verifyBlocking(pubkyService, never()) { publishPaykitProfile(any(), any()) } } @Test @@ -756,7 +781,9 @@ class PubkyRepoTest : BaseUnitTest() { whenever(pubkyService.registerIdentity("secret", "homeserver", "invite")).thenReturn(registeredSession) assertTrue(sut.approveSignupAuth(ringSignupRequest()).isSuccess) clearInvocations(pubkyService) - whenever(pubkyService.publishPaykitProfile(any())).thenAnswer { throw TestAppError("Publish failed") } + whenever( + pubkyService.publishPubkyProfile(any(), anyOrNull(), any()) + ).thenAnswer { throw TestAppError("Publish failed") } val result = sut.createIdentity( name = "Test", @@ -767,7 +794,7 @@ class PubkyRepoTest : BaseUnitTest() { ) assertTrue(result.isFailure) - verifyBlocking(pubkyService) { publishPaykitProfile(any()) } + verifyBlocking(pubkyService) { publishPubkyProfile(any(), anyOrNull(), any()) } verifyBlocking(pubkyService, never()) { signUp(any(), any(), any()) } verifyBlocking(pubkyService, never()) { signIn(any()) } verifyBlocking(pubkyService, never()) { signOut() } @@ -784,9 +811,9 @@ class PubkyRepoTest : BaseUnitTest() { whenever(pubkyService.deriveSecretKey("test mnemonic")).thenReturn("test-secret") whenever(pubkyService.publicKeyFromSecret("test-secret")).thenReturn(VALID_SELF_KEY.removePrefix("pubky")) whenever(pubkyService.signUp("test-secret", "test-homeserver", "test-code")).thenReturn(Unit) - whenever(pubkyService.publishPaykitProfile(any())).thenReturn(mock()) - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)) - .thenReturn(createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile())) + whenever(pubkyService.publishPaykitProfile(any(), any())).thenReturn(mock()) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)) + .thenReturn(createSnapshot(VALID_SELF_KEY, createPubkyProfile())) whenever(pubkyService.contactRecords()).doSuspendableAnswer { contactsLoadStarted.complete(Unit) finishContactsLoad.await() @@ -821,7 +848,7 @@ class PubkyRepoTest : BaseUnitTest() { fun `createIdentity returns cache failure after profile publication`() = test { authenticateForTesting(publicKey = VALID_SELF_KEY) profileSetupPending.value = true - whenever(pubkyService.publishPaykitProfile(any())).thenReturn(mock()) + whenever(pubkyService.publishPaykitProfile(any(), any())).thenReturn(mock()) whenever { pubkyStore.update(any()) }.thenAnswer { throw TestAppError("cache failed") } @@ -835,8 +862,8 @@ class PubkyRepoTest : BaseUnitTest() { fun `createIdentity keeps the published profile without waiting for readback`() = test { authenticateForTesting(publicKey = VALID_SELF_KEY) profileSetupPending.value = true - whenever(pubkyService.publishPaykitProfile(any())).thenReturn(mock()) - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)) + whenever(pubkyService.publishPaykitProfile(any(), any())).thenReturn(mock()) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)) .thenReturn(null) clearInvocations(pubkyService) @@ -844,7 +871,7 @@ class PubkyRepoTest : BaseUnitTest() { assertTrue(result.isSuccess) assertEquals("Test", sut.profile.value?.name) - verify(pubkyService, never()).resolveContactProfile(any(), any(), any(), anyOrNull()) + verify(pubkyService, never()).fetchPubkyProfileWithRevision(any()) } @Test @@ -861,9 +888,9 @@ class PubkyRepoTest : BaseUnitTest() { } emptyList() } - whenever(pubkyService.publishPaykitProfile(any())).doSuspendableAnswer { + whenever(pubkyService.publishPubkyProfile(any(), anyOrNull(), any())).doSuspendableAnswer { profilePublished.complete(Unit) - mock() + createSnapshot(VALID_SELF_KEY, createPubkyProfile()) } val activeContactLoad = async { sut.loadContacts() } contactLoadStarted.await() @@ -898,8 +925,8 @@ class PubkyRepoTest : BaseUnitTest() { image = "pubky://image_uri", status = "active", ) - whenever(pubkyService.resolveContactProfile(pk, true)) - .thenReturn(createResolution(pk, pubkyProfile = pubkyProfile)) + whenever(pubkyService.fetchPubkyProfileWithRevision(pk)) + .thenReturn(createSnapshot(pk, pubkyProfile)) sut.loadProfile() @@ -911,6 +938,518 @@ class PubkyRepoTest : BaseUnitTest() { assertEquals("active", profile.status) } + @Test + fun `saveProfile writes only the changed fields at the loaded revision`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY, profileName = "Old") + + assertTrue(saveNewProfile().isSuccess) + + verifyBlocking(pubkyService) { + publishPubkyProfile( + PubkyProfileUpdate(name = "New", bio = null, image = null, links = null), + "revision-Old", + VALID_SELF_KEY, + ) + } + assertEquals("New", sut.profile.value?.name) + } + + @Test + fun `saveProfile signs in again once when the session lacks the pubky app scope`() = test { + val secretKey = "local_secret" + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn(secretKey) + whenever(pubkyService.signIn(secretKey)).thenReturn(Unit) + whenever(pubkyService.publicKeyFromSecret(secretKey)).thenReturn(VALID_SELF_KEY.removePrefix("pubky")) + whenever(pubkyService.publishPubkyProfile(any(), anyOrNull(), any())) + .thenAnswer { throw PaykitException.Identity("identity_error", "Missing capabilities") } + .thenReturn(createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "New"))) + + assertTrue(saveNewProfile().isSuccess) + + verifyBlocking(pubkyService) { signIn(secretKey) } + verifyBlocking(pubkyService, times(2)) { publishPubkyProfile(any(), anyOrNull(), any()) } + } + + @Test + fun `an edit opened before a refresh saves against the revision it opened with`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY, profileName = "Old") + val editBase = sut.profileEditBase() + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)) + .thenReturn(createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "Newer"))) + sut.loadProfile() + assertEquals("revision-Newer", sut.profileEditBase().revision) + + sut.saveProfile( + name = "New", + bio = "", + links = emptyList(), + tags = emptyList(), + imageUrl = null, + editBase = editBase + ) + + verifyBlocking(pubkyService) { publishPubkyProfile(any(), eq("revision-Old"), any()) } + } + + @Test + fun `loadProfile keeps the Bitkit avatar when moving it to pubky app fails`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).thenReturn(null) + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenReturn( + PaykitProfileRecord( + publicKey = VALID_SELF_KEY, + profile = createPaykitProfile("Bitkit Name", image = "pubky://self/pub/paykit/blobs/avatar.jpg"), + path = "/pub/paykit/profile.json", + revision = "paykit-revision", + updatedAt = "2026-01-01T00:00:00Z", + ) + ) + whenever(pubkyService.fetchFile(any(), any())).thenAnswer { throw TestAppError("offline") } + clearInvocations(pubkyService) + + sut.loadProfile() + + assertEquals("pubky://self/pub/paykit/blobs/avatar.jpg", sut.profile.value?.imageUrl) + verifyBlocking(pubkyService, never()) { publishPaykitProfile(any(), any()) } + } + + @Test + fun `createIdentity does not overwrite a pubky app profile its form was not filled from`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(pubkyService.publishPubkyProfile(any(), anyOrNull(), any())) + .thenAnswer { throw PaykitException.ConcurrentUpdate("concurrent_update", "Pubky profile changed") } + + val result = sut.createIdentity("Updated", "", emptyList(), emptyList(), null) + + assertIs(result.exceptionOrNull()) + verifyBlocking(pubkyService, times(1)) { publishPubkyProfile(any(), anyOrNull(), any()) } + } + + @Test + fun `createIdentity does not restore against a profile from an earlier lookup after a failed one`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)) + .thenReturn(createSnapshot(VALID_SELF_KEY, createPubkyProfile(bio = "Existing bio"))) + checkNotNull(sut.fetchRemoteProfile(VALID_SELF_KEY).getOrThrow()) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)) + .thenAnswer { throw TestAppError("offline") } + assertTrue(sut.fetchRemoteProfile(VALID_SELF_KEY).isFailure) + clearInvocations(pubkyService) + + sut.createIdentity("New Name", "", emptyList(), emptyList(), null) + + val revision = nullableArgumentCaptor() + verifyBlocking(pubkyService) { publishPubkyProfile(any(), revision.capture(), any()) } + assertEquals(null, revision.firstValue) + } + + @Test + fun `createIdentity restores against the pubky app profile its form was filled from`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + val restored = checkNotNull(sut.fetchRemoteProfile(VALID_SELF_KEY).getOrThrow()) + clearInvocations(pubkyService) + + sut.createIdentity("Renamed", restored.bio, restored.links, restored.tags, null) + + verifyBlocking(pubkyService) { + publishPubkyProfile(PubkyProfileUpdate("Renamed", null, null, null), "revision-Test", VALID_SELF_KEY) + } + } + + @Test + fun `saveProfile reports a tag change it could not store while the tags cannot be read`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenAnswer { throw TestAppError("offline") } + sut.loadProfile() + + val result = sut.saveProfile( + name = "Test", + bio = "", + links = emptyList(), + tags = listOf("new"), + imageUrl = null + ) + + val error = assertIs(result.exceptionOrNull()) + assertEquals("revision-", error.base.revision) + verifyBlocking(pubkyService, never()) { publishPaykitProfile(any(), any()) } + } + + @Test + fun `loadProfile keeps an avatar set on pubky app over a pending avatar move`() = test { + whenever(pubkyStore.data).thenReturn( + flowOf( + PubkyStoreData( + pubkyAppProfileOwners = setOf(VALID_SELF_KEY), + pubkyAppAvatarPending = setOf(VALID_SELF_KEY) + ) + ) + ) + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).thenReturn( + createSnapshot(VALID_SELF_KEY, createPubkyProfile(image = "pubky://self/pub/pubky.app/files/0000000000000")) + ) + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenReturn( + PaykitProfileRecord( + publicKey = VALID_SELF_KEY, + profile = createPaykitProfile("Test", image = "pubky://self/pub/paykit/blobs/avatar.jpg"), + path = "/pub/paykit/profile.json", + revision = "paykit-revision", + updatedAt = "2026-01-01T00:00:00Z", + ) + ) + + sut.loadProfile() + + assertEquals("pubky://self/pub/pubky.app/files/0000000000000", sut.profile.value?.imageUrl) + verifyBlocking(pubkyService, never()) { fetchFile(any(), any()) } + } + + @Test + fun `loadProfile records the avatar move before it creates the pubky app profile`() = test { + val store = MutableStateFlow(PubkyStoreData()) + whenever(pubkyStore.data).thenReturn(store) + whenever { pubkyStore.update(any()) }.thenAnswer { + store.value = it.getArgument<(PubkyStoreData) -> PubkyStoreData>(0)(store.value) + Unit + } + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).thenReturn(null) + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenReturn( + paykitRecord(createPaykitProfile("Bitkit Name", image = "pubky://self/pub/paykit/blobs/avatar.jpg")) + ) + var pendingAtCreate: Set? = null + whenever { pubkyService.publishPubkyProfile(any(), anyOrNull(), any()) }.doSuspendableAnswer { + pendingAtCreate = pendingAtCreate ?: store.value.pubkyAppAvatarPending + createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "Bitkit Name")) + } + store.value = PubkyStoreData() + + sut.loadProfile() + + assertEquals(setOf(VALID_SELF_KEY), pendingAtCreate) + } + + @Test + fun `loadProfile keeps a pending avatar move when the Paykit copy cannot be read`() = test { + val store = MutableStateFlow( + PubkyStoreData(pubkyAppProfileOwners = setOf(VALID_SELF_KEY), pubkyAppAvatarPending = setOf(VALID_SELF_KEY)) + ) + whenever(pubkyStore.data).thenReturn(store) + whenever { pubkyStore.update(any()) }.thenAnswer { + store.value = it.getArgument<(PubkyStoreData) -> PubkyStoreData>(0)(store.value) + Unit + } + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenAnswer { throw TestAppError("offline") } + authenticateForTesting(publicKey = VALID_SELF_KEY) + sut.loadProfile() + doReturn( + paykitRecord(createPaykitProfile("Test", image = "pubky://self/pub/paykit/blobs/avatar.jpg")) + ).whenever(pubkyService).fetchPaykitProfile(VALID_SELF_KEY) + clearInvocations(pubkyService) + + sut.loadProfile() + + verifyBlocking(pubkyService) { fetchFile(eq("pubky://self/pub/paykit/blobs/avatar.jpg"), any()) } + } + + @Test + fun `createIdentity fits a restored Bitkit-only profile to pubky app limits`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).thenReturn(null) + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenReturn( + paykitRecord( + PubkyProfileData( + name = "Bitkit Name", + bio = "b".repeat(200), + links = listOf(PubkyProfileDataLink("City", "New York")) + + (1..6).map { PubkyProfileDataLink("Site $it", "site$it.com") }, + ).toPaykitProfile() + ) + ) + val restored = checkNotNull(sut.fetchRemoteProfile(VALID_SELF_KEY).getOrThrow()) + clearInvocations(pubkyService) + + sut.createIdentity(restored.name, restored.bio, restored.links, restored.tags, null) + + val update = argumentCaptor() + verifyBlocking(pubkyService) { publishPubkyProfile(update.capture(), anyOrNull(), any()) } + assertEquals("b".repeat(160), update.firstValue.bio) + assertEquals((1..5).map { "https://site$it.com" }, update.firstValue.links?.map { it.url }) + } + + @Test + fun `saveProfile keeps the stored tags when a tag retry follows a failed read and write`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenAnswer { throw TestAppError("offline") } + sut.loadProfile() + doReturn( + paykitRecord(PubkyProfileData(name = "Test", bio = "", tags = listOf("friend", "work")).toPaykitProfile()) + ) + .whenever(pubkyService).fetchPaykitProfile(VALID_SELF_KEY) + whenever(pubkyService.publishPaykitProfile(any(), any())) + .thenAnswer { throw TestAppError("offline") } + .thenAnswer { paykitRecord(it.getArgument(0)) } + + val first = sut.saveProfile(name = "Test", bio = "", links = emptyList(), tags = listOf("vip"), imageUrl = null) + val base = assertIs(first.exceptionOrNull()).base + sut.saveProfile( + name = "Test", + bio = "", + links = emptyList(), + tags = listOf("vip"), + imageUrl = null, + editBase = base + ) + + val copy = argumentCaptor() + verifyBlocking(pubkyService, times(2)) { publishPaykitProfile(copy.capture(), any()) } + assertEquals(listOf("friend", "work", "vip"), PubkyProfileData.fromPaykitProfile(copy.lastValue).tags) + } + + @Test + fun `saveProfile keeps the stored tags when the edit began while they could not be read`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenAnswer { throw TestAppError("offline") } + sut.loadProfile() + val editBase = sut.profileEditBase() + doReturn( + paykitRecord(PubkyProfileData(name = "Test", bio = "", tags = listOf("friend", "work")).toPaykitProfile()) + ).whenever(pubkyService).fetchPaykitProfile(VALID_SELF_KEY) + whenever(pubkyService.publishPaykitProfile(any(), any())).thenAnswer { paykitRecord(it.getArgument(0)) } + sut.loadProfile() + + sut.saveProfile( + name = "Renamed", + bio = "", + links = emptyList(), + tags = emptyList(), + imageUrl = null, + editBase = editBase + ).getOrThrow() + + val copy = argumentCaptor() + verifyBlocking(pubkyService, atLeastOnce()) { publishPaykitProfile(copy.capture(), any()) } + assertEquals(listOf("friend", "work"), PubkyProfileData.fromPaykitProfile(copy.lastValue).tags) + } + + @Test + fun `deleteProfile deletes the pubky app profile of a wallet identity`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + + sut.deleteProfile() + + verifyBlocking(pubkyService) { deletePubkyProfile("revision-Test", VALID_SELF_KEY) } + } + + @Test + fun `deleteProfile is not followed by a profile copy write from a load under way`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)) + .thenReturn(paykitRecord(PubkyProfileData(name = "Old", bio = "").toPaykitProfile())) + whenever(pubkyService.publishPaykitProfile(any(), any())).thenAnswer { paykitRecord(it.getArgument(0)) } + val snapshot = createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "Test")) + val loadReading = CompletableDeferred() + val finishLoad = CompletableDeferred() + var reads = 0 + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).doSuspendableAnswer { + if (reads++ == 0) { + loadReading.complete(Unit) + finishLoad.await() + } + snapshot + } + val copyDeleted = CompletableDeferred() + whenever(pubkyService.deletePaykitProfile()).doSuspendableAnswer { + copyDeleted.complete(Unit) + Unit + } + clearInvocations(pubkyService) + + val load = async { sut.loadProfile() } + loadReading.await() + val deletion = async { sut.deleteProfile() } + copyDeleted.await() + finishLoad.complete(Unit) + deletion.await().getOrThrow() + load.await() + + verifyBlocking(pubkyService, never()) { publishPaykitProfile(any(), any()) } + } + + @Test + fun `a load under way does not write back the tags a save replaced`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + var copy = PubkyProfileData(name = "Test", bio = "", tags = listOf("old")).toPaykitProfile() + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenAnswer { paykitRecord(copy) } + whenever(pubkyService.publishPaykitProfile(any(), any())).thenAnswer { + copy = it.getArgument(0) + paykitRecord(copy) + } + sut.loadProfile() + val loadReading = CompletableDeferred() + val finishLoad = CompletableDeferred() + val saved = createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "New")) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).doSuspendableAnswer { + loadReading.complete(Unit) + finishLoad.await() + saved + } + + val load = async { sut.loadProfile() } + loadReading.await() + sut.saveProfile(name = "New", bio = "", links = emptyList(), tags = listOf("new"), imageUrl = null).getOrThrow() + finishLoad.complete(Unit) + load.await() + + assertEquals(listOf("new"), PubkyProfileData.fromPaykitProfile(copy).tags) + } + + @Test + fun `a load during two saves does not write the profile copy back`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + val copy = PubkyProfileData(name = "Test", bio = "", tags = listOf("old")).toPaykitProfile() + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenAnswer { paykitRecord(copy) } + whenever(pubkyService.publishPaykitProfile(any(), any())).thenAnswer { paykitRecord(it.getArgument(0)) } + sut.loadProfile() + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)) + .thenReturn(createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "Loaded"))) + whenever { pubkyService.publishPubkyProfile(any(), anyOrNull(), any()) } + .thenReturn(createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "New"))) + // Both saves wait between their pubky.app write and their copy write, outside the write lock. + val savesWaiting = CompletableDeferred() + val finishSaves = CompletableDeferred() + var waiting = 0 + whenever { pubkyStore.update(any()) }.doSuspendableAnswer { + if (++waiting <= 2) { + if (waiting == 2) savesWaiting.complete(Unit) + finishSaves.await() + } + Unit + } + clearInvocations(pubkyService) + + val saves = (1..2).map { + async { + sut.saveProfile(name = "New", bio = "", links = emptyList(), tags = listOf("new"), imageUrl = null) + } + } + savesWaiting.await() + sut.loadProfile() + + verifyBlocking(pubkyService, never()) { publishPaykitProfile(any(), any()) } + finishSaves.complete(Unit) + saves.awaitAll() + } + + @Test + fun `loadProfile moves a multi-line bio and scheme-less links to pubky app`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).thenReturn(null) + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenReturn( + PaykitProfileRecord( + publicKey = VALID_SELF_KEY, + profile = PubkyProfileData( + name = "Bitkit Name", + bio = "line one\nline two", + links = listOf( + PubkyProfileDataLink("Site", "example.com"), + PubkyProfileDataLink("Mail", "a@b.com"), + PubkyProfileDataLink("Medium", "medium.com/@alice"), + PubkyProfileDataLink("City", "New York"), + PubkyProfileDataLink("Date", "2024-01-01"), + PubkyProfileDataLink("Dotted", "555.123.4567"), + PubkyProfileDataLink("Version", "v1.2.3"), + PubkyProfileDataLink("Loopback", "https://127.1"), + ), + ).toPaykitProfile(), + path = "/pub/paykit/profile.json", + revision = "paykit-revision", + updatedAt = "2026-01-01T00:00:00Z", + ) + ) + + sut.loadProfile() + + verifyBlocking(pubkyService) { + publishPubkyProfile( + PubkyProfileUpdate( + name = "Bitkit Name", + bio = "line one line two", + image = null, + links = listOf( + SdkPubkyProfileLink(title = "Site", url = "https://example.com"), + SdkPubkyProfileLink(title = "Mail", url = "mailto:a@b.com"), + SdkPubkyProfileLink(title = "Medium", url = "https://medium.com/@alice"), + SdkPubkyProfileLink(title = "Dotted", url = "tel:5551234567"), + SdkPubkyProfileLink(title = "Loopback", url = "https://127.1"), + ), + ), + null, + VALID_SELF_KEY, + ) + } + } + + @Test + fun `loadProfile shows the Bitkit profile when moving it to pubky app fails`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).thenReturn(null) + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenReturn( + PaykitProfileRecord( + publicKey = VALID_SELF_KEY, + profile = createPaykitProfile("Al"), + path = "/pub/paykit/profile.json", + revision = "paykit-revision", + updatedAt = "2026-01-01T00:00:00Z", + ) + ) + whenever(pubkyService.publishPubkyProfile(any(), anyOrNull(), any())) + .thenAnswer { throw PaykitException.Protocol("protocol", "Pubky profile name must be 3 to 50 characters") } + + sut.loadProfile() + + assertEquals("Al", sut.profile.value?.name) + } + + @Test + fun `saveProfile reports a profile that changed in pubky app`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(pubkyService.publishPubkyProfile(any(), anyOrNull(), any())) + .thenAnswer { throw PaykitException.ConcurrentUpdate("concurrent_update", "Pubky profile changed") } + + val result = saveNewProfile() + + assertIs(result.exceptionOrNull()) + } + + @Test + fun `loadProfile moves a Bitkit-only profile to pubky app`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).thenReturn(null) + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenReturn( + PaykitProfileRecord( + publicKey = VALID_SELF_KEY, + profile = createPaykitProfile("Bitkit Name", bio = "b".repeat(200)), + path = "/pub/paykit/profile.json", + revision = "paykit-revision", + updatedAt = "2026-01-01T00:00:00Z", + ) + ) + + sut.loadProfile() + + verifyBlocking(pubkyService) { + publishPubkyProfile( + PubkyProfileUpdate(name = "Bitkit Name", bio = "b".repeat(160), image = null, links = emptyList()), + null, + VALID_SELF_KEY, + ) + } + assertEquals("Bitkit Name", sut.profile.value?.name) + } + @Test fun `loadProfile should keep existing profile on failure`() = test { authenticateForTesting() @@ -918,7 +1457,7 @@ class PubkyRepoTest : BaseUnitTest() { assertNotNull(existingProfile) val pk = checkNotNull(sut.publicKey.value) { "publicKey should be set after authentication" } - whenever(pubkyService.resolveContactProfile(pk, true)).thenAnswer { throw TestAppError("Network error") } + whenever(pubkyService.fetchPubkyProfileWithRevision(pk)).thenAnswer { throw TestAppError("Network error") } sut.loadProfile() @@ -929,13 +1468,13 @@ class PubkyRepoTest : BaseUnitTest() { @Test fun `loadProfile retries a failed own profile resolution once`() = test { authenticateForTesting(publicKey = VALID_SELF_KEY) - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)) .thenAnswer { throw TestAppError("Network error") } clearInvocations(pubkyService) sut.loadProfile() - verify(pubkyService, times(2)).resolveContactProfile(VALID_SELF_KEY, true) + verify(pubkyService, times(2)).fetchPubkyProfileWithRevision(VALID_SELF_KEY) } @Test @@ -944,10 +1483,10 @@ class PubkyRepoTest : BaseUnitTest() { resetForCase() authenticateForTesting(publicKey = VALID_SELF_KEY) val finishLoad = CompletableDeferred() - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)).doSuspendableAnswer { + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).doSuspendableAnswer { finishLoad.await() if (fails) throw TestAppError("Offline") - createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile(name = "Loaded")) + createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "Loaded")) } clearInvocations(pubkyService) @@ -957,10 +1496,10 @@ class PubkyRepoTest : BaseUnitTest() { loads.awaitAll() val attempts = if (fails) 2 else 1 - verify(pubkyService, times(attempts)).resolveContactProfile(VALID_SELF_KEY, true) + verify(pubkyService, times(attempts)).fetchPubkyProfileWithRevision(VALID_SELF_KEY) assertFalse(sut.isLoadingProfile.value) sut.loadProfile() - verify(pubkyService, times(attempts * 2)).resolveContactProfile(VALID_SELF_KEY, true) + verify(pubkyService, times(attempts * 2)).fetchPubkyProfileWithRevision(VALID_SELF_KEY) } } @@ -968,9 +1507,9 @@ class PubkyRepoTest : BaseUnitTest() { fun `profile load after a save does not reuse an outdated in-flight read`() = test { authenticateForTesting(publicKey = VALID_SELF_KEY) val finishLoad = CompletableDeferred() - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)).doSuspendableAnswer { + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).doSuspendableAnswer { finishLoad.await() - createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile(name = "Loaded")) + createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "Loaded")) } clearInvocations(pubkyService) @@ -981,7 +1520,7 @@ class PubkyRepoTest : BaseUnitTest() { first.await() next.await() - verify(pubkyService, times(2)).resolveContactProfile(VALID_SELF_KEY, true) + verify(pubkyService, times(2)).fetchPubkyProfileWithRevision(VALID_SELF_KEY) assertEquals("Loaded", sut.profile.value?.name) } @@ -989,9 +1528,9 @@ class PubkyRepoTest : BaseUnitTest() { fun `cancelled profile load leaves queued refresh available`() = test { authenticateForTesting(publicKey = VALID_SELF_KEY) val finishLoad = CompletableDeferred() - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)).doSuspendableAnswer { + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).doSuspendableAnswer { finishLoad.await() - createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile(name = "Loaded")) + createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "Loaded")) } clearInvocations(pubkyService) @@ -1001,7 +1540,7 @@ class PubkyRepoTest : BaseUnitTest() { finishLoad.complete(Unit) next.await() - verify(pubkyService, times(2)).resolveContactProfile(VALID_SELF_KEY, true) + verify(pubkyService, times(2)).fetchPubkyProfileWithRevision(VALID_SELF_KEY) assertEquals("Loaded", sut.profile.value?.name) assertFalse(sut.isLoadingProfile.value) } @@ -1019,8 +1558,8 @@ class PubkyRepoTest : BaseUnitTest() { val pk = checkNotNull(sut.publicKey.value) { "publicKey should be set after authentication" } val pubkyProfile = createPubkyProfile(name = "Cached Name", image = "pubky://cached_image") - whenever(pubkyService.resolveContactProfile(pk, true)) - .thenReturn(createResolution(pk, pubkyProfile = pubkyProfile)) + whenever(pubkyService.fetchPubkyProfileWithRevision(pk)) + .thenReturn(createSnapshot(pk, pubkyProfile)) sut.loadProfile() @@ -1038,10 +1577,10 @@ class PubkyRepoTest : BaseUnitTest() { authenticateForTesting(publicKey = VALID_SELF_KEY, profileName = "Old") val loadStarted = CompletableDeferred() val finishLoad = CompletableDeferred() - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)).doSuspendableAnswer { + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).doSuspendableAnswer { loadStarted.complete(Unit) finishLoad.await() - createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile(name = "Loaded")) + createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "Loaded")) } val load = async { sut.loadProfile() } loadStarted.await() @@ -1059,9 +1598,9 @@ class PubkyRepoTest : BaseUnitTest() { fun `loadProfile marks the profile as loading before its first suspension`() = test { authenticateForTesting(publicKey = VALID_SELF_KEY) val finishLoad = CompletableDeferred() - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)).doSuspendableAnswer { + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).doSuspendableAnswer { finishLoad.await() - createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile()) + createSnapshot(VALID_SELF_KEY, createPubkyProfile()) } assertFalse(sut.isLoadingProfile.value) @@ -1171,7 +1710,7 @@ class PubkyRepoTest : BaseUnitTest() { assertTrue(result.isSuccess) assertEquals(backupVersion + 1, sut.backupStateVersion.value) - verifyBlocking(pubkyService) { publishPaykitProfile(any()) } + verifyBlocking(pubkyService) { publishPubkyProfile(any(), anyOrNull(), any()) } } @Test @@ -1477,7 +2016,7 @@ class PubkyRepoTest : BaseUnitTest() { importStarted.complete(Unit) finishImport.await() } - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)).thenReturn(null) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).thenReturn(null) val initialize = async { sut.initialize() } importStarted.await() val disconnect = async(start = CoroutineStart.UNDISPATCHED) { sut.forgetUnrestoredIdentity() } @@ -1760,7 +2299,7 @@ class PubkyRepoTest : BaseUnitTest() { authenticateForTesting(publicKey = VALID_CONTACT_KEY_A, profileName = "Previous") val ringPubky = stubRingCredential() whenever(pubkyService.signIn("ring_secret")).thenReturn(Unit) - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)).thenReturn(null) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).thenReturn(null) sut.adoptRingIdentity(ringPubky) sut.restoreContactProfileOverrides(emptyMap()) @@ -1922,7 +2461,7 @@ class PubkyRepoTest : BaseUnitTest() { fun `adoptRingIdentity should mark profile setup pending when the pubky has no profile`() = test { val ringPubky = stubRingCredential() whenever(pubkyService.signIn("ring_secret")).thenReturn(Unit) - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)).thenReturn(null) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).thenReturn(null) val result = sut.adoptRingIdentity(ringPubky) @@ -1936,8 +2475,8 @@ class PubkyRepoTest : BaseUnitTest() { profileSetupPending.value = true val ringPubky = stubRingCredential() whenever(pubkyService.signIn("ring_secret")).thenReturn(Unit) - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)) - .thenReturn(createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile())) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)) + .thenReturn(createSnapshot(VALID_SELF_KEY, createPubkyProfile())) val result = sut.adoptRingIdentity(ringPubky) @@ -1950,7 +2489,7 @@ class PubkyRepoTest : BaseUnitTest() { authenticateForTesting(publicKey = VALID_CONTACT_KEY_A, profileName = "Previous") val ringPubky = stubRingCredential() whenever(pubkyService.signIn("ring_secret")).thenReturn(Unit) - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)).thenReturn(null) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).thenReturn(null) val result = sut.adoptRingIdentity(ringPubky) @@ -1999,8 +2538,8 @@ class PubkyRepoTest : BaseUnitTest() { val ringPubky = stubRingCredential() var signedIn = false whenever(pubkyService.signIn("ring_secret")).doSuspendableAnswer { signedIn = true } - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)).thenReturn( - case.remoteName?.let { createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile(name = it)) }, + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).thenReturn( + case.remoteName?.let { createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = it)) }, ) val handoff = case.handoff(ringPubky) @@ -2009,7 +2548,7 @@ class PubkyRepoTest : BaseUnitTest() { assertEquals(case.adopted, result.getOrNull(), case.name) assertEquals(case.profileName, sut.profile.value?.name, case.name) assertEquals(!case.adopted, profileSetupPending.value, case.name) - verify(pubkyService, case.resolves.description(case.name)).resolveContactProfile(VALID_SELF_KEY, true) + verify(pubkyService, case.resolves.description(case.name)).fetchPubkyProfileWithRevision(VALID_SELF_KEY) } } @@ -2090,10 +2629,10 @@ class PubkyRepoTest : BaseUnitTest() { whenever(pubkyService.signIn("ring_secret")).thenReturn(Unit) val profileLoadStarted = CompletableDeferred() val finishProfileLoad = CompletableDeferred() - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)).doSuspendableAnswer { + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).doSuspendableAnswer { profileLoadStarted.complete(Unit) finishProfileLoad.await() - createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile()) + createSnapshot(VALID_SELF_KEY, createPubkyProfile()) } clearInvocations(pubkyStore) val adoption = async { sut.adoptRingIdentity(ringPubky) } @@ -2132,7 +2671,7 @@ class PubkyRepoTest : BaseUnitTest() { Unit } val profileLoadStarted = CompletableDeferred() - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)).doSuspendableAnswer { + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).doSuspendableAnswer { profileLoadStarted.complete(Unit) awaitCancellation() } @@ -2172,7 +2711,7 @@ class PubkyRepoTest : BaseUnitTest() { Unit } val profileLoadStarted = CompletableDeferred() - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)).doSuspendableAnswer { + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).doSuspendableAnswer { profileLoadStarted.complete(Unit) awaitCancellation() } @@ -2206,12 +2745,12 @@ class PubkyRepoTest : BaseUnitTest() { } val firstProfileLoadStarted = CompletableDeferred() var profileLoads = 0 - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)).doSuspendableAnswer { + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).doSuspendableAnswer { if (++profileLoads == 1) { firstProfileLoadStarted.complete(Unit) awaitCancellation() } - createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile()) + createSnapshot(VALID_SELF_KEY, createPubkyProfile()) } val firstPick = async { sut.adoptRingIdentity(ringPubky) } firstProfileLoadStarted.await() @@ -2246,7 +2785,7 @@ class PubkyRepoTest : BaseUnitTest() { Unit } val profileLoadStarted = CompletableDeferred() - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)).doSuspendableAnswer { + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).doSuspendableAnswer { profileLoadStarted.complete(Unit) awaitCancellation() } @@ -2283,7 +2822,7 @@ class PubkyRepoTest : BaseUnitTest() { Unit } val profileLoadStarted = CompletableDeferred() - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)).doSuspendableAnswer { + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).doSuspendableAnswer { profileLoadStarted.complete(Unit) awaitCancellation() } @@ -2309,10 +2848,10 @@ class PubkyRepoTest : BaseUnitTest() { val contactsLoadStarted = CompletableDeferred() val finishOldProfileLoad = CompletableDeferred() val finishOldContactsLoad = CompletableDeferred() - whenever(pubkyService.resolveContactProfile(oldPublicKey, true)).doSuspendableAnswer { + whenever(pubkyService.fetchPubkyProfileWithRevision(oldPublicKey)).doSuspendableAnswer { profileLoadStarted.complete(Unit) finishOldProfileLoad.await() - createResolution(oldPublicKey, pubkyProfile = createPubkyProfile(name = "Old Profile")) + createSnapshot(oldPublicKey, createPubkyProfile(name = "Old Profile")) } whenever(pubkyService.contactRecords()).doSuspendableAnswer { if (sut.publicKey.value == oldPublicKey) { @@ -2333,8 +2872,8 @@ class PubkyRepoTest : BaseUnitTest() { whenever(sharedPubkyClient.ringCredential(ringPubky)).thenReturn(Result.success("new_ring_secret")) whenever(pubkyService.publicKeyFromSecret("new_ring_secret")).thenReturn(ringPubky) whenever(pubkyService.signIn("new_ring_secret")).thenReturn(Unit) - whenever(pubkyService.resolveContactProfile(newPublicKey, true)) - .thenReturn(createResolution(newPublicKey, pubkyProfile = createPubkyProfile(name = "New Profile"))) + whenever(pubkyService.fetchPubkyProfileWithRevision(newPublicKey)) + .thenReturn(createSnapshot(newPublicKey, createPubkyProfile(name = "New Profile"))) val adoption = async { sut.adoptRingIdentity(ringPubky) } assertFalse(adoption.isCompleted) @@ -2411,8 +2950,8 @@ class PubkyRepoTest : BaseUnitTest() { val ringPubky = stubRingCredential() whenever(pubkyService.signIn("ring_secret")).thenReturn(Unit) - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)) - .thenReturn(createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile())) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)) + .thenReturn(createSnapshot(VALID_SELF_KEY, createPubkyProfile())) val adoption = sut.adoptRingIdentity(ringPubky) finishListing.complete(Unit) sourceCheck.await() @@ -2475,9 +3014,9 @@ class PubkyRepoTest : BaseUnitTest() { val profileLoad = CompletableDeferred() whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenReturn("saved_session") whenever(pubkyService.importSession("saved_session")).thenReturn(VALID_SELF_KEY) - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)).doSuspendableAnswer { + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).doSuspendableAnswer { profileLoad.await() - createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile()) + createSnapshot(VALID_SELF_KEY, createPubkyProfile()) } val repo = createSut() val waiter = async { repo.awaitInitialization() } @@ -2558,8 +3097,8 @@ class PubkyRepoTest : BaseUnitTest() { whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenReturn(session) whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn(null) whenever(pubkyService.importSession(session)).thenReturn(unprefixedPublicKey) - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)) - .thenReturn(createResolution(VALID_SELF_KEY, pubkyProfile = pubkyProfile)) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)) + .thenReturn(createSnapshot(VALID_SELF_KEY, pubkyProfile)) sut.initialize() @@ -2608,13 +3147,13 @@ class PubkyRepoTest : BaseUnitTest() { } whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn("saved-secret") whenever(pubkyService.publicKeyFromSecret("saved-secret")).thenReturn(VALID_SELF_KEY) - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)) - .thenReturn(createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile(name = "Alice"))) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)) + .thenReturn(createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "Alice"))) sut = createSut() val load = launch { sut.loadProfile() } runCurrent() - verify(pubkyService, never()).resolveContactProfile(VALID_SELF_KEY, true) + verify(pubkyService, never()).fetchPubkyProfileWithRevision(VALID_SELF_KEY) importGate.complete(Unit) load.join() advanceUntilIdle() @@ -2622,7 +3161,7 @@ class PubkyRepoTest : BaseUnitTest() { assertEquals(VALID_SELF_KEY, sut.publicKey.value) assertEquals("Alice", sut.profile.value?.name) assertNull(sut.readOnlyProfile.value) - verify(pubkyService).resolveContactProfile(VALID_SELF_KEY, true) + verify(pubkyService).fetchPubkyProfileWithRevision(VALID_SELF_KEY) } @Test @@ -2633,10 +3172,10 @@ class PubkyRepoTest : BaseUnitTest() { whenever(pubkyService.publicKeyFromSecret("saved-secret")).thenReturn(VALID_SELF_KEY) val response = CompletableDeferred() var profileUnavailable = false - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)).doSuspendableAnswer { + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).doSuspendableAnswer { response.await() if (profileUnavailable) throw AppError("Profile temporarily unavailable") - createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile(name = "Alice")) + createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "Alice")) } sut.initialize() @@ -2671,8 +3210,8 @@ class PubkyRepoTest : BaseUnitTest() { fun `saved public profile uses the adopted Ring credential without authenticating`() = test { val owner = stubRingCredential() adoptedSource = "${SharedPubkyContract.RING_SOURCE_PREFIX}$owner" - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)) - .thenReturn(createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile(name = "Alice"))) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)) + .thenReturn(createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "Alice"))) sut.loadProfile() @@ -2689,9 +3228,9 @@ class PubkyRepoTest : BaseUnitTest() { whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn("saved-secret") whenever(pubkyService.publicKeyFromSecret("saved-secret")).thenReturn(VALID_SELF_KEY) val response = CompletableDeferred() - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)).doSuspendableAnswer { + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).doSuspendableAnswer { response.await() - createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile(name = "Alice")) + createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "Alice")) } sut.initialize() val load = launch { sut.loadProfile() } @@ -2723,7 +3262,7 @@ class PubkyRepoTest : BaseUnitTest() { sut.loadProfile() assertNull(sut.readOnlyProfile.value) - verify(pubkyService, never()).resolveContactProfile(VALID_SELF_KEY, true) + verify(pubkyService, never()).fetchPubkyProfileWithRevision(VALID_SELF_KEY) } @Test @@ -2918,8 +3457,8 @@ class PubkyRepoTest : BaseUnitTest() { whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenReturn(session) whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn(null) whenever(pubkyService.importSession(session)).thenReturn(unprefixedPublicKey) - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)) - .thenReturn(createResolution(VALID_SELF_KEY, pubkyProfile = pubkyProfile)) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)) + .thenReturn(createSnapshot(VALID_SELF_KEY, pubkyProfile)) whenever(pubkyService.observedContactRecords(VALID_SELF_KEY)).thenAnswer { throw TestAppError("Offline") } sut.initialize() @@ -2939,8 +3478,8 @@ class PubkyRepoTest : BaseUnitTest() { whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn(secretKey) whenever(pubkyService.signIn(secretKey)).thenReturn(Unit) whenever(pubkyService.publicKeyFromSecret(secretKey)).thenReturn(publicKey) - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)) - .thenReturn(createResolution(VALID_SELF_KEY, pubkyProfile = pubkyProfile)) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)) + .thenReturn(createSnapshot(VALID_SELF_KEY, pubkyProfile)) sut.initialize() @@ -2970,8 +3509,8 @@ class PubkyRepoTest : BaseUnitTest() { whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenReturn(session) whenever(pubkyService.importSession(session)).thenAnswer { throw TestAppError("Expired") } whenever(sharedPubkyClient.listRingIdentities()).thenReturn(Result.success(persistentListOf(ringPubky))) - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)) - .thenReturn(createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile(name = "Ring User"))) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)) + .thenReturn(createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = "Ring User"))) sut = createSut() sut.awaitInitialization() @@ -3192,9 +3731,9 @@ class PubkyRepoTest : BaseUnitTest() { val restore = stubSavedSessionRestore() restore.answer = { VALID_SELF_KEY } val finishProfile = CompletableDeferred() - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)).doSuspendableAnswer { + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).doSuspendableAnswer { finishProfile.await() - createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile()) + createSnapshot(VALID_SELF_KEY, createPubkyProfile()) } var contactsLoaded = false whenever(pubkyService.contactRecords()).thenAnswer { @@ -3224,8 +3763,8 @@ class PubkyRepoTest : BaseUnitTest() { sut.initialize() assertNull(sut.publicKey.value) restore.answer = { VALID_SELF_KEY } - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)) - .thenReturn(createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile())) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)) + .thenReturn(createSnapshot(VALID_SELF_KEY, createPubkyProfile())) val contactsRequested = CompletableDeferred() val finishContacts = CompletableDeferred>() whenever(pubkyService.contactRecords()).doSuspendableAnswer { @@ -3292,8 +3831,8 @@ class PubkyRepoTest : BaseUnitTest() { signInStarted.complete(Unit) finishSignIn.await() } - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)) - .thenReturn(createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile())) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)) + .thenReturn(createSnapshot(VALID_SELF_KEY, createPubkyProfile())) val adoption = async { sut.adoptRingIdentity(ringPubky) } signInStarted.await() @@ -3337,8 +3876,8 @@ class PubkyRepoTest : BaseUnitTest() { signInStarted.complete(Unit) finishSignIn.await() } - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)) - .thenReturn(createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile())) + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)) + .thenReturn(createSnapshot(VALID_SELF_KEY, createPubkyProfile())) val adoption = async { sut.adoptRingIdentity(ringPubky) } signInStarted.await() @@ -3396,10 +3935,10 @@ class PubkyRepoTest : BaseUnitTest() { whenever(pubkyService.importSession("saved_session")).thenReturn(VALID_SELF_KEY) val profileLoadStarted = CompletableDeferred() val finishProfileLoad = CompletableDeferred() - whenever(pubkyService.resolveContactProfile(VALID_SELF_KEY, true)).doSuspendableAnswer { + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).doSuspendableAnswer { profileLoadStarted.complete(Unit) finishProfileLoad.await() - createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile()) + createSnapshot(VALID_SELF_KEY, createPubkyProfile()) } clearInvocations(pubkyStore) val restore = async { sut.restoreSessionIfNeeded() } @@ -4887,7 +5426,7 @@ class PubkyRepoTest : BaseUnitTest() { val session = "test_session" val currentPublicKey = "pubkyalice" whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenReturn(session) - whenever(pubkyService.uploadProfileAvatar(any(), any())).thenReturn("pubky://avatar") + whenever(pubkyService.uploadPubkyAppAvatar(any(), any(), any())).thenReturn("pubky://avatar") authenticateForTesting(publicKey = currentPublicKey, secret = session, profileName = "Alice") @@ -4895,7 +5434,7 @@ class PubkyRepoTest : BaseUnitTest() { assertTrue(result.isSuccess) assertEquals("pubky://avatar", result.getOrNull()) - verifyBlocking(pubkyService) { uploadProfileAvatar(any(), any()) } + verifyBlocking(pubkyService) { uploadPubkyAppAvatar(any(), any(), any()) } } @Test @@ -4909,7 +5448,7 @@ class PubkyRepoTest : BaseUnitTest() { val result = sut.uploadAvatar(byteArrayOf(1, 2, 3)) assertTrue(result.isFailure) - verifyBlocking(pubkyService, never()) { uploadProfileAvatar(any(), any()) } + verifyBlocking(pubkyService, never()) { uploadPubkyAppAvatar(any(), any(), any()) } } @Test @@ -5018,6 +5557,8 @@ class PubkyRepoTest : BaseUnitTest() { val prefixedPublicKey = publicKey.ensurePubkyPrefixForTest() whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenReturn(secret) whenever { pubkyService.importSession(secret) }.thenReturn(publicKey) + whenever { pubkyService.fetchPubkyProfileWithRevision(prefixedPublicKey) } + .thenReturn(createSnapshot(prefixedPublicKey, createPubkyProfile(name = profileName))) whenever { pubkyService.resolveContactProfile(prefixedPublicKey, true) } .thenReturn(createResolution(prefixedPublicKey, pubkyProfile = createPubkyProfile(name = profileName))) whenever { pubkyService.contactRecords() }.thenReturn(emptyList()) @@ -5069,9 +5610,9 @@ class PubkyRepoTest : BaseUnitTest() { } private fun gateNextProfileLoadStoreWrite(store: GatedPubkyStore, loadedName: String) { - whenever { pubkyService.resolveContactProfile(VALID_SELF_KEY, true) }.doSuspendableAnswer { + whenever { pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY) }.doSuspendableAnswer { store.gateNextUpdate = true - createResolution(VALID_SELF_KEY, pubkyProfile = createPubkyProfile(name = loadedName)) + createSnapshot(VALID_SELF_KEY, createPubkyProfile(name = loadedName)) } } @@ -5122,6 +5663,14 @@ class PubkyRepoTest : BaseUnitTest() { "pubkyauth://direct_signup?hs=homeserver&st=invite", ).getOrThrow() + private fun paykitRecord(profile: PaykitProfile) = PaykitProfileRecord( + publicKey = VALID_SELF_KEY, + profile = profile, + path = "/pub/paykit/profile.json", + revision = "paykit-revision", + updatedAt = "2026-01-01T00:00:00Z", + ) + private fun createPaykitProfile( name: String, bio: String = "", @@ -5153,6 +5702,13 @@ class PubkyRepoTest : BaseUnitTest() { publicContactLastError = null, ) + private fun createSnapshot(publicKey: String, profile: SdkPubkyProfile) = PubkyProfileSnapshot( + publicKey = publicKey, + profile = profile, + revision = "revision-${profile.name}", + fetchedAt = "2026-01-01T00:00:00Z", + ) + private fun createResolution( publicKey: String, paykitProfile: PaykitProfile? = null, diff --git a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt index 3ef1927900..f879b16854 100644 --- a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt @@ -43,6 +43,7 @@ import com.synonym.paykit.PublicContactPaymentResolution import com.synonym.paykit.PublicContactSharingPolicy import com.synonym.paykit.PublicPaymentResolutionStatus import com.synonym.paykit.paykitAuthorizerSessionCapabilities +import com.synonym.paykit.pubkyAppProfileSessionCapabilities import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Deferred @@ -1937,6 +1938,7 @@ class PaykitSdkServiceTest { } mockStatic(Class.forName("com.synonym.paykit.Paykit_androidKt")).use { native -> native.`when` { paykitAuthorizerSessionCapabilities() }.thenReturn("capabilities") + native.`when` { pubkyAppProfileSessionCapabilities() }.thenReturn("profile") val restoration = async { service.initializeAndImportSession("saved-session") } val read = async { service.resolveContactProfile(RING_PUBKY, true) } runCurrent() @@ -1992,6 +1994,7 @@ class PaykitSdkServiceTest { mockStatic(Class.forName("com.synonym.paykit.Paykit_androidKt")).use { native -> native.`when` { paykitAuthorizerSessionCapabilities() }.thenReturn("capabilities") + native.`when` { pubkyAppProfileSessionCapabilities() }.thenReturn("profile") if (failure is CancellationException) { assertFailsWith { service.initializeAndImportSession("saved-session") } assertFailsWith { service.contactRecords() } @@ -2045,6 +2048,7 @@ class PaykitSdkServiceTest { mockStatic(Class.forName("com.synonym.paykit.Paykit_androidKt")).use { native -> native.`when` { paykitAuthorizerSessionCapabilities() }.thenReturn("capabilities") + native.`when` { pubkyAppProfileSessionCapabilities() }.thenReturn("profile") assertSame(failure, service.initializeAndImportSession("saved-session").exceptionOrNull()) verify(sdk, times(1)).initialize() verify(sdk, never()).publishPaykitApp(any(), any()) @@ -3420,13 +3424,13 @@ class PaykitSdkServiceTest { cleared = (if (failRecovery) listOf(other) else keys).map { PrivatePaymentListSyncChange(it, 1uL, null) }, + acknowledged = emptyList(), failedToQueue = if (failRecovery) { listOf(PrivatePaymentListSyncChange(RING_PUBKY, null, null)) } else { emptyList() }, failedToDeliver = emptyList(), - acknowledged = emptyList(), ) } val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } diff --git a/app/src/test/java/to/bitkit/services/PaykitSdkServiceWipeTest.kt b/app/src/test/java/to/bitkit/services/PaykitSdkServiceWipeTest.kt index 2d55fd108c..1267f7fcf1 100644 --- a/app/src/test/java/to/bitkit/services/PaykitSdkServiceWipeTest.kt +++ b/app/src/test/java/to/bitkit/services/PaykitSdkServiceWipeTest.kt @@ -9,6 +9,7 @@ import com.synonym.paykit.PubkySessionAccess import com.synonym.paykit.PubkySessionBootstrap import com.synonym.paykit.PubkySessionBootstrapResult import com.synonym.paykit.paykitAuthorizerSessionCapabilities +import com.synonym.paykit.pubkyAppProfileSessionCapabilities import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -206,6 +207,7 @@ class PaykitSdkServiceWipeTest { mockStatic(Class.forName("com.synonym.paykit.Paykit_androidKt")).use { native -> native.`when` { paykitAuthorizerSessionCapabilities() }.thenReturn("capabilities") + native.`when` { pubkyAppProfileSessionCapabilities() }.thenReturn("profile") val active = async(start = CoroutineStart.UNDISPATCHED) { service.importSession("active") } bootstrapStarted.await() val queued = async(start = CoroutineStart.UNDISPATCHED) { diff --git a/app/src/test/java/to/bitkit/ui/screens/contacts/ContactSaveSessionChangeTest.kt b/app/src/test/java/to/bitkit/ui/screens/contacts/ContactSaveSessionChangeTest.kt index 9645c467ea..cca371bf28 100644 --- a/app/src/test/java/to/bitkit/ui/screens/contacts/ContactSaveSessionChangeTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/contacts/ContactSaveSessionChangeTest.kt @@ -6,6 +6,7 @@ import coil3.ImageLoader import com.synonym.paykit.ContactRecord import com.synonym.paykit.ProfileResolution import com.synonym.paykit.ProfileSource +import com.synonym.paykit.PubkyProfileSnapshot import com.synonym.paykit.PublicationStatus import io.ktor.client.HttpClient import kotlinx.coroutines.CompletableDeferred @@ -302,6 +303,14 @@ class ContactSaveSessionChangeTest : BaseUnitTest() { } whenever(pubkyService.resolveContactProfile(owner, true, PaykitReadLane.Interactive, null)) .thenReturn(ownerResolution(owner)) + whenever(pubkyService.fetchPubkyProfileWithRevision(owner)).thenReturn( + PubkyProfileSnapshot( + publicKey = owner, + profile = checkNotNull(ownerResolution(owner).pubkyProfile), + revision = "revision", + fetchedAt = "2026-01-01T00:00:00Z", + ) + ) whenever(pubkyService.contactRecords()).thenReturn(records) sdkContacts[owner] = records.map { it.publicKey }.toSet() repo.initialize() diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt index f9c005d101..83107c23de 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt @@ -12,6 +12,7 @@ import kotlinx.coroutines.test.advanceUntilIdle import org.junit.Test import org.mockito.Mockito.clearInvocations import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.eq import org.mockito.kotlin.inOrder @@ -24,6 +25,7 @@ import to.bitkit.R import to.bitkit.models.PubkyProfile import to.bitkit.models.PubkyProfileLink import to.bitkit.repositories.PrivatePaykitRepo +import to.bitkit.repositories.ProfileEditBase import to.bitkit.repositories.PubkyRepo import to.bitkit.test.BaseUnitTest import to.bitkit.utils.AppError @@ -61,7 +63,7 @@ class EditProfileViewModelTest : BaseUnitTest() { advanceUntilIdle() verify(pubkyRepo, times(1)).forgetUnrestoredIdentity() verify(pubkyRepo, never()).deleteProfileWithSessionRetry() - verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), any()) + verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), anyOrNull(), any()) assertFalse(sut.uiState.value.showDeleteDialog) sut.viewModelScope.cancel() @@ -130,7 +132,7 @@ class EditProfileViewModelTest : BaseUnitTest() { sut.showDeleteConfirmation() advanceUntilIdle() verify(pubkyRepo, times(1)).deleteProfileWithSessionRetry() - verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), any()) + verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), anyOrNull(), any()) verify(pubkyRepo, never()).signOut() assertFalse(sut.uiState.value.showDeleteDialog) @@ -146,7 +148,9 @@ class EditProfileViewModelTest : BaseUnitTest() { val sut = createSut() advanceUntilIdle() val result = CompletableDeferred>() - whenever(pubkyRepo.saveProfile(any(), any(), any(), any(), any())).doSuspendableAnswer { result.await() } + whenever( + pubkyRepo.saveProfile(any(), any(), any(), any(), anyOrNull(), any()) + ).doSuspendableAnswer { result.await() } sut.save() advanceUntilIdle() @@ -160,7 +164,7 @@ class EditProfileViewModelTest : BaseUnitTest() { sut.disconnectProfile() sut.showDeleteConfirmation() advanceUntilIdle() - verify(pubkyRepo, times(1)).saveProfile(any(), any(), any(), any(), any()) + verify(pubkyRepo, times(1)).saveProfile(any(), any(), any(), any(), anyOrNull(), any()) verify(pubkyRepo, never()).deleteProfileWithSessionRetry() verify(pubkyRepo, never()).forgetUnrestoredIdentity() assertFalse(sut.uiState.value.showDeleteDialog) @@ -400,6 +404,7 @@ class EditProfileViewModelTest : BaseUnitTest() { } whenever { pubkyRepo.forgetUnrestoredIdentity() }.thenReturn(Result.success(false)) whenever(pubkyRepo.profile).thenReturn(MutableStateFlow(createProfile())) + whenever(pubkyRepo.profileEditBase()).thenReturn(ProfileEditBase(createProfile(), "revision")) whenever(pubkyRepo.publicKey).thenReturn(MutableStateFlow(TEST_PUBLIC_KEY)) whenever { privatePaykitRepo.removePublishedEndpointsForCleanup(any()) } .thenReturn(Result.success(Unit)) diff --git a/changelog.d/next/1801.added.md b/changelog.d/next/1801.added.md new file mode 100644 index 0000000000..0a48534fc2 --- /dev/null +++ b/changelog.d/next/1801.added.md @@ -0,0 +1 @@ +Bitkit now uses your pubky.app profile, so edits in Bitkit and on pubky.app show in both. diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 842f1aa85c..9f73f46188 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -22,7 +22,7 @@ appcompat = { module = "androidx.appcompat:appcompat", version = "1.7.1" } barcode-scanning = { module = "com.google.mlkit:barcode-scanning", version = "17.3.0" } biometric = { module = "androidx.biometric:biometric", version = "1.4.0-alpha05" } bitkit-core = { module = "com.synonym:bitkit-core-android", version = "0.8.0-rc11" } -paykit = { module = "com.synonym:paykit-android", version = "0.1.1-rc6" } +paykit = { module = "com.synonym:paykit-android", version = "0.1.1-rc7" } bouncycastle-pkix-jdk = { module = "org.bouncycastle:bcpkix-jdk18on", version = "1.83" } bouncycastle-provider-jdk = { module = "org.bouncycastle:bcprov-jdk18on", version = "1.83" } camera-camera2 = { module = "androidx.camera:camera-camera2", version.ref = "camera" } diff --git a/journeys/profile/README.md b/journeys/profile/README.md index a149edc490..9252188444 100644 --- a/journeys/profile/README.md +++ b/journeys/profile/README.md @@ -50,4 +50,6 @@ For controlled fault testing, interrupt deletion after private withdrawal but be `create-profile.xml` records the name-only saving interval and checks the saved name after reopening and relaunching. Use a fresh unfunded identity per run and record the exact app/SDK revisions and network. With controlled network fault injection, block direct UDP while keeping the configured HTTP relays and homeserver reachable; saving should still complete. Reject the required profile write separately and verify saving reports failure instead of navigating to Pay Contacts. Fault injection is a manual check beyond journey-runner capabilities. +`edit-pubky-app-profile.xml` checks that Edit Profile presents the profile as the public pubky.app profile and that a name edit is saved and survives a relaunch. Use an identity whose pubky.app profile you can open on pubky.app; checking the edit there, and an edit made in pubky.app while Bitkit is open, are manual checks beyond journey-runner capabilities. + On Android, the restart check waits for the full profile (`ProfileViewName`). A matching `ProfileCachedName` during loading does not complete that check. Record an unfinished load separately from a loaded profile with a missing or incorrect name. diff --git a/journeys/profile/edit-pubky-app-profile.xml b/journeys/profile/edit-pubky-app-profile.xml new file mode 100644 index 0000000000..ee1913eba2 --- /dev/null +++ b/journeys/profile/edit-pubky-app-profile.xml @@ -0,0 +1,18 @@ + + + Precondition: a disposable wallet signed in to a Pubky profile, PIN off and an English device. + This checks that Edit Profile presents the profile as the user's public pubky.app profile and + that a name change is saved and shown again after a relaunch. Whether the change also reached + pubky.app is checked outside the app, under the PR's manual tests. + + + Open Profile using "ProfileButton" and wait for "ProfileViewName" + Tap "ProfileEdit" and wait for "ProfileEditName" + Verify the footer note says this is your pubky.app profile and that it is public + Replace the name with "Edited In Bitkit" and dismiss the keyboard + Tap "ProfileEditSave" and wait for "ProfileUpdatedToast" + Verify "ProfileViewName" shows "Edited In Bitkit" + Relaunch the app, open Profile using "ProfileButton" and wait for the full profile name (id "ProfileViewName", predicate exists) + Verify "ProfileViewName" shows "Edited In Bitkit" + + From 40fd247fdd09722ec4574741c2d2f08f5f6630bd Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 17:14:55 +0100 Subject: [PATCH 04/11] Merge pull request #1865 from synonymdev/fix/profile-save-one-write fix: save the profile without waiting for an unchanged copy (cherry picked from commit 831c4d2a669a5b2b1a8f160dfda2c785bd91fafe) --- .../java/to/bitkit/repositories/PubkyRepo.kt | 38 +++++- .../to/bitkit/repositories/PubkyRepoTest.kt | 113 ++++++++++++++++++ 2 files changed, 148 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index 725f8307c4..a0bafa39db 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -236,6 +236,10 @@ class PubkyRepo @Inject constructor( private val profileSaveEpoch = AtomicLong(0L) private val profileSavesRunning = AtomicInteger(0) + // Orders each save's Paykit copy write after the one an earlier save left running. + private val copyWriteOrder = Mutex() + private var pendingCopyWrite: Job? = null + /** Revision of the loaded pubky.app profile, which a save must still match; null when none exists. */ @Volatile private var ownProfileRevision: String? = null @@ -244,6 +248,9 @@ class PubkyRepo @Inject constructor( @Volatile private var tagsUnavailable = false + // Moved on each time a load sets tagsUnavailable, so a save clears it only if no load set it since the save began. + private val tagsReadEpoch = AtomicLong(0L) + @Volatile private var restoreBase: RestoreBase? = null private val signInGeneration = AtomicLong(0L) @@ -939,6 +946,7 @@ class PubkyRepo @Inject constructor( restoreBase = RestoreBase(prefixedKey, it, revision = null) } } + tagsReadEpoch.incrementAndGet() tagsUnavailable = paykitRead.isFailure PubkyProfile.fromPubkyProfile(prefixedKey, snapshot.profile).copy(tags = paykitData?.tags.orEmpty()).also { restoreBase = RestoreBase(prefixedKey, it, snapshot.revision) @@ -1277,6 +1285,7 @@ class PubkyRepo @Inject constructor( tagsUnread: Boolean, ): SavedProfile { val generation = profileDeletionGeneration.get() + val readEpoch = tagsReadEpoch.get() // Unread when the edit began or now: either way the form's tags are not the stored ones. val copyUnread = tagsUnread || tagsUnavailable // A profile written without a base is fitted to pubky.app's limits, as a move is. @@ -1330,11 +1339,24 @@ class PubkyRepo @Inject constructor( } // Tags live only in the Paykit copy, so a changed tag that it does not take is reported. val copyData = profile.toProfileData().toPaykitProfile() - val copyError = keptTags?.let { + val writeCopy = suspend { runSuspendCatching { profileWrite(generation) { pubkyService.publishPaykitProfile(copyData, publicKey) } } - .onSuccess { tagsUnavailable = false } .onFailure { Logger.warn("Failed to update Bitkit profile copy", it, context = TAG) } - .exceptionOrNull() + } + val copyError = keptTags?.let { + copyWriteOrder.withLock { + // A copy write left running by an earlier save lands first, so it never overwrites this one. + pendingCopyWrite?.join() + if (it == baseTags) { + // With no tag change to report, the save does not wait for the copy; a deletion refuses or waits + // for it. Its outcome leaves the unread flag alone, which a load may have set since. + pendingCopyWrite = scope.launch { writeCopy() } + markTagsRead(stored, readEpoch) + null + } else { + writeCopy().onSuccess { tagsUnavailable = false }.exceptionOrNull() + } + } } val saved = if (keptTags != null && copyError == null) profile else profile.copy(tags = baseTags) val tagsLost = (keptTags == null || copyError != null) && tags != baseTags @@ -1356,6 +1378,15 @@ class PubkyRepo @Inject constructor( return StoredCopy(tags = data?.tags.orEmpty(), image = data?.image) } + /** + * Clears the unread flag after a save read the copy itself and kept its tags in the profile it stores, unless a + * load found the copy unreadable since [readEpoch]. A save that writes the copy at once clears it only once that + * write succeeds, since a failed one stores the profile without the copy's tags. + */ + private fun markTagsRead(stored: StoredCopy?, readEpoch: Long) { + if (stored?.tags != null && tagsReadEpoch.get() == readEpoch) tagsUnavailable = false + } + /** [name], [bio] and [links] fitted to pubky.app's limits: one line, cut to length, at most five valid links. */ private fun fitted(name: String, bio: String, links: List) = FittedProfile( name = name.singleLine().takeCodePoints(PUBKY_APP_NAME_MAX_LENGTH), @@ -1374,6 +1405,7 @@ class PubkyRepo @Inject constructor( val saveEpoch = profileSaveEpoch.get() val paykitRead = runSuspendCatching { pubkyService.fetchPaykitProfile(publicKey) } .onFailure { Logger.warn("Failed to read Bitkit profile copy", it, context = TAG) } + tagsReadEpoch.incrementAndGet() tagsUnavailable = paykitRead.isFailure val paykitData = paykitRead.getOrNull()?.let { PubkyProfileData.fromPaykitProfile(it.profile) } val fetched = readRetryingOnce(publicKey) { pubkyService.fetchPubkyProfileWithRevision(publicKey) } diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index 81352e2b05..9e5d9701a4 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -954,6 +954,77 @@ class PubkyRepoTest : BaseUnitTest() { assertEquals("New", sut.profile.value?.name) } + @Test + fun `saveProfile without a tag change does not wait for the profile copy`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + val finishCopy = CompletableDeferred() + whenever { pubkyService.publishPaykitProfile(any(), any()) }.doSuspendableAnswer { + finishCopy.await() + paykitRecord(it.getArgument(0)) + } + clearInvocations(pubkyService) + + val save = async { + sut.saveProfile(name = "Renamed", bio = "", links = emptyList(), tags = emptyList(), imageUrl = null) + } + runCurrent() + + assertTrue(save.isCompleted) + save.await().getOrThrow() + verifyBlocking(pubkyService) { publishPaykitProfile(any(), any()) } + finishCopy.complete(Unit) + } + + @Test + fun `a background copy write keeps a later load's unread tags`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + val finishCopy = CompletableDeferred() + whenever { pubkyService.publishPaykitProfile(any(), any()) }.doSuspendableAnswer { + finishCopy.await() + paykitRecord(it.getArgument(0)) + } + sut.saveProfile(name = "Renamed", bio = "", links = emptyList(), tags = emptyList(), imageUrl = null) + .getOrThrow() + runCurrent() + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenAnswer { throw TestAppError("offline") } + sut.loadProfile() + + finishCopy.complete(Unit) + runCurrent() + + assertTrue(sut.profileEditBase().tagsUnread) + } + + @Test + fun `a save that reads the copy itself lets the next edit remove a tag`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + var copy = PubkyProfileData(name = "Test", bio = "", tags = listOf("a", "b")).toPaykitProfile() + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenAnswer { paykitRecord(copy) } + whenever(pubkyService.publishPaykitProfile(any(), any())).thenAnswer { + copy = it.getArgument(0) + paykitRecord(copy) + } + sut.loadProfile() + val editBase = sut.profileEditBase() + doAnswer { throw TestAppError("offline") }.whenever(pubkyService).fetchPaykitProfile(VALID_SELF_KEY) + sut.loadProfile() + doAnswer { paykitRecord(copy) }.whenever(pubkyService).fetchPaykitProfile(VALID_SELF_KEY) + + sut.saveProfile( + name = "Test", + bio = "", + links = emptyList(), + tags = listOf("a"), + imageUrl = null, + editBase = editBase + ).getOrThrow() + runCurrent() + sut.saveProfile(name = "Test", bio = "", links = emptyList(), tags = listOf("a"), imageUrl = null).getOrThrow() + runCurrent() + + assertEquals(listOf("a"), PubkyProfileData.fromPaykitProfile(copy).tags) + } + @Test fun `saveProfile signs in again once when the session lacks the pubky app scope`() = test { val secretKey = "local_secret" @@ -1208,6 +1279,48 @@ class PubkyRepoTest : BaseUnitTest() { assertEquals(listOf("friend", "work", "vip"), PubkyProfileData.fromPaykitProfile(copy.lastValue).tags) } + @Test + fun `a tag save after a failed read and write keeps the stored tags without the error's base`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenAnswer { throw TestAppError("offline") } + sut.loadProfile() + doReturn( + paykitRecord(PubkyProfileData(name = "Test", bio = "", tags = listOf("friend", "work")).toPaykitProfile()) + ) + .whenever(pubkyService).fetchPaykitProfile(VALID_SELF_KEY) + whenever(pubkyService.publishPaykitProfile(any(), any())) + .thenAnswer { throw TestAppError("offline") } + .thenAnswer { paykitRecord(it.getArgument(0)) } + + sut.saveProfile(name = "Test", bio = "", links = emptyList(), tags = listOf("vip"), imageUrl = null) + sut.saveProfile(name = "Test", bio = "", links = emptyList(), tags = listOf("vip"), imageUrl = null) + + val copy = argumentCaptor() + verifyBlocking(pubkyService, times(2)) { publishPaykitProfile(copy.capture(), any()) } + assertEquals(listOf("friend", "work", "vip"), PubkyProfileData.fromPaykitProfile(copy.lastValue).tags) + } + + @Test + fun `a name save after a failed read and write keeps the stored tags`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenAnswer { throw TestAppError("offline") } + sut.loadProfile() + doReturn( + paykitRecord(PubkyProfileData(name = "Test", bio = "", tags = listOf("friend", "work")).toPaykitProfile()) + ) + .whenever(pubkyService).fetchPaykitProfile(VALID_SELF_KEY) + whenever(pubkyService.publishPaykitProfile(any(), any())) + .thenAnswer { throw TestAppError("offline") } + .thenAnswer { paykitRecord(it.getArgument(0)) } + + sut.saveProfile(name = "Renamed", bio = "", links = emptyList(), tags = emptyList(), imageUrl = null) + sut.saveProfile(name = "Renamed Again", bio = "", links = emptyList(), tags = emptyList(), imageUrl = null) + + val copy = argumentCaptor() + verifyBlocking(pubkyService, times(2)) { publishPaykitProfile(copy.capture(), any()) } + assertEquals(listOf("friend", "work"), PubkyProfileData.fromPaykitProfile(copy.lastValue).tags) + } + @Test fun `saveProfile keeps the stored tags when the edit began while they could not be read`() = test { authenticateForTesting(publicKey = VALID_SELF_KEY) From b079e7e05db8c343f972a63fe75baa6d6480a6e0 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 19:28:11 +0100 Subject: [PATCH 05/11] Merge pull request #1824 from synonymdev/chore/bump-ldk-node-vss chore: bump ldk-node and vss client (cherry picked from commit 7d579661273c2b0aa5334f2b985b15527561054d) --- gradle/libs.versions.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 9f73f46188..bf4a43a360 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -66,7 +66,7 @@ ktor-client-logging = { module = "io.ktor:ktor-client-logging", version.ref = "k ktor-client-mock = { module = "io.ktor:ktor-client-mock", version.ref = "ktor" } ktor-client-okhttp = { module = "io.ktor:ktor-client-okhttp", version.ref = "ktor" } ktor-serialization-kotlinx-json = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" } -ldk-node-android = { module = "com.synonym:ldk-node-android", version = "0.7.0-rc.78" } +ldk-node-android = { module = "com.synonym:ldk-node-android", version = "0.7.0-rc.79" } lifecycle-process = { group = "androidx.lifecycle", name = "lifecycle-process", version.ref = "lifecycle" } lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycle" } lifecycle-runtime-ktx = { module = "androidx.lifecycle:lifecycle-runtime-ktx", version.ref = "lifecycle" } @@ -92,7 +92,7 @@ test-junit-ext = { module = "androidx.test.ext:junit", version = "1.3.0" } test-mockito-kotlin = { module = "org.mockito.kotlin:mockito-kotlin", version = "6.2.2" } test-robolectric = { module = "org.robolectric:robolectric", version = "4.16.1" } test-turbine = { group = "app.cash.turbine", name = "turbine", version = "1.2.1" } -vss-client = { module = "com.synonym:vss-client-android", version = "0.5.26-rc1" } +vss-client = { module = "com.synonym:vss-client-android", version = "0.5.26-rc2" } webkit = { module = "androidx.webkit:webkit", version = "1.16.0" } work-runtime-ktx = { module = "androidx.work:work-runtime-ktx", version = "2.11.0" } zxing = { module = "com.google.zxing:core", version = "3.5.4" } From 1b5800642af3c100b3a3247304355d6bbe892658 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 19:23:49 +0100 Subject: [PATCH 06/11] Merge pull request #1872 from synonymdev/chore/bump-ldk-node-rc80 chore: bump ldk-node to 0.7.0-rc.80 (cherry picked from commit 428ed54a91e53cc1c57b9ef2c59f6b9be4c51bba) --- changelog.d/next/1870.security.md | 1 + gradle/libs.versions.toml | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) create mode 100644 changelog.d/next/1870.security.md diff --git a/changelog.d/next/1870.security.md b/changelog.d/next/1870.security.md new file mode 100644 index 0000000000..53f44a5b92 --- /dev/null +++ b/changelog.d/next/1870.security.md @@ -0,0 +1 @@ +Updated the Lightning node with upstream security fixes. diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index bf4a43a360..116b40f121 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -66,7 +66,7 @@ ktor-client-logging = { module = "io.ktor:ktor-client-logging", version.ref = "k ktor-client-mock = { module = "io.ktor:ktor-client-mock", version.ref = "ktor" } ktor-client-okhttp = { module = "io.ktor:ktor-client-okhttp", version.ref = "ktor" } ktor-serialization-kotlinx-json = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" } -ldk-node-android = { module = "com.synonym:ldk-node-android", version = "0.7.0-rc.79" } +ldk-node-android = { module = "com.synonym:ldk-node-android", version = "0.7.0-rc.80" } lifecycle-process = { group = "androidx.lifecycle", name = "lifecycle-process", version.ref = "lifecycle" } lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycle" } lifecycle-runtime-ktx = { module = "androidx.lifecycle:lifecycle-runtime-ktx", version.ref = "lifecycle" } From ff9c74c82c5502d28314a1c80f43a79255e3419e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 19:14:03 +0100 Subject: [PATCH 07/11] Merge pull request #1873 from synonymdev/chore/paykit-rc8 chore: bump paykit to 0.1.1-rc8 (cherry picked from commit 8e86d30d3da04e0a4dd72a5343fb4299c8841bc2) --- gradle/libs.versions.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 116b40f121..de74e1b522 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -22,7 +22,7 @@ appcompat = { module = "androidx.appcompat:appcompat", version = "1.7.1" } barcode-scanning = { module = "com.google.mlkit:barcode-scanning", version = "17.3.0" } biometric = { module = "androidx.biometric:biometric", version = "1.4.0-alpha05" } bitkit-core = { module = "com.synonym:bitkit-core-android", version = "0.8.0-rc11" } -paykit = { module = "com.synonym:paykit-android", version = "0.1.1-rc7" } +paykit = { module = "com.synonym:paykit-android", version = "0.1.1-rc8" } bouncycastle-pkix-jdk = { module = "org.bouncycastle:bcpkix-jdk18on", version = "1.83" } bouncycastle-provider-jdk = { module = "org.bouncycastle:bcprov-jdk18on", version = "1.83" } camera-camera2 = { module = "androidx.camera:camera-camera2", version.ref = "camera" } From ce4d5cb25704d19d42860380251b57a0b7e6caff Mon Sep 17 00:00:00 2001 From: Piotr Stachyra Date: Thu, 12 Nov 2026 08:13:30 +0100 Subject: [PATCH 08/11] chore: version 3.1.1 --- CHANGELOG.md | 19 ++++++++++++++++++- app/build.gradle.kts | 4 ++-- changelog.d/next/1798.fixed.md | 1 - changelog.d/next/1801.added.md | 1 - changelog.d/next/1803.fixed.md | 1 - changelog.d/next/1870.security.md | 1 - 6 files changed, 20 insertions(+), 7 deletions(-) delete mode 100644 changelog.d/next/1798.fixed.md delete mode 100644 changelog.d/next/1801.added.md delete mode 100644 changelog.d/next/1803.fixed.md delete mode 100644 changelog.d/next/1870.security.md diff --git a/CHANGELOG.md b/CHANGELOG.md index a858f0dd15..361890de7b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [3.1.1] - 2026-11-12 + +### Added +- Bitkit now uses your pubky.app profile, so edits in Bitkit and on pubky.app show in both. #1801 + +### Fixed +- Fixed an occasional app freeze on launch while Pubky contacts start up. #1798 +- Paykit payment requests now check that a payment proof fits before paying, explain notes that are too long and refused signup codes, and no longer count a USDT transfer sent before its request as payment. #1803 + +### Security +- Updated the Lightning node with upstream security fixes. #1870 + + + + + ## [3.1.0] - 2026-11-02 ### Added @@ -431,7 +447,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - About screen (content merged into Support) #857 - Standalone General, Security, and Advanced settings screens (merged into tabs) #857 -[Unreleased]: https://github.com/synonymdev/bitkit-android/compare/v3.1.0...HEAD +[Unreleased]: https://github.com/synonymdev/bitkit-android/compare/v3.1.1...HEAD +[3.1.1]: https://github.com/synonymdev/bitkit-android/compare/v3.1.0...v3.1.1 [3.1.0]: https://github.com/synonymdev/bitkit-android/compare/v3.0.1...v3.1.0 [3.0.1]: https://github.com/synonymdev/bitkit-android/compare/v3.0.0..v3.0.1 [3.0.0]: https://github.com/synonymdev/bitkit-android/compare/v2.5.1..v3.0.0 diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 6c55b7270a..2159c5da91 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -186,8 +186,8 @@ android { applicationId = "to.bitkit" minSdk = 28 targetSdk = 36 - versionCode = 196 - versionName = "3.1.0" + versionCode = 197 + versionName = "3.1.1" testInstrumentationRunner = "to.bitkit.test.HiltTestRunner" bitkitAndroidTestAnnotation?.let { testInstrumentationRunnerArguments["annotation"] = it diff --git a/changelog.d/next/1798.fixed.md b/changelog.d/next/1798.fixed.md deleted file mode 100644 index 6f2612265b..0000000000 --- a/changelog.d/next/1798.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Fixed an occasional app freeze on launch while Pubky contacts start up. diff --git a/changelog.d/next/1801.added.md b/changelog.d/next/1801.added.md deleted file mode 100644 index 0a48534fc2..0000000000 --- a/changelog.d/next/1801.added.md +++ /dev/null @@ -1 +0,0 @@ -Bitkit now uses your pubky.app profile, so edits in Bitkit and on pubky.app show in both. diff --git a/changelog.d/next/1803.fixed.md b/changelog.d/next/1803.fixed.md deleted file mode 100644 index 23eb778524..0000000000 --- a/changelog.d/next/1803.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Paykit payment requests now check that a payment proof fits before paying, explain notes that are too long and refused signup codes, and no longer count a USDT transfer sent before its request as payment. diff --git a/changelog.d/next/1870.security.md b/changelog.d/next/1870.security.md deleted file mode 100644 index 53f44a5b92..0000000000 --- a/changelog.d/next/1870.security.md +++ /dev/null @@ -1 +0,0 @@ -Updated the Lightning node with upstream security fixes. From 47d05d80833d298265576cc4230cec6ca2db4bc6 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 21:17:47 +0100 Subject: [PATCH 09/11] Merge pull request #1820 from mdozhdev/ci/blocktank-regtest-auth ci: pass Blocktank regtest auth to E2E jobs (cherry picked from commit 176430965fe1e27ca572a9c4fe5d48c339f8b1e9) --- .github/workflows/e2e-staging.yml | 3 +++ .github/workflows/e2e_migration.yml | 1 + 2 files changed, 4 insertions(+) diff --git a/.github/workflows/e2e-staging.yml b/.github/workflows/e2e-staging.yml index 8074bee499..5ba76e7595 100644 --- a/.github/workflows/e2e-staging.yml +++ b/.github/workflows/e2e-staging.yml @@ -186,6 +186,7 @@ jobs: script: cd bitkit-e2e-tests && ./ci_run_android.sh --mochaOpts.grep "${{ matrix.shard.grep }}" env: BACKEND: regtest + BLOCKTANK_REGTEST_AUTH: ${{ secrets.BLOCKTANK_REGTEST_AUTH }} RECORD_VIDEO: true ATTEMPT: 1 @@ -204,6 +205,7 @@ jobs: script: cd bitkit-e2e-tests && ./ci_run_android.sh --mochaOpts.grep "${{ matrix.shard.grep }}" env: BACKEND: regtest + BLOCKTANK_REGTEST_AUTH: ${{ secrets.BLOCKTANK_REGTEST_AUTH }} RECORD_VIDEO: true ATTEMPT: 2 @@ -221,6 +223,7 @@ jobs: script: cd bitkit-e2e-tests && ./ci_run_android.sh --mochaOpts.grep "${{ matrix.shard.grep }}" env: BACKEND: regtest + BLOCKTANK_REGTEST_AUTH: ${{ secrets.BLOCKTANK_REGTEST_AUTH }} RECORD_VIDEO: true ATTEMPT: 3 diff --git a/.github/workflows/e2e_migration.yml b/.github/workflows/e2e_migration.yml index 8525b0e33a..6663a06a3d 100644 --- a/.github/workflows/e2e_migration.yml +++ b/.github/workflows/e2e_migration.yml @@ -131,6 +131,7 @@ jobs: name: android - ${{ matrix.scenario.version }} - ${{ matrix.scenario.name }} env: BACKEND: regtest + BLOCKTANK_REGTEST_AUTH: ${{ secrets.BLOCKTANK_REGTEST_AUTH }} MIGRATION_EXTENDED: ${{ inputs.extended_rn || false }} steps: From 9eb6a88962ed1c60b05b93db13f78ce3946ff6c7 Mon Sep 17 00:00:00 2001 From: Piotr Stachyra Date: Thu, 12 Nov 2026 11:17:24 +0100 Subject: [PATCH 10/11] fix: preserve tags when restoring a profile --- .../java/to/bitkit/repositories/PubkyRepo.kt | 15 +++++++++--- .../to/bitkit/repositories/PubkyRepoTest.kt | 23 +++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index a0bafa39db..30926869fc 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -137,7 +137,12 @@ private class StoredCopy(val tags: List?, val image: String?) private class FittedProfile(val name: String, val bio: String, val links: List) -private class RestoreBase(val publicKey: String, val profile: PubkyProfile, val revision: String?) +private class RestoreBase( + val publicKey: String, + val profile: PubkyProfile, + val revision: String?, + val tagsUnread: Boolean = false, +) /** Whether a Pubky identity is ready to use once restores already under way have finished. */ enum class PubkyIdentityReadiness { @@ -949,7 +954,7 @@ class PubkyRepo @Inject constructor( tagsReadEpoch.incrementAndGet() tagsUnavailable = paykitRead.isFailure PubkyProfile.fromPubkyProfile(prefixedKey, snapshot.profile).copy(tags = paykitData?.tags.orEmpty()).also { - restoreBase = RestoreBase(prefixedKey, it, snapshot.revision) + restoreBase = RestoreBase(prefixedKey, it, snapshot.revision, tagsUnread = paykitRead.isFailure) } } } @@ -1062,7 +1067,11 @@ class PubkyRepo @Inject constructor( val imageUrl = avatarBytes?.let { uploadAvatar(it, publicKey).getOrNull() } ?: restore?.profile?.imageUrl val base = restore?.profile?.takeIf { restore.revision != null } val saved = runSuspendCatching { - writeProfile(publicKey, name, bio, links, tags, imageUrl, base, expectedRevision = restore?.revision) + writeProfile( + publicKey, name, bio, links, tags, imageUrl, base, + expectedRevision = restore?.revision, + tagsUnread = restore?.tagsUnread == true, + ) }.getOrElse { if (!it.isConcurrentUpdate()) throw it throw PubkyProfileChangedError(it) diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index 9e5d9701a4..036d756ce6 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -1128,6 +1128,29 @@ class PubkyRepoTest : BaseUnitTest() { } } + @Test + fun `createIdentity keeps stored tags when the restore form could not read them`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenAnswer { throw TestAppError("offline") } + val restored = checkNotNull(sut.fetchRemoteProfile(VALID_SELF_KEY).getOrThrow()) + assertTrue(restored.tags.isEmpty()) + + val storedTags = listOf("friend", "work") + doReturn( + paykitRecord(PubkyProfileData(name = "Test", bio = "", tags = storedTags).toPaykitProfile()) + ).whenever(pubkyService).fetchPaykitProfile(VALID_SELF_KEY) + whenever(pubkyService.publishPaykitProfile(any(), any())).thenAnswer { paykitRecord(it.getArgument(0)) } + sut.loadProfile() + clearInvocations(pubkyService) + + sut.createIdentity("Renamed", restored.bio, restored.links, restored.tags, null).getOrThrow() + + assertEquals(storedTags, sut.profile.value?.tags) + val copy = argumentCaptor() + verifyBlocking(pubkyService) { publishPaykitProfile(copy.capture(), any()) } + assertEquals(storedTags, PubkyProfileData.fromPaykitProfile(copy.firstValue).tags) + } + @Test fun `saveProfile reports a tag change it could not store while the tags cannot be read`() = test { authenticateForTesting(publicKey = VALID_SELF_KEY) From 0f23fc253a0cb6cd69b6d673f25d2ade7f34c8bc Mon Sep 17 00:00:00 2001 From: Piotr Stachyra Date: Thu, 12 Nov 2026 12:55:22 +0100 Subject: [PATCH 11/11] fix: preserve profile tags through refresh and setup --- CHANGELOG.md | 5 +- .../java/to/bitkit/repositories/PubkyRepo.kt | 169 +++++++++++------- .../screens/profile/CreateProfileViewModel.kt | 11 +- .../ui/screens/profile/ProfileViewModel.kt | 4 +- .../to/bitkit/repositories/PubkyRepoTest.kt | 115 ++++++++++++ .../profile/CreateProfileViewModelTest.kt | 25 +++ .../screens/profile/ProfileViewModelTest.kt | 24 +-- 7 files changed, 273 insertions(+), 80 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 361890de7b..bdceef387a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,10 +18,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Security - Updated the Lightning node with upstream security fixes. #1870 - - - - +- Updated the VSS client and Paykit with upstream rustls security fixes. #1824, #1873 ## [3.1.0] - 2026-11-02 diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index 30926869fc..7b1c40e048 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -131,7 +131,15 @@ class PubkyProfileTagsNotSavedError(val base: ProfileEditBase, cause: Throwable? private class PubkyProfileNotFoundError : AppError("Profile not found") -private class SavedProfile(val profile: PubkyProfile, val revision: String, val tagError: Throwable?) +private class LoadedProfile(val profile: PubkyProfile, val revision: String?, val tagsUnread: Boolean) + +private class SavedProfile( + val profile: PubkyProfile, + val revision: String, + val tagsUnread: Boolean?, + val tagsReadEpoch: Long?, + val tagError: Throwable?, +) private class StoredCopy(val tags: List?, val image: String?) @@ -230,6 +238,7 @@ class PubkyRepo @Inject constructor( private val adoptedSourceCheckMutex = Mutex() private val adoptionMutex = Mutex() private val profileWriteGeneration = AtomicLong(0L) + private val profileStateLock = Any() // Held by each own-profile write and by profile deletion, so a deletion waits for the writes under way. The // deletion moves the generation on, so a load or save that started before or during it writes nothing after. @@ -249,7 +258,7 @@ class PubkyRepo @Inject constructor( @Volatile private var ownProfileRevision: String? = null - /** Whether the last profile load could not read the Paykit copy, so the shown tags are not the stored ones. */ + /** Whether the shown tags may omit tags from the Paykit copy. */ @Volatile private var tagsUnavailable = false @@ -878,26 +887,34 @@ class PubkyRepo @Inject constructor( withContext(ioDispatcher) { loadOwnProfile(signIn.publicKey) ?: throw PubkyProfileNotFoundError() } - }.onSuccess { (loadedProfile, revision) -> - var isCurrent = false - _profile.update { - isCurrent = isCurrentLoad() - if (isCurrent) loadedProfile else it + }.onSuccess { loaded -> + val installed = synchronized(profileStateLock) { + if (!isCurrentLoad()) return@synchronized false + ownProfileRevision = loaded.revision + tagsReadEpoch.incrementAndGet() + tagsUnavailable = loaded.tagsUnread + _profile.value = loaded.profile + true } - if (!isCurrent) { + if (!installed) { Logger.debug("Skipped stale profile load for '${redacted(signIn.publicKey)}'", context = TAG) return@onSuccess } - ownProfileRevision = revision invalidateReadOnlyProfile() - cacheMetadata(loadedProfile, isCurrentLoad) + cacheMetadata(loaded.profile, isCurrentLoad) }.onFailure { Logger.error("Failed to load profile", it, context = TAG) // A profile deleted on pubky.app is set up again rather than left unreachable. - if (it is PubkyProfileNotFoundError && isCurrentLoad()) { - _profile.update { null } - ownProfileRevision = null - settingsStore.setPubkyProfileSetupPending(true) + if (it is PubkyProfileNotFoundError) { + val cleared = synchronized(profileStateLock) { + if (!isCurrentLoad()) return@synchronized false + ownProfileRevision = null + tagsUnavailable = false + tagsReadEpoch.incrementAndGet() + _profile.value = null + true + } + if (cleared) settingsStore.setPubkyProfileSetupPending(true) } } completedProfileSignInGeneration = signIn.generation @@ -951,8 +968,6 @@ class PubkyRepo @Inject constructor( restoreBase = RestoreBase(prefixedKey, it, revision = null) } } - tagsReadEpoch.incrementAndGet() - tagsUnavailable = paykitRead.isFailure PubkyProfile.fromPubkyProfile(prefixedKey, snapshot.profile).copy(tags = paykitData?.tags.orEmpty()).also { restoreBase = RestoreBase(prefixedKey, it, snapshot.revision, tagsUnread = paykitRead.isFailure) } @@ -996,7 +1011,7 @@ class PubkyRepo @Inject constructor( withContext(ioDispatcher) { val publicKey = requireNotNull(_publicKey.value) { "No active Pubky session" } val saved = publishIdentityProfile(publicKey, name, bio, links, tags, avatarBytes) - finishIdentityCreation(publicKey, saved) + finishIdentityCreation(publicKey, saved) to saved.tagError } } } @@ -1011,7 +1026,7 @@ class PubkyRepo @Inject constructor( val saved = publishIdentityProfile(publicKeyZ32, name, bio, links, tags, avatarBytes) shouldRevokeSessionOnFailure = false - finishIdentityCreation(publicKeyZ32, saved) + finishIdentityCreation(publicKeyZ32, saved) to saved.tagError } } if (creationResult.isFailure) revokeIncompleteIdentitySessionIfNeeded(shouldRevokeSessionOnFailure) @@ -1022,14 +1037,14 @@ class PubkyRepo @Inject constructor( } } - val publicKey = result.getOrElse { return Result.failure(it) } + val (publicKey, tagError) = result.getOrElse { return Result.failure(it) } val signIn = currentSignIn()?.takeIf { it.publicKey == publicKey } if (signIn != null) { scope.launch { if (isCurrent(signIn)) loadContacts() } } - return Result.success(Unit) + return tagError?.let { Result.failure(it) } ?: Result.success(Unit) } private suspend fun createLocalIdentitySession(markSessionCreated: () -> Unit): String { @@ -1077,15 +1092,13 @@ class PubkyRepo @Inject constructor( throw PubkyProfileChangedError(it) } restoreBase = null - saved.tagError?.let { Logger.warn("Created profile without its tag change", it, context = TAG) } return saved } private suspend fun finishIdentityCreation(publicKey: String, saved: SavedProfile): String { val createdProfile = saved.profile startSignIn(publicKey) - ownProfileRevision = saved.revision - setProfile(createdProfile) + installSavedProfile(saved) cacheMetadata(createdProfile) settingsStore.setPubkyProfileSetupPending(false) notifyBackupStateChanged() @@ -1133,7 +1146,9 @@ class PubkyRepo @Inject constructor( } /** The profile and pubky.app revision an edit starts from; its save is checked against that revision. */ - fun profileEditBase() = ProfileEditBase(_profile.value, ownProfileRevision, tagsUnavailable) + fun profileEditBase() = synchronized(profileStateLock) { + ProfileEditBase(_profile.value, ownProfileRevision, tagsUnavailable) + } suspend fun saveProfile( name: String, @@ -1176,9 +1191,7 @@ class PubkyRepo @Inject constructor( throw PubkyProfileChangedError(it) } // A session change while the save ran leaves the new session's profile alone. - if (!isCurrent(signIn)) return@withContext - setProfile(saved.profile) - ownProfileRevision = saved.revision + if (!installSavedProfile(saved, signIn)) return@withContext cacheMetadata(saved.profile) notifyBackupStateChanged() saved.tagError?.let { throw it } @@ -1348,32 +1361,51 @@ class PubkyRepo @Inject constructor( } // Tags live only in the Paykit copy, so a changed tag that it does not take is reported. val copyData = profile.toProfileData().toPaykitProfile() - val writeCopy = suspend { + val copyError = writeProfileCopy(keptTags, baseTags) { runSuspendCatching { profileWrite(generation) { pubkyService.publishPaykitProfile(copyData, publicKey) } } .onFailure { Logger.warn("Failed to update Bitkit profile copy", it, context = TAG) } + .exceptionOrNull() } - val copyError = keptTags?.let { - copyWriteOrder.withLock { - // A copy write left running by an earlier save lands first, so it never overwrites this one. - pendingCopyWrite?.join() - if (it == baseTags) { - // With no tag change to report, the save does not wait for the copy; a deletion refuses or waits - // for it. Its outcome leaves the unread flag alone, which a load may have set since. - pendingCopyWrite = scope.launch { writeCopy() } - markTagsRead(stored, readEpoch) - null - } else { - writeCopy().onSuccess { tagsUnavailable = false }.exceptionOrNull() - } - } - } - val saved = if (keptTags != null && copyError == null) profile else profile.copy(tags = baseTags) - val tagsLost = (keptTags == null || copyError != null) && tags != baseTags + val copySaved = keptTags != null && copyError == null + val saved = if (copySaved) profile else profile.copy(tags = baseTags) + val wroteTags = copySaved && keptTags != baseTags + val tagsUnreadAfterSave = unreadTagsAfterCopy(copyUnread, copySaved, stored?.tags != null, wroteTags) val tagError = PubkyProfileTagsNotSavedError( ProfileEditBase(saved, snapshot.revision, tagsUnread = copyUnread), copyError - ).takeIf { tagsLost } - return SavedProfile(saved, snapshot.revision, tagError) + ).takeIf { !copySaved && tags != baseTags } + return SavedProfile(saved, snapshot.revision, tagsUnreadAfterSave, readEpoch.takeUnless { wroteTags }, tagError) + } + + private fun unreadTagsAfterCopy( + copyUnread: Boolean, + copySaved: Boolean, + readTags: Boolean, + wroteTags: Boolean, + ): Boolean? = when { + !copySaved -> true.takeIf { copyUnread } + readTags || wroteTags -> false + else -> null + } + + private suspend fun writeProfileCopy( + tags: List?, + baseTags: List, + writeCopy: suspend () -> Throwable?, + ): Throwable? { + if (tags == null) return null + return copyWriteOrder.withLock { + // A copy write left running by an earlier save lands first, so it never overwrites this one. + pendingCopyWrite?.join() + if (tags == baseTags) { + // With no tag change to report, the save does not wait for the copy; a deletion refuses or waits + // for it. Its outcome leaves the unread flag alone, which a load may have set since. + pendingCopyWrite = scope.launch { writeCopy() } + null + } else { + writeCopy() + } + } } /** @@ -1387,15 +1419,6 @@ class PubkyRepo @Inject constructor( return StoredCopy(tags = data?.tags.orEmpty(), image = data?.image) } - /** - * Clears the unread flag after a save read the copy itself and kept its tags in the profile it stores, unless a - * load found the copy unreadable since [readEpoch]. A save that writes the copy at once clears it only once that - * write succeeds, since a failed one stores the profile without the copy's tags. - */ - private fun markTagsRead(stored: StoredCopy?, readEpoch: Long) { - if (stored?.tags != null && tagsReadEpoch.get() == readEpoch) tagsUnavailable = false - } - /** [name], [bio] and [links] fitted to pubky.app's limits: one line, cut to length, at most five valid links. */ private fun fitted(name: String, bio: String, links: List) = FittedProfile( name = name.singleLine().takeCodePoints(PUBKY_APP_NAME_MAX_LENGTH), @@ -1409,13 +1432,11 @@ class PubkyRepo @Inject constructor( .take(PUBKY_APP_LINKS_MAX_COUNT), ) - private suspend fun loadOwnProfile(publicKey: String): Pair? { + private suspend fun loadOwnProfile(publicKey: String): LoadedProfile? { val generation = profileDeletionGeneration.get() val saveEpoch = profileSaveEpoch.get() val paykitRead = runSuspendCatching { pubkyService.fetchPaykitProfile(publicKey) } .onFailure { Logger.warn("Failed to read Bitkit profile copy", it, context = TAG) } - tagsReadEpoch.incrementAndGet() - tagsUnavailable = paykitRead.isFailure val paykitData = paykitRead.getOrNull()?.let { PubkyProfileData.fromPaykitProfile(it.profile) } val fetched = readRetryingOnce(publicKey) { pubkyService.fetchPubkyProfileWithRevision(publicKey) } if (fetched == null) paykitRead.getOrThrow() @@ -1424,7 +1445,9 @@ class PubkyRepo @Inject constructor( val migrating = fetched == null && !hadPubkyAppProfile var snapshot = fetched ?: paykitData?.takeIf { migrating }?.let { migrateToPubkyApp(publicKey, it, generation) } // While the move cannot finish, the Bitkit profile is shown and the next save creates the pubky.app profile. - snapshot ?: return paykitData?.takeIf { migrating }?.let { it.toPubkyProfile(publicKey) to null } + snapshot ?: return paykitData?.takeIf { migrating }?.let { + LoadedProfile(it.toPubkyProfile(publicKey), revision = null, tagsUnread = false) + } val pendingAvatar = paykitData?.image?.takeIf { it.isPaykitStorage() } var retryingAvatar = fetched != null && publicKey in stored.pubkyAppAvatarPending val avatarMoveSettled = fetched?.profile?.image != null || (paykitRead.isSuccess && pendingAvatar == null) @@ -1448,7 +1471,7 @@ class PubkyRepo @Inject constructor( if (!avatarPending && paykitData != null && paykitData != profile.toProfileData()) { publishPaykitProfileCopy(publicKey, profile, generation, saveEpoch) } - return profile to snapshot.revision + return LoadedProfile(profile, snapshot.revision, tagsUnread = paykitRead.isFailure) } private suspend fun migrateToPubkyApp( @@ -2586,10 +2609,28 @@ class PubkyRepo @Inject constructor( _backupStateVersion.update { it + 1 } } - private fun setProfile(profile: PubkyProfile?) { + private fun setProfile(profile: PubkyProfile?) = synchronized(profileStateLock) { profileWriteGeneration.incrementAndGet() - if (profile == null) ownProfileRevision = null - _profile.update { profile } + if (profile == null) { + ownProfileRevision = null + tagsUnavailable = false + } + _profile.value = profile + } + + private fun installSavedProfile( + saved: SavedProfile, + signIn: PubkySignIn? = null, + ): Boolean = synchronized(profileStateLock) { + if (signIn != null && !isCurrent(signIn)) return@synchronized false + ownProfileRevision = saved.revision + saved.tagsUnread?.let { unread -> + // A completed copy write has the installed tags. A read alone must respect any newer load. + val currentRead = saved.tagsReadEpoch == null || tagsReadEpoch.get() == saved.tagsReadEpoch + if (unread || currentRead) tagsUnavailable = unread + } + setProfile(saved.profile) + true } private fun startSignIn(publicKey: String, restoringStoredIdentity: Boolean = false) { diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/CreateProfileViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/CreateProfileViewModel.kt index 2daf5d751f..882625b5ae 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/CreateProfileViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/CreateProfileViewModel.kt @@ -22,6 +22,7 @@ import to.bitkit.models.PubkyProfileLink import to.bitkit.models.Toast import to.bitkit.models.takeCodePoints import to.bitkit.repositories.PubkyProfileChangedError +import to.bitkit.repositories.PubkyProfileTagsNotSavedError import to.bitkit.repositories.PubkyRepo import to.bitkit.ui.components.ProfileEditLink import to.bitkit.ui.shared.toast.ToastEventBus @@ -199,8 +200,16 @@ class CreateProfileViewModel @Inject constructor( _uiState.update { it.copy(isSaving = false) } _effects.emit(CreateProfileEffect.CreateSuccess) }.onFailure { - Logger.error("Failed to create identity", it, context = TAG) _uiState.update { it.copy(isSaving = false) } + if (it is PubkyProfileTagsNotSavedError) { + ToastEventBus.send( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.profile__edit_tags_error), + ) + _effects.emit(CreateProfileEffect.CreateSuccess) + return@onFailure + } + Logger.error("Failed to create identity", it, context = TAG) val changed = it is PubkyProfileChangedError ToastEventBus.send( type = Toast.ToastType.ERROR, diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/ProfileViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/ProfileViewModel.kt index 862871d2b4..1089d3f21e 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/ProfileViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/ProfileViewModel.kt @@ -226,7 +226,8 @@ class ProfileViewModel @Inject constructor( ) { viewModelScope.launch { tagUpdateMutex.withLock { - val profile = pubkyRepo.profile.value ?: return@withLock + val editBase = pubkyRepo.profileEditBase() + val profile = editBase.profile ?: return@withLock val tags = transform(profile.tags) if (tags == profile.tags) { onSuccess() @@ -239,6 +240,7 @@ class ProfileViewModel @Inject constructor( links = profile.links, tags = tags, imageUrl = profile.imageUrl, + editBase = editBase, ).onSuccess { onSuccess() }.onFailure { diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index 036d756ce6..a0324521eb 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -801,6 +801,24 @@ class PubkyRepoTest : BaseUnitTest() { assertTrue(profileSetupPending.value) } + @Test + fun `createIdentity reports a failed tag write and keeps the new identity`() = test { + val httpClient = identityHttpClient() + sut = createSut(httpClient) + stubSignupKeys() + whenever(pubkyService.publishPaykitProfile(any(), any())).thenAnswer { throw TestAppError("offline") } + + val result = sut.createIdentity("Test", "", emptyList(), listOf("vip"), null) + httpClient.close() + + assertIs(result.exceptionOrNull()) + assertEquals(VALID_SELF_KEY, sut.publicKey.value) + assertEquals("Test", sut.profile.value?.name) + assertEquals(emptyList(), sut.profile.value?.tags) + assertFalse(profileSetupPending.value) + verifyBlocking(pubkyService, never()) { signOut() } + } + @Test fun `createIdentity completes while contacts are still loading`() = test { val contactsLoadStarted = CompletableDeferred() @@ -995,6 +1013,41 @@ class PubkyRepoTest : BaseUnitTest() { assertTrue(sut.profileEditBase().tagsUnread) } + @Test + fun `a failed profile refresh cannot mark the displayed empty tags as read`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenAnswer { throw TestAppError("offline") } + sut.loadProfile() + assertEquals(emptyList(), sut.profile.value?.tags) + assertTrue(sut.profileEditBase().tagsUnread) + + val storedTags = listOf("friend", "work") + val record = paykitRecord(PubkyProfileData(name = "Test", bio = "", tags = storedTags).toPaykitProfile()) + doReturn(record).whenever(pubkyService).fetchPaykitProfile(VALID_SELF_KEY) + whenever(pubkyService.publishPaykitProfile(any(), any())).thenAnswer { paykitRecord(it.getArgument(0)) } + val refreshReading = CompletableDeferred() + val finishRefresh = CompletableDeferred() + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).doSuspendableAnswer { + refreshReading.complete(Unit) + finishRefresh.await() + throw TestAppError("public profile unavailable") + } + + val refresh = async { sut.loadProfile() } + refreshReading.await() + val editBase = sut.profileEditBase() + assertTrue(editBase.tagsUnread) + finishRefresh.complete(Unit) + refresh.await() + assertTrue(sut.profileEditBase().tagsUnread) + + sut.saveProfile("Test", "", emptyList(), listOf("vip"), null, editBase).getOrThrow() + + val copy = argumentCaptor() + verifyBlocking(pubkyService) { publishPaykitProfile(copy.capture(), any()) } + assertEquals(storedTags + "vip", PubkyProfileData.fromPaykitProfile(copy.firstValue).tags) + } + @Test fun `a save that reads the copy itself lets the next edit remove a tag`() = test { authenticateForTesting(publicKey = VALID_SELF_KEY) @@ -1151,6 +1204,68 @@ class PubkyRepoTest : BaseUnitTest() { assertEquals(storedTags, PubkyProfileData.fromPaykitProfile(copy.firstValue).tags) } + @Test + fun `an edit after restoring without the Paykit copy keeps the stored tags`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenAnswer { throw TestAppError("offline") } + val restored = checkNotNull(sut.fetchRemoteProfile(VALID_SELF_KEY).getOrThrow()) + val storedTags = listOf("friend", "work") + val record = paykitRecord(PubkyProfileData(name = "Test", bio = "", tags = storedTags).toPaykitProfile()) + doReturn(record).whenever(pubkyService).fetchPaykitProfile(VALID_SELF_KEY) + sut.loadProfile() + + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenAnswer { throw TestAppError("offline") } + clearInvocations(pubkyService) + sut.createIdentity("Renamed", restored.bio, restored.links, restored.tags, null).getOrThrow() + verifyBlocking(pubkyService, never()) { publishPaykitProfile(any(), any()) } + + doReturn(record).whenever(pubkyService).fetchPaykitProfile(VALID_SELF_KEY) + whenever(pubkyService.publishPaykitProfile(any(), any())).thenAnswer { paykitRecord(it.getArgument(0)) } + sut.saveProfile("Renamed Again", restored.bio, restored.links, restored.tags, null).getOrThrow() + + val copy = argumentCaptor() + verifyBlocking(pubkyService) { publishPaykitProfile(copy.capture(), any()) } + assertEquals(storedTags, PubkyProfileData.fromPaykitProfile(copy.firstValue).tags) + } + + @Test + fun `a stale load cannot mark tags readable after restoring without the Paykit copy`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + val storedTags = listOf("friend", "work") + val record = paykitRecord(PubkyProfileData(name = "Test", bio = "", tags = storedTags).toPaykitProfile()) + val loadReading = CompletableDeferred() + val finishLoad = CompletableDeferred() + var reads = 0 + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).doSuspendableAnswer { + when (++reads) { + 1, 4 -> throw TestAppError("offline") + 3 -> { + loadReading.complete(Unit) + finishLoad.await() + } + } + record + } + whenever(pubkyService.publishPaykitProfile(any(), any())).thenAnswer { paykitRecord(it.getArgument(0)) } + val restored = checkNotNull(sut.fetchRemoteProfile(VALID_SELF_KEY).getOrThrow()) + sut.loadProfile() + clearInvocations(pubkyService) + + val staleLoad = async { sut.loadProfile() } + loadReading.await() + sut.createIdentity("Renamed", restored.bio, restored.links, restored.tags, null).getOrThrow() + finishLoad.complete(Unit) + staleLoad.await() + assertEquals("Renamed", sut.profile.value?.name) + verifyBlocking(pubkyService, never()) { publishPaykitProfile(any(), any()) } + + sut.saveProfile("Renamed Again", restored.bio, restored.links, restored.tags, null).getOrThrow() + + val copy = argumentCaptor() + verifyBlocking(pubkyService) { publishPaykitProfile(copy.capture(), any()) } + assertEquals(storedTags, PubkyProfileData.fromPaykitProfile(copy.firstValue).tags) + } + @Test fun `saveProfile reports a tag change it could not store while the tags cannot be read`() = test { authenticateForTesting(publicKey = VALID_SELF_KEY) diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/CreateProfileViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/CreateProfileViewModelTest.kt index 28fef51b6e..7bc92a52b6 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/CreateProfileViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/CreateProfileViewModelTest.kt @@ -15,6 +15,8 @@ import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import to.bitkit.R import to.bitkit.models.Toast +import to.bitkit.repositories.ProfileEditBase +import to.bitkit.repositories.PubkyProfileTagsNotSavedError import to.bitkit.repositories.PubkyRepo import to.bitkit.test.BaseUnitTest import to.bitkit.ui.shared.toast.ToastEventBus @@ -68,6 +70,29 @@ class CreateProfileViewModelTest : BaseUnitTest() { toastJob.cancel() } + @Test + fun `save finishes setup and warns when tags could not be saved`() = test { + val warning = "Your profile was saved. Try saving the tags again." + whenever(context.getString(R.string.profile__edit_tags_error)).thenReturn(warning) + whenever(pubkyRepo.createIdentity(any(), any(), any(), any(), anyOrNull())) + .thenReturn(Result.failure(PubkyProfileTagsNotSavedError(ProfileEditBase(null, "revision")))) + val effects = mutableListOf() + val toasts = mutableListOf() + val effectsJob = launch { sut.effects.collect { effects.add(it) } } + val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } + + sut.onNameChange("Alice") + advanceUntilIdle() + sut.save() + advanceUntilIdle() + + assertEquals(CreateProfileEffect.CreateSuccess, effects.single()) + assertEquals(warning, toasts.single().title) + + effectsJob.cancel() + toastJob.cancel() + } + @Test fun `save should not publish after a failed lookup for a signed-in pubky`() = test { whenever(pubkyRepo.publicKey).thenReturn(MutableStateFlow("pubkyalice")) diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/ProfileViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/ProfileViewModelTest.kt index 2a45e49029..83d8ebe20e 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/ProfileViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/ProfileViewModelTest.kt @@ -23,6 +23,7 @@ import to.bitkit.data.PubkyCachedProfile import to.bitkit.models.PubkyProfile import to.bitkit.models.PubkyProfileLink import to.bitkit.repositories.PrivatePaykitRepo +import to.bitkit.repositories.ProfileEditBase import to.bitkit.repositories.PubkyRepo import to.bitkit.test.BaseUnitTest import to.bitkit.test.forEachCase @@ -66,7 +67,7 @@ class ProfileViewModelTest : BaseUnitTest() { sut.addTag("Bitcoin") sut.removeTag("Founder") advanceUntilIdle() - verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), any()) + verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), any(), any()) restore.complete(false) advanceUntilIdle() @@ -331,7 +332,7 @@ class ProfileViewModelTest : BaseUnitTest() { advanceUntilIdle() assertNull(sut.uiState.value.profile) - verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), any()) + verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), any(), any()) } @Test @@ -401,6 +402,7 @@ class ProfileViewModelTest : BaseUnitTest() { links = listOf(PubkyProfileLink("Website", "https://example.com")), tags = listOf("Founder", "Bitcoin"), imageUrl = "https://example.com/avatar.png", + editBase = ProfileEditBase(createProfile(), null), ) } @@ -418,7 +420,7 @@ class ProfileViewModelTest : BaseUnitTest() { sut.addTag("Founder") assertFalse(awaitItem().showAddTagSheet) } - verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), any()) + verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), any(), any()) } @Test @@ -435,6 +437,7 @@ class ProfileViewModelTest : BaseUnitTest() { links = any(), tags = eq(listOf("Bitcoin")), imageUrl = eq("https://example.com/avatar.png"), + editBase = any(), ) } @@ -444,7 +447,7 @@ class ProfileViewModelTest : BaseUnitTest() { createProfile(tags = listOf("Founder", "Bitcoin")), ) val sut = createSut(profileFlow = profileFlow) - whenever(pubkyRepo.saveProfile(any(), any(), any(), any(), any())).doSuspendableAnswer { + whenever(pubkyRepo.saveProfile(any(), any(), any(), any(), any(), any())).doSuspendableAnswer { val tags = it.getArgument>(3) profileFlow.value = requireNotNull(profileFlow.value).copy(tags = tags) Result.success(Unit) @@ -456,8 +459,8 @@ class ProfileViewModelTest : BaseUnitTest() { advanceUntilIdle() inOrder(pubkyRepo).apply { - verify(pubkyRepo).saveProfile(any(), any(), any(), eq(listOf("Bitcoin")), any()) - verify(pubkyRepo).saveProfile(any(), any(), any(), eq(emptyList()), any()) + verify(pubkyRepo).saveProfile(any(), any(), any(), eq(listOf("Bitcoin")), any(), any()) + verify(pubkyRepo).saveProfile(any(), any(), any(), eq(emptyList()), any(), any()) } assertEquals(emptyList(), profileFlow.value?.tags) } @@ -468,7 +471,7 @@ class ProfileViewModelTest : BaseUnitTest() { createProfile(tags = listOf("Founder", "Bitcoin")), ) val sut = createSut(profileFlow = profileFlow) - whenever(pubkyRepo.saveProfile(any(), any(), any(), any(), any())).doSuspendableAnswer { + whenever(pubkyRepo.saveProfile(any(), any(), any(), any(), any(), any())).doSuspendableAnswer { val tags = it.getArgument>(3) profileFlow.value = requireNotNull(profileFlow.value).copy(tags = tags) Result.success(Unit) @@ -479,14 +482,14 @@ class ProfileViewModelTest : BaseUnitTest() { sut.removeTag("Founder") advanceUntilIdle() - verify(pubkyRepo, times(1)).saveProfile(any(), any(), any(), eq(listOf("Bitcoin")), any()) + verify(pubkyRepo, times(1)).saveProfile(any(), any(), any(), eq(listOf("Bitcoin")), any(), any()) assertEquals(listOf("Bitcoin"), profileFlow.value?.tags) } @Test fun `failed tag save keeps the add sheet open for retry`() = test { val sut = createSut(createProfile()) - whenever(pubkyRepo.saveProfile(any(), any(), any(), any(), any())) + whenever(pubkyRepo.saveProfile(any(), any(), any(), any(), any(), any())) .thenReturn(Result.failure(ProfileTestAppError("save failed"))) advanceUntilIdle() @@ -519,6 +522,7 @@ class ProfileViewModelTest : BaseUnitTest() { whenever(context.getString(any())).thenReturn("") whenever { pubkyRepo.forgetUnrestoredIdentity() }.thenReturn(Result.success(false)) whenever(pubkyRepo.profile).thenReturn(profileFlow) + whenever(pubkyRepo.profileEditBase()).thenAnswer { ProfileEditBase(profileFlow.value, null) } whenever(pubkyRepo.readOnlyProfile).thenReturn(readOnlyProfileFlow) whenever(pubkyRepo.publicKey).thenReturn(publicKeyFlow) whenever(pubkyRepo.isLoadingProfile).thenReturn(isLoadingFlow) @@ -527,7 +531,7 @@ class ProfileViewModelTest : BaseUnitTest() { whenever { pubkyRepo.restoreSessionIfNeeded() }.doSuspendableAnswer { onRestore() } whenever { pubkyRepo.loadProfile() }.thenAnswer { onLoadProfile() } whenever { pubkyRepo.signOut() }.thenReturn(Result.success(Unit)) - whenever { pubkyRepo.saveProfile(any(), any(), any(), any(), any()) }.thenReturn(Result.success(Unit)) + whenever { pubkyRepo.saveProfile(any(), any(), any(), any(), any(), any()) }.thenReturn(Result.success(Unit)) whenever { privatePaykitRepo.removePublishedEndpointsForCleanup(any()) } .thenReturn(Result.success(Unit)) whenever { privatePaykitRepo.closeAndClear() }.thenReturn(Result.success(Unit))