Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
86 commits
Select commit Hold shift + click to select a range
40b2a25
feat: nfc and bluetooth nearby payments
jvsena42 Nov 12, 2026
3e377fb
chore: rename changelog fragment
jvsena42 Nov 12, 2026
28639c4
fix: address review of nfc and bluetooth nearby payments
jvsena42 Nov 12, 2026
1dffebb
test: add Square and Numo NFC regression tests
jvsena42 Nov 12, 2026
be3d4b7
chore: merge master into feat/nfc-payments
jvsena42 Nov 16, 2026
a22544e
fix: hold nfc reader mode until a read tag leaves the field
jvsena42 Nov 16, 2026
2336ef1
fix: skip the channel wait when spark covers the payment
jvsena42 Nov 16, 2026
4f85528
chore: merge master into feat/nfc-payments
jvsena42 Nov 16, 2026
4d5af84
fix: keep bip 321 uris with required params unrewritten
jvsena42 Nov 16, 2026
82f44a4
fix: filter nearby requests after rewriting them
jvsena42 Nov 16, 2026
d88da7f
fix: stop offering a receive request the qr no longer shows
jvsena42 Nov 16, 2026
b373d5b
fix: treat phones that cannot advertise as without bluetooth
jvsena42 Nov 16, 2026
49538ae
fix: name the scanner source buttons for talkback
jvsena42 Nov 16, 2026
c37460c
fix: open app settings once nearby permission is blocked
jvsena42 Nov 16, 2026
c06c3b7
fix: keep bip 321 uris with empty required params
jvsena42 Nov 16, 2026
943e052
fix: keep the channel wait while the node runs
jvsena42 Nov 16, 2026
9e09c6b
chore: merge master into feat/nfc-payments
jvsena42 Nov 16, 2026
71680fc
fix: refresh channels without waiting when spark covers the send
jvsena42 Nov 16, 2026
f67cde8
fix: drop a nearby read on enter manually
jvsena42 Nov 16, 2026
34f2559
fix: rewrite bip 321 requests from nfc tag launches
jvsena42 Nov 16, 2026
4f16c11
fix: stop serving a selected tag once receive closes
jvsena42 Nov 16, 2026
a88e203
fix: keep nearby scan cancellable after a duplicate read
jvsena42 Nov 17, 2026
3a21060
fix: drop an in-flight nfc read on enter manually
jvsena42 Nov 17, 2026
d9c4ede
Merge remote-tracking branch 'origin/master' into feat/nfc-payments
jvsena42 Nov 17, 2026
869b45f
fix: drop a decoding nearby read when contacts opens
jvsena42 Nov 17, 2026
5ca051c
fix: ignore an nfc read that finishes after the scanner closes
jvsena42 Nov 17, 2026
24180fd
fix: drop nfc reads that finish after the reader pauses
jvsena42 Nov 17, 2026
a3496bf
fix: retry a nearby phone after its request is rejected
jvsena42 Nov 17, 2026
483562d
chore: translate scanner bluetooth and nfc button labels
jvsena42 Nov 17, 2026
79e9f71
fix: bind each nfc reader callback to its activation
jvsena42 Nov 17, 2026
baeab2d
fix: drop the tap label when nearby advertising fails
jvsena42 Nov 17, 2026
965ff98
fix: ignore advertising failures from a stopped start
jvsena42 Nov 17, 2026
0ccac85
fix: cancel a nearby read still preparing when send closes
jvsena42 Nov 20, 2026
4098e78
fix: keep a bluetooth read from replacing the chosen request
jvsena42 Nov 20, 2026
adbcb2b
fix: keep nearby payments off until the saved setting loads
jvsena42 Nov 20, 2026
ba4d982
fix: offer only the arbitrum usdt request nearby
jvsena42 Nov 20, 2026
fe7e30a
fix: stop accepting bolt12 offers from nearby devices
jvsena42 Nov 20, 2026
933f9ae
fix: keep a bip 321 uri that repeats a single parameter
jvsena42 Nov 20, 2026
32e1fb5
fix: refuse a bluetooth unified uri carrying an lnurl
jvsena42 Nov 20, 2026
84a88d0
fix: read nearby payments only on payment scanners
jvsena42 Nov 20, 2026
5d8e5e8
fix: advertise only after the gatt service registers
jvsena42 Nov 20, 2026
35fef0d
fix: drop the tap label when the nfc tag fails to register
jvsena42 Nov 20, 2026
7d2391f
fix: engage the nfc repeat guard only for the open reader
jvsena42 Nov 20, 2026
88ff9a8
fix: pause nearby payments behind the connection issues screen
jvsena42 Nov 20, 2026
7263458
fix: keep a bip 321 uri that repeats any parameter
jvsena42 Nov 20, 2026
2431c1b
fix: keep a bip 321 uri whose amount its invoice does not carry
jvsena42 Nov 20, 2026
abc4ca5
fix: cancel a send scanner read still preparing when send closes
jvsena42 Nov 23, 2026
cb0d92d
fix: skip quickpay for a scan that was preparing when the wallet locked
jvsena42 Nov 23, 2026
30fb75c
fix: check every lightning value of a bluetooth unified uri
jvsena42 Nov 23, 2026
f949c6f
fix: allow a bip 321 uri to repeat an optional parameter
jvsena42 Nov 23, 2026
fdd56de
fix: unwrap a bip 321 uri only when its amount is plain decimal
jvsena42 Nov 23, 2026
f14fb29
fix: accept only a bolt11-shaped invoice from nearby devices
jvsena42 Nov 23, 2026
3efaa56
fix: keep the first bluetooth read while its request prepares
jvsena42 Nov 23, 2026
973f81d
fix: release the nfc aid when the preferred service is refused
jvsena42 Nov 23, 2026
be73063
fix: list no nearby source on a scanner while nearby is paused
jvsena42 Nov 23, 2026
a7298df
fix: keep a send scanner read that closes send itself running
jvsena42 Nov 23, 2026
a9e2d7e
fix: recheck the wallet lock right before quickpay starts
jvsena42 Nov 23, 2026
b646b95
fix: count the background lock for scans still preparing
jvsena42 Nov 23, 2026
6832a63
test: cover a contact scanned from the send scanner
jvsena42 Nov 23, 2026
b9af9cd
fix: refuse a nearby request with a required bip 321 parameter
jvsena42 Nov 23, 2026
e7b8edc
docs: keep the bip 321 amount note above its regex
jvsena42 Nov 23, 2026
70e40e8
fix: check the wallet lock where quickpay starts paying
jvsena42 Nov 23, 2026
233f7f3
fix: refuse a required parameter only on a bitcoin uri
jvsena42 Nov 23, 2026
24c644a
fix: check a wrapped bitcoin request for required parameters
jvsena42 Nov 23, 2026
e690388
fix: check a request behind every wrapper for required parameters
jvsena42 Nov 23, 2026
3915f55
fix: refuse a req- key behind an inner bitkit:// scheme
jvsena42 Nov 23, 2026
535efc4
fix: repeat the bitkit:// deletion as the decoder does
jvsena42 Nov 23, 2026
13f9951
fix: recheck quickpay authorization at first submission
jvsena42 Nov 24, 2026
3084ff3
fix: validate the amount when quickpay falls back
jvsena42 Nov 24, 2026
2a45117
fix: delete bitkit:// only while the request starts with it
jvsena42 Nov 24, 2026
c7e0f5d
fix: keep a bip 321 request with an empty amount
jvsena42 Nov 24, 2026
cfead7f
test: verify quickpay forwards its dispatch check
jvsena42 Nov 24, 2026
70bd2a7
fix: trim nfc requests like the decoder before the req- check
jvsena42 Nov 24, 2026
d8a0dae
chore: merge master into feat/nfc-payments
jvsena42 Nov 24, 2026
592203d
fix: check quickpay authorization on the ldk queue
jvsena42 Nov 24, 2026
f0a9f3f
fix: keep a fixed invoice payable after quickpay falls back
jvsena42 Nov 24, 2026
cafc812
fix: delete only lowercase bitkit:// like the decoder
jvsena42 Nov 24, 2026
3ae50d7
fix: forget an ldk send stopped before submission
jvsena42 Nov 24, 2026
23ec7a1
fix: require a valid bolt11 checksum over bluetooth
jvsena42 Nov 24, 2026
92d42f9
fix: refuse a nearby bitcoin uri without an address
jvsena42 Nov 24, 2026
6a97430
fix: forget only the stopped send's own ldk records
jvsena42 Nov 24, 2026
fa0ebe8
revert: keep the ldk send record of a stopped send
jvsena42 Nov 24, 2026
7dcc947
fix: validate a nearby bitcoin address before scanning it
jvsena42 Nov 24, 2026
dcabb9d
fix: validate nearby addresses like the decoder and for this network
jvsena42 Nov 24, 2026
bca0fa0
chore: merge master into feat/nfc-payments
jvsena42 Nov 24, 2026
7ebf6ef
docs: list the requests bluetooth accepts in nearby payments
jvsena42 Nov 25, 2026
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
Original file line number Diff line number Diff line change
Expand Up @@ -61,5 +61,5 @@ private val FAMILIES: List<SheetDeepLinkFamily> = listOf(
private val STANDALONE: List<Sheet> = listOf(
Sheet.ActivityDateRangeSelector,
Sheet.ActivityTagSelector,
Sheet.QrScanner(),
Sheet.QrScanner(readsNearby = true),
)
23 changes: 23 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />

<!-- NFC payments: reading payment tags and offering the Receive request as a tag -->
<uses-permission android:name="android.permission.NFC" />
<uses-feature
android:name="android.hardware.nfc"
android:required="false" />
<uses-feature
android:name="android.hardware.nfc.hce"
android:required="false" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission
android:name="android.permission.FOREGROUND_SERVICE"
Expand All @@ -32,6 +41,8 @@

<!-- Bluetooth permissions for hardware wallets (Trezor Safe 7, Blockstream Jade) on Android 12+ -->
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<!-- Nearby payments: advertising the Receive request to nearby Bitkit wallets -->
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN"
android:usesPermissionFlags="neverForLocation"
tools:targetApi="s" />
Expand Down Expand Up @@ -71,6 +82,18 @@
android:enabled="true"
android:exported="false" />

<service
android:name=".androidServices.NdefTagService"
android:exported="true"
android:permission="android.permission.BIND_NFC_SERVICE">
<intent-filter>
<action android:name="android.nfc.cardemulation.action.HOST_APDU_SERVICE" />
</intent-filter>
<meta-data
android:name="android.nfc.cardemulation.host_apdu_service"
android:resource="@xml/ndef_tag_service" />
</service>

<service
android:name="androidx.appcompat.app.AppLocalesMetadataHolderService"
android:enabled="false"
Expand Down
24 changes: 24 additions & 0 deletions app/src/main/java/to/bitkit/androidServices/NdefTagService.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package to.bitkit.androidServices

import android.nfc.cardemulation.HostApduService
import android.os.Bundle
import to.bitkit.nfc.NfcTagEmitter
import to.bitkit.nfc.Type4TagEmulator

/**
* Presents the Receive screen's payment request as an NFC Forum Type 4 tag, so another phone
* or a point of sale reads it like any NDEF tag. It answers only while [NfcTagEmitter] holds a
* request, which the Receive screen publishes while it is in the foreground.
*/
class NdefTagService : HostApduService() {
private val emulator = Type4TagEmulator(NfcTagEmitter::currentMessage)

override fun processCommandApdu(commandApdu: ByteArray?, extras: Bundle?): ByteArray {
val apdu = commandApdu ?: return Type4TagEmulator.SW_WRONG_LENGTH
return emulator.process(apdu)
}

override fun onDeactivated(reason: Int) {
emulator.reset()
}
}
2 changes: 2 additions & 0 deletions app/src/main/java/to/bitkit/data/SettingsStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,8 @@ data class SettingsData(
val publicPaykitBolt11PaymentHash: String = "",
val publicPaykitBolt11ExpiresAtMillis: Long = 0,
val quickPayIntroSeen: Boolean = false,
val nfcIntroSeen: Boolean = false,
val isNearbyPaymentsEnabled: Boolean = true,
val bgPaymentsIntroSeen: Boolean = false,
val isQuickPayEnabled: Boolean = false,
val quickPayAmount: Int = 5,
Expand Down
2 changes: 2 additions & 0 deletions app/src/main/java/to/bitkit/models/QrCodePayload.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@ package to.bitkit.models
data class QrCodePayload(
val text: String?,
val rawBytes: ByteArray?,
/** Read from a nearby device over Bluetooth, which QuickPay must not pay without review. */
val isNearby: Boolean = false,
)
169 changes: 169 additions & 0 deletions app/src/main/java/to/bitkit/nearby/NearbyAdvertiser.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
package to.bitkit.nearby

import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattServer
import android.bluetooth.BluetoothGattServerCallback
import android.bluetooth.BluetoothGattService
import android.bluetooth.le.AdvertiseCallback
import android.bluetooth.le.AdvertiseData
import android.bluetooth.le.AdvertiseSettings
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.ParcelUuid
import androidx.annotation.RequiresPermission
import to.bitkit.ext.bluetoothManager
import to.bitkit.utils.Logger

/**
* Serves one payment request to nearby Bitkit wallets: a GATT server with the nearby service and a
* connectable advertisement carrying only the service UUID. Advertising starts once Android confirms the
* service is registered, so a payer never finds a phone it cannot read. [start] and [stop] run on the main thread.
*/
class NearbyAdvertiser(
private val context: Context,
private val onFailed: () -> Unit = {},
) {
private val bluetoothManager = context.bluetoothManager

@Volatile
private var request: ByteArray? = null
private var gattServer: BluetoothGattServer? = null
private var advertiseCallback: AdvertiseCallback? = null
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. */
private var serverGeneration = 0
private var isServiceRegistered = false

/** A new callback per start, so a failure reported after [stop] or a later start is ignored. */
private fun newAdvertiseCallback(): AdvertiseCallback = object : AdvertiseCallback() {
override fun onStartFailure(errorCode: Int) {
Logger.warn("Failed nearby advertising with error '$errorCode'", context = TAG)
if (advertiseCallback !== this) return
advertiseCallback = null
onFailed()
}
}

private fun newServerCallback(generation: Int) = object : BluetoothGattServerCallback() {
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 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)
}
}
}

