diff --git a/app/src/main/java/to/bitkit/ext/JadeExceptionExt.kt b/app/src/main/java/to/bitkit/ext/JadeExceptionExt.kt index bb72fc8bb5..6f6b386f8c 100644 --- a/app/src/main/java/to/bitkit/ext/JadeExceptionExt.kt +++ b/app/src/main/java/to/bitkit/ext/JadeExceptionExt.kt @@ -9,6 +9,9 @@ fun Throwable.isJadeUserCancellation(): Boolean = fun Throwable.isJadeDeviceBusy(): Boolean = generateSequence(this) { it.cause }.any { it is JadeException.DeviceBusy || it is JadeException.DeviceLocked } +fun Throwable.isJadeDeviceLocked(): Boolean = + generateSequence(this) { it.cause }.any { it is JadeException.DeviceLocked } + fun Throwable.isJadeFirmwareError(): Boolean = generateSequence(this) { it.cause }.any { it is JadeException.UnsupportedFirmware } diff --git a/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt b/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt index 0a6aac25a9..1c9cd0cf3c 100644 --- a/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt @@ -46,6 +46,7 @@ import to.bitkit.data.SettingsStore import to.bitkit.di.IoDispatcher import to.bitkit.env.Env import to.bitkit.ext.isHwSessionFailure +import to.bitkit.ext.isJadeDeviceLocked import to.bitkit.ext.runSuspendCatching import to.bitkit.ext.scopedId import to.bitkit.ext.timestamp @@ -705,6 +706,12 @@ class HwWalletRepo @Inject constructor( ensureConnected(walletId).getOrThrow() runSuspendCatching { verifyOnDevice() } + .recoverCatching { error -> + // A Jade logged out on the device asks for its PIN on reconnect, which also checks its wallet. + if (!error.isJadeDeviceLocked()) throw error + ensureConnected(walletId).getOrThrow() + verifyOnDevice() + } .recoverCatching { error -> if (!error.isHwSessionFailure()) throw error disconnectStaleSession(walletId).getOrThrow() diff --git a/app/src/main/java/to/bitkit/repositories/JadeRepo.kt b/app/src/main/java/to/bitkit/repositories/JadeRepo.kt index df0d147de8..1b0f586aaa 100644 --- a/app/src/main/java/to/bitkit/repositories/JadeRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/JadeRepo.kt @@ -36,6 +36,7 @@ import to.bitkit.data.PendingNameUpdate import to.bitkit.di.IoDispatcher import to.bitkit.env.Env import to.bitkit.ext.isJadeDeviceBusy +import to.bitkit.ext.isJadeDeviceLocked import to.bitkit.ext.isJadeUserCancellation import to.bitkit.ext.nowMs import to.bitkit.ext.runSuspendCatching @@ -359,6 +360,7 @@ class JadeRepo @Inject constructor( expectedAddress = expectedAddress, ) }.onFailure { + markLockedIfLoggedOut(it) Logger.error("Jade verifyAddress failed", it, context = TAG) _state.update { s -> s.copy(error = errorMessage(it)) } } @@ -370,6 +372,7 @@ class JadeRepo @Inject constructor( val signed = jadeService.signPsbt(network = Env.network.toJadeNetwork(), psbtBase64 = psbtBase64) jadeService.finalizePsbt(originalPsbt = psbtBase64, signedPsbt = signed) }.onFailure { + markLockedIfLoggedOut(it) Logger.error("Jade signPsbt failed", it, context = TAG) _state.update { s -> s.copy(error = errorMessage(it)) } } @@ -377,7 +380,10 @@ class JadeRepo @Inject constructor( suspend fun getMasterFingerprint(): Result = withContext(ioDispatcher) { runSuspendCatching { jadeService.getMasterFingerprint(Env.network.toJadeNetwork()) } - .onFailure { Logger.error("Jade getMasterFingerprint failed", it, context = TAG) } + .onFailure { + markLockedIfLoggedOut(it) + Logger.error("Jade getMasterFingerprint failed", it, context = TAG) + } } suspend fun disconnect(): Result = withContext(ioDispatcher) { @@ -723,6 +729,14 @@ class JadeRepo @Inject constructor( } } + private fun markLockedIfLoggedOut(error: Throwable) { + if (!error.isJadeDeviceLocked()) return + val current = _state.value.connected ?: return + Logger.info("Marked Jade '${current.id}' locked after it logged out on the device", context = TAG) + val locked = current.copy(versionInfo = current.versionInfo.copy(jadeState = JadeState.LOCKED)) + _state.update { it.copy(connected = locked) } + } + private suspend fun unlockConnected(): JadeVersionInfo { _state.update { it.copy(isUnlocking = true) } try { diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt index 3330e9dbe5..edd5ae6177 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/HwSendViewModel.kt @@ -31,6 +31,7 @@ import to.bitkit.ext.isHwDeviceBusy import to.bitkit.ext.isHwFirmwareError import to.bitkit.ext.isHwSessionFailure import to.bitkit.ext.isHwUserCancellation +import to.bitkit.ext.isJadeDeviceLocked import to.bitkit.ext.runSuspendCatching import to.bitkit.models.HwFundingBroadcastResult import to.bitkit.models.HwFundingSignedTx @@ -640,8 +641,7 @@ class HwSendViewModel @Inject constructor( amountSats: ULong, satsPerVByte: ULong, ): HwFundingSignedTx { - ensureConnected(walletId) - val funding = withTimeout(COMPOSE_TIMEOUT) { + suspend fun compose() = withTimeout(COMPOSE_TIMEOUT) { hwWalletRepo.composeFundingTransaction( walletId = walletId, address = address, @@ -649,13 +649,25 @@ class HwSendViewModel @Inject constructor( satsPerVByte = satsPerVByte, ).getOrThrow() } + + ensureConnected(walletId) + val firstAttempt = runSuspendCatching { compose() } + val error = firstAttempt.exceptionOrNull() + val funding = if (error == null) { + firstAttempt.getOrThrow() + } else { + // A Jade logged out on the device asks for its PIN here, where the sheet can still be left. + if (!error.isJadeDeviceLocked()) throw error + ensureConnected(walletId) + compose() + } return sign(walletId, funding) } private suspend fun sign(walletId: String, funding: HwFundingTransaction): HwFundingSignedTx { val firstAttempt = runSuspendCatching { signWithTimeoutCleanup(walletId, funding) } val error = firstAttempt.exceptionOrNull() ?: return firstAttempt.getOrThrow() - if (!error.isHwSessionFailure()) throw error + if (!error.isHwSessionFailure() && !error.isJadeDeviceLocked()) throw error ensureConnected(walletId) return signWithTimeoutCleanup(walletId, funding) diff --git a/app/src/test/java/to/bitkit/repositories/JadeRepoTest.kt b/app/src/test/java/to/bitkit/repositories/JadeRepoTest.kt index 78a573ba78..d406703b00 100644 --- a/app/src/test/java/to/bitkit/repositories/JadeRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/JadeRepoTest.kt @@ -40,6 +40,7 @@ import to.bitkit.models.TransportType import to.bitkit.services.JadeService import to.bitkit.services.JadeTransport import to.bitkit.test.BaseUnitTest +import to.bitkit.utils.AppError import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertIs @@ -728,6 +729,33 @@ class JadeRepoTest : BaseUnitTest() { verify(jadeService).verifyAddress(JadeNetwork.REGTEST, JadeAddressVariant.WPKH, "m/84'/1'/0'/0/0", "bcrt1q") } + @Test + fun `a jade logged out on the device marks the session locked so ensureConnected unlocks it`() = test { + val sut = connectedReadyRepo() + whenever(jadeService.verifyAddress(any(), any(), any(), any())) + .doSuspendableAnswer { throw AppError(JadeException.DeviceLocked()) } + + val verified = sut.verifyAddress(HwFundingAddressType.NATIVE_SEGWIT, "m/84'/1'/0'/0/0", "bcrt1q") + + assertTrue(verified.isFailure) + assertTrue(sut.state.value.connected?.isLocked == true) + val unlocked = sut.ensureConnected(knownUsb.id, WALLET_ID).getOrThrow() + assertFalse(unlocked.isLocked) + assertEquals(WALLET_ID, unlocked.walletId) + verify(jadeService).unlock(JadeNetwork.REGTEST) + } + + private suspend fun connectedReadyRepo(): JadeRepo { + whenever { hwWalletStore.loadKnownDevices(HwWalletVendor.BLOCKSTREAM) }.thenReturn(listOf(knownUsb)) + whenever { jadeService.scan(any(), any()) }.thenReturn(listOf(usbDevice)) + whenever { jadeService.connect(any(), any(), any()) }.thenReturn(versionInfo(JadeState.READY)) + val sut = createRepo() + val connected = sut.autoReconnect(preferredTransport = TransportType.USB).getOrThrow() + assertEquals(WALLET_ID, connected.walletId) + whenever { jadeService.isConnected() }.thenReturn(true) + return sut + } + private fun createRepo() = JadeRepo( context = context, jadeService = jadeService, diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt index 5483a9942e..4a3a19c0fa 100644 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/send/HwSendViewModelTest.kt @@ -3,6 +3,7 @@ package to.bitkit.ui.screens.wallets.send import android.content.Context import androidx.lifecycle.viewModelScope import com.synonym.bitkitcore.BroadcastException +import com.synonym.bitkitcore.JadeException import com.synonym.bitkitcore.TrezorException import kotlinx.collections.immutable.persistentListOf import kotlinx.coroutines.CompletableDeferred @@ -907,6 +908,24 @@ class HwSendViewModelTest : BaseUnitTest() { return PaymentFixture(funding, signedTx, broadcast) } + @Test + fun `a jade logged out on the device unlocks in the connect step before composing and signing again`() = test { + val fixture = stubSuccessfulPayment() + val locked = AppError(JadeException.DeviceLocked()) + whenever(hwWalletRepo.composeFundingTransaction(WALLET_ID, ADDRESS, AMOUNT_SATS, SATS_PER_VBYTE)) + .thenReturn(Result.failure(locked), Result.success(fixture.funding)) + whenever(hwWalletRepo.signFunding(WALLET_ID, fixture.funding)) + .thenReturn(Result.failure(locked), Result.success(fixture.signedTx)) + + sut.signAndBroadcast(request()) + advanceUntilIdle() + + verify(hwWalletRepo, times(3)).ensureConnected(WALLET_ID) + verify(hwWalletRepo, times(2)).composeFundingTransaction(WALLET_ID, ADDRESS, AMOUNT_SATS, SATS_PER_VBYTE) + verify(hwWalletRepo, times(2)).signFunding(WALLET_ID, fixture.funding) + verify(hwWalletRepo).broadcastFunding(fixture.signedTx) + } + @Test fun `retained hardware receipt blocks ordinary and foreign request signing after restart`() = test { stubSuccessfulPayment() diff --git a/changelog.d/next/2050.fixed.md b/changelog.d/next/2050.fixed.md new file mode 100644 index 0000000000..5758427dbb --- /dev/null +++ b/changelog.d/next/2050.fixed.md @@ -0,0 +1 @@ +Fixed a Jade logged out on the device showing as busy: it now asks for its PIN and carries on. diff --git a/journeys/hardware-wallet/README.md b/journeys/hardware-wallet/README.md index 95cca5216d..85ecb35cf3 100644 --- a/journeys/hardware-wallet/README.md +++ b/journeys/hardware-wallet/README.md @@ -84,7 +84,7 @@ the other three rely on, and `passphrase-settings-remove.xml` removes it again. | `jade-uninitialized.xml` | Jade emulator with no wallet: Found shows the not-set-up message | | `jade-wrong-pin.xml` | Interactive Jade emulator: wrong PIN on the device → Found shows the wrong-PIN message, retry pairs | | `jade-network-mismatch.xml` | Jade emulator restricted to mainnet: Found shows the network message | -| `jade-device-locked.xml` | Interactive Jade logged out on the device after pairing: Verify on Device shows the busy message | +| `jade-device-locked.xml` | Interactive Jade logged out on the device after pairing: Verify on Device and Sign With Jade ask for the PIN on the device and retry | | `jade-psbt-too-large.xml` | Jade with about 200 small inputs: sending all of it shows the too-large message | | `jade-sign-on-device.xml` | Interactive Jade: decline on the device keeps the payment unsent, approve sends it | | `jade-wallet-mismatch.xml` | Paired Jade reseeded: Verify on Device shows the different-wallet message | @@ -179,7 +179,6 @@ The error journeys start the emulator in another state first: `jade-uninitialize (`JADE_MNEMONIC=`), `jade-wrong-pin.xml` (`JADE_MODE=interactive`, where the device shows its own PIN pad and `./scripts/jade-emulator pin` types on it) and `jade-network-mismatch.xml` (`JADE_NETWORK=mainnet`), and `jade-device-locked.xml` logs the interactive device out after -pairing (Android reports the locked Jade as busy; iOS asks for the PIN on the device again and retries, -so its copy of the journey checks that); `jade-psbt-too-large.xml` needs the app on the bitkit-docker Electrum and about 200 small +pairing, so Verify on Device and then Sign With Jade ask for the PIN on the device again and retry (the send steps need the app on the bitkit-docker Electrum and funds on the Jade); `jade-psbt-too-large.xml` needs the app on the bitkit-docker Electrum and about 200 small inputs on the Jade. `jade-sign-on-device.xml` declines and then approves a payment on the interactive device's own screens. `jade-wallet-mismatch.xml` restarts the emulator with another seed after pairing. `jade-passphrase.xml` starts it with `JADE_PASSPHRASE=always` and pairs the wallet a passphrase typed on the device opens (`./scripts/jade-emulator passphrase`). The bitkit-docker `docs/jade-emulator.md` lists the modes and recipes. diff --git a/journeys/hardware-wallet/jade-device-locked.xml b/journeys/hardware-wallet/jade-device-locked.xml index f67eb0e352..b870356a66 100644 --- a/journeys/hardware-wallet/jade-device-locked.xml +++ b/journeys/hardware-wallet/jade-device-locked.xml @@ -3,7 +3,12 @@ Logs the paired Jade out on the device itself and checks the message the app shows when it next needs the Jade. Requires `JADE_MODE=interactive ./scripts/jade-emulator start` in `bitkit-docker`, a regtest debug build with the Jade emulator enabled (see the README) and no - Jade paired. The device answers the next request with HW_LOCKED, which the app reports as busy. + Jade paired. For the send steps, Settings, Advanced, Electrum Server must point at the + `bitkit-docker` Electrum, and the Jade must hold funds there: after pairing, run + `./bitcoin-cli sendtoaddress JADE_ADDRESS 0.001; ./bitcoin-cli -generate 1` in + `bitkit-docker`, where `JADE_ADDRESS` is the address Receive shows on the Jade tab. The device answers + the next request with HW_LOCKED, and the app asks for the PIN on the device again and retries, + on Verify on Device and on Sign With Jade. @@ -22,7 +27,22 @@ Run `./scripts/jade-emulator press front right front` in `bitkit-docker` to choose Session, then Log Out, on the device - Tap Receive (testTag "Receive"), select the Jade tab, tap "Show Details" if the address is hidden behind it, then tap "Verify on Device" (testTag "HardwareVerifyAddress") and verify a toast reads "Your Jade is busy. Finish what is shown on the device, then try again." + Tap Receive (testTag "Receive"), select the Jade tab, tap "Show Details" if the address is hidden behind it, then tap "Verify on Device" (testTag "HardwareVerifyAddress") and verify the Jade shows its PIN pad again + + + Run `./scripts/jade-emulator pin 012345`, then `./scripts/jade-emulator press right front` once the device shows Verify Address, and verify the button returns to "Verify on Device" with no error + + + Close the receive sheet and run `./scripts/jade-emulator press front right front` to log out on the device again + + + Tap Send (testTag "Send"), enter a regtest address of the bitkit-docker node manually, select the Jade as the funding source on the amount screen (testTag "AssetButton-switch"), enter 50 000 sats, tap Continue (testTag "ContinueAmount"), swipe to confirm and tap "Sign With Jade" (testTag "HardwareSendOpenTrezorConnect") + + + Verify the Jade shows its PIN pad, then run `./scripts/jade-emulator pin 012345` + + + Run `./scripts/jade-emulator press front` to pass the Output screen, then `./scripts/jade-emulator press right front` to sign on Send Transaction, and verify the success screen (testTag "SendSuccess") headed "Bitcoin Sent" appears within 30 seconds, with one payment sent