diff --git a/app/src/main/java/to/bitkit/nearby/NearbyAdvertiser.kt b/app/src/main/java/to/bitkit/nearby/NearbyAdvertiser.kt index bb912e8f2a..0f7a9c151a 100644 --- a/app/src/main/java/to/bitkit/nearby/NearbyAdvertiser.kt +++ b/app/src/main/java/to/bitkit/nearby/NearbyAdvertiser.kt @@ -8,6 +8,7 @@ import android.bluetooth.BluetoothGattCharacteristic import android.bluetooth.BluetoothGattServer import android.bluetooth.BluetoothGattServerCallback import android.bluetooth.BluetoothGattService +import android.bluetooth.BluetoothProfile import android.bluetooth.le.AdvertiseCallback import android.bluetooth.le.AdvertiseData import android.bluetooth.le.AdvertiseSettings @@ -18,6 +19,8 @@ import android.os.ParcelUuid import androidx.annotation.RequiresPermission import to.bitkit.ext.bluetoothManager import to.bitkit.utils.Logger +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicReference /** * Serves one payment request to nearby Bitkit wallets: a GATT server with the nearby service and a @@ -28,7 +31,7 @@ class NearbyAdvertiser( private val context: Context, private val onFailed: () -> Unit = {}, ) { - private val bluetoothManager = context.bluetoothManager + private val bluetoothManager by lazy { context.bluetoothManager } @Volatile private var request: ByteArray? = null @@ -37,7 +40,8 @@ class NearbyAdvertiser( private val isAdvertising get() = advertiseCallback != null private val mainHandler = Handler(Looper.getMainLooper()) - /** Counts opened servers, so a registration result for a closed server is ignored. */ + /** Counts opened servers, so a registration result or read for a closed server is ignored. */ + @Volatile private var serverGeneration = 0 private var isServiceRegistered = false @@ -51,28 +55,50 @@ class NearbyAdvertiser( } } - private fun newServerCallback(generation: Int) = object : BluetoothGattServerCallback() { - override fun onServiceAdded(status: Int, service: BluetoothGattService?) { - mainHandler.post { onServiceRegistered(generation, status == BluetoothGatt.GATT_SUCCESS) } - } + private fun newServerCallback(generation: Int, server: AtomicReference) = + object : BluetoothGattServerCallback() { + /** The request each payer read the meta of, so its chunks come from that request when it changes. */ + private val requestsByPayer = ConcurrentHashMap() + + override fun onConnectionStateChange(device: BluetoothDevice, status: Int, newState: Int) { + if (newState == BluetoothProfile.STATE_DISCONNECTED) requestsByPayer.remove(device) + } - @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT) - override fun onCharacteristicReadRequest( - device: BluetoothDevice, - requestId: Int, - offset: Int, - characteristic: BluetoothGattCharacteristic, - ) { - val server = gattServer ?: return - val value = valueFor(characteristic) - val response = value?.let { NearbyProtocol.readAt(it, offset) } - if (response == null) { - server.sendResponse(device, requestId, BluetoothGatt.GATT_INVALID_OFFSET, offset, null) - } else { - server.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, response) + override fun onServiceAdded(status: Int, service: BluetoothGattService?) { + mainHandler.post { onServiceRegistered(generation, status == BluetoothGatt.GATT_SUCCESS) } + } + + @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT) + override fun onCharacteristicReadRequest( + device: BluetoothDevice, + requestId: Int, + offset: Int, + characteristic: BluetoothGattCharacteristic, + ) { + val owner = server.get() ?: return + val value = if (generation == serverGeneration) valueFor(characteristic, device) else null + val response = value?.let { NearbyProtocol.readAt(it, offset) } + val status = when { + value == null -> BluetoothGatt.GATT_FAILURE + response == null -> BluetoothGatt.GATT_INVALID_OFFSET + else -> BluetoothGatt.GATT_SUCCESS + } + // False means nothing was sent (a closed server returns it), so the payer waits for its own timeout. + runCatching { owner.sendResponse(device, requestId, status, offset, response) } + .onSuccess { sent -> if (!sent) Logger.warn("Sent no answer to a nearby read", context = TAG) } + .onFailure { Logger.warn("Failed to answer a nearby read", it, context = TAG) } + } + + private fun valueFor(characteristic: BluetoothGattCharacteristic, payer: BluetoothDevice): ByteArray? { + val current = request ?: return null + if (characteristic.uuid == NearbyProtocol.META_UUID) { + requestsByPayer[payer] = current + return NearbyProtocol.meta(current) + } + val index = NearbyProtocol.DATA_UUIDS.indexOf(characteristic.uuid) + return if (index >= 0) NearbyProtocol.chunk(requestsByPayer[payer] ?: current, index) else null } } - } @RequiresPermission(allOf = [Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_ADVERTISE]) fun start(uri: String) { @@ -103,25 +129,25 @@ class NearbyAdvertiser( runCatching { bluetoothManager.adapter?.bluetoothLeAdvertiser?.stopAdvertising(callback) } } advertiseCallback = null - runCatching { gattServer?.close() } + // Removing the service first keeps a stack that fails to drop a closed server's services from serving it. + gattServer?.let { server -> + runCatching { server.clearServices() } + runCatching { server.close() } + } gattServer = null isServiceRegistered = false serverGeneration++ } - private fun valueFor(characteristic: BluetoothGattCharacteristic): ByteArray? { - val current = request ?: return null - if (characteristic.uuid == NearbyProtocol.META_UUID) return NearbyProtocol.meta(current) - val index = NearbyProtocol.DATA_UUIDS.indexOf(characteristic.uuid) - return if (index >= 0) NearbyProtocol.chunk(current, index) else null - } - @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT) private fun openServer(): BluetoothGattServer? { val generation = ++serverGeneration - val server = runCatching { bluetoothManager.openGattServer(context, newServerCallback(generation)) } + val opened = AtomicReference() + val callback = newServerCallback(generation, opened) + val server = runCatching { bluetoothManager.openGattServer(context, callback) } .onFailure { Logger.warn("Failed to open nearby GATT server", it, context = TAG) } .getOrNull() ?: return null + opened.set(server) val service = BluetoothGattService(NearbyProtocol.SERVICE_UUID, BluetoothGattService.SERVICE_TYPE_PRIMARY) (listOf(NearbyProtocol.META_UUID) + NearbyProtocol.DATA_UUIDS).forEach { service.addCharacteristic( diff --git a/app/src/main/java/to/bitkit/ui/shared/effects/NearbyEffects.kt b/app/src/main/java/to/bitkit/ui/shared/effects/NearbyEffects.kt index f2c48c145f..646cde84b9 100644 --- a/app/src/main/java/to/bitkit/ui/shared/effects/NearbyEffects.kt +++ b/app/src/main/java/to/bitkit/ui/shared/effects/NearbyEffects.kt @@ -162,36 +162,37 @@ private fun startScanner(scanner: NearbyScanner) = scanner.start() /** * Serves [uri] to nearby Bitkit wallets over Bluetooth while the calling screen is resumed. * [onFailed] runs when advertising can't start, so the screen stops saying it can be tapped. + * A new [uri] is served from the open GATT server, so request updates don't close and reopen it. */ @Composable fun NearbyAdvertiseEffect(uri: String?, onFailed: () -> Unit = {}) { val context = LocalContext.current val lifecycleOwner = LocalLifecycleOwner.current val currentOnFailed by rememberUpdatedState(onFailed) + val advertiser = remember(context) { NearbyAdvertiser(context.applicationContext) { currentOnFailed() } } - DisposableEffect(context, lifecycleOwner, uri) { - if (uri.isNullOrBlank()) return@DisposableEffect onDispose {} - val advertiser = NearbyAdvertiser(context.applicationContext) { currentOnFailed() } + DisposableEffect(advertiser) { + onDispose { stopAdvertiser(advertiser) } + } + DisposableEffect(lifecycleOwner, advertiser, uri) { + // Adding the observer replays ON_RESUME when the screen is already resumed, which serves the new uri. val observer = LifecycleEventObserver { _, event -> when (event) { - Lifecycle.Event.ON_RESUME -> startAdvertiser(advertiser, uri) + Lifecycle.Event.ON_RESUME -> serveNearby(advertiser, uri) Lifecycle.Event.ON_PAUSE -> stopAdvertiser(advertiser) else -> Unit } } lifecycleOwner.lifecycle.addObserver(observer) - if (lifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) startAdvertiser(advertiser, uri) - onDispose { - lifecycleOwner.lifecycle.removeObserver(observer) - stopAdvertiser(advertiser) - } + onDispose { lifecycleOwner.lifecycle.removeObserver(observer) } } } @SuppressLint("MissingPermission") // NearbyAdvertiseEffect gets a uri only while the advertise permissions are granted. -private fun startAdvertiser(advertiser: NearbyAdvertiser, uri: String) = advertiser.start(uri) +private fun serveNearby(advertiser: NearbyAdvertiser, uri: String?) = + if (uri.isNullOrBlank()) advertiser.stop() else advertiser.start(uri) -@SuppressLint("MissingPermission") // Same as startAdvertiser. +@SuppressLint("MissingPermission") // Same as serveNearby. private fun stopAdvertiser(advertiser: NearbyAdvertiser) = advertiser.stop() /** diff --git a/app/src/test/java/to/bitkit/nearby/NearbyAdvertiserTest.kt b/app/src/test/java/to/bitkit/nearby/NearbyAdvertiserTest.kt index 19f41a44d4..65cd79e927 100644 --- a/app/src/test/java/to/bitkit/nearby/NearbyAdvertiserTest.kt +++ b/app/src/test/java/to/bitkit/nearby/NearbyAdvertiserTest.kt @@ -1,10 +1,13 @@ package to.bitkit.nearby import android.bluetooth.BluetoothAdapter +import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothGatt +import android.bluetooth.BluetoothGattCharacteristic import android.bluetooth.BluetoothGattServer import android.bluetooth.BluetoothGattServerCallback import android.bluetooth.BluetoothManager +import android.bluetooth.BluetoothProfile import android.bluetooth.le.AdvertiseSettings import android.bluetooth.le.BluetoothLeAdvertiser import android.content.Context @@ -13,14 +16,20 @@ import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.eq +import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock import org.mockito.kotlin.never +import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config +import org.robolectric.shadows.ShadowLog +import to.bitkit.utils.Logger import kotlin.test.assertEquals @Config(sdk = [34]) @@ -29,6 +38,7 @@ class NearbyAdvertiserTest { private val advertiser = mock() private val adapter = mock { on { bluetoothLeAdvertiser }.thenReturn(advertiser) } private val server = mock() + private val device = mock() private val manager = mock { on { adapter }.thenReturn(adapter) } private val context = mock { on { getSystemService(Context.BLUETOOTH_SERVICE) }.thenReturn(manager) } private var failures = 0 @@ -36,8 +46,11 @@ class NearbyAdvertiserTest { @Before fun setUp() { + Logger.reset() + ShadowLog.clear() whenever(manager.openGattServer(any(), any())).thenReturn(server) whenever(server.addService(any())).thenReturn(true) + whenever(server.sendResponse(any(), any(), any(), any(), anyOrNull())).thenReturn(true) sut = NearbyAdvertiser(context) { failures++ } } @@ -47,6 +60,8 @@ class NearbyAdvertiserTest { return captor.lastValue } + private fun unansweredReads() = ShadowLog.getLogsForTag("APP").count { it.msg.contains("Sent no answer") } + private fun reportServiceAdded(status: Int) { serverCallback().onServiceAdded(status, null) shadowOf(Looper.getMainLooper()).idle() @@ -87,7 +102,114 @@ class NearbyAdvertiserTest { assertEquals(1, failures) } + private fun readMeta(callback: BluetoothGattServerCallback) = callback.onCharacteristicReadRequest( + device, + REQUEST_ID, + 0, + BluetoothGattCharacteristic(NearbyProtocol.META_UUID, 0, 0), + ) + + @Test + fun `serves a new request from the open server`() { + sut.start(URI) + reportServiceAdded(BluetoothGatt.GATT_SUCCESS) + + sut.start(OTHER_URI) + readMeta(serverCallback()) + + verify(manager, times(1)).openGattServer(any(), any()) + val expected = NearbyProtocol.meta(OTHER_URI.toByteArray()) + verify(server).sendResponse(eq(device), eq(REQUEST_ID), eq(BluetoothGatt.GATT_SUCCESS), eq(0), eq(expected)) + assertEquals(0, unansweredReads()) + } + + @Test + fun `serves a payer the chunks of the request it read the meta of`() { + val first = "bitcoin:" + "a".repeat(NearbyProtocol.CHUNK_SIZE + 100) + sut.start(first) + reportServiceAdded(BluetoothGatt.GATT_SUCCESS) + val callback = serverCallback() + readMeta(callback) + + sut.start("bitcoin:" + "b".repeat(NearbyProtocol.CHUNK_SIZE + 100)) + callback.onCharacteristicReadRequest( + device, + REQUEST_ID, + 0, + BluetoothGattCharacteristic(NearbyProtocol.DATA_UUIDS[1], 0, 0), + ) + + val expected = NearbyProtocol.chunk(first.toByteArray(), 1) + verify(server).sendResponse(eq(device), eq(REQUEST_ID), eq(BluetoothGatt.GATT_SUCCESS), eq(0), eq(expected)) + } + + @Test + fun `serves the current request after the payer disconnects`() { + sut.start(URI) + reportServiceAdded(BluetoothGatt.GATT_SUCCESS) + val callback = serverCallback() + readMeta(callback) + + callback.onConnectionStateChange(device, BluetoothGatt.GATT_SUCCESS, BluetoothProfile.STATE_DISCONNECTED) + sut.start(OTHER_URI) + callback.onCharacteristicReadRequest( + device, + REQUEST_ID, + 0, + BluetoothGattCharacteristic(NearbyProtocol.DATA_UUIDS[0], 0, 0), + ) + + val expected = NearbyProtocol.chunk(OTHER_URI.toByteArray(), 0) + verify(server).sendResponse(eq(device), eq(REQUEST_ID), eq(BluetoothGatt.GATT_SUCCESS), eq(0), eq(expected)) + } + + @Test + fun `fails a read that arrives after stop on its own server`() { + sut.start(URI) + reportServiceAdded(BluetoothGatt.GATT_SUCCESS) + val callback = serverCallback() + + sut.stop() + whenever(server.sendResponse(any(), any(), any(), any(), anyOrNull())).thenReturn(false) + readMeta(callback) + + verify(server).sendResponse(eq(device), eq(REQUEST_ID), eq(BluetoothGatt.GATT_FAILURE), eq(0), anyOrNull()) + assertEquals(1, unansweredReads()) + } + + @Test + fun `never answers a closed server's read on the new server`() { + sut.start(URI) + reportServiceAdded(BluetoothGatt.GATT_SUCCESS) + val staleCallback = serverCallback() + val newServer = mock() + whenever(newServer.addService(any())).thenReturn(true) + whenever(manager.openGattServer(any(), any())).thenReturn(newServer) + + sut.stop() + whenever(server.sendResponse(any(), any(), any(), any(), anyOrNull())).thenReturn(false) + sut.start(OTHER_URI) + readMeta(staleCallback) + + verify(server).sendResponse(eq(device), eq(REQUEST_ID), eq(BluetoothGatt.GATT_FAILURE), eq(0), anyOrNull()) + verify(newServer, never()).sendResponse(any(), any(), any(), any(), anyOrNull()) + } + + @Test + fun `clears the service before closing the server`() { + sut.start(URI) + + sut.stop() + + inOrder(server) { + verify(server).clearServices() + verify(server).close() + } + } + private companion object { const val URI = "bitcoin:bcrt1qs04g2ka4pr9s3mv73nu32tvfy7r3cxd27wkyu8" + const val OTHER_URI = "bitcoin:bcrt1qs04g2ka4pr9s3mv73nu32tvfy7r3cxd27wkyu8?amount=0.0001" + const val REQUEST_ID = 7 } } diff --git a/app/src/test/java/to/bitkit/ui/shared/effects/NearbyAdvertiseEffectTest.kt b/app/src/test/java/to/bitkit/ui/shared/effects/NearbyAdvertiseEffectTest.kt new file mode 100644 index 0000000000..bdbb54ecc6 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/shared/effects/NearbyAdvertiseEffectTest.kt @@ -0,0 +1,69 @@ +package to.bitkit.ui.shared.effects + +import android.bluetooth.BluetoothGattServer +import android.bluetooth.BluetoothManager +import android.content.Context +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.test.junit4.createComposeRule +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.kotlin.any +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@Config(sdk = [34]) +@RunWith(RobolectricTestRunner::class) +class NearbyAdvertiseEffectTest { + @get:Rule + val composeRule = createComposeRule() + + private val server = mock() + private val manager = mock() + private val context = mock() + private val uri = mutableStateOf(URI) + + @Before + fun setUp() { + whenever(context.applicationContext).thenReturn(context) + whenever(context.getSystemService(Context.BLUETOOTH_SERVICE)).thenReturn(manager) + whenever(manager.openGattServer(any(), any())).thenReturn(server) + whenever(server.addService(any())).thenReturn(true) + composeRule.setContent { + CompositionLocalProvider(LocalContext provides context) { + NearbyAdvertiseEffect(uri.value) + } + } + composeRule.waitForIdle() + } + + @Test + fun `keeps the server open when the request changes`() { + uri.value = OTHER_URI + composeRule.waitForIdle() + + verify(manager, times(1)).openGattServer(any(), any()) + verify(server, never()).close() + } + + @Test + fun `closes the server when there is nothing to offer`() { + uri.value = null + composeRule.waitForIdle() + + verify(server).close() + } + + private companion object { + const val URI = "bitcoin:bcrt1qs04g2ka4pr9s3mv73nu32tvfy7r3cxd27wkyu8" + const val OTHER_URI = "bitcoin:bcrt1qs04g2ka4pr9s3mv73nu32tvfy7r3cxd27wkyu8?amount=0.0001" + } +} diff --git a/changelog.d/next/2257.fixed.md b/changelog.d/next/2257.fixed.md new file mode 100644 index 0000000000..96526e5ebc --- /dev/null +++ b/changelog.d/next/2257.fixed.md @@ -0,0 +1 @@ +Phones reading a payment request from an Android phone over Bluetooth no longer time out until Bluetooth is turned off and on.