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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions app/src/main/java/to/bitkit/ext/JadeExceptionExt.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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 }

Expand Down
7 changes: 7 additions & 0 deletions app/src/main/java/to/bitkit/repositories/HwWalletRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down
16 changes: 15 additions & 1 deletion app/src/main/java/to/bitkit/repositories/JadeRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)) }
}
Expand All @@ -370,14 +372,18 @@ 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)) }
}
}

suspend fun getMasterFingerprint(): Result<String> = 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<Unit> = withContext(ioDispatcher) {
Expand Down Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -640,22 +641,33 @@ 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,
sats = amountSats,
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)
Expand Down
28 changes: 28 additions & 0 deletions app/src/test/java/to/bitkit/repositories/JadeRepoTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down
1 change: 1 addition & 0 deletions changelog.d/next/2050.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed a Jade logged out on the device showing as busy: it now asks for its PIN and carries on.
5 changes: 2 additions & 3 deletions journeys/hardware-wallet/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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.
24 changes: 22 additions & 2 deletions journeys/hardware-wallet/jade-device-locked.xml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
</description>
<actions>
<action>
Expand All @@ -22,7 +27,22 @@
Run `./scripts/jade-emulator press front right front` in `bitkit-docker` to choose Session, then Log Out, on the device
</action>
<action>
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
</action>
<action>
Comment thread
ovitrif marked this conversation as resolved.
Resolved
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
</action>
<action>
Close the receive sheet and run `./scripts/jade-emulator press front right front` to log out on the device again
</action>
<action>
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")
</action>
<action>
Verify the Jade shows its PIN pad, then run `./scripts/jade-emulator pin 012345`
</action>
<action>
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
</action>
</actions>
</journey>