Repository navigation
Conversation
Payment scanners read requests from NFC tags (reader mode) and from nearby Bitkit wallets over Bluetooth LE. The Receive screen offers its request as an emulated NFC Forum Type 4 tag and over a BLE GATT service while it is on screen. Adds the TapPay (NFC) intro sheet, the scanner source states from Figma and a Nearby payments setting. Protocol in docs/nearby-payments.md. Refs #1740 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Regtest APKDownload bitkit-dev-debug universal APK (expires in 30 days). |
- Accept only bitcoin:, lightning: invoice/offer and ethereum: requests over Bluetooth; skip the device otherwise. - Stop offering and listening while the app is locked. - Show the Scan to pay panel on every payment scanner when the camera is denied. - Android 9-11: report location services off for scanning, and advertise without the location permission. - Recreate the scanner/advertiser when Bluetooth or location is switched. - Keep scanning after a delivered request, retry failed scans, and ignore callbacks from stale read sessions. - Register the NDEF tag AID only while Receive is shown and present no tag when nothing is published; owner tokens for the emitter and reader mode. - Translations, journeys, and repo conventions (nowMillis, Duration, Context.bluetoothManager, narrow lint suppressions, log wording). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Square Register serves lightning:<uppercase BOLT11> as a long-format NDEF URI record; Numo serves BIP 321 without an address. Add a real 447-char signet fixture and tests for record decoding, byte-exact encoding, chunked tag reads and the Bluetooth allowlist. bitkit-core rejects bitcoin:?lightning=<invoice> (synonymdev/bitkit-core#212), so requests read over NFC or Bluetooth are rewritten to lightning:<invoice>. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
# Conflicts: # app/src/main/java/to/bitkit/ui/settings/SettingsScreen.kt
[High impact] The latest change appears safe to merge and fixes the old advertising-failure callback problem. SummaryAdds NFC and Bluetooth nearby payments. The latest change prevents an old Bluetooth advertising failure from stopping a newer request.
DiagramsequenceDiagram
participant Receive
participant Advertiser
participant Bluetooth
Receive->>Advertiser: Start request
Advertiser->>Bluetooth: Start with callback A
Receive->>Advertiser: Stop or replace request
Advertiser->>Bluetooth: Stop callback A
Advertiser->>Advertiser: Clear current callback
Bluetooth-->>Advertiser: Late failure for callback A
Advertiser->>Advertiser: Ignore old callback
Reviews (13) · Last reviewed commit: "fix: ignore advertising failures from a ..." · Reviewed by Greptile |
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
talosmachina
left a comment
There was a problem hiding this comment.
1 finding (1 P1). Adds NFC reading on the payment scanners, HCE Type 4 tag emulation on Receive, and a BLE GATT request exchange between Bitkit phones. Reviewed 4d5af8435, oversized tier (65 files, about 3,000 lines): I read the security-relevant paths in full (the NFC and Bluetooth transport, the request filter and rewrite, the QuickPay suppression plumbing into AppViewModel, the manifest and HCE service) and did not review the UI, sheet, string and resource changes.
- P1: the Bluetooth payment-only filter is applied before the
bitcoin:?lightning=rewrite, so LNURL auth, withdraw and channel requests from any nearby advertiser reach their sheets.
Build: not built here. This review answers in public, where no packages token is available for the Gradle build, so CI is the gate. At the time of review build reported failure because its upstream jobs were cancelled (BUILD_RESULT: cancelled), and build-and-test, compose-ui / ui-tests and lint were still pending, so CI says nothing yet either way.
What I checked, and 6 candidates I ruled out
Read in full: NearbyScanner.kt, NearbyAdvertiser.kt, NearbyProtocol.kt, NearbyRequestFilter.kt, NfcPaymentUri.kt, NdefCodec.kt, Type4TagEmulator.kt, NfcTagEmitter.kt, NfcRepeatGuard.kt, NdefTagService.kt, NfcEffects.kt, NearbyEffects.kt, NearbyScanSources.kt, the AppViewModel diff and the launchScan/handleScan/handleDecodedScan path, MainActivity diff, manifest and ndef_tag_service.xml.
Ruled out
- HCE serving while locked or off-screen:
requireDeviceUnlock="true", the AID is registered only while Receive is resumed,offerPaymentNearbydrops the URI whileLocalIsAppLocked, and the emulator answers SELECT with 6A82 when nothing is published. - Stale publisher clearing a newer request:
NfcTagEmitter.clearis token-checked with compare-and-set;NfcTagEmitterTestcovers it. - NDEF parser out-of-bounds on a hostile tag: every read is inside
runCatchingindecodeTexts, and a negative long length is rejected. - BLE read overflow or wrong reassembly: length capped at 4,096 bytes by
requestLength,decoderejects a size mismatch, each session has an 8 s timeout. - QuickPay on a Bluetooth read:
isNearbyreachessuppressQuickPayon all three scanner routes (SendRecipientScreen,QrScanningSheet,SendSheetQR route); the USDT scanner goes to its own recipient path, which has no QuickPay. - Channel-wait skip paying through the wrong rail:
waitForUsableChannelsnow skips only whencanSendWithSpark(amount)is true, and the followingcanSendcheck is unchanged. - Cold reader: the P1 stood (traced the same chain to
onScanLnurlAuth).
Merge confidence: 3/5, the oversized tier caps it there, and the open P1 on the Bluetooth filter would hold it at 3 on its own.
Reviewer model: claude-opus-5-5, xiaomi/mimo-v2.6-pro (cold reader)
Reasoning effort: Not exposed (the run metadata carries no effort setting for either)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
piotr-iohk
left a comment
There was a problem hiding this comment.
QA review
Scope: Full reassessment of bitkit-android#1883 at 5ca051cf. The PR base and merge base are both 5fa540e9. No coverage baseline was supplied, so inherited coverage is empty.
2 actionable findings — resolve or provide an evidence-backed rebuttal.
The usable-channel wait now applies to every lightning scan. When Spark can pay and the node is stopped, the wait is skipped. When the node is running, current channels are still published before the spending limit is read. AppViewModelSendFlowTest covers those branches; this review inspected those tests and did not run them.
Parity used bitkit-ios#1302 at 6451b282 for the shared nearby protocol and scanner behavior. Service UUIDs, 512-byte chunks, the -60 dBm threshold, and Bluetooth QuickPay suppression match. iOS accepts lnurlp: over Bluetooth after decoding; Android's allowlist refuses every LNURL, including LNURL-pay, and NearbyRequestFilterTest locks that refusal.
Device testing: not performed in this review.
Validation: source inspection of the pinned diff. Unit tests were read, not executed. No emulator or device was started.
Suggested additional test cases
-
Android. Two phones with Bluetooth allowed, Send open on phone B's recipient camera. Phone A advertises an expired lightning invoice, then replaces it with a payable invoice. B reads the first invoice and the expired-invoice toast appears. Expected: within about 10 seconds B reads A's new invoice without leaving the scanner.
-
Android. The node is running and the Spark balance covers a lightning invoice. Pay that invoice. Expected: the next send's spending limit uses the updated channel outbound, since a Spark-covered scan publishes channels without waiting for a usable one.
Earlier findings reconciled at this revision: 2 still present, 10 verified fixed.
Findings
- [MEDIUM] Retry a Bluetooth phone after its request is rejected — inline at
app/src/main/java/to/bitkit/nearby/NearbyScanner.kt:129. - [LOW] Translate the scanner Bluetooth and NFC button labels — inline at
app/src/main/res/values/strings.xml:645.
Existing concerns
- [MEDIUM] Drop an NFC read that finishes after the scanner pauses — The thread #1883 (comment) is marked resolved. The author fixed the two cases stated there: Contacts cancels a decode that is already stored, and NfcReadDispatcher drops a result posted after onDispose. The follow-up at #1883 (comment), on this head, and the review #1883 (review) describe the remaining window. ON_PAUSE disables reader mode and leaves the dispatcher open until disposal. The Send recipient exit keeps the composable up for the 300ms transition, so a ReaderCallback already reading a tag can post AddressContinue after Contacts or Enter Manually has cancelled the previous job. That new scan is not cancelled. NFC deliveries use suppressQuickPay false, so handleQuickPayIfApplicable can still take an eligible invoice (AppViewModel.kt:6639). ovi-reviewer reports that releasing a raw completion on the recipient ON_PAUSE, before disposal, opened Bitcoin Amount over Contact selection at 5ca051c. This reconciliation did not run that device check. No matching GitHub issue was found.
- [LOW] Receive tap label follows adapter state after advertising fails to start — The thread is marked resolved. The hardware half is fixed: bluetoothState returns UNAVAILABLE for the advertise role when isMultipleAdvertisementSupported is false (NearbyEffects.kt:77), so Receive does not claim Bluetooth on a phone that cannot advertise. The runtime half is unchanged. onStartFailure sets isAdvertising false and logs, and offerPaymentNearby still returns whether NFC emulation or the preflight advertise state is available. With NFC off, a failed start leaves the tap label up. The author left that path unchanged in #1883 (comment) as a rare transient, and #1883 (comment) kept the narrowed label issue. No matching GitHub issue was found. This pass only re-read the current source.
Reviewer model: grok-4.7
Reasoning effort: xhigh
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
piotr-iohk
left a comment
There was a problem hiding this comment.
QA review
Scope: Follow-up at 483562df, covering the three commits since 5ca051cf. Inherited baseline: previous QA review. The merge base is unchanged at 5fa540e9, and the pull request still touches the same 71 paths.
No new actionable code findings.
Pausing or leaving an NFC scanner invalidates that reader activation. A tag read that captured the previous activation is dropped, including when it finishes after the scanner resumes. NfcReadDispatcherTest covers that rule, and NfcReaderEffect invalidates from disable() on pause and dispose.
A nearby phone is skipped for 10 seconds after every completed read, then can be read again while the scanner stays open. That retries a request the screen rejected without leaving, such as an expired invoice or a non-USDT request on the USDT scanner. An accepted request leaves the scanner, which stops scanning; while the first scan job is still running, the same request is ignored as a duplicate. On bitkit-ios#1302 at d1d63897, scanning resumes only when the request was not taken, with the same 10-second per-phone debounce. That iOS revision differs from the baseline comparison 6451b282 only by button-label translations. iOS NFC reads are a user-started session, so they do not use this pause generation.
other__bluetooth_enable and other__nfc_enable each appear once in the default strings and in all 15 locales, as the TalkBack labels on the scanner enable buttons.
Validation: Inspected the delta, its callers, and NfcReadDispatcherTest. The unit suite was not run locally. On this revision, build-and-test and detekt succeeded.
Device testing: not performed in this review.
Suggested additional test cases
- Android, two phones, Bluetooth on. A shows an expired Lightning invoice on Receive, or a Lightning request while B is on the USDT send scanner. B stays on the scanner and shows the error. Keep the phones within range. Expected: about 10 seconds later B reads A again.
- Android, NFC on. On B's Send scanner, start a tag or phone-A read and open Contacts before it finishes. Expected: no payment opens over Contacts, including if the read completes after B returns to the scanner. After the tag leaves, a new tap is read.
- Android, two phones, Bluetooth on. B reads A's valid invoice and the review opens. Leave the phones together. Expected: B stays on that one review and does not open a second payment.
Earlier findings reconciled at this revision: 1 still present, 13 verified fixed.
Existing concerns
- [LOW] Receive tap label follows adapter state after advertising fails to start — The runtime start-failure path is still present. The thread is marked resolved. The author fixed only the deterministic hardware case: advertise-role Bluetooth state is UNAVAILABLE when isMultipleAdvertisementSupported is false. An advertising start that fails later still does not change the label. offerPaymentNearby sets canAdvertise from the nearby setting and BluetoothState.ON, starts NearbyAdvertiseEffect from that flag, and returns whether NFC emission or that preflight is active. NearbyAdvertiser.onStartFailure sets the private isAdvertising flag to false and logs. Nothing outside NearbyAdvertiser reads that flag. ReceiveQrScreen uses the returned boolean as canTapToPay and shows wallet__receive_scan_or_tap while it is true. With NFC off, a failed Bluetooth advertise start would leave that label up. A focused issue search for onStartFailure, offerPaymentNearby, and isMultipleAdvertisementSupported in synonymdev/bitkit-android returned no issues. At bitkit-ios d1d638977a45a8c910767f61d7a154682e330c8a, ReceiveQr.swift:428 and :452 pass nearbyAdvertiser.isAdvertising into showsTapToPay.
Reviewer model: grok-4.7
Reasoning effort: xhigh
There was a problem hiding this comment.
Verdict: ⛔️ Request changes — a callback that first starts after NFC reader disposal can still replace manual entry.
Findings:
- MEDIUM — Keep disposed NFC readers closed to late callbacks.
app/src/main/java/to/bitkit/ui/shared/effects/NfcEffects.kt:104: The callback capturesdispatcher.activationwhen it starts.disable()increments that number, and disposal no longer permanently closes the dispatcher. Android can retain the callback before reader mode is disabled and invoke it afterward; that old callback then captures the new number and passes the delivery check. With Enter Manually already selected, this starts a new scan after cancellation. I reproduced the schedule at this head by holding raw callback entry until after disposal: it captured activation 2 and replaced typed manual input with Bitcoin Amount. The captured-before-pause and captured-before-disposal controls now pass. Bind delivery to the activation that registered the callback and reject callbacks once its effect is disposed. Android’s callback dispatch copies the callback under its lock and invokes it outside that lock, so disabling reader mode does not revoke a reference already copied.
QA for 483562d:
Built regtest devDebug from 483562d with the shipped bitkit-core 0.8.0-rc15. Device checks used Android 16 emulators. NFC timing checks used the debug-only raw callback hook below; Bluetooth used the real GATT link. The funded confirmation check used an ordinary Receive invoice. No payment was submitted.
Drop an NFC read when Contacts pauses the scanner ✅ A read captured before pause completed during the exit transition and was dropped; Select Contact remained.
The read captured activation 0 before Contacts. Its completion arrived after the real ON_PAUSE and before disposal, and no new address scan started. This repeats the previously failing transition window. Physical tag reading was not exercised.
nfc-paused.2x.mp4
Drop an old NFC read after the scanner resumes ✅ The old activation result was dropped after resume; a new activation then decoded the same request and opened Bitcoin Amount.
After backgrounding and resuming the scanner, the held old activation opened nothing. A new read in the resumed activation then opened Bitcoin Amount. These are raw callback completions, not hardware NFC taps.
nfc-resumed.2x.mp4
Drop an NFC read completed after the scanner closes ✅ A read captured before disposal was dropped afterward and manual input remained.
The read captured its activation before Enter Manually and completed after disposal. The dispatcher dropped it and the typed placeholder remained.
nfc-disposed.2x.mp4
Drop an NFC callback delayed until after the scanner closes ❌ A callback queued before exit but started after disposal captured activation 2 and replaced manual entry with Bitcoin Amount.
The callback was retained before leaving, but its entry was held before the production activation capture. After Enter Manually and disposal, release captured activation 2 and started a fresh address scan, replacing the typed input with Bitcoin Amount. Logcat establishes disposal before callback entry. This exercises the framework-permitted schedule described in the finding; it does not establish its frequency on physical NFC hardware.
nfc-late-entry.2x.mp4
Reject an expired Bluetooth invoice ✅ A signed expired regtest invoice arrived over Bluetooth, showed the expired-invoice toast and closed Send.
A signed expired regtest invoice was served by the prepared-payload peer. The requested expired-then-valid scenario cannot stay on this Send scanner: the unchanged clearIncomingPaymentRequestTarget closes Send on expiry. The in-place retry is verified on the USDT scanner below.
bt-expired.2x.mp4
Read a corrected USDT request from the same Bluetooth phone ✅ USDT scanner rejected a Bitcoin request and stayed open; the same peer delivered a corrected ERC-681 USDT request 10.7 seconds later and opened amount entry.
The same peripheral delivered the Bitcoin request and then ethereum:<USDT contract>@42161/transfer?address=<recipient> 10.7 seconds later. The first produced the address error while scanning stayed active; the second opened Amount. Delivery logs confirm both payloads and the same peripheral. The peer’s QR remains its ordinary Bitcoin QR because only its Bluetooth payload was overridden. Left: advertising peer; right: payer.
bt-usdt.2x.mp4
Keep manual entry after an automatic duplicate Bluetooth read ✅ An automatic Bluetooth reread reached the duplicate guard while the real decode was held; Enter Manually cancelled the original job and typed input remained.
The same peripheral delivered the held invoice again automatically after the retry interval. Logcat confirms the duplicate skip and cancellation of the original job. The deliberately invalid typed placeholder produces its ordinary Decoding Error toast; it remains on screen after the invoice hold is released. Left: advertising peer; right: payer.
bt-duplicate.2x.mp4
Keep one review open while the Bluetooth phone remains nearby ✅ A funded 1,000-sat Bluetooth request opened Review and stayed on that same review for 15 seconds, with only one delivery logged.
This covers the additional accepted-request check. The payer had a funded Spark spending balance. The 1,000-sat invoice opened Review and stayed there for 15 seconds while the peer kept Receive open. Logcat contains one delivery; Bluetooth inspection confirms the scanner stopped. Left: receiver; right: payer.
bt-single-review.2x.mp4
Check: Run NFC and nearby regression checks ✅ Pinned-head NFC, nearby and send-flow regression selection passed.
Ran assembleDevDebug and testDevDebugUnitTest for to.bitkit.nfc.*, to.bitkit.nearby.* and AppViewModelSendFlowTest against the unmodified pinned-head application before adding hooks. The activation, normalization, protocol and send-cancellation regressions passed. Both newly translated keys are present in every non-English resource file, checked from the parsed XML.
Read an Android Receive invoice over NFC ⏭️ Not run: No connected NFC-capable Android test pair; device discovery found none. Callback injection cannot prove tag exchange.
PR manual case 1.
Pay a small NFC request with QuickPay ⏭️ Not run: No connected NFC-capable Android test pair; no physical current-head QuickPay payment was driven.
PR manual case 1a.
Review a large NFC request ⏭️ Not run: No connected NFC-capable Android test pair to test a request above the QuickPay threshold.
PR manual case 1b.
Read Lightning Bitcoin and LNURL-pay tags ⏭️ Not run: No connected NFC-capable Android reader or written Lightning, Bitcoin and LNURL-pay tags.
PR manual case 2.
Read a USDT request over NFC ⏭️ Not run: No connected NFC-capable Android pair for USDT tag exchange.
PR manual case 3.
Reject a non-payment NFC tag ⏭️ Not run: No connected NFC-capable Android reader or non-payment NFC tag.
PR manual case 4.
Exchange Bluetooth requests with iPhone ⏭️ Not run: No physical Android/iPhone test pair is available; no physical Android test phone is connected. Simulators cannot establish Bluetooth interoperability.
PR manual case 7.
Read Android Receive with iPhone NFC ⏭️ Not run: No physical NFC-capable Android/iPhone test pair; no physical Android test phone is connected.
PR manual case 8.
Show the introduction on an NFC phone ⏭️ Not run: Physical NFC eligibility needs an NFC-capable Android phone. The introduction controls and PIN gate were checked with eligibility forced.
PR manual case 9.
Enable disabled NFC and Bluetooth sources ⏭️ Not run: Physical NFC activation needs an NFC-capable Android phone. The unchanged Bluetooth permissions portion retains earlier passing evidence.
PR manual case 10.
Read a Square Register request ⏭️ Not run: No Square Register or connected NFC-capable Android payer. Parser fixtures do not establish terminal compatibility.
PR manual case 11.
Pause NFC receiving while locked ⏭️ Not run: No connected NFC-capable Android pair to test receiving while locked. Earlier Bluetooth lock/unlock evidence remains applicable.
PR manual case 13-nfc.
Open Bitkit once from a background NFC tap ⏭️ Not run: No connected NFC-capable Android pair. Injected callbacks or intents do not prove background dispatch or repeat polling.
PR manual case 15.
I retained the previous cancellation report for Enter Manually cancellation after decode has already started. The automatic Bluetooth duplicate form was repeated above because the retry policy changed. The NFC reader lifetime checks were also repeated because their dispatcher changed.
The funded payment report retains the completed Bluetooth payment with QuickPay suppressed, NFC launch-intent normalization, required-parameter preservation, selected-tag revocation and Spark channel-refresh checks. Their payment and decoding paths are unchanged in this delta; the new accepted-review lifetime check is above.
The earlier nearby report and initial device report retain J1, J2, case 6, permission recovery, non-payment filtering, failed-Receive gating, Bluetooth lock/unlock and Android 11 location recovery. The last delta report retains TapPay introduction PIN authorization and persistence. Those successful paths are untouched here. The older physical NFC results used a local bitkit-core master build and do not establish the still-unrun physical cases with the shipped library.
Debug-only test hooks
Not pushed. The NFC hook bypasses hardware availability and substitutes a prepared text for the raw tag read, with explicit holds before or after activation capture. It leaves the dispatcher, actual lifecycle callbacks, scan admission, decoder, cancellation and routing intact. The Bluetooth peer can serve a prepared URI from its app-private file through the real GATT server. The decoder hold waits for explicit release and provides no decoder result. Additional Bluetooth logging records actual GATT results and delivered payloads. The funded confirmation case used no payload override or decode hold.
diff --git a/app/src/main/java/to/bitkit/nearby/NearbyAdvertiser.kt b/app/src/main/java/to/bitkit/nearby/NearbyAdvertiser.kt
index e5229152f..ad6aea258 100644
--- a/app/src/main/java/to/bitkit/nearby/NearbyAdvertiser.kt
+++ b/app/src/main/java/to/bitkit/nearby/NearbyAdvertiser.kt
@@ -74,7 +74,8 @@ class NearbyAdvertiser(private val context: Context) {
}
private fun valueFor(characteristic: BluetoothGattCharacteristic): ByteArray? {
- val current = request ?: return null
+ val override = java.io.File(context.filesDir, "review-nearby-uri") // test hook
+ val current = (if (to.bitkit.BuildConfig.DEBUG && override.exists()) NearbyProtocol.encodeRequest(override.readText().trim()) else request) ?: return null // test hook
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
diff --git a/app/src/main/java/to/bitkit/nearby/NearbyScanner.kt b/app/src/main/java/to/bitkit/nearby/NearbyScanner.kt
index d7abee300..2a42839c6 100644
--- a/app/src/main/java/to/bitkit/nearby/NearbyScanner.kt
+++ b/app/src/main/java/to/bitkit/nearby/NearbyScanner.kt
@@ -122,6 +122,7 @@ class NearbyScanner(
session?.close()
session = null
val payment = request?.let(::nearbyPaymentRequest)
+ if (to.bitkit.BuildConfig.DEBUG) Logger.info("ReviewHook finished nearby read from '${device.address}': request='$request', accepted='${payment != null}'", context = TAG) // test hook
if (request != null && payment == null) {
Logger.warn("Ignored nearby request that is not a payment", context = TAG)
}
@@ -207,6 +208,7 @@ class NearbyScanner(
value: ByteArray,
status: Int,
) {
+ if (to.bitkit.BuildConfig.DEBUG) Logger.info("ReviewHook GATT read '${characteristic.uuid}' status '$status', bytes '${value.size}'", context = TAG) // test hook
if (status != BluetoothGatt.GATT_SUCCESS) return complete(null)
if (characteristic.uuid == NearbyProtocol.META_UUID) {
length = NearbyProtocol.requestLength(value) ?: return complete(null)
diff --git a/app/src/main/java/to/bitkit/ui/shared/effects/NfcEffects.kt b/app/src/main/java/to/bitkit/ui/shared/effects/NfcEffects.kt
index fa8299f27..865a82401 100644
--- a/app/src/main/java/to/bitkit/ui/shared/effects/NfcEffects.kt
+++ b/app/src/main/java/to/bitkit/ui/shared/effects/NfcEffects.kt
@@ -41,6 +41,7 @@ private val NDEF_AIDS = listOf(Type4TagEmulator.NDEF_AID_HEX)
enum class NfcState { UNAVAILABLE, OFF, ON }
fun Context.nfcState(): NfcState {
+ if (to.bitkit.BuildConfig.DEBUG && java.io.File(filesDir, "review-nfc").exists()) return NfcState.ON // test hook
val adapter = NfcAdapter.getDefaultAdapter(this) ?: return NfcState.UNAVAILABLE
return if (adapter.isEnabled) NfcState.ON else NfcState.OFF
}
@@ -96,10 +97,32 @@ fun NfcReaderEffect(
DisposableEffect(activity, lifecycleOwner, enabled) {
val adapter = NfcAdapter.getDefaultAdapter(activity)
- if (!enabled || adapter == null) return@DisposableEffect onDispose {}
+ val reviewNfc = to.bitkit.BuildConfig.DEBUG && java.io.File(activity.filesDir, "review-nfc").exists() // test hook
+ if (!enabled || (adapter == null && !reviewNfc)) return@DisposableEffect onDispose {}
val mainHandler = Handler(Looper.getMainLooper())
val dispatcher = NfcReadDispatcher(onRead = { currentOnRead(it) }, onUnreadable = { currentOnUnreadable() })
+ val reviewStopped = java.util.concurrent.atomic.AtomicBoolean(false) // test hook
+ if (reviewNfc) Thread { // test hook
+ repeat(1800) { // test hook
+ if (reviewStopped.get()) return@Thread // test hook
+ val input = java.io.File(activity.filesDir, "review-raw-input") // test hook
+ if (input.exists()) { // test hook
+ val text = input.readText().trim() // test hook
+ input.delete() // test hook
+ Logger.info("ReviewHook raw callback queued", context = TAG) // test hook
+ val entryHold = java.io.File(activity.filesDir, "review-hold-entry") // test hook
+ while (entryHold.exists()) Thread.sleep(10) // test hook
+ val activation = dispatcher.activation // test hook: mirrors callback entry below
+ Logger.info("ReviewHook raw read started activation '$activation'", context = TAG) // test hook
+ val hold = java.io.File(activity.filesDir, "review-hold-raw") // test hook
+ while (hold.exists()) Thread.sleep(10) // test hook
+ Logger.info("ReviewHook raw read finished activation '$activation' at '${lifecycleOwner.lifecycle.currentState}'", context = TAG) // test hook
+ mainHandler.post { dispatcher.deliver(text.ifEmpty { null }, activation) } // test hook
+ } // test hook
+ Thread.sleep(50) // test hook
+ } // test hook
+ }.start() // test hook
val callback = NfcAdapter.ReaderCallback { tag ->
val activation = dispatcher.activation
val text = readPaymentText(tag)
@@ -111,7 +134,7 @@ fun NfcReaderEffect(
val owner = Any()
fun enable() = runCatching {
- adapter.enableReaderMode(activity, callback, READER_FLAGS, null)
+ adapter?.enableReaderMode(activity, callback, READER_FLAGS, null) // test hook
ReaderModeOwner.current = owner
}.onFailure { Logger.warn("Failed to enable NFC reader mode", it, context = TAG) }
@@ -123,11 +146,12 @@ fun NfcReaderEffect(
if (ReaderModeOwner.resumeScanner === resume) ReaderModeOwner.resumeScanner = null
if (ReaderModeOwner.current !== owner) return
ReaderModeOwner.current = null
- runCatching { adapter.disableReaderMode(activity) }
+ runCatching { adapter?.disableReaderMode(activity) } // test hook
.onFailure { Logger.warn("Failed to disable NFC reader mode", it, context = TAG) }
}
val observer = LifecycleEventObserver { _, event ->
+ if (reviewNfc) Logger.info("ReviewHook reader lifecycle '$event' activation '${dispatcher.activation}'", context = TAG) // test hook
when (event) {
Lifecycle.Event.ON_RESUME -> {
ReaderModeOwner.resumeScanner = resume
@@ -147,6 +171,8 @@ fun NfcReaderEffect(
lifecycleOwner.lifecycle.removeObserver(observer)
disable()
mainHandler.removeCallbacksAndMessages(null)
+ reviewStopped.set(true) // test hook
+ if (reviewNfc) Logger.info("ReviewHook reader disposed activation '${dispatcher.activation}'", context = TAG) // test hook
}
}
}
diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
index 84a7ac60e..ae3326dd5 100644
--- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
+++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
@@ -5560,6 +5560,19 @@ class AppViewModel @Inject constructor(
}
}
+ if (to.bitkit.BuildConfig.DEBUG) { // test hook
+ val hold = java.io.File(context.filesDir, "review-hold-decode") // test hook
+ if (hold.exists()) { // test hook
+ Logger.info("ReviewHook held before real decode", context = TAG) // test hook
+ try { // test hook
+ while (hold.exists()) delay(50) // test hook
+ Logger.info("ReviewHook released before real decode", context = TAG) // test hook
+ } catch (cancelled: kotlinx.coroutines.CancellationException) { // test hook
+ Logger.info("ReviewHook cancelled held decode", context = TAG) // test hook
+ throw cancelled // test hook
+ } // test hook
+ } // test hook
+ } // test hook
val scan = runSuspendCatching { coreService.decode(input) }
.onFailure {
if (isPaymentRequest) {Deciding NFC sequence (from the device log):
ReviewHook raw callback queued - NfcEffects
ReviewHook reader lifecycle 'ON_PAUSE' activation '0' - NfcEffects
ReviewHook reader lifecycle 'ON_STOP' activation '1' - NfcEffects
ReviewHook reader disposed activation '2' - NfcEffects
ReviewHook raw read started activation '2' - NfcEffects
ReviewHook raw read finished activation '2' at 'CREATED' - NfcEffects
Read nearby request
Started scan from address continue
Routed to Bitcoin Amount
Reviewed the complete contiguous 5ca051c..483562d delta, previous findings, NFC lifecycle and scan cancellation, Bluetooth read/retry and accepted-route lifetimes, tests and translated resources. No physical NFC reading, emulation, terminal or Android ↔ iPhone exchange was driven.
Twin: bitkit-ios#1302 feat: nfc and bluetooth nearby payments, checked at d1d6389. The shared protocol documents are byte-identical, and both implementations use the same 10-second Bluetooth retry interval. iOS intentionally uses a user-started NFC session and has no card-emulation role. Physical interoperability remains unverified.
Reviewed by gpt-6.1-sol-high
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
piotr-iohk
left a comment
There was a problem hiding this comment.
QA review
Scope: Follow-up of 79e9f719 since 483562df, on merge base 5fa540e9. The previous head is an ancestor and the base is unchanged, so unchanged coverage is inherited from the baseline review. This pass rechecked the one new commit, which binds each NFC reader callback to the activation that registered it.
No new actionable code findings.
enableReaderMode opens an activation and registers a callback closed over that number. Pause and dispose call close(), and deliver ignores a callback that is not the open activation. That drops a tag callback the NFC service has already copied and then runs after reader mode is disabled, including when it runs after a later resume. On Android 9, 13, and 14, NfcActivityManager.onTagDiscovered copies the current reader callback and invokes it outside the lock, which is that race. A callback that finishes after pause can still call NfcRepeatGuard.engage before deliver; the guard holds reader mode until the tag leaves, and the closed activation does not open a payment. A read that has already reached AddressContinue is still cancelled by Enter Manually and Contacts.
Compared with bitkit-ios#1302 at d9a0b2a: iOS drops an NFC result when the Send sheet closes or its navigation path changes, and it ignores a callback from an older NFC session. Android drops the reader callback when its activation is closed, and cancels a decode already handed to the send flow on Enter Manually and Contacts. Leaving the scanner and moving on to Enter Manually or Contacts have the same outcome.
Validation: inspected NfcReadDispatcherTest at this revision; it was not executed because this environment has no Android SDK. Device testing: not performed in this review.
Suggested additional test cases
- Android, NFC phone, devDebug at this revision. Phone A is on Receive with a request. Phone B is on the Send scanner. Start a tap so B discovers A's tag, then leave B's scanner before a review appears. Expected: no payment review opens on the screen B navigated to. Separate the phones, return B to the scanner, and tap once more. Expected: the review opens once.
Earlier findings reconciled at this revision: 1 still present.
Existing concerns
- [LOW] Receive tap label follows adapter state after advertising fails to start — The runtime start-failure path is still present at 79e9f71. The thread #1883 (comment) is marked resolved. The author fixed only the deterministic hardware case: advertise-role Bluetooth state is UNAVAILABLE when isMultipleAdvertisementSupported is false. An advertising start that fails later still does not change the label. offerPaymentNearby sets canAdvertise from the nearby setting and BluetoothState.ON, starts NearbyAdvertiseEffect from that flag, and returns whether NFC emission or that preflight is active. NearbyAdvertiser.onStartFailure sets the private isAdvertising flag to false and logs. A synchronous startAdvertising failure only logs. Nothing outside NearbyAdvertiser reads isAdvertising. ReceiveQrScreen uses the returned boolean as canTapToPay and shows wallet__receive_scan_or_tap while it is true. With NFC off, a failed Bluetooth advertise start would leave that label up. The only commit since 483562d changes the NFC reader callback binding and does not touch these files. A focused issue search for onStartFailure, offerPaymentNearby, and isMultipleAdvertisementSupported in synonymdev/bitkit-android returned no issues. At bitkit-ios d9a0b2a80bdaa07a983765e397592c4ba4e7861d, ReceiveQr.swift:428 and :452 pass nearbyAdvertiser.isAdvertising into showsTapToPay. This check is source inspection and did not execute the failure callback.
Reviewer model: grok-4.7
Reasoning effort: xhigh
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Verdict:
Findings: No new defect found in the reviewed delta. The previous late-callback finding is fixed at 79e9f71.
QA for 79e9f71:
Built regtest devDebug at 79e9f71 with the shipped bitkit-core 0.8.0-rc15. Timing cases ran on an Android 16 emulator with the debug-only callback hook below. They exercise the actual registered ReaderCallback, lifecycle, dispatcher and downstream decoding. NFC hardware and the repeat guard were not exercised. No payment was submitted.
Drop an NFC read when Contacts pauses the scanner ✅ A read started before pause completed before disposal and was dropped; Select Contact remained.
The raw read started before Contacts. Logcat confirms completion and rejection after the real ON_PAUSE but before disposal; Select Contact remained open.
nfc-paused.2x.mp4
Drop an old NFC read after the scanner resumes ✅ The in-progress old activation read was rejected after resume; a fresh callback decoded the amountless Lightning request and opened Bitcoin Amount.
The old read had already entered its callback before pause. After resume, its old activation was rejected. The scanner stayed open; a fresh callback then opened Bitcoin Amount with a signed amountless regtest Lightning request.
nfc-resumed.2x.mp4
Drop an NFC read completed after the scanner closes ✅ A read already in progress completed after disposal and was dropped; manualdraft remained.
The callback had started reading before Enter Manually. After disposal and typing manualdraft, releasing the held read left that text intact. Logcat confirms closed-state rejection and no new address scan.
nfc-disposed.2x.mp4
Drop an NFC callback delayed until after the scanner closes ✅ A retained callback first invoked after disposal was dropped; manualdraft remained.
This repeats the previously failing schedule. The hook retained the actual callback before exit, then first invoked it after disposal and typing manualdraft. It retained its registration token and was rejected by the closed dispatcher; the typed text remained.
nfc-late-entry.2x.mp4
Drop a retained NFC callback after a new reader activation ✅ A callback retained before pause and first invoked after resume was rejected; a fresh callback opened Bitcoin Amount.
The hook retained the registered callback before pause and first invoked it after resume. Logcat confirms its old activation was rejected while the new one was open. The scanner remained; invoking the newly registered callback then opened Bitcoin Amount.
nfc-late-resume.2x.mp4
Check: Run NFC and nearby regression checks ✅ Pinned-head build and selected NFC, nearby and send-flow regressions passed.
Ran assembleDevDebug and testDevDebugUnitTest for to.bitkit.nfc.*, to.bitkit.nearby.* and AppViewModelSendFlowTest against unchanged application source before adding hooks. The dispatcher, codec, normalization, protocol and send-flow regressions passed.
Read an Android Receive invoice over NFC ⏭️ Not run: Requires two NFC-capable Android test phones; none are connected.
PR manual case 1.
Pay a small NFC request with QuickPay ⏭️ Not run: Requires NFC-capable Android test phones and a funded payer for a physical QuickPay payment.
PR manual case 1a.
Review a large NFC request ⏭️ Not run: Requires NFC-capable Android test phones to read an above-threshold request.
PR manual case 1b.
Read Lightning Bitcoin and LNURL-pay tags ⏭️ Not run: Requires an NFC-capable Android reader and written Lightning, Bitcoin and LNURL-pay tags.
PR manual case 2.
Read a USDT request over NFC ⏭️ Not run: Requires an NFC-capable Android pair for USDT tag exchange.
PR manual case 3.
Reject a non-payment NFC tag ⏭️ Not run: Requires an NFC-capable Android reader and a non-payment tag.
PR manual case 4.
Exchange Bluetooth requests with iPhone ⏭️ Not run: Requires a physical Android/iPhone test pair; no physical Android test phone is reachable.
PR manual case 7.
Read Android Receive with iPhone NFC ⏭️ Not run: Requires an NFC-capable Android/iPhone pair; no physical Android test phone is reachable.
PR manual case 8.
Show the introduction on an NFC phone ⏭️ Not run: Physical NFC eligibility needs an NFC-capable Android phone. Introduction controls and PIN authorization retain earlier passing evidence.
PR manual case 9.
Enable disabled NFC and Bluetooth sources ⏭️ Not run: NFC activation needs an NFC-capable Android phone. Bluetooth permission recovery retains earlier passing evidence.
PR manual case 10.
Read a Square Register request ⏭️ Not run: Requires a Square Register and an NFC-capable Android payer; parser fixtures do not establish terminal compatibility.
PR manual case 11.
Pause NFC receiving while locked ⏭️ Not run: Requires NFC-capable Android test phones to check receiving while locked. Bluetooth lock/unlock retains earlier passing evidence.
PR manual case 13-nfc.
Open Bitkit once from a background NFC tap ⏭️ Not run: Requires NFC-capable Android test phones. Injected callbacks do not establish physical background dispatch or repeat polling.
PR manual case 15.
Read a new NFC tap after leaving and returning to the scanner ⏭️ Not run: The [latest review](https://github.com//pull/1883#pullrequestreview-5940939599) asks for a physical leave-and-retap check. No physical Android test phone is reachable; callback injection cannot establish tag separation or a fresh physical tap.
The callback-lifetime portions passed above; the physical exchange remains unverified.
Earlier passing evidence retained because the exercised code is untouched by this delta:
- The previous report covers Bluetooth rejected-request retry, automatic duplicate cancellation, a single accepted Review and the translated labels.
- The PIN authorization report covers TapPay introduction authorization and persistence, and Contacts cancelling an already-decoding Bluetooth request.
- The cancellation report covers Enter Manually cancelling an already-decoding NFC or Bluetooth request.
- The funded-payment report covers case
5, NFC launch-intent normalization, required-parameter refusal, selected-tag revocation and Spark channel-refresh checks. - The nearby report covers
J2, permission recovery, case12and failed-Receive publication gating. - The initial report covers
J1, case6, Bluetooth lock/unlock and case14.
The author's older physical NFC payments used a local bitkit-core master build and predate the changed reader lifetime; they do not establish the unrun physical cases above.
Debug-only test hook
Not pushed. The hook forces NFC availability on the emulator, substitutes prepared tag text and retains the actual callback created by the production callback factory. Explicit file holds delay callback entry or raw-read completion. Registration still calls dispatcher.open(); pause/disposal still call close(); the real deliver checks remain unchanged. Hardware adapter calls and NfcRepeatGuard.engage are bypassed because no tag exists. Additional logging records activation checks. The pause, disposal and late-entry cases use a valid regtest Bitcoin address; the resume controls use a signed, amountless regtest Lightning request.
diff --git a/app/src/main/java/to/bitkit/nfc/NfcReadDispatcher.kt b/app/src/main/java/to/bitkit/nfc/NfcReadDispatcher.kt
index ac31bd091..ec437d636 100644
--- a/app/src/main/java/to/bitkit/nfc/NfcReadDispatcher.kt
+++ b/app/src/main/java/to/bitkit/nfc/NfcReadDispatcher.kt
@@ -32,6 +32,7 @@ internal class NfcReadDispatcher(
}
fun deliver(text: String?, readActivation: Int) {
+ if (to.bitkit.BuildConfig.DEBUG) to.bitkit.utils.Logger.info("ReviewHook deliver read '$readActivation' current '$activation' open '$isOpen'", context = "NfcEffects") // test hook
if (!isOpen || readActivation != activation) return
if (text == null) {
onUnreadable()
diff --git a/app/src/main/java/to/bitkit/ui/shared/effects/NfcEffects.kt b/app/src/main/java/to/bitkit/ui/shared/effects/NfcEffects.kt
index 6a624553b..ddbc382d0 100644
--- a/app/src/main/java/to/bitkit/ui/shared/effects/NfcEffects.kt
+++ b/app/src/main/java/to/bitkit/ui/shared/effects/NfcEffects.kt
@@ -41,6 +41,7 @@ private val NDEF_AIDS = listOf(Type4TagEmulator.NDEF_AID_HEX)
enum class NfcState { UNAVAILABLE, OFF, ON }
fun Context.nfcState(): NfcState {
+ if (to.bitkit.BuildConfig.DEBUG && java.io.File(filesDir, "review-nfc").exists()) return NfcState.ON // test hook
val adapter = NfcAdapter.getDefaultAdapter(this) ?: return NfcState.UNAVAILABLE
return if (adapter.isEnabled) NfcState.ON else NfcState.OFF
}
@@ -96,23 +97,50 @@ fun NfcReaderEffect(
DisposableEffect(activity, lifecycleOwner, enabled) {
val adapter = NfcAdapter.getDefaultAdapter(activity)
- if (!enabled || adapter == null) return@DisposableEffect onDispose {}
+ val reviewNfc = to.bitkit.BuildConfig.DEBUG && java.io.File(activity.filesDir, "review-nfc").exists() // test hook
+ if (!enabled || (adapter == null && !reviewNfc)) return@DisposableEffect onDispose {}
val mainHandler = Handler(Looper.getMainLooper())
val dispatcher = NfcReadDispatcher(onRead = { currentOnRead(it) }, onUnreadable = { currentOnUnreadable() })
+ val reviewCallback = java.util.concurrent.atomic.AtomicReference<NfcAdapter.ReaderCallback?>() // test hook
+ val reviewText = java.util.concurrent.atomic.AtomicReference<String?>() // test hook
+ val reviewStopped = java.util.concurrent.atomic.AtomicBoolean(false) // test hook
+ if (reviewNfc) Thread { // test hook
+ repeat(2400) { // test hook, bounded 120 seconds while idle
+ if (reviewStopped.get()) return@Thread // test hook
+ val input = java.io.File(activity.filesDir, "review-raw-input") // test hook
+ if (input.exists()) { // test hook
+ val text = input.readText().trim() // test hook
+ input.delete() // test hook
+ val retained = reviewCallback.get() // test hook: retain the actual registered ReaderCallback
+ Logger.info("ReviewHook raw callback queued", context = TAG) // test hook
+ val entryHold = java.io.File(activity.filesDir, "review-hold-entry") // test hook
+ while (entryHold.exists()) Thread.sleep(10) // test hook
+ reviewText.set(text) // test hook
+ retained?.onTagDiscovered(null) // test hook: invoke the production callback after the hold
+ } // test hook
+ Thread.sleep(50) // test hook
+ } // test hook
+ }.start() // test hook
+
// Android may call a callback after reader mode is disabled, so each activation gets its own callback.
fun callback(activation: Int) = NfcAdapter.ReaderCallback { tag ->
- val text = readPaymentText(tag)
+ if (reviewNfc) Logger.info("ReviewHook raw read started activation '$activation'", context = TAG) // test hook
+ val hold = java.io.File(activity.filesDir, "review-hold-raw") // test hook
+ if (reviewNfc) while (hold.exists()) Thread.sleep(10) // test hook
+ val text = if (reviewNfc) reviewText.getAndSet(null)?.ifEmpty { null } else readPaymentText(tag) // test hook
+ if (reviewNfc) Logger.info("ReviewHook raw read finished activation '$activation' at '${lifecycleOwner.lifecycle.currentState}'", context = TAG) // test hook
// The tag stays in range after the read; hold reader mode so Android does not deliver it again.
- if (text != null) NfcRepeatGuard.engage(activity, tag)
+ if (text != null && !reviewNfc) NfcRepeatGuard.engage(activity, tag) // test hook: no tag exists on the emulator
mainHandler.post { dispatcher.deliver(text, activation) }
- }
+ }.also { if (reviewNfc) reviewCallback.set(it) } // test hook
val owner = Any()
fun enable() = runCatching {
- adapter.enableReaderMode(activity, callback(dispatcher.open()), READER_FLAGS, null)
+ val registered = callback(dispatcher.open()) // test hook: same registration, even without hardware
+ adapter?.enableReaderMode(activity, registered, READER_FLAGS, null) // test hook
ReaderModeOwner.current = owner
}.onFailure { Logger.warn("Failed to enable NFC reader mode", it, context = TAG) }
@@ -124,11 +152,12 @@ fun NfcReaderEffect(
if (ReaderModeOwner.resumeScanner === resume) ReaderModeOwner.resumeScanner = null
if (ReaderModeOwner.current !== owner) return
ReaderModeOwner.current = null
- runCatching { adapter.disableReaderMode(activity) }
+ runCatching { adapter?.disableReaderMode(activity) } // test hook
.onFailure { Logger.warn("Failed to disable NFC reader mode", it, context = TAG) }
}
val observer = LifecycleEventObserver { _, event ->
+ if (reviewNfc) Logger.info("ReviewHook reader lifecycle '$event'", context = TAG) // test hook
when (event) {
Lifecycle.Event.ON_RESUME -> {
ReaderModeOwner.resumeScanner = resume
@@ -148,6 +177,8 @@ fun NfcReaderEffect(
lifecycleOwner.lifecycle.removeObserver(observer)
disable()
mainHandler.removeCallbacksAndMessages(null)
+ reviewStopped.set(true) // test hook
+ if (reviewNfc) Logger.info("ReviewHook reader disposed", context = TAG) // test hook
}
}
}Reviewed the complete contiguous 483562d..79e9f71 delta, its three changed files and previous findings. Traced the shared reader ownership and scanner callers. No physical NDEF reading, card emulation, repeat-guard hardware behavior, terminal or Android/iPhone exchange was driven.
Twin: bitkit-ios#1302 feat: nfc and bluetooth nearby payments, checked at d9a0b2a. The shared protocol documents are byte-identical. iOS rejects older NFC sessions by session identity and uses a user-started system sheet; it has no card-emulation role. The same user-visible lifetime protection is present; physical interoperability remains unverified.
Reviewed by gpt-6.1-sol-high
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Verdict:
Findings: No new defect found in the reviewed delta. The runtime advertising failure and old advertising callback points are fixed at 965ff98.
QA for 965ff98:
Built regtest devDebug at 965ff980c06a65fc8c97cae391bae5cfdf614106 with the shipped bitkit-core 0.8.0-rc15. Device cases ran on Android 16 emulators. Failure cases used the unpushed debug hook disclosed below; the callback guard, failure handling, Compose state and Receive UI were unchanged. Normal Bluetooth delivery used the ordinary Receive request and an unchanged-source payer. No payment was submitted in this run.
Hide the tap label when Bluetooth advertising fails ✅ Forced callback failures hid the Bitcoin and USDT tap labels; Bluetooth inspection confirmed service removal and recovery after changing the request.
The hook retained each actual registered callback without submitting its hardware start, then invoked onStartFailure. Bitcoin and USDT both lost the label. Bluetooth inspection confirmed the GATT service was removed, then restored after changing the request. This verifies failure handling, not the frequency of hardware start failures.
advertise-callback-final2x.2x.mp4
Hide the tap label after an advertising exception ✅ The forced start failure removed the tap label; clearing the fault and selecting another request restored it.
The debug hook forced this transport boundary to fail. Bluetooth inspection confirmed no nearby GATT service in the failed state and a started service after recovery.
advertise-exception2x.2x.mp4
Hide the tap label when the GATT server cannot open ✅ The forced start failure removed the tap label; clearing the fault and selecting another request restored it.
The debug hook forced this transport boundary to fail. Bluetooth inspection confirmed no nearby GATT service in the failed state and a started service after recovery.
advertise-server2x.2x.mp4
Hide the tap label when the Bluetooth advertiser disappears ✅ The forced start failure removed the tap label; clearing the fault and selecting another request restored it.
The debug hook forced this transport boundary to fail. Bluetooth inspection confirmed no nearby GATT service in the failed state and a started service after recovery.
advertise-advertiser2x.2x.mp4
Ignore an old advertising failure after the request changes ✅ A late failure from the replaced advertiser left the new tap label visible, with logcat and Bluetooth inspection confirming rejection and the active service.
The old pending callback was retained before replacing the request. Its late failure reached the old advertiser with no current callback and was ignored. The newer request kept its label and GATT service. Callback identities and the rejection were checked in logcat.
advertise-old-request2x.2x.mp4
Ignore an old advertising failure after Receive resumes ✅ A late failure after pause/resume left the tap label visible, with logcat and Bluetooth inspection confirming the newer callback and service remained active.
The same advertiser stopped callback 13 on pause and registered callback 14 on resume. A late failure for 13 found 14 current and was ignored. Logcat confirms the identities; the label and GATT service remained.
advertise-old-resume2x.2x.mp4
Read a Receive request after advertising recovers ✅ The label and GATT service followed the setting, checked by recording and Bluetooth inspection, and real Bluetooth delivery opened Bitcoin Amount on the funded payer.
Case 6 and a normal transport control. Turning Nearby payments off removed the label and GATT service; the payer scanner received nothing. Enabling it restored advertising, and the funded payer decoded the ordinary unified request over Bluetooth and opened Bitcoin Amount. Left: Receive; right: payer. This does not repeat the earlier completed Lightning payment.
advertise-transport2x.2x.mp4
Check: Build and check NFC and Bluetooth regressions ✅ Pristine assembleDevDebug and the selected NFC and nearby unit suites passed.
Ran assembleDevDebug and testDevDebugUnitTest for to.bitkit.nfc.* and to.bitkit.nearby.* against pristine application source before adding hooks.
Read an Android Receive invoice over NFC ⏭️ Not run: requires two NFC-capable Android test phones.
PR manual case 1.
Pay a small NFC request with QuickPay ⏭️ Not run: requires NFC-capable Android test phones and a funded physical payer.
PR manual case 1a.
Review a large NFC request ⏭️ Not run: requires NFC-capable Android test phones.
PR manual case 1b.
Read Lightning Bitcoin and LNURL-pay tags ⏭️ Not run: requires an NFC-capable Android reader and written tags.
PR manual case 2.
Read a USDT request over NFC ⏭️ Not run: requires two NFC-capable Android test phones.
PR manual case 3.
Reject a non-payment NFC tag ⏭️ Not run: requires an NFC-capable Android reader and a non-payment tag.
PR manual case 4.
Exchange Bluetooth requests with iPhone ⏭️ Not run: requires a physical Android and iPhone test pair; iOS Simulator has no Bluetooth.
PR manual case 7.
Read Android Receive with iPhone NFC ⏭️ Not run: requires an NFC-capable Android and iPhone test pair.
PR manual case 8.
Show the introduction on an NFC phone ⏭️ Not run: requires a physical NFC-capable Android phone; earlier introduction controls and PIN authorization still apply.
PR manual case 9.
Enable disabled NFC and Bluetooth sources ⏭️ Not run: requires a physical NFC-capable Android phone for the NFC part; earlier Bluetooth permission recovery still applies.
PR manual case 10.
Read a Square Register request ⏭️ Not run: requires a Square Register and an NFC-capable Android payer.
PR manual case 11.
Pause NFC receiving while locked ⏭️ Not run: requires an NFC-capable Android test pair.
PR manual case 13-nfc.
Open Bitkit once from a background NFC tap ⏭️ Not run: requires an NFC-capable Android test pair; callback injection cannot establish physical dispatch or repeat polling.
PR manual case 15.
Read a new NFC tap after returning to the scanner ⏭️ Not run: requires physical NFC phones to separate and retap; earlier callback-lifetime checks still apply.
Additional physical leave-and-retap check requested in the previous QA review. Earlier callback-lifetime checks remain applicable.
Device discovery found no connected Android test phone or advertised wireless target; the known iPhone was offline. Emulators cannot establish physical NFC, terminal compatibility or Android/iPhone exchange.
Earlier passing evidence retained for behavior untouched by this delta:
- The latest NFC report covers pending and retained reader callbacks across pause, disposal and resume.
- The Bluetooth retry report covers rejected-request retry, automatic duplicate cancellation, one accepted review and translated labels. Advertising delivery was rechecked above.
- The PIN authorization report covers the TapPay introduction and Contacts cancelling an already-decoding request.
- The cancellation report covers Enter Manually cancelling an already-decoding NFC or Bluetooth request.
- The funded-payment report covers case
5, NFC launch normalization, required-parameter refusal, selected-tag revocation and Spark channel refresh. The payment preparation and routing code are unchanged. - The nearby report covers
J2, permission recovery, case12and failed-invoice publication gating. - The initial report covers
J1, Bluetooth lock/unlock and case14. Case6was repeated above.
The older physical NFC payments predate the changed reader lifetime and used a local bitkit-core master build; they do not establish the physical cases listed as unrun.
Debug-only advertising test hook
Not pushed. The hook stages four failure boundaries: a pending start callback, a synchronous start exception, a null GATT server and a missing LE advertiser. Pending mode retains the actual callback created by the production factory and omits the hardware start; a bounded main-thread command poll invokes that callback later, including after replacement or pause/resume. Successful controls call the real Bluetooth APIs. Additional logs expose callback identities. No failure handler, callback identity guard, effect lifecycle, availability decision or UI branch is replaced.
diff --git a/app/src/main/java/to/bitkit/nearby/NearbyAdvertiser.kt b/app/src/main/java/to/bitkit/nearby/NearbyAdvertiser.kt
index 323f25cd0..38ab00d82 100644
--- a/app/src/main/java/to/bitkit/nearby/NearbyAdvertiser.kt
+++ b/app/src/main/java/to/bitkit/nearby/NearbyAdvertiser.kt
@@ -25,6 +25,7 @@ class NearbyAdvertiser(
private val onFailed: () -> Unit = {},
) {
private val bluetoothManager = context.bluetoothManager
+ init { if (to.bitkit.BuildConfig.DEBUG) ReviewBleHook.attach(context) } // test hook
@Volatile
private var request: ByteArray? = null
@@ -36,8 +37,10 @@ class NearbyAdvertiser(
private fun newAdvertiseCallback(): AdvertiseCallback = object : AdvertiseCallback() {
override fun onStartFailure(errorCode: Int) {
Logger.warn("Failed nearby advertising with error '$errorCode'", context = TAG)
+ if (to.bitkit.BuildConfig.DEBUG) Logger.info("ReviewHook failure callback '${ReviewBleHook.id(this)}' current '${advertiseCallback?.let { ReviewBleHook.id(it) }}'", context = TAG) // test hook
if (advertiseCallback !== this) return
advertiseCallback = null
+ if (to.bitkit.BuildConfig.DEBUG) Logger.info("ReviewHook forwarded current failure", context = TAG) // test hook
onFailed()
}
}
@@ -72,6 +75,7 @@ class NearbyAdvertiser(
@RequiresPermission(allOf = [Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_ADVERTISE])
fun stop() {
request = null
+ if (to.bitkit.BuildConfig.DEBUG) Logger.info("ReviewHook stop callback '${advertiseCallback?.let { ReviewBleHook.id(it) }}'", context = TAG) // test hook
advertiseCallback?.let { callback ->
runCatching { bluetoothManager.adapter?.bluetoothLeAdvertiser?.stopAdvertising(callback) }
}
@@ -89,7 +93,7 @@ class NearbyAdvertiser(
@RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
private fun openServer(): BluetoothGattServer? {
- val server = runCatching { bluetoothManager.openGattServer(context, serverCallback) }
+ val server = runCatching { if (to.bitkit.BuildConfig.DEBUG && ReviewBleHook.fault() == "server") null else bluetoothManager.openGattServer(context, serverCallback) } // test hook
.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)
@@ -108,7 +112,7 @@ class NearbyAdvertiser(
@RequiresPermission(Manifest.permission.BLUETOOTH_ADVERTISE)
private fun startAdvertising() {
- val advertiser = bluetoothManager.adapter?.bluetoothLeAdvertiser ?: return onFailed()
+ val advertiser = bluetoothManager.adapter?.bluetoothLeAdvertiser?.takeUnless { to.bitkit.BuildConfig.DEBUG && ReviewBleHook.fault() == "advertiser" } ?: return onFailed() // test hook
val settings = AdvertiseSettings.Builder()
.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_LOW)
@@ -121,7 +125,11 @@ class NearbyAdvertiser(
.build()
val callback = newAdvertiseCallback()
advertiseCallback = callback
- runCatching { advertiser.startAdvertising(settings, data, callback) }
+ if (to.bitkit.BuildConfig.DEBUG) ReviewBleHook.register(callback) // test hook
+ runCatching { // test hook
+ if (to.bitkit.BuildConfig.DEBUG && ReviewBleHook.fault() == "exception") error("ReviewHook start failure") // test hook
+ if (!to.bitkit.BuildConfig.DEBUG || ReviewBleHook.fault() != "callback") advertiser.startAdvertising(settings, data, callback) // test hook
+ }
.onFailure {
advertiseCallback = null
Logger.warn("Failed to start nearby advertising", it, context = TAG)
@@ -133,3 +141,35 @@ class NearbyAdvertiser(
const val TAG = "NearbyAdvertiser"
}
}
+
+// Debug-only fault controls. Production failure decisions and cleanup remain unchanged. // test hook
+private object ReviewBleHook { // test hook
+ private var appContext: Context? = null // test hook
+ private val callbacks = mutableListOf<AdvertiseCallback>() // test hook
+ fun id(callback: AdvertiseCallback) = callbacks.indexOf(callback) // test hook
+ fun register(callback: AdvertiseCallback) { // test hook
+ callbacks.add(callback) // test hook
+ Logger.info("ReviewHook registered callback '${id(callback)}'", context = "NearbyAdvertiser") // test hook
+ } // test hook
+ fun fault() = appContext?.let { java.io.File(it.filesDir, "review-fault").takeIf { f -> f.exists() }?.readText()?.trim() } // test hook
+ fun attach(context: Context) { // test hook
+ if (appContext != null) return // test hook
+ appContext = context.applicationContext // test hook
+ val handler = android.os.Handler(android.os.Looper.getMainLooper()) // test hook
+ var remaining = 18000 // test hook: bounded 30 minutes
+ val poll = object : Runnable { // test hook
+ override fun run() { // test hook
+ val file = java.io.File(context.filesDir, "review-command") // test hook
+ if (file.exists()) { // test hook
+ val command = file.readText().trim() // test hook
+ file.delete() // test hook
+ val index = if (command == "latest") callbacks.lastIndex else command.toIntOrNull() ?: -1 // test hook
+ Logger.info("ReviewHook injecting failure '$index'", context = "NearbyAdvertiser") // test hook
+ callbacks.getOrNull(index)?.onStartFailure(AdvertiseCallback.ADVERTISE_FAILED_INTERNAL_ERROR) // test hook
+ } // test hook
+ if (--remaining > 0) handler.postDelayed(this, 100) // test hook
+ } // test hook
+ } // test hook
+ handler.post(poll) // test hook
+ } // test hook
+} // test hookReviewed the complete contiguous 79e9f71..965ff98 delta, its two changed files, the prior open points and reached Bitcoin/USDT Receive, lock, settings and lifecycle paths. NFC remaining available when Bluetooth fails was checked in code only; physical NFC, terminal and cross-platform behavior was not driven.
Twin: bitkit-ios#1302 feat: nfc and bluetooth nearby payments, checked at 594cbab. The protocol documents are byte-identical. Both platforms remove failed Bluetooth advertising from the Receive label and reject obsolete advertising callbacks. Android also has an independent NFC-emulation source; iOS has no card-emulation role. Physical interoperability remains unverified.
Reviewed by gpt-6.1-sol-high
piotr-iohk
left a comment
There was a problem hiding this comment.
QA review
Scope: full reassessment of Android PR #1883 against its merge base at 965ff980, as requested. No coverage was inherited.
11 actionable findings — resolve or provide an evidence-backed rebuttal.
The highest-priority issue is cancellation. An NFC request can survive dismissal of Send and reach QuickPay afterwards. Bluetooth also needs to respect an explicit recipient selection and the saved Receive privacy setting from the first render.
Validation: 45 tests passed under Kotlin 2.3.21 and JUnit 4.13.2 across the NDEF codec, Type 4 emulator, emitter ownership, URI normalization, Bluetooth protocol and request filter. The Android app suite was not run. I compared the shared wire format, scanner ownership, QuickPay suppression and USDT advertising with the pinned iOS twin, and traced decoding into shipped bitkit-core rc15. The Appium send and receive coverage and linked Figma frame structures were inspected. Visual rendering and radio interoperability remain unverified at this pin.
Device testing: not performed in this review. The runtime plan retains J1, J2 and all numbered author manual cases, including both Bluetooth directions, iPhone reading Android HCE, Square hardware, lock/unlock and Android 9–11 location settings. Use the shipped rc15 dependency for the Android acceptance run.
Suggested additional test cases: On Android, delay payment preparation, tap an under-threshold test invoice and dismiss Send before releasing the delay. Assert that Home remains visible and no payment starts. Cold-start with Nearby payments previously disabled and observe the first Receive visit from a second phone. Open the RGS configuration scanner beside a receiving wallet and verify it waits for the intended QR. For USDT, switch between native Arbitrum Receive and a prepared Tron deposit and check both the tap label and the request served.
Earlier findings reconciled at this revision: 14 verified fixed.
The repeat-guard concern is referenced in its existing discussion rather than reported again. That thread is resolved, and the later controlled checks verified stale payload delivery was dropped. At this revision, the separate reader-mode side effect still precedes activation validation; this review does not claim a new device reproduction of that side effect.
Findings
- [HIGH] Cancel pending nearby payment preparation when Send is dismissed — inline at
app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt:4081. - [MEDIUM] Keep a passive Bluetooth read from replacing a payment the user selected — inline at
app/src/main/java/to/bitkit/ui/screens/wallets/send/SendRecipientScreen.kt:114. - [MEDIUM] Wait for the saved privacy setting before starting Bluetooth advertising — inline at
app/src/main/java/to/bitkit/viewmodels/SettingsViewModel.kt:347. - [MEDIUM] Offer only payable USDT deposit requests over nearby transports — inline at
app/src/main/java/to/bitkit/ui/screens/wallets/usdt/UsdtReceiveContent.kt:51. - [MEDIUM] Preserve the requested amount when unwrapping an addressless Lightning URI — inline at
app/src/main/java/to/bitkit/nfc/NfcPaymentUri.kt:49. - [MEDIUM] Enable nearby payment scanning only for payment entry points — inline at
app/src/main/java/to/bitkit/ui/sheets/QrScanningSheet.kt:41. - [MEDIUM] Wait for GATT service registration before advertising Receive — inline at
app/src/main/java/to/bitkit/nearby/NearbyAdvertiser.kt:105. - [MEDIUM] Match nearby BOLT12 acceptance to the shipped decoder — inline at
app/src/main/java/to/bitkit/nearby/NearbyRequestFilter.kt:5. - [MEDIUM] Provide an NFC scan action on phones that suspend polling while the camera is open — inline at
app/src/main/java/to/bitkit/ui/screens/scanner/NearbyScanSources.kt:64. - [MEDIUM] Show NFC tap availability only after the payment tag is registered — inline at
app/src/main/java/to/bitkit/ui/shared/effects/NfcEffects.kt:189. - [LOW] Keep the NFC-specific error for readable tags without a payment request — inline at
app/src/main/java/to/bitkit/ui/shared/effects/NfcEffects.kt:165.
Existing concerns
- [MEDIUM] Check the NFC reader activation before engaging the repeat guard — Existing discussion is resolved after the activation-token fix and controlled checks confirmed stale payloads were dropped. The remaining source concern is the repeat-guard side effect: at 965ff98, NfcEffects.kt:108 calls NfcRepeatGuard.engage before dispatcher.deliver checks activation, and NfcRepeatGuard.kt:54-66 posts to the main thread and replaces the activity-wide reader callback. This consequence was already raised in the linked discussion; no duplicate inline or new device reproduction is claimed.
Reviewer model: gpt-6.2-astra
Reasoning effort: high
| // A nearby read (NFC or Bluetooth) arrives on its own, so Enter Manually must be able to drop it. | ||
| // Its job ends once it routes, so cancelling it never stops a payment in progress. | ||
| // A duplicate read returns no job; keep the handle of the scan still running. | ||
| if (isNearbyRead) job?.let { nearbyAddressScanJob = it } |
There was a problem hiding this comment.
[HIGH] Cancel pending nearby payment preparation when Send is dismissed
Tap an eligible NFC invoice on Send, then dismiss the sheet while resetSendState is waiting for the Blocktank refresh. hideSheet() clears the current payment state but leaves nearbyAddressScanJob running. After the refresh, handleScan reads isMainScanner from the now-empty sheet. It can consequently open a new QuickPay sheet, whose effect calls pay without another gesture. Bind preparation to the originating Send visit and cancel it on dismissal. The new tests exercise Enter Manually and Contacts, but neither dismisses Send. This is a source-predicted payment after cancellation. Routing, QuickPay execution.
|
|
||
| val nearbySources = rememberNearbyScanSources(enabled = true) { text, isNearby -> | ||
| Logger.debug("Read nearby request '${text.sanitizedQrLogValue()}'", context = TAG) | ||
| onEvent(SendEvent.AddressContinue(text, suppressQuickPay = isNearby, isNearbyRead = true)) |
There was a problem hiding this comment.
[MEDIUM] Keep a passive Bluetooth read from replacing a payment the user selected
Scan merchant A’s QR while wallet B is advertising a different invoice nearby. If B’s read arrives while A’s request is preparing, both use AddressContinue. launchScan starts the different request and cancels the previous job. The review can therefore show B’s recipient and amount after the user deliberately scanned A. Bluetooth QuickPay suppression still requires confirmation, but it does not preserve the recipient choice. Give an in-progress QR, paste or NFC selection priority over passive Bluetooth discovery. Scan scheduling.
| .asStateFlow(initialValue = false) | ||
|
|
||
| val isNearbyPaymentsEnabled = settingsStore.data.map { it.isNearbyPaymentsEnabled } | ||
| .asStateFlow(initialValue = true) |
There was a problem hiding this comment.
[MEDIUM] Wait for the saved privacy setting before starting Bluetooth advertising
Turn Nearby payments off, restart the process, then open Receive with Bluetooth permission granted and an invoice available. The preference is a WhileSubscribed state flow seeded with true. On its first subscription, Receive can start the GATT server and advertising before DataStore emits the persisted false. This creates a window in which an opted-out wallet can announce its presence. Hold advertising off until the first stored value is known. The settings journey revisits Settings in the same process, so it does not catch this startup ordering. Receive gate.
| amount: String = "", | ||
| ) { | ||
| var showDetails by rememberSaveable { mutableStateOf(false) } | ||
| val canTapToPay = offerPaymentNearby(uri) |
There was a problem hiding this comment.
[MEDIUM] Offer only payable USDT deposit requests over nearby transports
Prepare a Tron or Solana USDT deposit and return to its QR. UsdtReceiveContent passes every deposit URI to offerPaymentNearby. Shipped core returns a bare address for these networks, so nfcPaymentUri adds bitcoin:. A focused Kotlin check using core’s Tron fixture produced bitcoin:TJRabPrwbZy45sbavfcjinPJC18kjpRTv8. The receiving phone would advertise a Bitcoin request that cannot pay the displayed USDT deposit. Other EVM deposit URIs retain their chain ID, but the payer’s token-URI parser accepts only Arbitrum. Gate the nearby offer and label on a supported USDT payment request. Deposit formats, payer validation, iOS deposit guard.
| if (key.isEmpty() || value.isEmpty()) null else key.lowercase() to value | ||
| }.toMap() | ||
| val request = LIGHTNING_PARAMS.firstNotNullOfOrNull { params[it] } ?: return trimmed | ||
| return "lightning:$request" |
There was a problem hiding this comment.
[MEDIUM] Preserve the requested amount when unwrapping an addressless Lightning URI
Read an addressless BIP 321 request with an amount and a valid amountless BOLT11 invoice. The normalizer returns only the embedded invoice. Core decodes its amount as zero, so Send would ask the payer to enter an amount even though the terminal supplied one. A Kotlin probe confirmed that changing only the outer amount produces identical scanner input. Preserve the amount through payment preparation, or reject a combination the app cannot represent faithfully. Add an amountless-invoice case that asserts the amount shown in Send. Core amount decoding, Send routing.
| ) | ||
| ) | ||
| } | ||
| server.addService(service) |
There was a problem hiding this comment.
[MEDIUM] Wait for GATT service registration before advertising Receive
If Android refuses the request to add the GATT service, or reports failure asynchronously, openServer() still returns the server and start() advertises the UUID. A payer could discover and connect to the phone but never find the metadata characteristic. Receive would continue showing tap availability on a Bluetooth-only device. Check the immediate return value and begin advertising only after onServiceAdded reports success for the current server. The protocol unit tests exercise characteristic contents after registration. Android registration contract.
|
|
||
| import to.bitkit.nfc.scannedPaymentRequest | ||
|
|
||
| private val LIGHTNING_INVOICE_PREFIXES = listOf("lnbc", "lntb", "lnbcrt", "lnsb", "lno1") |
There was a problem hiding this comment.
[MEDIUM] Match nearby BOLT12 acceptance to the shipped decoder
A nearby device serving a BOLT12 offer passes the lno1 filter, and an addressless lno= request is rewritten as Lightning. Android strips the wrapper before calling bitkit-core. The shipped decoder has a BOLT11 parser and no offer branch, so a valid offer would end in a scan error instead of the advertised payment review. Support offers end to end or exclude them from the advertised formats and handle them as unsupported before closing the scanner. The filter test only checks that the prefix is accepted. Shipped decoder.
| val onEnableNfc: () -> Unit, | ||
| val onEnableBluetooth: () -> Unit, | ||
| ) { | ||
| val isNfcActive get() = nfcState == NfcState.ON |
There was a problem hiding this comment.
[MEDIUM] Provide an NFC scan action on phones that suspend polling while the camera is open
The author reports that on a Pixel 11 with camera permission granted, opening the camera disables NFC polling and denying camera permission restores it. At this head, isNfcActive follows the adapter’s enabled setting, so the scanner would still say it is scanning NFC and offer no NFC action. Provide an in-scanner way to pause the camera and perform the tap on affected devices. The hardware observation is the author’s. The status and missing recovery action were verified in source. Author’s Pixel 11 observations.
| fun start() { | ||
| token = NfcTagEmitter.publish(uri) | ||
| runCatching { | ||
| cardEmulation.registerAidsForService(service, CardEmulation.CATEGORY_OTHER, NDEF_AIDS) |
There was a problem hiding this comment.
[MEDIUM] Show NFC tap availability only after the payment tag is registered
With Bluetooth unavailable, an HCE-capable phone still shows “Scan or tap to pay” if Android returns false from registerAidsForService. The service XML has no static AID, the boolean result is ignored, and Receive derives its label from hardware capability. In this state tapping cannot retrieve the request. Propagate successful registration to Receive and clear the advertised state on failure. The emulator tests start after the reader has already reached the service. Android registration result.
| }.onFailure { | ||
| Logger.warn("Failed to read NFC tag", it, context = TAG) | ||
| }.getOrNull() ?: return null | ||
| return NdefCodec.payableText(NdefCodec.decodeTexts(message.toByteArray()))?.let(::scannedPaymentRequest) |
There was a problem hiding this comment.
[LOW] Keep the NFC-specific error for readable tags without a payment request
Manual case 4 expects “Unable To Read NFC” for a tag without a payment request. A Kotlin probe with a valid NDEF URI record containing an ordinary menu URL returned that URL as payable text. The main scanner would consequently dismiss itself, pass the URL to the generic decoder and report a QR error. Preserve the NFC source through validation so a readable non-payment tag produces the specified feedback and the user can retry. Manual case 4.
|
Physical-device follow-up on 18 November 2026, supplementing the current-head code review. Cross-testing used iPhone 13 (iOS 27.0.1) and Samsung Galaxy S22 SM-S901B (Android 16) on staging/regtest:
Results combine observed screen behavior with app/system logs where available. No wallet logs or payment addresses are attached. Passed in this session
Observations and separate bug One BLE recovery after toggling Nearby payments took about 102 seconds from advertising start to a new peer connection; it recovered on its own, and a repeat was immediate. Cause remains unconfirmed. Android Receive amount resets after background/foreground: #1971. Confirmed on this NFC build and installed mainnet 3.1.1 (197). The same 4,000-sat check retained the amount on iOS Scope still open The ordinary manual-entry and lifecycle checks did not deliberately hold an in-flight decode or payment preparation. They do not verify the new code-review findings involving cancellation, scene inactivity, recipient takeover, offline overlays or the initial saved privacy setting. The earlier controlled iOS routing checks are separate evidence. Static/malformed NFC tags, physical POS/Square hardware, a second Android NFC reader, Android 9–11 location behavior, a specifically expired Lightning invoice, reads during invoice regeneration, and funded USDT settlement remain untested here. The rejected-BTC/valid-USDT case does not cover all USDT networks or deposit variants. Earlier partial testing at iOS This is a partial device pass. The code-review findings remain open for fixes or evidence-backed rebuttals; these results do not establish merge approval. |
Closes #1740
Twin: synonymdev/bitkit-ios#1302
This PR adds NFC and Bluetooth nearby payments. Payment scanners read requests from NFC tags, payment terminals and nearby Bitkit wallets. The Receive screen offers its request to nearby phones. The protocol is in
docs/nearby-payments.mdand is shared with iOS.Platform support
Description
lightning:, BIP21bitcoin:(withlightning=), LNURL, and USDTethereum:.NdefTagService(host card emulation) serves the current request as a read-only NFC Forum Type 4 tag (categoryother, device unlock required). It also covers the USDT receive screen.D2760000850101is registered for the service only while Receive is shown, and the service is the preferred one meanwhile.bitcoin:, alightning:invoice or offer, and USDTethereum:. Anything else the scanner understands (Pubky auth, LNURL auth/withdraw/channel, wallet connection setups, contact keys) is ignored, and that device is skipped.NFC,BLUETOOTH_ADVERTISE, optionalnfcandnfc.hcefeatures, and the HCE service.Device test fixes
Testing on two phones found two problems, both fixed:
NfcRepeatGuardnow holds reader mode, with a callback that ignores tags, untilNfcAdapter.ignorereports that the tag has left the field. It then hands reader mode back to a scan screen that is still open. It engages after a scanner read, and when a tag tap launches or resumes the app (a22544e97).2336ef1ca).Review round (from bitkit-ios#1302)
A
bitcoin:?…URI with a required (req-) parameter is no longer rewritten tolightning:<invoice>, since the rewrite dropped that parameter. The scanner then refuses it. Test:NfcPaymentUriTest"request with a required parameter is kept"; it fails without the fix (4d5af8435).Wrapped login requests over Bluetooth: a request read over Bluetooth is now rewritten before the payment-only filter.
bitcoin:?lightning=<LNURL-auth>therefore can no longer reach the login sheet (82f44a4d8). Tests are inNearbyRequestFilterTest; the wrapped-request test fails without the fix.Stale request on Receive: Receive offers a request over NFC and Bluetooth only while its QR shows one. While the invoice updates, or after an update fails, nothing is offered, so the previous invoice can't be paid (
d88da7fad). Test:ReceiveInvoiceUtilsTest"nearby offers only the request the QR shows"; it fails without the fix.No Bluetooth advertising: a phone that can't advertise over Bluetooth counts as having no Bluetooth for Receive, so it no longer claims "Scan or tap to pay" when NFC is off (
b373d5ba0). An advertising start that fails at run time now drops the label too, until the request or the Bluetooth state changes (baeab2d1f). A late failure from an advertiser that already stopped is ignored (965ff980c). Not driven on a device.Button labels: the camera, Bluetooth and NFC source buttons have localized TalkBack labels (
49538ae06).Blocked permission: after the nearby-devices permission is denied for good, the Bluetooth button opens the app's settings (
c37460c77).Device check on the Pixel 11: the Bluetooth button reads "Enable Bluetooth". The first tap showed the permission dialog, which I denied; the second showed it again, which I denied for good. The third tap opened App info.
nearby-permission-settings-trimmed.mp4
Empty required parameters: a
req-key with an empty or no value (&req-foo=,&req-foo) also keeps the URI unrewritten (c06c3b7e1). TheNfcPaymentUriTestcases fail without the fix.Send E2E regression: the channel wait is skipped only while the node is not running yet and Spark covers the amount (
943e052ec). Skipping it with a running node also skipped publishing current channels. After a payment, the send limit then stayed too high, and thesendE2E's amount-exceeded check failed. The launch case still skips the wait. Test: "lightning scan waits for a running node even when spark covers the amount"; it fails without the fix.No 15 s wait when Spark pays: when Spark covers a Lightning payment, a running node now only publishes its current channels and doesn't wait for a usable one (
71680fc61). Before, it could wait up to 15 s when channels existed but none were usable.Enter Manually: a nearby request still decoding on the recipient screen is cancelled when the user taps Enter Manually, so it can't route over the address being typed (
f67cde893, ported from an iOS finding). The test fails without the fix.NFC launch: a tag that launches Bitkit gets the same
bitcoin:?lightning=rewrite as a scanner read, so the shipped core no longer rejects Numo's form (34f255940).Closed Receive: the tag emulator stops serving a selected request once Receive stops offering it, instead of serving it until the reader disconnects (
4f16c11ce).Duplicate Bluetooth read: a second delivery of the same request no longer drops the handle of the read still decoding, so Enter Manually still cancels it (
a88e203cd).Contacts: opening Contacts from the Send recipient screen drops a nearby read that is still decoding, as Enter Manually does (
869b45f3a).NFC after leaving the scanner: a tag read that finishes after the scanner screen closed is dropped instead of opening a payment (
5ca051cfb).Master merge (
d9c4ede2c): master now asks for the payment PIN before QuickPay settings are raised (QuickPaySettingsViewModel). The TapPay (NFC) intro sheet's QuickPay toggle now goes through that view model and shows the same PIN check, instead of writing the setting directly. Not driven on a device.NFC read after pause: each NFC reader activation now has a number, and pausing the reader ends that activation. A tag read that started before the scanner paused is dropped, even if it finishes after a later resume. Before this fix, it could still open a payment over Contacts during the 300 ms exit transition (
24180fd39). Each activation also registers its own callback, so a callback Android calls after reader mode was disabled carries a closed activation and is dropped (79e9f719f). Tests:NfcReadDispatcherTest"drops a read from a reader that paused or closed" and "drops a read from an earlier activation after the reader resumed"; they fail without the fix. Not driven on a device.Rejected Bluetooth request: a phone whose request was rejected without leaving the scanner (an expired invoice, or a non-USDT request on the USDT scanner) is read again after 10 s, as on iOS. Before, it was ignored until the scanner closed (
a3496bf06). Not driven on a device.Translated button labels:
other__bluetooth_enableandother__nfc_enableare in all 15 locales (483562df5).NFC read on Enter Manually: an NFC read on the Send recipient screen that is still decoding is dropped when the user taps Enter Manually, as a Bluetooth read already was (
3a21060c6).Merged
masteragain (9e09c6bea): the conflicts were translated strings, and both sides were kept.Merged
masteragain (4f8552895). The only conflict wasSettingsScreen.kt, wheremasterremoved the contact and public payments rows; this branch now adds only the nearby payments row there.POS request formats
lightning:<uppercase BOLT11>as one long-format NDEF URI record (header0xC1, identifier code0x00). Bitkit decodes it as is. Tests cover it with a real 447-character signet invoice, a 465-byte message laid out like Square's.bitcoin:?lightning=<BOLT11>. bitkit-core v0.8.0-rc15 rejects that form, so requests read over NFC or Bluetooth are rewritten tolightning:<invoice>before decoding. feat: decode BIP 321 URIs without an address bitkit-core#218 fixes this on coremaster, but no release includes it yet. The rewrite goes with the core bump: Remove the BIP 321 rewrite after the bitkit-core bump #1935.Out of Scope
nfc: being read by Bolt Card terminals (Blink, BTCPay, LNbits TPoS, Swiss Bitcoin Pay, Wallet of Satoshi merchant mode). They read anlnurlwcard and pull the payment, which needs a server-side LNURL-withdraw relay for a self-custodial wallet.nfc: USDT over NFC terminals. None exist on any chain, Arbitrum included. A USDTethereum:request read from another Bitkit is supported.nearby: requesting the Nearby devices permission from Receive. Receive advertises only once the permission was granted from the scanner, because the design has no Receive permission state.settings: the design's "QRs + NFC" QuickPay row value. The row keeps On/Off.Design
NFC compatibility (research, Nov 2026):
lightning:Type 4 taglightning:/bitcoin:/LNURL tagslnurlwcardPreview
Screenshots are from an emulator, which has no NFC hardware. For these captures only, the NFC availability checks were forced on in a local build. That override is not in this branch. The Bluetooth states are real.
QA Notes
Setup
devDebug) from this branch on two NFC-capable Android phones, a third phone or a tag writer for static tags, and an iPhone running feat: nfc and bluetooth nearby payments bitkit-ios#1302 for the cross-platform cases.Testing with bitkit-core master
The branch ships with bitkit-core v0.8.0-rc15. To test against core
master(51276ae, which includes synonymdev/bitkit-core#218), build core locally. Its API is unchanged since rc15, so the app builds without code changes.master:./build_android.sh && cd bindings/android && ./gradlew publishToMavenLocal -Pversion=0.8.0-master-51276ae.bitkit-coreversion ingradle/libs.versions.tomlto0.8.0-master-51276ae. Don't commit it../gradlew assembleDevDebug -PuseMavenLocal=bitkit-core.What changes with core
master:bitcoin:?lightning=<BOLT11>in any case, open the Lightning send flow. On rc15 they show an invalid-address error.bitcoin:URIs with anyreq-parameter,req-popincluded, are rejected.Journeys
nearby-payments-toggle.xml— Settings shows Nearby payments on by default, and the choice persistsscanner-nearby-states.xml— the Send scanner shows Scan to pay when the camera is denied, a Bluetooth button and "Scanning QR" without the Nearby devices permission, then "Scanning QR & Bluetooth"NFC and Bluetooth between devices are not in the Capabilities table; see Manual Tests.
Manual Tests
lightning:tag, abitcoin:?lightning=tag and an LNURL-pay tag from the main scanner → each opens the matching send flow — NFC tagspubkyauth://URI from a test build) → B's scanner ignores it and opens nothing — Bluetooth between devicesAutomated Checks
NdefCodecTest.kt— URI/Text/absolute-URI records, prefix codes, long records, malformed input, and single-request selectionType4TagEmulatorTest.kt— the Type 4 APDU read sequence, chunked reads, no tag while nothing is published, read-only, and errorsNfcPaymentUriTest.kt— schemes added to bare invoices and addressesNearbyProtocolTest.kt— UUIDs, meta encoding, chunking and reassembly, offset reads, and limitsNfcTimedSheetTest.kt— shows once and only with NFC, and marks both intros seenNearbyRequestFilterTest.kt— Bluetooth accepts bitcoin, lightning invoice/offer and ethereum requests, and refuses auth, LNURL, setup and contact payloadsNfcTagEmitterTest.kt— an older publisher cannot clear a newer requestAppViewModelSendFlowTest.kt— new timed sheet dependency, and a Lightning scan skips the channel wait when Spark covers the amount but waits otherwiseAppViewModelSendFlowTest.kt— Enter Manually and Contacts drop an NFC or Bluetooth read still decoding, including after a duplicate Bluetooth deliveryNfcReadDispatcherTest.kt— duplicate reads within 3 s are dropped, and a read from a paused, closed or earlier reader activation is ignoredEvidence
On two physical phones, a Pixel 11 (Android 17) and a Xiaomi 22031116BG (Android 13), running regtest
devDebugbuilt against bitkit-coremaster(51276ae). Both wallets were funded on Spark through Lightspark's regtest faucet. The Xiaomi is on the left in each video, the Pixel on the right.Case 1a, NFC with QuickPay: the Pixel offers a ₿ 1,000 request and the Xiaomi's scanner reads it. QuickPay pays in about 9 s from the tap.
nfc-quickpay-side-by-side.mp4
Case 5, Bluetooth: the Xiaomi finds the Pixel's ₿ 1,000 request about 8 s after the nearby-devices permission is granted. It opens the review, because QuickPay is suppressed for requests read over Bluetooth. Swipe to pay completes in 4.4 s.
bluetooth-side-by-side.mp4
Case 15 and the repeat guard, on
2336ef1ca: the video shows three taps:nfc-repeat-guard-side-by-side.mp4
Case 1, with review: run with the Pixel paying, with its camera denied (see the Pixel 11 note). The tap opened the review for ₿ 25, and the payment completed.
On
28639c4e7:just compile,just testandjust lint(detekt and Android Lint) all pass.Read nearby request, thenHandling decoded scan data).On
40b2a250b:devDebug:dumpsys bluetooth_manager.Read nearby requestand thenHandling decoded scan data: OnChain(... lightning=lnbcrt1...). That covers case 5's transport, but not a completed payment, because B had no funds.Pixel 11: NFC reading stops while the camera is open
On a Pixel 11 (Android 17, build CD1A.261005.003), the system switches NFC polling off while the camera is in use. The scan screen shows the camera, so on this phone it cannot read an NFC payment request.
setReaderMode ... to.bitkit.dev, flags: 15,tech_mask = 0f). About 0.1 s after the QR camera opens, the system sets reader mode again (uid=1000, packageName: android, flags: 4096,tech_mask = 00), which disables polling. Polling comes back only when Bitkit leaves the scan screen. Reproduced three times.tech_mask = 0f) and a tap reads the request and opens the payment.Gaps
3e377fbf9, and its findings were addressed in28639c4e7. One finding was not taken: it flagged thatshowsTapToPaycomes aftermodifierinReceiveQrView, but AGENTS.md requiresmodifierto be the first optional parameter.Models used
claude-opus-5-5(reasoning:Not exposed)claude-opus-5-5(reasoning:Not exposed)claude-opus-5-5(reasoning:Not exposed)Metadata note: the session exposes the model ID but not the reasoning setting.
🤖 Generated with Claude Code