@RequiresPermission(allOf = [Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_ADVERTISE])
fun start(uri: String) {
val encoded = NearbyProtocol.encodeRequest(uri) ?: return stop()
request = encoded
if (gattServer == null) gattServer = openServer() ?: return onFailed()
if (isServiceRegistered && !isAdvertising) startAdvertising()
}

// start() holds both permissions, and this runs only for the server it opened.
@SuppressLint("MissingPermission")
private fun onServiceRegistered(generation: Int, isRegistered: Boolean) {
if (generation != serverGeneration || gattServer == null) return
if (!isRegistered) {
Logger.warn("Failed to register the nearby GATT service", context = TAG)
stop()
onFailed()
return
}
isServiceRegistered = true
if (request != null && !isAdvertising) startAdvertising()
}

@RequiresPermission(allOf = [Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_ADVERTISE])
fun stop() {
request = null
advertiseCallback?.let { callback ->
runCatching { bluetoothManager.adapter?.bluetoothLeAdvertiser?.stopAdvertising(callback) }
}
advertiseCallback = null
runCatching { gattServer?.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)) }
.onFailure { Logger.warn("Failed to open nearby GATT server", it, context = TAG) }
.getOrNull() ?: return null
val service = BluetoothGattService(NearbyProtocol.SERVICE_UUID, BluetoothGattService.SERVICE_TYPE_PRIMARY)
(listOf(NearbyProtocol.META_UUID) + NearbyProtocol.DATA_UUIDS).forEach {
service.addCharacteristic(
BluetoothGattCharacteristic(
it,
BluetoothGattCharacteristic.PROPERTY_READ,
BluetoothGattCharacteristic.PERMISSION_READ,
)
)
}
if (!runCatching { server.addService(service) }.getOrDefault(false)) {
Logger.warn("Failed to add the nearby GATT service", context = TAG)
runCatching { server.close() }
return null
}
return server
}

