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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 56 additions & 30 deletions app/src/main/java/to/bitkit/nearby/NearbyAdvertiser.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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

Expand All @@ -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<BluetoothGattServer?>) =
object : BluetoothGattServerCallback() {
/** The request each payer read the meta of, so its chunks come from that request when it changes. */
private val requestsByPayer = ConcurrentHashMap<BluetoothDevice, ByteArray>()

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) }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A read already dispatched on the old server can still reach this line after close(). Android 16 then returns false without sending GATT_FAILURE. The tests verify the call, so they pass even when the response never goes out. If the connection stays up, the payer can still wait for its timeout. Could we log the failed send and check what the payer sees when Receive closes during a read? Android 16 source

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 5729094. A false return is now logged, and the tests stub it for a closed server and check the warning. What the payer sees when Receive closes mid-read needs two phones, so it's added as QA case 4 in the description.

.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) {
Expand Down Expand Up @@ -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<BluetoothGattServer?>()
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(
Expand Down
23 changes: 12 additions & 11 deletions app/src/main/java/to/bitkit/ui/shared/effects/NearbyEffects.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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()

/**
Expand Down
122 changes: 122 additions & 0 deletions app/src/test/java/to/bitkit/nearby/NearbyAdvertiserTest.kt
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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])
Expand All @@ -29,15 +38,19 @@ class NearbyAdvertiserTest {
private val advertiser = mock<BluetoothLeAdvertiser>()
private val adapter = mock<BluetoothAdapter> { on { bluetoothLeAdvertiser }.thenReturn(advertiser) }
private val server = mock<BluetoothGattServer>()
private val device = mock<BluetoothDevice>()
private val manager = mock<BluetoothManager> { on { adapter }.thenReturn(adapter) }
private val context = mock<Context> { on { getSystemService(Context.BLUETOOTH_SERVICE) }.thenReturn(manager) }
private var failures = 0
private lateinit var sut: NearbyAdvertiser

@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++ }
}

Expand All @@ -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()
Expand Down Expand Up @@ -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))
Comment thread
ovitrif marked this conversation as resolved.
Resolved
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<BluetoothGattServer>()
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
}
}
Loading