@RequiresPermission(Manifest.permission.BLUETOOTH_ADVERTISE)
private fun startAdvertising() {
val advertiser = bluetoothManager.adapter?.bluetoothLeAdvertiser ?: return onFailed()
val settings = AdvertiseSettings.Builder()
.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_LOW)
.setConnectable(true)
.build()
val data = AdvertiseData.Builder()
.setIncludeDeviceName(false)
.setIncludeTxPowerLevel(false)
.addServiceUuid(ParcelUuid(NearbyProtocol.SERVICE_UUID))
.build()
val callback = newAdvertiseCallback()
advertiseCallback = callback
runCatching { advertiser.startAdvertising(settings, data, callback) }
.onFailure {
advertiseCallback = null
Logger.warn("Failed to start nearby advertising", it, context = TAG)
onFailed()
}
}

private companion object {
const val TAG = "NearbyAdvertiser"
}
}
58 changes: 58 additions & 0 deletions app/src/main/java/to/bitkit/nearby/NearbyProtocol.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package to.bitkit.nearby

import java.util.UUID

/**
* Bitkit nearby payments over Bluetooth LE, version 1. See docs/nearby-payments.md.
*
* The receiving phone serves its payment request from a GATT service; a paying phone reads the
* meta characteristic for the length and then as many 512-byte data chunks as it needs.
*/
object NearbyProtocol {
val SERVICE_UUID: UUID = UUID.fromString("CB0E128B-1CA5-4959-94DF-A4FE588E3E98")
val META_UUID: UUID = UUID.fromString("69A713E5-B0A7-42F1-8B7F-FA0BDA119C00")
val DATA_UUIDS: List<UUID> = (1..CHUNK_COUNT).map {
UUID.fromString("69A713E5-B0A7-42F1-8B7F-FA0BDA119C%02X".format(it))
}

const val VERSION: Byte = 0x01
const val CHUNK_SIZE = 512
const val CHUNK_COUNT = 8
const val MAX_REQUEST_BYTES = CHUNK_SIZE * CHUNK_COUNT
const val MIN_RSSI = -60

/** The request as served, or null when it is empty or too large to serve. */
fun encodeRequest(request: String): ByteArray? {
val bytes = request.toByteArray(Charsets.UTF_8)
return bytes.takeIf { it.isNotEmpty() && it.size <= MAX_REQUEST_BYTES }
}

fun meta(request: ByteArray): ByteArray =
byteArrayOf(VERSION, (request.size shr 8).toByte(), request.size.toByte())

/** Chunk [index] of [request]; empty past the end of the request. */
fun chunk(request: ByteArray, index: Int): ByteArray {
val start = index * CHUNK_SIZE
if (index !in 0 until CHUNK_COUNT || start >= request.size) return byteArrayOf()
return request.copyOfRange(start, minOf(request.size, start + CHUNK_SIZE))
}

/** The request length announced by [meta], or null for an unknown version or bad length. */
fun requestLength(meta: ByteArray): Int? {
if (meta.size < 3 || meta[0] != VERSION) return null
val length = ((meta[1].toInt() and 0xFF) shl 8) or (meta[2].toInt() and 0xFF)
return length.takeIf { it in 1..MAX_REQUEST_BYTES }
}

fun chunksFor(length: Int): Int = (length + CHUNK_SIZE - 1) / CHUNK_SIZE

/** Value served for a read at [offset] of a characteristic whose full value is [value]. */
fun readAt(value: ByteArray, offset: Int): ByteArray? =
if (offset in 0..value.size) value.copyOfRange(offset, value.size) else null

fun decode(chunks: List<ByteArray>, length: Int): String? {
val bytes = chunks.fold(byteArrayOf()) { acc, chunk -> acc + chunk }
if (bytes.size != length) return null
return bytes.toString(Charsets.UTF_8).trim().takeIf { it.isNotEmpty() }
}
}
Loading
Loading