diff --git a/app/src/debug/java/to/bitkit/ui/utils/ScreenDeepLinkRuntime.kt b/app/src/debug/java/to/bitkit/ui/utils/ScreenDeepLinkRuntime.kt index fe5febcd73..c95c10e471 100644 --- a/app/src/debug/java/to/bitkit/ui/utils/ScreenDeepLinkRuntime.kt +++ b/app/src/debug/java/to/bitkit/ui/utils/ScreenDeepLinkRuntime.kt @@ -61,5 +61,5 @@ private val FAMILIES: List = listOf( private val STANDALONE: List = listOf( Sheet.ActivityDateRangeSelector, Sheet.ActivityTagSelector, - Sheet.QrScanner(), + Sheet.QrScanner(readsNearby = true), ) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index eecc4b0cb0..9dbfa70c1d 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -19,6 +19,15 @@ + + + + + + + @@ -71,6 +82,18 @@ android:enabled="true" android:exported="false" /> + + + + + + + Unit = {}, +) { + private val bluetoothManager = context.bluetoothManager + + @Volatile + private var request: ByteArray? = null + private var gattServer: BluetoothGattServer? = null + private var advertiseCallback: AdvertiseCallback? = null + private val isAdvertising get() = advertiseCallback != null + private val mainHandler = Handler(Looper.getMainLooper()) + + /** Counts opened servers, so a registration result for a closed server is ignored. */ + private var serverGeneration = 0 + private var isServiceRegistered = false + + /** A new callback per start, so a failure reported after [stop] or a later start is ignored. */ + private fun newAdvertiseCallback(): AdvertiseCallback = object : AdvertiseCallback() { + override fun onStartFailure(errorCode: Int) { + Logger.warn("Failed nearby advertising with error '$errorCode'", context = TAG) + if (advertiseCallback !== this) return + advertiseCallback = null + onFailed() + } + } + + private fun newServerCallback(generation: Int) = object : BluetoothGattServerCallback() { + override fun onServiceAdded(status: Int, service: BluetoothGattService?) { + mainHandler.post { onServiceRegistered(generation, status == BluetoothGatt.GATT_SUCCESS) } + } + + @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT) + override fun onCharacteristicReadRequest( + device: BluetoothDevice, + requestId: Int, + offset: Int, + characteristic: BluetoothGattCharacteristic, + ) { + val server = gattServer ?: return + val value = valueFor(characteristic) + val response = value?.let { NearbyProtocol.readAt(it, offset) } + if (response == null) { + server.sendResponse(device, requestId, BluetoothGatt.GATT_INVALID_OFFSET, offset, null) + } else { + server.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, response) + } + } + } + + @RequiresPermission(allOf = [Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_ADVERTISE]) + fun start(uri: String) { + val encoded = NearbyProtocol.encodeRequest(uri) ?: return stop() + request = encoded + if (gattServer == null) gattServer = openServer() ?: return onFailed() + if (isServiceRegistered && !isAdvertising) startAdvertising() + } + + // start() holds both permissions, and this runs only for the server it opened. + @SuppressLint("MissingPermission") + private fun onServiceRegistered(generation: Int, isRegistered: Boolean) { + if (generation != serverGeneration || gattServer == null) return + if (!isRegistered) { + Logger.warn("Failed to register the nearby GATT service", context = TAG) + stop() + onFailed() + return + } + isServiceRegistered = true + if (request != null && !isAdvertising) startAdvertising() + } + + @RequiresPermission(allOf = [Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_ADVERTISE]) + fun stop() { + request = null + advertiseCallback?.let { callback -> + runCatching { bluetoothManager.adapter?.bluetoothLeAdvertiser?.stopAdvertising(callback) } + } + advertiseCallback = null + runCatching { gattServer?.close() } + gattServer = null + isServiceRegistered = false + serverGeneration++ + } + + private fun valueFor(characteristic: BluetoothGattCharacteristic): ByteArray? { + val current = request ?: return null + if (characteristic.uuid == NearbyProtocol.META_UUID) return NearbyProtocol.meta(current) + val index = NearbyProtocol.DATA_UUIDS.indexOf(characteristic.uuid) + return if (index >= 0) NearbyProtocol.chunk(current, index) else null + } + + @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT) + private fun openServer(): BluetoothGattServer? { + val generation = ++serverGeneration + val server = runCatching { bluetoothManager.openGattServer(context, newServerCallback(generation)) } + .onFailure { Logger.warn("Failed to open nearby GATT server", it, context = TAG) } + .getOrNull() ?: return null + val service = BluetoothGattService(NearbyProtocol.SERVICE_UUID, BluetoothGattService.SERVICE_TYPE_PRIMARY) + (listOf(NearbyProtocol.META_UUID) + NearbyProtocol.DATA_UUIDS).forEach { + service.addCharacteristic( + BluetoothGattCharacteristic( + it, + BluetoothGattCharacteristic.PROPERTY_READ, + BluetoothGattCharacteristic.PERMISSION_READ, + ) + ) + } + if (!runCatching { server.addService(service) }.getOrDefault(false)) { + Logger.warn("Failed to add the nearby GATT service", context = TAG) + runCatching { server.close() } + return null + } + return server + } + + @RequiresPermission(Manifest.permission.BLUETOOTH_ADVERTISE) + private fun startAdvertising() { + val advertiser = bluetoothManager.adapter?.bluetoothLeAdvertiser ?: return onFailed() + val settings = AdvertiseSettings.Builder() + .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY) + .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_LOW) + .setConnectable(true) + .build() + val data = AdvertiseData.Builder() + .setIncludeDeviceName(false) + .setIncludeTxPowerLevel(false) + .addServiceUuid(ParcelUuid(NearbyProtocol.SERVICE_UUID)) + .build() + val callback = newAdvertiseCallback() + advertiseCallback = callback + runCatching { advertiser.startAdvertising(settings, data, callback) } + .onFailure { + advertiseCallback = null + Logger.warn("Failed to start nearby advertising", it, context = TAG) + onFailed() + } + } + + private companion object { + const val TAG = "NearbyAdvertiser" + } +} diff --git a/app/src/main/java/to/bitkit/nearby/NearbyProtocol.kt b/app/src/main/java/to/bitkit/nearby/NearbyProtocol.kt new file mode 100644 index 0000000000..745cdf95e8 --- /dev/null +++ b/app/src/main/java/to/bitkit/nearby/NearbyProtocol.kt @@ -0,0 +1,58 @@ +package to.bitkit.nearby + +import java.util.UUID + +/** + * Bitkit nearby payments over Bluetooth LE, version 1. See docs/nearby-payments.md. + * + * The receiving phone serves its payment request from a GATT service; a paying phone reads the + * meta characteristic for the length and then as many 512-byte data chunks as it needs. + */ +object NearbyProtocol { + val SERVICE_UUID: UUID = UUID.fromString("CB0E128B-1CA5-4959-94DF-A4FE588E3E98") + val META_UUID: UUID = UUID.fromString("69A713E5-B0A7-42F1-8B7F-FA0BDA119C00") + val DATA_UUIDS: List = (1..CHUNK_COUNT).map { + UUID.fromString("69A713E5-B0A7-42F1-8B7F-FA0BDA119C%02X".format(it)) + } + + const val VERSION: Byte = 0x01 + const val CHUNK_SIZE = 512 + const val CHUNK_COUNT = 8 + const val MAX_REQUEST_BYTES = CHUNK_SIZE * CHUNK_COUNT + const val MIN_RSSI = -60 + + /** The request as served, or null when it is empty or too large to serve. */ + fun encodeRequest(request: String): ByteArray? { + val bytes = request.toByteArray(Charsets.UTF_8) + return bytes.takeIf { it.isNotEmpty() && it.size <= MAX_REQUEST_BYTES } + } + + fun meta(request: ByteArray): ByteArray = + byteArrayOf(VERSION, (request.size shr 8).toByte(), request.size.toByte()) + + /** Chunk [index] of [request]; empty past the end of the request. */ + fun chunk(request: ByteArray, index: Int): ByteArray { + val start = index * CHUNK_SIZE + if (index !in 0 until CHUNK_COUNT || start >= request.size) return byteArrayOf() + return request.copyOfRange(start, minOf(request.size, start + CHUNK_SIZE)) + } + + /** The request length announced by [meta], or null for an unknown version or bad length. */ + fun requestLength(meta: ByteArray): Int? { + if (meta.size < 3 || meta[0] != VERSION) return null + val length = ((meta[1].toInt() and 0xFF) shl 8) or (meta[2].toInt() and 0xFF) + return length.takeIf { it in 1..MAX_REQUEST_BYTES } + } + + fun chunksFor(length: Int): Int = (length + CHUNK_SIZE - 1) / CHUNK_SIZE + + /** Value served for a read at [offset] of a characteristic whose full value is [value]. */ + fun readAt(value: ByteArray, offset: Int): ByteArray? = + if (offset in 0..value.size) value.copyOfRange(offset, value.size) else null + + fun decode(chunks: List, length: Int): String? { + val bytes = chunks.fold(byteArrayOf()) { acc, chunk -> acc + chunk } + if (bytes.size != length) return null + return bytes.toString(Charsets.UTF_8).trim().takeIf { it.isNotEmpty() } + } +} diff --git a/app/src/main/java/to/bitkit/nearby/NearbyRequestFilter.kt b/app/src/main/java/to/bitkit/nearby/NearbyRequestFilter.kt new file mode 100644 index 0000000000..18650c1906 --- /dev/null +++ b/app/src/main/java/to/bitkit/nearby/NearbyRequestFilter.kt @@ -0,0 +1,99 @@ +package to.bitkit.nearby + +import com.synonym.bitkitcore.validateBitcoinAddress +import to.bitkit.env.Env +import to.bitkit.models.toLdkNetwork +import to.bitkit.nfc.hasRequiredParam +import to.bitkit.nfc.scannedPaymentRequest +import to.bitkit.utils.NetworkValidationHelper + +private const val BECH32_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l" +private val BECH32_GENERATOR = intArrayOf(0x3B6A57B2, 0x26508E6D, 0x1EA119FA, 0x3D4233DD, 0x2A1462B3) +private const val BECH32_CHECKSUM_LENGTH = 6 +private val BOLT11_NETWORKS = listOf("lnbcrt", "lntbs", "lnbc", "lntb") + +/** + * Whether [value] is a BOLT11 invoice: a mainnet, testnet, signet or regtest prefix the decoder reads as BOLT11, an + * optional amount, the `1` separator and bech32 data whose checksum holds. A Lightning address or LNURL never + * matches, and neither does a string that only looks like an invoice, which would fail to decode. + */ +internal fun isBolt11Invoice(value: String): Boolean { + val lowercase = value.lowercase() + val separator = lowercase.lastIndexOf('1') + if (separator < 0) return false + val hrp = lowercase.substring(0, separator) + val network = BOLT11_NETWORKS.firstOrNull { hrp.startsWith(it) } ?: return false + val amountAndUnit = hrp.removePrefix(network) + val hasUnit = amountAndUnit.isNotEmpty() && amountAndUnit.last() in "munp" + val amount = if (hasUnit) amountAndUnit.dropLast(1) else amountAndUnit + if (!amount.all { it in '0'..'9' }) return false + val data = lowercase.substring(separator + 1).map { BECH32_CHARSET.indexOf(it) } + if (data.size < BECH32_CHECKSUM_LENGTH || data.any { it < 0 }) return false + val values = hrp.map { it.code shr 5 } + 0 + hrp.map { it.code and 31 } + data + var checksum = 1 + for (value5 in values) { + val top = checksum ushr 25 + checksum = (checksum and 0x1FFFFFF) shl 5 xor value5 + BECH32_GENERATOR.forEachIndexed { bit, generator -> + if ((top shr bit) and 1 == 1) checksum = checksum xor generator + } + } + return checksum == 1 +} + +private val BECH32_ADDRESS_PREFIXES = listOf("bc1", "tb1", "bcrt1") + +/** + * Whether a `bitcoin:` URI names a valid address for this wallet's network, checked as the scanner does, so it can + * decode the request instead of resetting Send and closing on an error. Like the decoder, a bech32 address is + * validated in lowercase and a base58 one in its own case, so [uri] keeps its case. + */ +private fun hasPayableAddress(uri: String): Boolean { + val address = uri.substringAfter(':').substringBefore('?') + if (address.isEmpty()) return false + val lowercase = address.lowercase() + val normalized = if (BECH32_ADDRESS_PREFIXES.any(lowercase::startsWith)) lowercase else address + val network = runCatching { validateBitcoinAddress(normalized).network }.getOrNull() ?: return false + return !NetworkValidationHelper.isNetworkMismatch(network.toLdkNetwork(), Env.network) +} + +/** + * Whether [request], read from a nearby device over Bluetooth, is a payment request Bitkit serves: + * a BIP21 `bitcoin:` URI with an address, a `lightning:` BOLT11 invoice, or a USDT `ethereum:` request. + * + * Any device in range can answer a scan, so everything else the scanner understands (Pubky auth, + * LNURL-auth/withdraw/channel, wallet connection setups, contact keys) is refused for this source. + * So is what the scanner cannot pay, such as a BOLT12 offer or a `bitcoin:` URI left without an address, + * since accepting it would close the scanner on an error, and a `bitcoin:` URI whose Lightning request is not a + * BOLT11 invoice, since decoding an LNURL there would contact a server no one chose. + */ +fun isNearbyPaymentRequest(request: String): Boolean { + val trimmed = request.trim() + val lowercase = trimmed.lowercase() + return when { + // No Bitkit flow fulfils a required (`req-`) parameter, and the decoder ignores one next to an address. + hasRequiredParam(lowercase) -> false + // The app decodes a unified URI's Lightning request, and decoding an LNURL contacts its server. + // Every Lightning value is checked, since the decoder keeps the last one. + lowercase.startsWith("bitcoin:") -> + hasPayableAddress(trimmed) && lightningParams(lowercase).all(::isBolt11Invoice) + + lowercase.startsWith("ethereum:") -> true + lowercase.startsWith("lightning:") -> isBolt11Invoice(lowercase.removePrefix("lightning:")) + + else -> false + } +} + +private fun lightningParams(uri: String): List = uri.substringAfter('?', missingDelimiterValue = "") + .split('&') + .filter { it.startsWith("lightning=") } + .map { it.substringAfter('=') } + +/** + * The payment request to hand to the scanner for [request] read over Bluetooth, or null when it is refused. + * The request is rewritten before the check, so a wrapped value such as `bitcoin:?lightning=` + * is judged by what the scanner will actually receive. + */ +fun nearbyPaymentRequest(request: String): String? = + scannedPaymentRequest(request).takeIf(::isNearbyPaymentRequest) diff --git a/app/src/main/java/to/bitkit/nearby/NearbyScanner.kt b/app/src/main/java/to/bitkit/nearby/NearbyScanner.kt new file mode 100644 index 0000000000..d7abee3008 --- /dev/null +++ b/app/src/main/java/to/bitkit/nearby/NearbyScanner.kt @@ -0,0 +1,237 @@ +package to.bitkit.nearby + +import android.Manifest +import android.annotation.SuppressLint +import android.bluetooth.BluetoothDevice +import android.bluetooth.BluetoothGatt +import android.bluetooth.BluetoothGattCallback +import android.bluetooth.BluetoothGattCharacteristic +import android.bluetooth.BluetoothProfile +import android.bluetooth.le.ScanCallback +import android.bluetooth.le.ScanFilter +import android.bluetooth.le.ScanResult +import android.bluetooth.le.ScanSettings +import android.content.Context +import android.os.Handler +import android.os.Looper +import android.os.ParcelUuid +import androidx.annotation.RequiresPermission +import to.bitkit.ext.bluetoothManager +import to.bitkit.ext.connectGattDirect +import to.bitkit.ext.nowMillis +import to.bitkit.utils.Logger +import java.util.UUID +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds + +/** + * Finds the closest nearby Bitkit wallet that serves a payment request and reads that request. + * + * While started it scans for the nearby service. Once an advertiser at or above + * [NearbyProtocol.MIN_RSSI] is seen, it waits [CANDIDATE_WINDOW] for others, connects to the + * strongest one and reads the request. Only payment requests ([nearbyPaymentRequest]) reach + * [onRequest], on the main thread. A device is then skipped for [RETRY_AFTER], so the scanner keeps listening for + * others, and reads the device again if the screen stayed open after rejecting its request. + */ +class NearbyScanner( + private val context: Context, + private val onRequest: (String) -> Unit, +) { + private val handler = Handler(Looper.getMainLooper()) + private val candidates = mutableMapOf>() + private val skippedUntil = mutableMapOf() + private var isScanning = false + private var isStarted = false + private var session: ReadSession? = null + + private val scanCallback = object : ScanCallback() { + override fun onScanResult(callbackType: Int, result: ScanResult) { + handler.post { onCandidate(result.device, result.rssi) } + } + + override fun onScanFailed(errorCode: Int) { + Logger.warn("Failed nearby scan with error '$errorCode'", context = TAG) + handler.post { + isScanning = false + handler.postDelayed(::restartScan, SCAN_RETRY_DELAY.inWholeMilliseconds) + } + } + } + + @RequiresPermission(allOf = [Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT]) + fun start() { + isStarted = true + startScan() + } + + @SuppressLint("MissingPermission") // Only reachable after start(), which requires the scan permissions. + fun stop() { + isStarted = false + stopScan() + handler.removeCallbacksAndMessages(null) + session?.close() + session = null + candidates.clear() + skippedUntil.clear() + } + + @SuppressLint("MissingPermission") // Scheduled only by a started scanner. + private fun restartScan() = startScan() + + @RequiresPermission(Manifest.permission.BLUETOOTH_SCAN) + private fun startScan() { + if (isScanning || session != null || !isStarted) return + val scanner = context.bluetoothManager.adapter?.takeIf { it.isEnabled }?.bluetoothLeScanner ?: return + val filter = ScanFilter.Builder().setServiceUuid(ParcelUuid(NearbyProtocol.SERVICE_UUID)).build() + val settings = ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build() + runCatching { scanner.startScan(listOf(filter), settings, scanCallback) } + .onSuccess { isScanning = true } + .onFailure { Logger.warn("Failed to start nearby scan", it, context = TAG) } + } + + @SuppressLint("MissingPermission") // Stops a scan that start() began with the scan permissions. + private fun stopScan() { + if (!isScanning) return + runCatching { context.bluetoothManager.adapter?.bluetoothLeScanner?.stopScan(scanCallback) } + isScanning = false + } + + private fun onCandidate(device: BluetoothDevice, rssi: Int) { + if (!isStarted || session != null || rssi < NearbyProtocol.MIN_RSSI) return + val until = skippedUntil[device.address] + if (until != null && nowMillis() < until) return + val isFirst = candidates.isEmpty() + val previous = candidates[device.address]?.second + if (previous == null || rssi > previous) candidates[device.address] = device to rssi + if (isFirst) handler.postDelayed(::connectToClosest, CANDIDATE_WINDOW.inWholeMilliseconds) + } + + @SuppressLint("MissingPermission") // Scheduled only by a started scanner. + private fun connectToClosest() { + val closest = candidates.values.maxByOrNull { it.second }?.first ?: return + candidates.clear() + if (!isStarted) return + stopScan() + session = ReadSession(closest).also { it.open() } + } + + @SuppressLint("MissingPermission") // Called from a session that a started scanner opened. + private fun finish(finished: ReadSession, device: BluetoothDevice, request: String?) { + if (session !== finished) return + session?.close() + session = null + val payment = request?.let(::nearbyPaymentRequest) + if (request != null && payment == null) { + Logger.warn("Ignored nearby request that is not a payment", context = TAG) + } + skippedUntil[device.address] = nowMillis() + RETRY_AFTER.inWholeMilliseconds + if (!isStarted) return + if (payment != null) onRequest(payment) + startScan() + } + + @SuppressLint("MissingPermission") // Opened only by a started scanner, which holds BLUETOOTH_CONNECT. + private inner class ReadSession(private val device: BluetoothDevice) : BluetoothGattCallback() { + private var gatt: BluetoothGatt? = null + private var length = 0 + private val chunks = mutableListOf() + private var isDone = false + private val timeout = Runnable { complete(null) } + + fun open() { + handler.postDelayed(timeout, READ_TIMEOUT.inWholeMilliseconds) + gatt = runCatching { device.connectGattDirect(context, this, BluetoothDevice.TRANSPORT_LE) } + .onFailure { Logger.warn("Failed to connect to nearby device", it, context = TAG) } + .getOrNull() + if (gatt == null) complete(null) + } + + fun close() { + handler.removeCallbacks(timeout) + runCatching { + gatt?.disconnect() + gatt?.close() + } + gatt = null + } + + private fun complete(request: String?) { + handler.post { + if (isDone) return@post + isDone = true + finish(this, device, request) + } + } + + override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { + when { + status != BluetoothGatt.GATT_SUCCESS -> complete(null) + newState == BluetoothProfile.STATE_CONNECTED -> { + if (!gatt.requestMtu(MTU)) gatt.discoverServices() + } + newState == BluetoothProfile.STATE_DISCONNECTED -> complete(null) + } + } + + override fun onMtuChanged(gatt: BluetoothGatt, mtu: Int, status: Int) { + if (!gatt.discoverServices()) complete(null) + } + + override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) { + if (status != BluetoothGatt.GATT_SUCCESS || !read(gatt, NearbyProtocol.META_UUID)) complete(null) + } + + override fun onCharacteristicRead( + gatt: BluetoothGatt, + characteristic: BluetoothGattCharacteristic, + value: ByteArray, + status: Int, + ) { + onRead(gatt, characteristic, value, status) + } + + @Deprecated("Called instead of the variant with a value before API 33") + override fun onCharacteristicRead( + gatt: BluetoothGatt, + characteristic: BluetoothGattCharacteristic, + status: Int, + ) { + @Suppress("DEPRECATION") + onRead(gatt, characteristic, characteristic.value ?: byteArrayOf(), status) + } + + private fun onRead( + gatt: BluetoothGatt, + characteristic: BluetoothGattCharacteristic, + value: ByteArray, + status: Int, + ) { + if (status != BluetoothGatt.GATT_SUCCESS) return complete(null) + if (characteristic.uuid == NearbyProtocol.META_UUID) { + length = NearbyProtocol.requestLength(value) ?: return complete(null) + } else { + chunks += value + } + if (chunks.size < NearbyProtocol.chunksFor(length)) { + if (!read(gatt, NearbyProtocol.DATA_UUIDS[chunks.size])) complete(null) + } else { + complete(NearbyProtocol.decode(chunks, length)) + } + } + + private fun read(gatt: BluetoothGatt, uuid: UUID): Boolean { + val characteristic = gatt.getService(NearbyProtocol.SERVICE_UUID)?.getCharacteristic(uuid) ?: return false + return gatt.readCharacteristic(characteristic) + } + } + + private companion object { + const val TAG = "NearbyScanner" + const val MTU = 517 + val CANDIDATE_WINDOW: Duration = 400.milliseconds + val READ_TIMEOUT: Duration = 8.seconds + val RETRY_AFTER: Duration = 10.seconds + val SCAN_RETRY_DELAY: Duration = 5.seconds + } +} diff --git a/app/src/main/java/to/bitkit/nfc/NdefCodec.kt b/app/src/main/java/to/bitkit/nfc/NdefCodec.kt new file mode 100644 index 0000000000..60080c9471 --- /dev/null +++ b/app/src/main/java/to/bitkit/nfc/NdefCodec.kt @@ -0,0 +1,116 @@ +package to.bitkit.nfc + +import java.nio.ByteBuffer + +/** + * Encodes and decodes the NDEF records used for NFC payments. + * + * Bitkit writes one NFC Forum well-known URI record ("U") holding the payment request. + * When reading, it accepts URI records, Text records ("T", used by Numo and some POS apps) + * and absolute-URI records, so a tag from any payment terminal or wallet lands in the same + * scan flow as a QR code. + */ +object NdefCodec { + private const val FLAG_MB = 0x80 + private const val FLAG_ME = 0x40 + private const val FLAG_CF = 0x20 + private const val FLAG_SR = 0x10 + private const val FLAG_IL = 0x08 + private const val TNF_MASK = 0x07 + private const val TNF_WELL_KNOWN = 0x01 + private const val TNF_ABSOLUTE_URI = 0x03 + private const val TEXT_UTF16 = 0x80 + private const val TEXT_LANG_LENGTH_MASK = 0x3F + private const val SHORT_RECORD_MAX = 255 + private val TYPE_URI = byteArrayOf('U'.code.toByte()) + private val TYPE_TEXT = byteArrayOf('T'.code.toByte()) + + /** URI identifier codes, NFC Forum URI Record Type Definition, table 3. */ + private val URI_PREFIXES = listOf( + "", "http://www.", "https://www.", "http://", "https://", "tel:", "mailto:", + "ftp://anonymous:anonymous@", "ftp://ftp.", "ftps://", "sftp://", "smb://", "nfs://", + "ftp://", "dav://", "news:", "telnet://", "imap:", "rtsp://", "urn:", "pop:", "sip:", + "sips:", "tftp:", "btspp://", "btl2cap://", "btgoep://", "tcpobex://", "irdaobex://", + "file://", "urn:epc:id:", "urn:epc:tag:", "urn:epc:pat:", "urn:epc:raw:", "urn:epc:", "urn:nfc:", + ) + + /** One NDEF message with a single URI record, written without an abbreviation prefix. */ + fun encodeUriMessage(uri: String): ByteArray { + val payload = byteArrayOf(0x00) + uri.toByteArray(Charsets.UTF_8) + val isShort = payload.size <= SHORT_RECORD_MAX + val header = FLAG_MB or FLAG_ME or TNF_WELL_KNOWN or (if (isShort) FLAG_SR else 0) + val lengthBytes = if (isShort) { + byteArrayOf(payload.size.toByte()) + } else { + ByteBuffer.allocate(Int.SIZE_BYTES).putInt(payload.size).array() + } + return byteArrayOf(header.toByte(), TYPE_URI.size.toByte()) + lengthBytes + TYPE_URI + payload + } + + /** + * Returns the text of every URI, Text or absolute-URI record in [message]. + * Other record types are skipped. A malformed or chunked message yields an empty list. + */ + fun decodeTexts(message: ByteArray): List = runCatching { parse(message) }.getOrDefault(emptyList()) + + /** + * Picks the payment request from the decoded record texts: the single distinct non-blank + * value, or null when the tag holds nothing or several different requests. + */ + fun payableText(texts: List): String? { + val distinct = texts.map { it.trim() }.filter { it.isNotEmpty() }.distinct() + return distinct.singleOrNull() + } + + private fun parse(message: ByteArray): List { + val texts = mutableListOf() + var offset = 0 + while (offset < message.size) { + val header = message[offset].toInt() and 0xFF + require(header and FLAG_CF == 0) { "Chunked records are not supported" } + val typeLength = message[offset + 1].toInt() and 0xFF + offset += 2 + val payloadLength: Int + if (header and FLAG_SR != 0) { + payloadLength = message[offset].toInt() and 0xFF + offset += 1 + } else { + payloadLength = ByteBuffer.wrap(message, offset, Int.SIZE_BYTES).int + offset += Int.SIZE_BYTES + } + require(payloadLength >= 0) { "Invalid payload length" } + val idLength = if (header and FLAG_IL != 0) (message[offset++].toInt() and 0xFF) else 0 + val type = message.copyOfRange(offset, offset + typeLength) + offset += typeLength + idLength + require(offset + payloadLength <= message.size) { "Truncated record" } + val payload = message.copyOfRange(offset, offset + payloadLength) + offset += payloadLength + + recordText(header and TNF_MASK, type, payload)?.let(texts::add) + if (header and FLAG_ME != 0) break + } + return texts + } + + private fun recordText(tnf: Int, type: ByteArray, payload: ByteArray): String? = when { + tnf == TNF_WELL_KNOWN && type.contentEquals(TYPE_URI) -> decodeUri(payload) + tnf == TNF_WELL_KNOWN && type.contentEquals(TYPE_TEXT) -> decodeText(payload) + tnf == TNF_ABSOLUTE_URI -> type.toString(Charsets.UTF_8) + else -> null + } + + private fun decodeUri(payload: ByteArray): String? { + if (payload.isEmpty()) return null + val prefix = URI_PREFIXES.getOrNull(payload[0].toInt() and 0xFF) ?: return null + return prefix + payload.copyOfRange(1, payload.size).toString(Charsets.UTF_8) + } + + private fun decodeText(payload: ByteArray): String? { + if (payload.isEmpty()) return null + val status = payload[0].toInt() and 0xFF + val textStart = 1 + (status and TEXT_LANG_LENGTH_MASK) + if (textStart > payload.size) return null + val charset = if (status and TEXT_UTF16 != 0) Charsets.UTF_16 else Charsets.UTF_8 + return payload.copyOfRange(textStart, payload.size).toString(charset) + } +} diff --git a/app/src/main/java/to/bitkit/nfc/NfcPaymentUri.kt b/app/src/main/java/to/bitkit/nfc/NfcPaymentUri.kt new file mode 100644 index 0000000000..28e4d8b8dd --- /dev/null +++ b/app/src/main/java/to/bitkit/nfc/NfcPaymentUri.kt @@ -0,0 +1,127 @@ +package to.bitkit.nfc + +import java.math.BigDecimal + +private val URI_SCHEMES = listOf("bitcoin:", "lightning:", "ethereum:", "lnurlp:", "lnurlw:", "lnurlc:") +private val LIGHTNING_PREFIXES = listOf("lnbc", "lntb", "lntbs", "lnbcrt", "lnsb", "lno1", "lnurl") + +/** + * Turns a receive request into the URI written to an NFC tag. + * + * A tag needs a scheme for other wallets (and Android's tag dispatch) to recognise the request, + * so a bare BOLT11 invoice, offer or LNURL gets `lightning:` and a bare address gets `bitcoin:`. + * Requests that already carry a payment scheme are returned unchanged. + */ +fun nfcPaymentUri(request: String?): String? { + val trimmed = request?.trim().orEmpty() + if (trimmed.isEmpty()) return null + val lowercase = trimmed.lowercase() + return when { + URI_SCHEMES.any { lowercase.startsWith(it) } -> trimmed + LIGHTNING_PREFIXES.any { lowercase.startsWith(it) } -> "lightning:$trimmed" + else -> "bitcoin:$trimmed" + } +} + +private const val BITCOIN_WITHOUT_ADDRESS = "bitcoin:?" +private const val REQUIRED_PARAM_PREFIX = "req-" +private const val BITCOIN_SCHEME = "bitcoin:" +private const val DEEPLINK_SCHEME = "bitkit://" +private val DECODER_WRAPPERS = listOf("lightning:", "lnurl:", "lnurlw:", "lnurlc:", "lnurlp:") + +/** + * Keys BIP 321 ("Query Keys", "Invalid URIs") forbids repeating; `pop` and `req-pop` count as the same key. + * Unknown optional keys and payment instructions may repeat. + */ +private val SINGLETON_KEYS = setOf("amount", "label", "message", "pop") + +/** + * Turns a payment request read from a tag or a nearby device into one the scanner decodes. + * + * A BIP 321 URI may leave the address out and carry only a Lightning request + * (`bitcoin:?lightning=`, used by Numo and planned by Square). The scanner rejects a + * `bitcoin:` URI without an address, so that form becomes `lightning:`. A URI with a + * required (`req-`) parameter is kept, since BIP 321 forbids paying it without handling that + * parameter and the rewrite would drop it. So is a URI that repeats one of [SINGLETON_KEYS], which BIP 321 + * makes invalid; one with more than one `lightning` value, which Bitkit does not support, since the rewrite would + * have to pick one; and one whose `amount` the invoice does not carry: the invoice alone could not ask for it. + * Anything else is returned trimmed and unchanged. + */ +fun scannedPaymentRequest(text: String): String { + val trimmed = text.trim() + if (!trimmed.startsWith(BITCOIN_WITHOUT_ADDRESS, ignoreCase = true)) return trimmed + val pairs = trimmed.substring(BITCOIN_WITHOUT_ADDRESS.length).split('&') + // Checked on every key, since BIP 321 allows a required key with an empty or no value. + if (pairs.any { it.substringBefore('=').lowercase().startsWith(REQUIRED_PARAM_PREFIX) }) return trimmed + val keys = pairs.map { it.substringBefore('=').lowercase().removePrefix(REQUIRED_PARAM_PREFIX) } + val singletons = keys.filter { it in SINGLETON_KEYS } + if (singletons.size != singletons.toSet().size) return trimmed + if (keys.count { it == "lightning" } > 1) return trimmed + // An `amount` key with no value is a malformed amount, not a missing one. + val hasEmptyAmount = pairs.any { + it.substringBefore('=').equals("amount", ignoreCase = true) && it.substringAfter('=', "").isEmpty() + } + if (hasEmptyAmount) return trimmed + val params = pairs.mapNotNull { + val key = it.substringBefore('=', missingDelimiterValue = "") + val value = it.substringAfter('=', missingDelimiterValue = "") + if (key.isEmpty() || value.isEmpty()) null else key.lowercase() to value + }.toMap() + // A BOLT12 offer (`lno`) is left as is: the scanner cannot pay one yet. + val request = params["lightning"] ?: return trimmed + val amount = params["amount"] + if (amount != null && !isBolt11Amount(request, amount)) return trimmed + return "lightning:$request" +} + +/** + * Whether [uri] is a `bitcoin:` URI with a required (`req-`) BIP 321 parameter. No Bitkit flow fulfils one, and the + * shipped scanner ignores it on a URI with an address, so a request read from a nearby device or a tag with one is + * refused. Other schemes, such as an LNURL-pay URL, keep their own query untouched. + */ +fun hasRequiredParam(uri: String): Boolean { + // The app and the decoder strip the Lightning wrappers from the front. While the text starts with `bitkit://`, the + // decoder deletes every `bitkit://` in it, which can turn a key into `req-`, and decodes again. Follow the same + // steps and check the `bitcoin:` request the decoder would receive. + var decoded = uri.coreTrim() + while (true) { + val wrapper = DECODER_WRAPPERS.firstOrNull { decoded.startsWith(it, ignoreCase = true) } + decoded = when { + wrapper != null -> decoded.substring(wrapper.length).coreTrim() + decoded.startsWith(DEEPLINK_SCHEME) -> decoded.replace(DEEPLINK_SCHEME, "").coreTrim() + else -> break + } + } + if (!decoded.startsWith(BITCOIN_SCHEME, ignoreCase = true)) return false + return decoded.substringAfter('?', missingDelimiterValue = "") + .split('&') + .any { it.substringBefore('=').lowercase().startsWith(REQUIRED_PARAM_PREFIX) } +} + +/** Trims like the decoder's Rust `trim()`, which also removes U+0085 (NEL) that Kotlin's `trim()` keeps. */ +private fun String.coreTrim() = trim { it.isWhitespace() || it == '\u0085' } + +/** The request to hand to the scanner for [text] read from an NFC tag, or null when it is refused. */ +fun nfcPaymentRequest(text: String): String? = scannedPaymentRequest(text).takeUnless(::hasRequiredParam) + +/** BIP 321 amount syntax: decimal BTC, with no sign, exponent or unit. */ +private val BIP321_AMOUNT = Regex("^(\\d+(\\.\\d*)?|\\.\\d+)$") +private val BOLT11_HRP = Regex("^ln[a-z]+?(\\d+)([munp]?)$") +private val BTC_PER_UNIT = mapOf( + "" to BigDecimal.ONE, + "m" to BigDecimal("0.001"), + "u" to BigDecimal("0.000001"), + "n" to BigDecimal("0.000000001"), + "p" to BigDecimal("0.000000000001"), +) + +/** Whether [invoice] is a BOLT11 invoice for exactly [amountBtc], read from its human-readable part. */ +private fun isBolt11Amount(invoice: String, amountBtc: String): Boolean { + val hrp = invoice.lowercase().substringBeforeLast('1', missingDelimiterValue = "") + val match = BOLT11_HRP.matchEntire(hrp) ?: return false + val (digits, unit) = match.destructured + val invoiceBtc = BigDecimal(digits).multiply(BTC_PER_UNIT.getValue(unit)) + if (!BIP321_AMOUNT.matches(amountBtc)) return false + val requested = amountBtc.toBigDecimal() + return invoiceBtc.compareTo(requested) == 0 +} diff --git a/app/src/main/java/to/bitkit/nfc/NfcReadDispatcher.kt b/app/src/main/java/to/bitkit/nfc/NfcReadDispatcher.kt new file mode 100644 index 0000000000..ed82f3aa46 --- /dev/null +++ b/app/src/main/java/to/bitkit/nfc/NfcReadDispatcher.kt @@ -0,0 +1,54 @@ +package to.bitkit.nfc + +import to.bitkit.ext.nowMillis +import kotlin.time.Duration +import kotlin.time.Duration.Companion.seconds + +/** + * Hands NFC reads to a scanner screen. Call it on the main thread only. Each time reader mode is enabled, [open] + * starts a new activation, and the callback registered with it passes that number to [deliver]. A read is dropped + * when its activation is not the open one: the reader paused, the screen left, or Android called an old callback + * after reader mode was disabled. A repeat of the same request within [DUPLICATE_READ_WINDOW] is dropped too. + */ +internal class NfcReadDispatcher( + private val onRead: (String) -> Unit, + private val onUnreadable: () -> Unit, + private val now: () -> Long = { nowMillis() }, +) { + private var lastRead: Pair? = null + private var activation = 0 + private var isOpen = false + + /** Starts a new activation and returns its number, for the callback registered with it. */ + fun open(): Int { + activation++ + isOpen = true + return activation + } + + /** Ends the open activation. Reads from it, or from an earlier one, are dropped. */ + fun close() { + isOpen = false + } + + /** Whether a read from [readActivation] would be delivered: the reader is open and still on that activation. */ + fun isCurrent(readActivation: Int): Boolean = isOpen && readActivation == activation + + fun deliver(text: String?, readActivation: Int) { + if (!isCurrent(readActivation)) return + if (text == null) { + onUnreadable() + return + } + val time = now() + val previous = lastRead + val isRepeat = previous?.first == text && time - previous.second < DUPLICATE_READ_WINDOW.inWholeMilliseconds + if (isRepeat) return + lastRead = text to time + onRead(text) + } + + companion object { + val DUPLICATE_READ_WINDOW: Duration = 3.seconds + } +} diff --git a/app/src/main/java/to/bitkit/nfc/NfcRepeatGuard.kt b/app/src/main/java/to/bitkit/nfc/NfcRepeatGuard.kt new file mode 100644 index 0000000000..260a9d5333 --- /dev/null +++ b/app/src/main/java/to/bitkit/nfc/NfcRepeatGuard.kt @@ -0,0 +1,98 @@ +package to.bitkit.nfc + +import android.app.Activity +import android.nfc.NfcAdapter +import android.nfc.Tag +import android.os.Handler +import android.os.Looper +import to.bitkit.utils.Logger +import java.lang.ref.WeakReference +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds + +internal const val READER_FLAGS = NfcAdapter.FLAG_READER_NFC_A or + NfcAdapter.FLAG_READER_NFC_B or + NfcAdapter.FLAG_READER_NFC_F or + NfcAdapter.FLAG_READER_NFC_V + +/** + * Reader mode is activity-wide, so only its latest owner may switch it off. A scanning screen registers how to + * take it back in [resumeScanner], so the repeat guard can hand reader mode back instead of switching it off. + */ +internal object ReaderModeOwner { + var current: Any? = null + var resumeScanner: (() -> Unit)? = null +} + +/** + * Stops Android from delivering a payment tag again while the phone stays on it after a read. + * + * Outside reader mode, Android dispatches every activation of a tag as a new NDEF_DISCOVERED intent, and a phone + * emulating a tag activates again whenever the field drops. A read followed by the scanner closing, or a tap that + * launched the app, then opens the app chooser or the app again. The guard holds reader mode with a callback that + * reads nothing until the tag has left the field, then hands reader mode back to a scanning screen or switches it + * off. + */ +internal object NfcRepeatGuard { + private const val TAG = "NfcRepeatGuard" + + /** How long the guard holds when no tag answers, e.g. after a launch from a tag already removed. */ + private val HOLD_WITHOUT_TAG: Duration = 3.seconds + + /** How long a tag must stay out of range before Android may deliver it again. */ + private val REMOVAL_DEBOUNCE: Duration = 1.seconds + + /** Covers the gap while an emulating phone re-activates its tag after a removal is reported. */ + private val RELEASE_AFTER_REMOVAL: Duration = 500.milliseconds + + private val handler = Handler(Looper.getMainLooper()) + private val release = Runnable { release() } + private var activity = WeakReference(null) + + /** Holds reader mode on [activity], which must be resumed. Pass the [tag] just read so its removal ends it. */ + fun engage(activity: Activity, tag: Tag? = null) { + if (Looper.myLooper() != Looper.getMainLooper()) { + handler.post { engage(activity, tag) } + return + } + val adapter = NfcAdapter.getDefaultAdapter(activity) ?: return + val enabled = runCatching { + adapter.enableReaderMode(activity, { onTag(adapter, it) }, READER_FLAGS, null) + }.onFailure { Logger.warn("Failed to hold NFC reader mode", it, context = TAG) }.isSuccess + if (!enabled) return + ReaderModeOwner.current = this + this.activity = WeakReference(activity) + schedule(HOLD_WITHOUT_TAG) + tag?.let { onTag(adapter, it) } + } + + private fun onTag(adapter: NfcAdapter, tag: Tag) { + handler.post { handler.removeCallbacks(release) } + val ignored = runCatching { + adapter.ignore( + tag, + REMOVAL_DEBOUNCE.inWholeMilliseconds.toInt(), + { schedule(RELEASE_AFTER_REMOVAL) }, + handler, + ) + }.getOrDefault(false) + if (!ignored) schedule(HOLD_WITHOUT_TAG) + } + + private fun schedule(delay: Duration) { + handler.post { + handler.removeCallbacks(release) + handler.postDelayed(release, delay.inWholeMilliseconds) + } + } + + private fun release() { + if (ReaderModeOwner.current !== this) return + ReaderModeOwner.current = null + ReaderModeOwner.resumeScanner?.let { return it() } + val activity = activity.get() ?: return + runCatching { NfcAdapter.getDefaultAdapter(activity)?.disableReaderMode(activity) } + .onFailure { Logger.warn("Failed to release NFC reader mode", it, context = TAG) } + } +} diff --git a/app/src/main/java/to/bitkit/nfc/NfcTagEmitter.kt b/app/src/main/java/to/bitkit/nfc/NfcTagEmitter.kt new file mode 100644 index 0000000000..cb16a43c5b --- /dev/null +++ b/app/src/main/java/to/bitkit/nfc/NfcTagEmitter.kt @@ -0,0 +1,33 @@ +package to.bitkit.nfc + +import java.util.concurrent.atomic.AtomicLong +import java.util.concurrent.atomic.AtomicReference + +/** + * The payment request this device currently offers over NFC. + * + * The Receive screen publishes its request while it is in the foreground and clears it when it + * leaves, so [NdefTagService] answers a reader only while that request is on screen. + * The service and the UI run in the same process, so a process-wide holder is enough. + */ +object NfcTagEmitter { + private class Published(val token: Long, val message: ByteArray) + + private val tokens = AtomicLong(0) + private val published = AtomicReference(null) + + /** Publishes [uri] and returns the token that [clear] needs, so a later publisher is not cleared. */ + fun publish(uri: String): Long { + val token = tokens.incrementAndGet() + published.set(Published(token, NdefCodec.encodeUriMessage(uri))) + return token + } + + /** Clears the request published with [token]; returns false when another one replaced it. */ + fun clear(token: Long): Boolean { + val current = published.get() ?: return false + return current.token == token && published.compareAndSet(current, null) + } + + fun currentMessage(): ByteArray? = published.get()?.message +} diff --git a/app/src/main/java/to/bitkit/nfc/Type4TagEmulator.kt b/app/src/main/java/to/bitkit/nfc/Type4TagEmulator.kt new file mode 100644 index 0000000000..94054db952 --- /dev/null +++ b/app/src/main/java/to/bitkit/nfc/Type4TagEmulator.kt @@ -0,0 +1,128 @@ +package to.bitkit.nfc + +/** + * Read-only NFC Forum Type 4 tag, served over host card emulation. + * + * A reader selects the NDEF tag application, reads the capability container (file E103) + * and then the NDEF file (E104), which holds a 2-byte length followed by the message. + * [ndefMessage] is read when the NDEF file is selected, so one tap always sees one + * consistent request. While it returns null the application itself is reported as not found, + * so a reader sees no tag. + */ +class Type4TagEmulator( + private val ndefMessage: () -> ByteArray?, +) { + private var isApplicationSelected = false + private var selectedFile: ByteArray? = null + + fun process(apdu: ByteArray): ByteArray { + if (apdu.size < HEADER_SIZE) return SW_WRONG_LENGTH + if (apdu[0] != CLA) return SW_CLA_NOT_SUPPORTED + return when (apdu[1]) { + INS_SELECT -> select(apdu) + INS_READ_BINARY -> readBinary(apdu) + INS_UPDATE_BINARY -> SW_SECURITY_NOT_SATISFIED + else -> SW_INS_NOT_SUPPORTED + } + } + + fun reset() { + isApplicationSelected = false + selectedFile = null + } + + private fun select(apdu: ByteArray): ByteArray { + val p1 = apdu[2] + val data = commandData(apdu) ?: return SW_WRONG_LENGTH + return when (p1) { + // With nothing published Bitkit does not present a tag at all, so readers cannot detect it. + P1_SELECT_BY_NAME -> if (data.contentEquals(NDEF_AID) && ndefMessage() != null) { + isApplicationSelected = true + selectedFile = null + SW_OK + } else { + reset() + SW_FILE_NOT_FOUND + } + + P1_SELECT_BY_ID -> selectFile(data) + else -> SW_FILE_NOT_FOUND + } + } + + private fun selectFile(fileId: ByteArray): ByteArray { + if (!isApplicationSelected) return SW_FILE_NOT_FOUND + selectedFile = when { + fileId.contentEquals(CC_FILE_ID) -> CAPABILITY_CONTAINER + fileId.contentEquals(NDEF_FILE_ID) -> ndefFile() + else -> null + } + return if (selectedFile != null) SW_OK else SW_FILE_NOT_FOUND + } + + private fun ndefFile(): ByteArray? { + val message = ndefMessage() ?: return null + if (message.size > MAX_NDEF_SIZE) return null + val length = byteArrayOf((message.size shr 8).toByte(), message.size.toByte()) + return length + message + } + + private fun readBinary(apdu: ByteArray): ByteArray { + val file = selectedFile ?: return SW_FILE_NOT_FOUND + // The selected copy keeps one tap consistent, but once Receive stops offering, nothing more is served. + if (ndefMessage() == null) { + reset() + return SW_FILE_NOT_FOUND + } + val offset = ((apdu[2].toInt() and 0xFF) shl 8) or (apdu[3].toInt() and 0xFF) + if (offset > file.size) return SW_WRONG_OFFSET + val requested = if (apdu.size > HEADER_SIZE) apdu[HEADER_SIZE].toInt() and 0xFF else 0 + val length = if (requested == 0) SHORT_LE_MAX else requested + val end = minOf(file.size, offset + length) + return file.copyOfRange(offset, end) + SW_OK + } + + private fun commandData(apdu: ByteArray): ByteArray? { + if (apdu.size <= HEADER_SIZE) return null + val lc = apdu[HEADER_SIZE].toInt() and 0xFF + val start = HEADER_SIZE + 1 + if (apdu.size < start + lc) return null + return apdu.copyOfRange(start, start + lc) + } + + companion object { + /** NDEF Tag Application, NFC Forum Type 4 Tag specification. */ + val NDEF_AID = byteArrayOf(0xD2.toByte(), 0x76, 0x00, 0x00, 0x85.toByte(), 0x01, 0x01) + const val NDEF_AID_HEX = "D2760000850101" + const val MAX_NDEF_SIZE = 0x0FFE + + private const val HEADER_SIZE = 4 + private const val SHORT_LE_MAX = 256 + private const val CLA: Byte = 0x00 + private const val INS_SELECT: Byte = 0xA4.toByte() + private const val INS_READ_BINARY: Byte = 0xB0.toByte() + private const val INS_UPDATE_BINARY: Byte = 0xD6.toByte() + private const val P1_SELECT_BY_NAME: Byte = 0x04 + private const val P1_SELECT_BY_ID: Byte = 0x00 + + private val CC_FILE_ID = byteArrayOf(0xE1.toByte(), 0x03) + private val NDEF_FILE_ID = byteArrayOf(0xE1.toByte(), 0x04) + + /** + * Mapping version 2.0, MLe 0x003B, MLc 0x0034, then the NDEF file control TLV: + * file E104, maximum size [MAX_NDEF_SIZE] + 2, read access granted, write access denied. + */ + private val CAPABILITY_CONTAINER = byteArrayOf( + 0x00, 0x0F, 0x20, 0x00, 0x3B, 0x00, 0x34, + 0x04, 0x06, 0xE1.toByte(), 0x04, 0x10, 0x00, 0x00, 0xFF.toByte(), + ) + + val SW_OK = byteArrayOf(0x90.toByte(), 0x00) + val SW_FILE_NOT_FOUND = byteArrayOf(0x6A, 0x82.toByte()) + val SW_WRONG_LENGTH = byteArrayOf(0x67, 0x00) + val SW_WRONG_OFFSET = byteArrayOf(0x6B, 0x00) + val SW_SECURITY_NOT_SATISFIED = byteArrayOf(0x69, 0x82.toByte()) + val SW_INS_NOT_SUPPORTED = byteArrayOf(0x6D, 0x00) + val SW_CLA_NOT_SUPPORTED = byteArrayOf(0x6E, 0x00) + } +} diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index edd8bba7fe..ab1a3a98de 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1550,12 +1550,47 @@ class LightningRepo @Inject constructor( onBeforeSend: suspend () -> Boolean, ): Result = payInvoice(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat = null, onBeforeSend) + /** + * Like [payInvoice], with [isAuthorizedAtSubmission] checked again where a node send is submitted, after its queue + * wait. When it is false, nothing is sent and the result fails with [ServiceError.PaymentStoppedAtSubmission]. + */ + suspend fun payInvoiceAuthorizedAtSubmission( + bolt11: String, + sats: ULong?, + isAuthorizedAtSubmission: () -> Boolean, + onBeforeSend: suspend () -> Boolean, + ): Result = payInvoiceChecked( + bolt11 = bolt11, + sats = sats, + paymentDeadlineAt = null, + maxTotalRoutingFeeMsat = null, + isAuthorizedAtSubmission = isAuthorizedAtSubmission, + onBeforeSend = onBeforeSend, + ) + suspend fun payInvoice( bolt11: String, sats: ULong?, paymentDeadlineAt: Instant?, maxTotalRoutingFeeMsat: ULong?, onBeforeSend: suspend () -> Boolean, + ): Result = payInvoiceChecked( + bolt11 = bolt11, + sats = sats, + paymentDeadlineAt = paymentDeadlineAt, + maxTotalRoutingFeeMsat = maxTotalRoutingFeeMsat, + isAuthorizedAtSubmission = null, + onBeforeSend = onBeforeSend, + ) + + @Suppress("LongParameterList") + private suspend fun payInvoiceChecked( + bolt11: String, + sats: ULong?, + paymentDeadlineAt: Instant?, + maxTotalRoutingFeeMsat: ULong?, + isAuthorizedAtSubmission: (() -> Boolean)?, + onBeforeSend: suspend () -> Boolean, ): Result { // The rail is picked again on every attempt, so each one checks the other holds no live send of the invoice. val paymentHash = runCatching { Bolt11Invoice.fromStr(bolt11).paymentHash() }.getOrNull() @@ -1616,7 +1651,15 @@ class LightningRepo @Inject constructor( if (isAdmitted) releaseSend(key) } } - return payInvoiceWithLdk(bolt11, sats, paymentHash, paymentDeadlineAt, maxTotalRoutingFeeMsat, onBeforeSend) + return payInvoiceWithLdk( + bolt11, + sats, + paymentHash, + paymentDeadlineAt, + maxTotalRoutingFeeMsat, + isAuthorizedAtSubmission = isAuthorizedAtSubmission, + onBeforeSend = onBeforeSend, + ) } /** Pays [bolt11] from the node's channels only, for a send quoted on them that must never fall back to Spark. */ @@ -1733,6 +1776,7 @@ class LightningRepo @Inject constructor( paymentHash: String?, paymentDeadlineAt: Instant?, maxTotalRoutingFeeMsat: ULong?, + isAuthorizedAtSubmission: (() -> Boolean)? = null, onBeforeSend: suspend () -> Boolean, ): Result = executeWhenNodeRunning("payInvoice") { requireWalletRestoreComplete() @@ -1764,7 +1808,19 @@ class LightningRepo @Inject constructor( isCounted = true ldkSendRecordedAt[key] = ldkSendRecords.incrementAndGet() cacheStore.addLdkSendHash(key, invoiceExpiresAt(bolt11)) - runCatching { lightningService.send(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat) } + runCatching { + if (isAuthorizedAtSubmission == null) { + lightningService.send(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat) + } else { + lightningService.send( + bolt11, + sats, + paymentDeadlineAt, + maxTotalRoutingFeeMsat, + isAuthorizedAtSubmission, + ) + } + } .also { isCounted = false uncount() @@ -1879,7 +1935,11 @@ class LightningRepo @Inject constructor( lightningService.listPayments() } - suspend fun waitForUsableChannels() = withContext(bgDispatcher) { + /** + * Publishes current channels and, with [awaitUsable], waits for one to become usable. Without it the call returns + * once the channels are published, for a payment another rail (Spark) already covers. + */ + suspend fun waitForUsableChannels(awaitUsable: Boolean = true) = withContext(bgDispatcher) { var state = _lightningState.value if (!state.nodeLifecycleState.canRun()) { delayNoUsableChannelsFeedback() @@ -1894,6 +1954,7 @@ class LightningRepo @Inject constructor( // Usability can stay true while a payment changes the outbound HTLC limit. // Publish current channels before callers derive send capacity from them. refreshChannelsAndPeers() + if (!awaitUsable) return@withContext state = _lightningState.value if (!state.nodeLifecycleState.canRun()) { delayNoUsableChannelsFeedback() diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt index 2113d29c68..e6ff629b86 100644 --- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt @@ -50,6 +50,7 @@ import to.bitkit.services.SparkError import to.bitkit.utils.AppError import to.bitkit.utils.Logger import to.bitkit.utils.asNodeException +import to.bitkit.utils.isStoppedAtSubmission import java.math.BigDecimal import java.util.UUID import java.util.concurrent.ConcurrentHashMap @@ -129,8 +130,13 @@ class QuickPayRepo @Inject constructor( unackedFailures.remove(session.id) } - fun pay(session: QuickPaySession, request: QuickPayPayRequest) { - scope.launch { payNow(session, request) } + /** + * Pays [request] for [session]. [canDispatch] is checked right before the payment is first submitted; when it is + * false (for example the wallet locked while the invoice was prepared), nothing is sent and the session falls back + * to the swipe review. A payment already submitted keeps being tracked. + */ + fun pay(session: QuickPaySession, request: QuickPayPayRequest, canDispatch: () -> Boolean = { true }) { + scope.launch { payNow(session, request, canDispatch) } } suspend fun canApply(amountSats: ULong): Result = withContext(ioDispatcher) { @@ -264,7 +270,11 @@ class QuickPayRepo @Inject constructor( mutex.withLock { reconcileLocked(rows) } } - internal suspend fun payNow(session: QuickPaySession, request: QuickPayPayRequest) { + internal suspend fun payNow( + session: QuickPaySession, + request: QuickPayPayRequest, + canDispatch: () -> Boolean = { true }, + ) { if (request is QuickPayPayRequest.LnurlPay && !admitsLnurlFetch(session, request)) return val invoice = resolveInvoice(session, request) ?: return val invoiceHash = invoiceHashOrEmit(session, invoice) ?: return @@ -273,7 +283,7 @@ class QuickPayRepo @Inject constructor( PreparePayResult.REJECTED -> return PreparePayResult.RECOVERED -> settleRecovered(invoiceHash) PreparePayResult.FRESH -> { - dispatchBolt11(invoice, invoiceHash) + dispatchBolt11(invoice, invoiceHash, canDispatch) awaitCompletionOrPending(invoiceHash) } } @@ -422,15 +432,35 @@ class QuickPayRepo @Inject constructor( } } - private suspend fun dispatchBolt11(invoice: ResolvedInvoice, invoiceHash: String) { - lightningRepo.payInvoice(bolt11 = invoice.bolt11, sats = null) { - tryMarkDispatched(invoiceHash) + private suspend fun dispatchBolt11(invoice: ResolvedInvoice, invoiceHash: String, canDispatch: () -> Boolean) { + var isAuthorizationLapsed = false + lightningRepo.payInvoiceAuthorizedAtSubmission(invoice.bolt11, sats = null, canDispatch) { + isAuthorizationLapsed = !canDispatch() + !isAuthorizationLapsed && tryMarkDispatched(invoiceHash) }.fold( onSuccess = { onInvoiceAccepted(invoiceHash, it) }, - onFailure = { onInvoiceRejected(invoiceHash, invoice.bolt11, it) }, + onFailure = { + when { + isAuthorizationLapsed -> fallBackBeforeDispatch(invoiceHash) + // Stopped on the node's queue, after it was marked dispatched but before anything was submitted. + it.isStoppedAtSubmission() -> fallBackBeforeDispatch(invoiceHash, isMarkedDispatched = true) + else -> onInvoiceRejected(invoiceHash, invoice.bolt11, it) + } + }, ) } + /** Releases a payment that was never submitted and sends its session to the swipe review. */ + private suspend fun fallBackBeforeDispatch(invoiceHash: String, isMarkedDispatched: Boolean = false) { + mutex.withLock { + val current = opsByKey[invoiceHash] + if (current == null || current.dispatched != isMarkedDispatched) return@withLock + spend.release(invoiceHash) + removeOpLocked(current) + emitToSession(current.sessionId, QuickPaySessionEvent.FallBackToConfirm) + } + } + private suspend fun tryMarkDispatched(invoiceHash: String): Boolean { val settings = readSettings() return mutex.withLock { diff --git a/app/src/main/java/to/bitkit/services/LightningService.kt b/app/src/main/java/to/bitkit/services/LightningService.kt index 03bb0313bc..aff3b32467 100644 --- a/app/src/main/java/to/bitkit/services/LightningService.kt +++ b/app/src/main/java/to/bitkit/services/LightningService.kt @@ -1171,6 +1171,19 @@ class LightningService internal constructor( sats: ULong? = null, paymentDeadlineAt: Instant? = null, maxTotalRoutingFeeMsat: ULong? = null, + ): PaymentId = send(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat, isAuthorizedAtSubmission = { true }) + + /** + * Like [send], checking [isAuthorizedAtSubmission] on the node's queue right before the payment is submitted, + * after any wait behind other node work such as a wallet sync. Throws + * [ServiceError.PaymentStoppedAtSubmission] when false. + */ + suspend fun send( + bolt11: String, + sats: ULong?, + paymentDeadlineAt: Instant?, + maxTotalRoutingFeeMsat: ULong?, + isAuthorizedAtSubmission: () -> Boolean, ): PaymentId { val node = this.node ?: throw ServiceError.NodeNotSetup() @@ -1182,6 +1195,7 @@ class LightningService internal constructor( return ServiceQueue.LDK.background(ldkQueue) { keychain.requireWalletRestoreComplete() ensurePaymentDeadline(paymentDeadlineAt) + if (!isAuthorizedAtSubmission()) throw ServiceError.PaymentStoppedAtSubmission() runCatching { val routeParameters = maxTotalRoutingFeeMsat?.let(::routeParametersWithFeeCap) when (sats != null) { diff --git a/app/src/main/java/to/bitkit/ui/ContentView.kt b/app/src/main/java/to/bitkit/ui/ContentView.kt index 347b27ad3b..e824f99d44 100644 --- a/app/src/main/java/to/bitkit/ui/ContentView.kt +++ b/app/src/main/java/to/bitkit/ui/ContentView.kt @@ -82,6 +82,7 @@ import to.bitkit.ui.components.BottomSheetOverlayHost import to.bitkit.ui.components.BottomSheetOverlayState import to.bitkit.ui.components.DefaultSheetContainerColor import to.bitkit.ui.components.DrawerMenu +import to.bitkit.ui.components.PaymentAuthorizationHost import to.bitkit.ui.components.Sheet import to.bitkit.ui.components.SheetDragHandle import to.bitkit.ui.components.SheetHandlePlacement @@ -222,6 +223,7 @@ import to.bitkit.ui.settings.lightning.SparkExitViewModel import to.bitkit.ui.settings.pin.PinManagementScreen import to.bitkit.ui.settings.quickPay.QuickPayIntroScreen import to.bitkit.ui.settings.quickPay.QuickPaySettingsScreen +import to.bitkit.ui.settings.quickPay.QuickPaySettingsViewModel import to.bitkit.ui.settings.support.ReportIssueResultScreen import to.bitkit.ui.settings.support.ReportIssueScreen import to.bitkit.ui.settings.support.SupportScreen @@ -238,6 +240,7 @@ import to.bitkit.ui.sheets.ForceTransferSheet import to.bitkit.ui.sheets.HighBalanceWarningSheet import to.bitkit.ui.sheets.LnurlAuthSheet import to.bitkit.ui.sheets.MoveToSparkSheet +import to.bitkit.ui.sheets.NfcIntroSheet import to.bitkit.ui.sheets.PinSheet import to.bitkit.ui.sheets.QrScanningSheet import to.bitkit.ui.sheets.QuickPayIntroSheet @@ -794,6 +797,31 @@ fun ContentView( ) } + TimedSheetType.NFC -> { + // Turning QuickPay on asks for the payment PIN, as in QuickPay settings. + val quickPaySettings: QuickPaySettingsViewModel = hiltViewModel() + val quickPayState by quickPaySettings.uiState.collectAsStateWithLifecycle() + val authorization = quickPayState.authorization + PaymentAuthorizationHost( + useBiometrics = authorization?.useBiometrics, + pinDescriptionRes = R.string.security__pin_quickpay, + onCancel = quickPaySettings::onAuthorizationCancelled, + onVerify = { authorization?.let(quickPaySettings::onAuthorized) }, + ) { + NfcIntroSheet( + isQuickPayEnabled = quickPayState.isQuickPayEnabled, + onToggleQuickPay = { + quickPaySettings.setQuickPayEnabled(!quickPayState.isQuickPayEnabled) + }, + onSettings = { + appViewModel.dismissTimedSheet() + navController.navigateTo(Routes.QuickPaySettings) + }, + onContinue = { appViewModel.dismissTimedSheet() }, + ) + } + } + TimedSheetType.MOVE_TO_SPARK -> MoveToSparkSheet( viewModel = hiltViewModel(), onDismiss = { appViewModel.dismissTimedSheet() }, diff --git a/app/src/main/java/to/bitkit/ui/MainActivity.kt b/app/src/main/java/to/bitkit/ui/MainActivity.kt index 5fe9fcb7bd..8779a86cd9 100644 --- a/app/src/main/java/to/bitkit/ui/MainActivity.kt +++ b/app/src/main/java/to/bitkit/ui/MainActivity.kt @@ -4,6 +4,8 @@ import android.app.NotificationManager import android.content.Intent import android.hardware.usb.UsbDevice import android.hardware.usb.UsbManager +import android.nfc.NfcAdapter +import android.nfc.Tag import android.os.Bundle import android.os.Looper import androidx.activity.compose.setContent @@ -48,6 +50,7 @@ import to.bitkit.androidServices.LightningNodeService.Companion.ACTION_START_SER import to.bitkit.androidServices.LightningNodeService.Companion.CHANNEL_ID_NODE import to.bitkit.models.NewTransactionSheetDetails import to.bitkit.models.SamRockSetupRequest +import to.bitkit.nfc.NfcRepeatGuard import to.bitkit.repositories.HwWalletRepo import to.bitkit.repositories.PaykitPaymentRequestId import to.bitkit.ui.components.AuthCheckView @@ -103,6 +106,10 @@ class MainActivity : FragmentActivity() { private val settingsViewModel by viewModels() private val backupsViewModel by viewModels() + /** Set when a tag tap launched or resumed the app, so [onResume] can hold NFC while the tag stays in range. */ + private var nfcTagToGuard: Tag? = null + private var guardNfcOnResume = false + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -315,6 +322,10 @@ class MainActivity : FragmentActivity() { return } + if (intent.action == NfcAdapter.ACTION_NDEF_DISCOVERED) { + guardNfcOnResume = true + nfcTagToGuard = IntentCompat.getParcelableExtra(intent, NfcAdapter.EXTRA_TAG, Tag::class.java) + } appViewModel.handleDeeplinkIntent(intent) if (ScreenDeepLinks.detachScreenUri(intent)) { @@ -362,6 +373,11 @@ class MainActivity : FragmentActivity() { override fun onResume() { super.onResume() + if (guardNfcOnResume) { + guardNfcOnResume = false + NfcRepeatGuard.engage(this, nfcTagToGuard) + nfcTagToGuard = null + } appViewModel.onAppResumed() // A permission dialog launched from a sheet that has since closed loses its result callback. settingsViewModel.setNotificationPreference(areNotificationsEnabled()) diff --git a/app/src/main/java/to/bitkit/ui/components/SheetHost.kt b/app/src/main/java/to/bitkit/ui/components/SheetHost.kt index f764e63e0a..eeb05f9fdc 100644 --- a/app/src/main/java/to/bitkit/ui/components/SheetHost.kt +++ b/app/src/main/java/to/bitkit/ui/components/SheetHost.kt @@ -107,6 +107,8 @@ sealed interface Sheet { data class QrScanner( val isPubkyScan: Boolean = false, val showBackButton: Boolean = true, + /** Whether the scanner also takes payment requests over NFC and Bluetooth: only when it opens to pay. */ + val readsNearby: Boolean = false, ) : Sheet data class PubkyAuth(val authUrl: String) : Sheet @@ -120,6 +122,7 @@ enum class TimedSheetType(val priority: Int) { USDT(priority = 5), BACKUP(priority = 4), NOTIFICATIONS(priority = 3), + NFC(priority = 2), QUICK_PAY(priority = 2), HIGH_BALANCE(priority = 1) } diff --git a/app/src/main/java/to/bitkit/ui/screens/scanner/CameraPermissionView.kt b/app/src/main/java/to/bitkit/ui/screens/scanner/CameraPermissionView.kt index 9fac8ef1a6..9046d62cb8 100644 --- a/app/src/main/java/to/bitkit/ui/screens/scanner/CameraPermissionView.kt +++ b/app/src/main/java/to/bitkit/ui/screens/scanner/CameraPermissionView.kt @@ -60,7 +60,9 @@ fun DeniedContent( onClickPaste: (() -> Unit)? = {}, description: String = stringResource(R.string.other__camera_permission_description), accentColor: Color = Colors.Brand, + nearbySources: NearbyScanSources = NearbyScanSources.None, ) { + val readsNearby = nearbySources != NearbyScanSources.None Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier @@ -77,31 +79,46 @@ fun DeniedContent( .padding(32.dp) ) { Display( - stringResource(R.string.other__camera_permission_title) - .withAccent(accentColor = accentColor), + stringResource( + if (readsNearby) R.string.other__scan_to_pay_title else R.string.other__camera_permission_title + ).withAccent(accentColor = accentColor), color = Colors.White, ) VerticalSpacer(8.dp) BodyM( - description, + if (readsNearby) stringResource(R.string.other__scan_to_pay_description) else description, color = Colors.White64, modifier = Modifier.fillMaxWidth(), ) VerticalSpacer(32.dp) - PrimaryButton( - text = stringResource(R.string.other__camera_permission_button), - icon = { - Icon( - painter = painterResource(R.drawable.ic_camera), - contentDescription = null, - ) - }, - onClick = onClickRetry, - ) + if (readsNearby) { + NearbyEnableButtons( + sources = nearbySources, + leading = { + EnableSourceButton( + icon = R.drawable.ic_camera, + contentDescription = stringResource(R.string.other__camera_permission_button), + onClick = onClickRetry, + testTag = "ScannerEnableCamera", + ) + }, + ) + } else { + PrimaryButton( + text = stringResource(R.string.other__camera_permission_button), + icon = { + Icon( + painter = painterResource(R.drawable.ic_camera), + contentDescription = null, + ) + }, + onClick = onClickRetry, + ) + } } FillHeight() diff --git a/app/src/main/java/to/bitkit/ui/screens/scanner/NearbyScanSources.kt b/app/src/main/java/to/bitkit/ui/screens/scanner/NearbyScanSources.kt new file mode 100644 index 0000000000..955462602b --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/screens/scanner/NearbyScanSources.kt @@ -0,0 +1,264 @@ +package to.bitkit.ui.screens.scanner + +import android.bluetooth.BluetoothAdapter +import android.content.Context +import android.content.Intent +import android.provider.Settings +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.annotation.DrawableRes +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Icon +import androidx.compose.runtime.Composable +import androidx.compose.runtime.Stable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalResources +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.core.app.ActivityCompat +import to.bitkit.R +import to.bitkit.ext.findActivity +import to.bitkit.ext.startActivityAppSettings +import to.bitkit.models.Toast +import to.bitkit.ui.appViewModel +import to.bitkit.ui.components.ButtonSize +import to.bitkit.ui.components.SecondaryButton +import to.bitkit.ui.components.Text13Up +import to.bitkit.ui.shared.effects.BluetoothState +import to.bitkit.ui.shared.effects.NearbyRole +import to.bitkit.ui.shared.effects.NearbyScanEffect +import to.bitkit.ui.shared.effects.NfcReaderEffect +import to.bitkit.ui.shared.effects.NfcState +import to.bitkit.ui.shared.effects.isNearbyPaused +import to.bitkit.ui.shared.effects.nearbyPermissions +import to.bitkit.ui.shared.effects.openNfcSettings +import to.bitkit.ui.shared.effects.rememberBluetoothState +import to.bitkit.ui.shared.effects.rememberNfcState +import to.bitkit.ui.theme.Colors + +/** + * NFC and Bluetooth availability on a payment scanner, with the actions that turn each one on. + * While [isPaused], neither source reads, so neither counts as active. + */ +@Stable +data class NearbyScanSources( + val nfcState: NfcState, + val bluetoothState: BluetoothState, + val onEnableNfc: () -> Unit, + val onEnableBluetooth: () -> Unit, + val isPaused: Boolean = false, +) { + val isNfcActive get() = nfcState == NfcState.ON && !isPaused + val isBluetoothActive get() = bluetoothState == BluetoothState.ON && !isPaused + val canEnableNfc get() = nfcState == NfcState.OFF + val canEnableBluetooth + get() = bluetoothState in ENABLEABLE_BLUETOOTH_STATES + + companion object { + private val ENABLEABLE_BLUETOOTH_STATES = + setOf(BluetoothState.NEEDS_PERMISSION, BluetoothState.OFF, BluetoothState.LOCATION_OFF) + + val None = NearbyScanSources(NfcState.UNAVAILABLE, BluetoothState.UNAVAILABLE, {}, {}) + } +} + +/** + * Listens for payment requests over NFC and Bluetooth while the scanner is resumed and nearby payments + * are not paused. [onRead] receives the request and whether it came over Bluetooth. + */ +@Composable +fun rememberNearbyScanSources( + enabled: Boolean, + onRead: (text: String, isNearby: Boolean) -> Unit, +): NearbyScanSources { + if (!enabled) return NearbyScanSources.None + val context = LocalContext.current + val resources = LocalResources.current + val app = appViewModel + val isPaused = isNearbyPaused() + var refreshKey by remember { mutableIntStateOf(0) } + val nfcState = rememberNfcState() + val bluetoothState = rememberBluetoothState(NearbyRole.SCAN, refreshKey) + + var permissionRequested by remember { mutableStateOf(false) } + val permissionLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.RequestMultiplePermissions() + ) { refreshKey++ } + val enableBluetoothLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.StartActivityForResult() + ) { refreshKey++ } + + if (nfcState == NfcState.ON && !isPaused) { + NfcReaderEffect( + onRead = { onRead(it, false) }, + onUnreadable = { + app?.toast( + type = Toast.ToastType.ERROR, + title = resources.getString(R.string.other__nfc_read_error_title), + description = resources.getString(R.string.other__nfc_read_error_text), + ) + }, + ) + } + NearbyScanEffect(enabled = bluetoothState == BluetoothState.ON && !isPaused, onRead = { onRead(it, true) }) + + return NearbyScanSources( + nfcState = nfcState, + bluetoothState = bluetoothState, + isPaused = isPaused, + onEnableNfc = { context.openNfcSettings() }, + onEnableBluetooth = { + when (bluetoothState) { + // Once the permission is denied for good, Android shows no dialog; only Settings can grant it. + BluetoothState.NEEDS_PERMISSION -> if (permissionRequested && !context.canAskAgain(nearbyPermissions)) { + context.startActivityAppSettings() + } else { + permissionRequested = true + permissionLauncher.launch(nearbyPermissions) + } + BluetoothState.OFF -> runCatching { + enableBluetoothLauncher.launch(Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)) + } + + BluetoothState.LOCATION_OFF -> runCatching { + enableBluetoothLauncher.launch(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)) + } + + else -> Unit + } + }, + ) +} + +/** Enable buttons for sources that are off, then the status pill naming what is being scanned. */ +@Composable +fun NearbyScanStatus( + sources: NearbyScanSources, + modifier: Modifier = Modifier, +) { + Column( + verticalArrangement = Arrangement.spacedBy(8.dp), + modifier = modifier + .fillMaxWidth() + .padding(16.dp) + ) { + NearbyEnableButtons(sources) + ScannerStatusPill(text = stringResource(scannerStatusText(sources))) + } +} + +/** Icon buttons that turn on Bluetooth (permission or adapter) and NFC; nothing when both are on. */ +@Composable +fun NearbyEnableButtons( + sources: NearbyScanSources, + modifier: Modifier = Modifier, + leading: (@Composable () -> Unit)? = null, +) { + if (leading == null && !sources.canEnableBluetooth && !sources.canEnableNfc) return + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = modifier.fillMaxWidth() + ) { + leading?.let { Column(Modifier.weight(1f)) { it() } } + if (sources.canEnableBluetooth) { + EnableSourceButton( + icon = R.drawable.ic_bluetooth, + contentDescription = stringResource(R.string.other__bluetooth_enable), + onClick = sources.onEnableBluetooth, + testTag = "ScannerEnableBluetooth", + modifier = Modifier.weight(1f), + ) + } + if (sources.canEnableNfc) { + EnableSourceButton( + icon = R.drawable.ic_broadcast, + contentDescription = stringResource(R.string.other__nfc_enable), + onClick = sources.onEnableNfc, + testTag = "ScannerEnableNfc", + modifier = Modifier.weight(1f), + ) + } + } +} + +@Composable +internal fun EnableSourceButton( + @DrawableRes icon: Int, + contentDescription: String, + onClick: () -> Unit, + testTag: String, + modifier: Modifier = Modifier, +) { + SecondaryButton( + text = null, + size = ButtonSize.Small, + onClick = onClick, + icon = { + Icon( + painter = painterResource(icon), + contentDescription = contentDescription, + tint = Colors.White, + modifier = Modifier.size(16.dp) + ) + }, + modifier = modifier.testTag(testTag) + ) +} + +@Composable +internal fun ScannerStatusPill( + text: String, + modifier: Modifier = Modifier, +) { + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally), + verticalAlignment = Alignment.CenterVertically, + modifier = modifier + .fillMaxWidth() + .clip(RoundedCornerShape(999.dp)) + .background(Colors.Black50) + .padding(horizontal = 16.dp, vertical = 12.dp) + .testTag("ScannerStatus") + ) { + Icon( + painter = painterResource(R.drawable.ic_broadcast), + contentDescription = null, + tint = Colors.White64, + modifier = Modifier.size(16.dp) + ) + Text13Up( + text = text, + color = Colors.White64, + ) + } +} + +internal fun scannerStatusText(sources: NearbyScanSources): Int = when { + sources.isNfcActive && sources.isBluetoothActive -> R.string.other__scanner_status_qr_nfc_bluetooth + sources.isNfcActive -> R.string.other__scanner_status_qr_nfc + sources.isBluetoothActive -> R.string.other__scanner_status_qr_bluetooth + else -> R.string.other__scanner_status_qr +} + +/** Whether the system still shows the request dialog for a denied permission in [permissions]. */ +private fun Context.canAskAgain(permissions: Array): Boolean { + val activity = findActivity() ?: return true + return permissions.any { ActivityCompat.shouldShowRequestPermissionRationale(activity, it) } +} diff --git a/app/src/main/java/to/bitkit/ui/screens/scanner/QrScanningScreen.kt b/app/src/main/java/to/bitkit/ui/screens/scanner/QrScanningScreen.kt index edb41ba9cf..500b9c1c5c 100644 --- a/app/src/main/java/to/bitkit/ui/screens/scanner/QrScanningScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/scanner/QrScanningScreen.kt @@ -14,10 +14,8 @@ import androidx.camera.core.Preview import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.view.PreviewView import androidx.compose.foundation.background -import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height @@ -72,7 +70,6 @@ import to.bitkit.models.Toast import to.bitkit.ui.appViewModel import to.bitkit.ui.components.PrimaryButton import to.bitkit.ui.components.SecondaryButton -import to.bitkit.ui.components.Text13Up import to.bitkit.ui.components.TextInput import to.bitkit.ui.components.VerticalSpacer import to.bitkit.ui.scaffold.AppAlertDialog @@ -99,6 +96,7 @@ fun QrScanningScreen( isFullScreen: Boolean = false, isEmbedded: Boolean = false, acceptsBinaryPayload: Boolean = false, + readsNearby: Boolean = false, showsGradientBackground: Boolean = true, permissionDescription: String = stringResource(R.string.other__camera_permission_description), permissionAccentColor: Color = Colors.Brand, @@ -136,6 +134,9 @@ fun QrScanningScreen( val context = LocalContext.current val resources = LocalResources.current + val nearbySources = rememberNearbyScanSources(enabled = readsNearby) { text, isNearby -> + setScanResult(QrCodePayload(text = text, rawBytes = null, isNearby = isNearby)) + } val previewView = remember { PreviewView(context) } val preview = remember { Preview.Builder().build() } val analyzer = remember(acceptsBinaryPayload) { @@ -237,6 +238,7 @@ fun QrScanningScreen( permissionState = cameraPermissionState, deniedContent = { DeniedContent( + nearbySources = nearbySources, description = permissionDescription, accentColor = permissionAccentColor, onClickRetry = { context.startActivityAppSettings() }, @@ -246,6 +248,7 @@ fun QrScanningScreen( grantedContent = { Content( isPubkyScan = isPubkyScan, + nearbySources = nearbySources, isEmbedded = isEmbedded, isFlashlightOn = isFlashlightOn, previewView = previewView, @@ -306,6 +309,7 @@ internal fun textQrCodePayload(text: String) = QrCodePayload( @Composable private fun Content( isPubkyScan: Boolean, + nearbySources: NearbyScanSources, isEmbedded: Boolean, isFlashlightOn: Boolean, previewView: PreviewView, @@ -366,28 +370,17 @@ private fun Content( } if (isPubkyScan) { - Row( - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalAlignment = Alignment.CenterVertically, + ScannerStatusPill( + text = stringResource(R.string.contacts__scanner_status), modifier = Modifier .align(Alignment.BottomCenter) - .padding(16.dp) - .fillMaxWidth() - .clip(RoundedCornerShape(999.dp)) - .background(Colors.Black50) - .padding(horizontal = 16.dp, vertical = 12.dp) - ) { - Icon( - painter = painterResource(R.drawable.ic_broadcast), - contentDescription = null, - tint = Colors.White64, - modifier = Modifier.size(16.dp) - ) - Text13Up( - text = stringResource(R.string.contacts__scanner_status), - color = Colors.White64, - ) - } + .padding(16.dp), + ) + } else if (nearbySources != NearbyScanSources.None) { + NearbyScanStatus( + sources = nearbySources, + modifier = Modifier.align(Alignment.BottomCenter), + ) } } if (!isEmbedded) { diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveInvoiceUtils.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveInvoiceUtils.kt index cd157e6204..37da99fa2c 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveInvoiceUtils.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveInvoiceUtils.kt @@ -3,6 +3,22 @@ package to.bitkit.ui.screens.wallets.receive import to.bitkit.R import to.bitkit.utils.Bip21Utils +/** + * The request Receive offers over NFC and Bluetooth for [tab]: the one its QR shows, or null while that QR is replaced + * by a spinner or an error. A failed update keeps the previous invoice, which must not stay payable nearby. + * USDT draws its own screen and offers its request itself. + */ +internal fun nearbyReceiveRequest( + tab: ReceiveTab, + request: String?, + hasInvoiceError: Boolean, + isUpdating: Boolean, +): String? { + if (tab == ReceiveTab.USDT) return null + val mode = getReceiveInvoiceDisplayMode(tab, hasInvoiceError, isUpdating, showDetails = false) + return request.takeIf { mode == ReceiveInvoiceDisplayMode.QR } +} + internal fun getReceiveInvoiceDisplayMode( tab: ReceiveTab, hasInvoiceError: Boolean, diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreen.kt index 1a408dbfce..35fe047143 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveQrScreen.kt @@ -79,6 +79,7 @@ import to.bitkit.ui.components.PrimaryButton import to.bitkit.ui.components.QrCodeImage import to.bitkit.ui.components.SecondaryButton import to.bitkit.ui.components.TertiaryButton +import to.bitkit.ui.components.Text13Up import to.bitkit.ui.components.Tooltip import to.bitkit.ui.components.VerticalSpacer import to.bitkit.ui.components.rememberQrBitmap @@ -86,6 +87,7 @@ import to.bitkit.ui.scaffold.SheetTopBar import to.bitkit.ui.screens.wallets.activity.components.CustomTabRowWithSpacing import to.bitkit.ui.screens.wallets.usdt.UsdtDepositReceiveScreen import to.bitkit.ui.shared.effects.SetMaxBrightness +import to.bitkit.ui.shared.effects.offerPaymentNearby import to.bitkit.ui.shared.modifiers.sheetHeight import to.bitkit.ui.shared.util.gradientBackground import to.bitkit.ui.shared.util.shareQrCode @@ -315,6 +317,15 @@ fun ReceiveQrScreen( hardwareTabLabel?.let { persistentMapOf(ReceiveTab.HARDWARE to it) } ?: persistentMapOf() } + val canTapToPay = offerPaymentNearby( + nearbyReceiveRequest( + tab = selectedTab, + request = invoicesByTab[selectedTab], + hasInvoiceError = walletState.hasReceiveInvoiceError, + isUpdating = walletState.isReceiveInvoiceUpdating, + ) + ) + if (selectedTab == ReceiveTab.USDT) { Column( modifier = modifier.fillMaxSize().background( @@ -473,6 +484,7 @@ fun ReceiveQrScreen( { onClickEditInvoice(tab) } }, accentColor = tab.accentColor, + showsTapToPay = canTapToPay, modifier = Modifier.fillMaxWidth() ) } @@ -572,6 +584,7 @@ fun ReceiveQrView( onClickEditInvoice: (() -> Unit)?, accentColor: Color, modifier: Modifier = Modifier, + showsTapToPay: Boolean = false, shareContent: String = copyText, copyMessage: String = stringResource(R.string.wallet__receive_copied), ) { @@ -667,6 +680,30 @@ fun ReceiveQrView( ) } VerticalSpacer(16.dp) + if (showsTapToPay) { + TapToPayLabel() + VerticalSpacer(16.dp) + } + } +} + +@Composable +private fun TapToPayLabel(modifier: Modifier = Modifier) { + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + modifier = modifier.testTag("ReceiveTapToPay") + ) { + Icon( + painter = painterResource(R.drawable.ic_broadcast), + contentDescription = null, + tint = Colors.White64, + modifier = Modifier.size(16.dp) + ) + Text13Up( + text = stringResource(R.string.wallet__receive_scan_or_tap), + color = Colors.White64, + ) } } diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendQuickPayScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendQuickPayScreen.kt index 9e0c0c5cb5..3381992272 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendQuickPayScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendQuickPayScreen.kt @@ -47,6 +47,7 @@ fun SendQuickPayScreen( onPaymentPending: (String, Long, String) -> Unit, onFallBackToConfirm: () -> Unit, onShowError: (SendFailureDetails) -> Unit, + canStart: () -> Boolean = { true }, viewModel: QuickPayViewModel = hiltViewModel(), ) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() @@ -66,7 +67,9 @@ fun SendQuickPayScreen( ) LaunchedEffect(quickPayData, canPay, isRequestActive) { if (isRequestActive && canPay) { - viewModel.pay(session, quickPayData) + // Checked where the payment starts and again at its first submission: navigation, waiting for funds and + // preparing the invoice can all outlast a wallet lock. + if (canStart()) viewModel.pay(session, quickPayData, canDispatch = canStart) else onFallBackToConfirm() } } diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendRecipientScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendRecipientScreen.kt index 227d9b379b..159369140d 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendRecipientScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendRecipientScreen.kt @@ -66,12 +66,18 @@ import to.bitkit.ui.components.BodyM import to.bitkit.ui.components.BodyMSB import to.bitkit.ui.components.BottomSheetPreview import to.bitkit.ui.components.Display -import to.bitkit.ui.components.PrimaryButton import to.bitkit.ui.components.RectangleButton import to.bitkit.ui.components.VerticalSpacer import to.bitkit.ui.scaffold.SheetTopBar import to.bitkit.ui.screens.scanner.CameraOverlayButtonSize +import to.bitkit.ui.screens.scanner.EnableSourceButton +import to.bitkit.ui.screens.scanner.NearbyEnableButtons +import to.bitkit.ui.screens.scanner.NearbyScanSources +import to.bitkit.ui.screens.scanner.NearbyScanStatus import to.bitkit.ui.screens.scanner.QrCodeAnalyzer +import to.bitkit.ui.screens.scanner.rememberNearbyScanSources +import to.bitkit.ui.shared.effects.BluetoothState +import to.bitkit.ui.shared.effects.NfcState import to.bitkit.ui.shared.modifiers.sheetHeight import to.bitkit.ui.shared.util.gradientBackground import to.bitkit.ui.theme.AppThemeSurface @@ -102,6 +108,11 @@ fun SendRecipientScreen( val lifecycleOwner = LocalLifecycleOwner.current val cameraPermissionState = rememberPermissionState(Manifest.permission.CAMERA) + val nearbySources = rememberNearbyScanSources(enabled = true) { text, isNearby -> + Logger.debug("Read nearby request '${text.sanitizedQrLogValue()}'", context = TAG) + onEvent(SendEvent.AddressContinue(text, suppressQuickPay = isNearby, isNearbyRead = true)) + } + // Camera state var isFlashlightOn by remember { mutableStateOf(false) } var isCameraInitialized by remember { mutableStateOf(false) } @@ -238,6 +249,7 @@ fun SendRecipientScreen( SendRecipientContent( previewView = previewView, + nearbySources = nearbySources, isFlashlightOn = isFlashlightOn, onClickFlashlight = { camera?.cameraControl?.let { control -> @@ -273,6 +285,7 @@ fun SendRecipientScreen( @Composable private fun SendRecipientContent( previewView: PreviewView?, + nearbySources: NearbyScanSources, isFlashlightOn: Boolean, onClickFlashlight: () -> Unit, onClickGallery: () -> Unit, @@ -310,8 +323,15 @@ private fun SendRecipientContent( onClickGallery = onClickGallery, modifier = Modifier.fillMaxSize() ) + if (nearbySources != NearbyScanSources.None) { + NearbyScanStatus( + sources = nearbySources, + modifier = Modifier.align(Alignment.BottomCenter), + ) + } } else { PermissionDenied( + nearbySources = nearbySources, onClickRetry = onRequestPermission, modifier = Modifier .fillMaxWidth() @@ -418,6 +438,7 @@ private fun CameraPreviewWithControls( @Composable private fun PermissionDenied( + nearbySources: NearbyScanSources, onClickRetry: () -> Unit, modifier: Modifier = Modifier, ) { @@ -428,7 +449,7 @@ private fun PermissionDenied( .padding(32.dp) ) { Display( - stringResource(R.string.other__camera_permission_title) + stringResource(R.string.other__scan_to_pay_title) .withAccent(accentColor = Colors.Brand), color = Colors.White ) @@ -436,19 +457,23 @@ private fun PermissionDenied( VerticalSpacer(8.dp) BodyM( - stringResource(R.string.other__camera_permission_description), + stringResource(R.string.other__scan_to_pay_description), color = Colors.White64, modifier = Modifier.fillMaxWidth() ) VerticalSpacer(32.dp) - PrimaryButton( - text = stringResource(R.string.other__camera_permission_button), - icon = { - Icon(painter = painterResource(R.drawable.ic_camera), contentDescription = null) + NearbyEnableButtons( + sources = nearbySources, + leading = { + EnableSourceButton( + icon = R.drawable.ic_camera, + contentDescription = stringResource(R.string.other__camera_permission_button), + onClick = onClickRetry, + testTag = "ScannerEnableCamera", + ) }, - onClick = onClickRetry, ) } } @@ -495,6 +520,7 @@ private fun Preview() { BottomSheetPreview { SendRecipientContent( previewView = null, + nearbySources = NearbyScanSources(NfcState.OFF, BluetoothState.NEEDS_PERMISSION, {}, {}), isFlashlightOn = false, onClickFlashlight = {}, onClickGallery = {}, diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/usdt/UsdtDepositReceiveScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/usdt/UsdtDepositReceiveScreen.kt index ba4342775e..9da44477cb 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/usdt/UsdtDepositReceiveScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/usdt/UsdtDepositReceiveScreen.kt @@ -254,6 +254,7 @@ internal fun ColumnScope.UsdtDepositReceiveContent( UsdtReceiveContent( address = state.address?.address ?: wallet.address, uri = state.address?.uri ?: uri, + nearbyRequest = usdtNearbyRequest(depositUri = state.address?.uri, receiveUri = uri), error = receiveError, network = state.network?.label ?: "Arbitrum One", amount = state.address?.let { usdtFormatAmount(it.amount) } @@ -386,3 +387,10 @@ internal val UsdtDepositDetail.statusCode: String? get() = if (order != null) order?.code else deposit.code internal fun UsdtDepositDetail.statusResource(): Int = depositStatus(order?.status ?: deposit.status, statusCode) + +/** + * The request offered to nearby phones on USDT Receive. Nearby phones pay USDT on Arbitrum only, so a deposit + * address on another network is not offered. + */ +internal fun usdtNearbyRequest(depositUri: String?, receiveUri: String): String? = + receiveUri.takeIf { depositUri == null && it.isNotEmpty() } diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/usdt/UsdtReceiveContent.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/usdt/UsdtReceiveContent.kt index 87e034c24d..088ef0d317 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/usdt/UsdtReceiveContent.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/usdt/UsdtReceiveContent.kt @@ -33,6 +33,7 @@ import to.bitkit.ui.components.VerticalSpacer import to.bitkit.ui.screens.wallets.receive.CopyAddressCard import to.bitkit.ui.screens.wallets.receive.CopyAddressType import to.bitkit.ui.screens.wallets.receive.ReceiveQrView +import to.bitkit.ui.shared.effects.offerPaymentNearby import to.bitkit.ui.theme.AppShapes import to.bitkit.ui.theme.Colors @@ -45,8 +46,10 @@ internal fun ColumnScope.UsdtReceiveContent( onEdit: () -> Unit, onNetwork: () -> Unit, amount: String = "", + nearbyRequest: String? = null, ) { var showDetails by rememberSaveable { mutableStateOf(false) } + val canTapToPay = offerPaymentNearby(nearbyRequest) BackHandler(enabled = showDetails) { showDetails = false } val networkTitle = stringResource(R.string.usdt__receive_network, network) val copyMessage = stringResource(R.string.usdt__receive_copied) @@ -79,6 +82,7 @@ internal fun ColumnScope.UsdtReceiveContent( qrLogoPainter = painterResource(R.drawable.tether_circle), onClickEditInvoice = onEdit, accentColor = Colors.Usdt, + showsTapToPay = canTapToPay, shareContent = shareContent, copyMessage = copyMessage, modifier = Modifier.fillMaxWidth().height( diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/usdt/UsdtSendContent.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/usdt/UsdtSendContent.kt index 663860ee52..f52d33a05e 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/usdt/UsdtSendContent.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/usdt/UsdtSendContent.kt @@ -383,6 +383,7 @@ private fun UsdtRecipientContent( QrScanningScreen( showsGradientBackground = false, isEmbedded = true, + readsNearby = true, permissionDescription = stringResource(R.string.usdt__camera_permission_description), permissionAccentColor = Colors.Usdt, onScanSuccess = { it.text?.trim()?.let(onRecipientContinue) }, diff --git a/app/src/main/java/to/bitkit/ui/settings/SettingsScreen.kt b/app/src/main/java/to/bitkit/ui/settings/SettingsScreen.kt index 8a6d3febfd..afce021f0d 100644 --- a/app/src/main/java/to/bitkit/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/SettingsScreen.kt @@ -94,6 +94,7 @@ fun SettingsScreen( val bgPaymentsIntroSeen by settings.bgPaymentsIntroSeen.collectAsStateWithLifecycle() val notificationsGranted by settings.notificationsGranted.collectAsStateWithLifecycle() val isPaykitEnabled by settings.isPaykitEnabled.collectAsStateWithLifecycle() + val isNearbyPaymentsEnabled by settings.isNearbyPaymentsEnabled.collectAsStateWithLifecycle() LaunchedEffect(Unit) { settings.refreshUsdtAvailability() } val canDisableUsdt by settings.canDisableUsdt.collectAsStateWithLifecycle() val isUsdtEnabled by settings.isUsdtEnabled.collectAsStateWithLifecycle() @@ -134,6 +135,7 @@ fun SettingsScreen( tagCount = lastUsedTags.size, isQuickPayEnabled = isQuickPayEnabled, notificationsGranted = notificationsGranted, + isNearbyPaymentsEnabled = isNearbyPaymentsEnabled, hardwareWalletCount = hardwareWallets.size, isUsdtEnabled = isUsdtEnabled, canDisableUsdt = canDisableUsdt, @@ -167,6 +169,7 @@ fun SettingsScreen( SettingsEvent.WidgetsClick -> navController.navigateToWidgetsSettings() SettingsEvent.TagsClick -> navController.navigateToTagsSettings() SettingsEvent.TransactionSpeedClick -> navController.navigateToTransactionSpeedSettings() + SettingsEvent.NearbyPaymentsClick -> settings.setNearbyPaymentsEnabled(!isNearbyPaymentsEnabled) SettingsEvent.UsdtClick -> settings.setUsdtEnabled(!isUsdtEnabled) SettingsEvent.QuickPayClick -> navController.navigateToQuickPaySettings(quickPayIntroSeen) SettingsEvent.BgPaymentsClick -> { @@ -379,6 +382,15 @@ private fun GeneralTabContent( onClick = { onEvent(SettingsEvent.HardwareWalletsClick) }, modifier = Modifier.testTag("HardwareWalletsSettings") ) + SettingsSwitchRow( + title = stringResource(R.string.settings__nearby__title), + subtitle = stringResource(R.string.settings__nearby__subtitle), + isChecked = state.isNearbyPaymentsEnabled, + icon = { SettingsIcon(R.drawable.ic_broadcast) }, + onClick = { onEvent(SettingsEvent.NearbyPaymentsClick) }, + switchTestTag = "NearbyPaymentsToggle", + modifier = Modifier.testTag("NearbyPaymentsSettings") + ) if (Env.isUsdtEnabled) { SettingsSwitchRow( @@ -678,6 +690,7 @@ sealed interface SettingsEvent { data object WidgetsClick : SettingsEvent data object TagsClick : SettingsEvent data object TransactionSpeedClick : SettingsEvent + data object NearbyPaymentsClick : SettingsEvent data object UsdtClick : SettingsEvent data object QuickPayClick : SettingsEvent data object BgPaymentsClick : SettingsEvent @@ -723,6 +736,7 @@ data class GeneralTabState( val tagCount: Int = 0, val isQuickPayEnabled: Boolean = false, val notificationsGranted: Boolean = false, + val isNearbyPaymentsEnabled: Boolean = true, val hardwareWalletCount: Int = 0, val isUsdtEnabled: Boolean = false, val canDisableUsdt: Boolean = false, diff --git a/app/src/main/java/to/bitkit/ui/shared/effects/BluetoothState.kt b/app/src/main/java/to/bitkit/ui/shared/effects/BluetoothState.kt new file mode 100644 index 0000000000..9978bdd07d --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/shared/effects/BluetoothState.kt @@ -0,0 +1,4 @@ +package to.bitkit.ui.shared.effects + +/** [LOCATION_OFF] applies to scanning before Android 12, where BLE scans need location services on. */ +enum class BluetoothState { UNAVAILABLE, NEEDS_PERMISSION, OFF, LOCATION_OFF, ON } diff --git a/app/src/main/java/to/bitkit/ui/shared/effects/NearbyEffects.kt b/app/src/main/java/to/bitkit/ui/shared/effects/NearbyEffects.kt new file mode 100644 index 0000000000..f302772571 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/shared/effects/NearbyEffects.kt @@ -0,0 +1,229 @@ +package to.bitkit.ui.shared.effects + +import android.Manifest +import android.annotation.SuppressLint +import android.bluetooth.BluetoothAdapter +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.content.pm.PackageManager +import android.location.LocationManager +import android.os.Build +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.platform.LocalContext +import androidx.core.content.ContextCompat +import androidx.core.location.LocationManagerCompat +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import androidx.lifecycle.compose.LocalLifecycleOwner +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import to.bitkit.ext.bluetoothManager +import to.bitkit.nearby.NearbyAdvertiser +import to.bitkit.nearby.NearbyScanner +import to.bitkit.nfc.nfcPaymentUri +import to.bitkit.repositories.ConnectivityState +import to.bitkit.ui.LocalIsAppLocked +import to.bitkit.ui.appViewModel +import to.bitkit.ui.settingsViewModel + +/** + * Permissions requested from the scanner's Bluetooth button: the Android 12+ "Nearby devices" group + * (all three, so Receive can advertise afterwards), or location before Android 12, which scanning needs. + */ +val nearbyPermissions: Array = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + arrayOf( + Manifest.permission.BLUETOOTH_SCAN, + Manifest.permission.BLUETOOTH_ADVERTISE, + Manifest.permission.BLUETOOTH_CONNECT, + ) +} else { + arrayOf(Manifest.permission.ACCESS_FINE_LOCATION) +} + +private val scanPermissions: Array = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + arrayOf(Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT) +} else { + arrayOf(Manifest.permission.ACCESS_FINE_LOCATION) +} + +/** Advertising and the GATT server need no runtime permission before Android 12. */ +private val advertisePermissions: Array = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + arrayOf(Manifest.permission.BLUETOOTH_ADVERTISE, Manifest.permission.BLUETOOTH_CONNECT) +} else { + emptyArray() +} + +enum class NearbyRole { SCAN, ADVERTISE } + +fun Context.bluetoothState(role: NearbyRole): BluetoothState { + if (!packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) return BluetoothState.UNAVAILABLE + val adapter = bluetoothManager.adapter ?: return BluetoothState.UNAVAILABLE + val permissions = if (role == NearbyRole.SCAN) scanPermissions else advertisePermissions + val granted = permissions.all { + ContextCompat.checkSelfPermission(this, it) == PackageManager.PERMISSION_GRANTED + } + return when { + !granted -> BluetoothState.NEEDS_PERMISSION + !adapter.isEnabled -> BluetoothState.OFF + role == NearbyRole.SCAN && Build.VERSION.SDK_INT < Build.VERSION_CODES.S && !isLocationEnabled() -> + BluetoothState.LOCATION_OFF + + // Some phones can scan but not advertise; Receive must not claim it can be found over Bluetooth there. + role == NearbyRole.ADVERTISE && !adapter.isMultipleAdvertisementSupported -> BluetoothState.UNAVAILABLE + + else -> BluetoothState.ON + } +} + +/** Before Android 12, BLE scans return nothing while location services are off. */ +private fun Context.isLocationEnabled(): Boolean { + val locationManager = getSystemService(LocationManager::class.java) ?: return false + return LocationManagerCompat.isLocationEnabled(locationManager) +} + +/** + * Bluetooth availability for nearby payments in [role]. Refreshed when the screen resumes, when + * [refreshKey] changes (after a permission result) and when Bluetooth or location is switched. + */ +@Composable +fun rememberBluetoothState(role: NearbyRole, refreshKey: Any? = null): BluetoothState { + val context = LocalContext.current + val lifecycleOwner = LocalLifecycleOwner.current + var state by remember(role, refreshKey) { mutableStateOf(context.bluetoothState(role)) } + DisposableEffect(context, lifecycleOwner, role, refreshKey) { + val observer = LifecycleEventObserver { _, event -> + if (event == Lifecycle.Event.ON_RESUME) state = context.bluetoothState(role) + } + val receiver = object : BroadcastReceiver() { + override fun onReceive(receiverContext: Context, intent: Intent) { + state = context.bluetoothState(role) + } + } + val filter = IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED).apply { + addAction(LocationManager.PROVIDERS_CHANGED_ACTION) + } + ContextCompat.registerReceiver(context, receiver, filter, ContextCompat.RECEIVER_NOT_EXPORTED) + lifecycleOwner.lifecycle.addObserver(observer) + onDispose { + lifecycleOwner.lifecycle.removeObserver(observer) + context.unregisterReceiver(receiver) + } + } + return state +} + +/** + * Reads payment requests from nearby Bitkit wallets while the calling screen is resumed. + * Pass [enabled] only while [rememberBluetoothState] reports [BluetoothState.ON] for [NearbyRole.SCAN]; + * the effect restarts whenever it changes, so an adapter that was switched off and on is picked up again. + */ +@Composable +fun NearbyScanEffect(enabled: Boolean, onRead: (String) -> Unit) { + val context = LocalContext.current + val lifecycleOwner = LocalLifecycleOwner.current + val currentOnRead by rememberUpdatedState(onRead) + + DisposableEffect(context, lifecycleOwner, enabled) { + if (!enabled) return@DisposableEffect onDispose {} + val scanner = NearbyScanner(context.applicationContext) { currentOnRead(it) } + val observer = LifecycleEventObserver { _, event -> + when (event) { + Lifecycle.Event.ON_RESUME -> startScanner(scanner) + Lifecycle.Event.ON_PAUSE -> scanner.stop() + else -> Unit + } + } + lifecycleOwner.lifecycle.addObserver(observer) + if (lifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) startScanner(scanner) + onDispose { + lifecycleOwner.lifecycle.removeObserver(observer) + scanner.stop() + } + } +} + +@SuppressLint("MissingPermission") // NearbyScanEffect runs only while the scan permissions are granted. +private fun startScanner(scanner: NearbyScanner) = scanner.start() + +/** + * Serves [uri] to nearby Bitkit wallets over Bluetooth while the calling screen is resumed. + * [onFailed] runs when advertising can't start, so the screen stops saying it can be tapped. + */ +@Composable +fun NearbyAdvertiseEffect(uri: String?, onFailed: () -> Unit = {}) { + val context = LocalContext.current + val lifecycleOwner = LocalLifecycleOwner.current + val currentOnFailed by rememberUpdatedState(onFailed) + + DisposableEffect(context, lifecycleOwner, uri) { + if (uri.isNullOrBlank()) return@DisposableEffect onDispose {} + val advertiser = NearbyAdvertiser(context.applicationContext) { currentOnFailed() } + val observer = LifecycleEventObserver { _, event -> + when (event) { + Lifecycle.Event.ON_RESUME -> startAdvertiser(advertiser, uri) + Lifecycle.Event.ON_PAUSE -> stopAdvertiser(advertiser) + else -> Unit + } + } + lifecycleOwner.lifecycle.addObserver(observer) + if (lifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) startAdvertiser(advertiser, uri) + onDispose { + lifecycleOwner.lifecycle.removeObserver(observer) + stopAdvertiser(advertiser) + } + } +} + +@SuppressLint("MissingPermission") // NearbyAdvertiseEffect gets a uri only while the advertise permissions are granted. +private fun startAdvertiser(advertiser: NearbyAdvertiser, uri: String) = advertiser.start(uri) + +@SuppressLint("MissingPermission") // Same as startAdvertiser. +private fun stopAdvertiser(advertiser: NearbyAdvertiser) = advertiser.stop() + +/** + * Whether nearby payments pause: while the PIN screen covers the app, or while the connection issues screen + * covers the payment sheets, so nothing is offered or read that the user cannot see. + */ +@Composable +fun isNearbyPaused(): Boolean { + val isLocked = LocalIsAppLocked.current + val connectivity = appViewModel?.isOnline?.collectAsStateWithLifecycle()?.value ?: ConnectivityState.CONNECTED + return isLocked || connectivity != ConnectivityState.CONNECTED +} + +/** The URI offered to nearby payers for [request], or null while nearby payments are paused. */ +internal fun nearbyOfferUri(request: String?, isPaused: Boolean): String? = + nfcPaymentUri(request)?.takeUnless { isPaused } + +/** + * Offers the Receive request to nearby payers while the calling screen is resumed and nearby payments + * are not paused: over NFC when the device can emulate a tag, and over Bluetooth when it is on and the + * nearby setting allows it. Returns whether either is active, which is when Receive says it can be tapped. + * NFC stops counting as active once its tag service fails to register, and Bluetooth once its advertising + * fails to start. + */ +@Composable +fun offerPaymentNearby(request: String?): Boolean { + val uri = nearbyOfferUri(request, isPaused = isNearbyPaused()) + val canEmitNfc = rememberCanEmitNfc() + // A failed registration is retried when the request or the NFC state changes. + var emitFailed by remember(uri, canEmitNfc) { mutableStateOf(false) } + val emitsNfc = canEmitNfc && !emitFailed + val bluetoothState = rememberBluetoothState(NearbyRole.ADVERTISE) + val isNearbyEnabled by settingsViewModel?.isNearbyPaymentsEnabled?.collectAsStateWithLifecycle() + ?: remember { mutableStateOf(false) } + // A failed start is retried when the request or the Bluetooth state changes. + var advertiseFailed by remember(uri, bluetoothState) { mutableStateOf(false) } + val canAdvertise = isNearbyEnabled && bluetoothState == BluetoothState.ON && !advertiseFailed + + NfcEmitterEffect(uri = uri.takeIf { emitsNfc }, onFailed = { emitFailed = true }) + NearbyAdvertiseEffect(uri = uri.takeIf { canAdvertise }, onFailed = { advertiseFailed = true }) + return uri != null && (emitsNfc || canAdvertise) +} 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 new file mode 100644 index 0000000000..5bd5fb26c6 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/shared/effects/NfcEffects.kt @@ -0,0 +1,247 @@ +package to.bitkit.ui.shared.effects + +import android.app.Activity +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.nfc.NfcAdapter +import android.nfc.Tag +import android.nfc.cardemulation.CardEmulation +import android.nfc.tech.Ndef +import android.os.Handler +import android.os.Looper +import android.provider.Settings +import androidx.activity.compose.LocalActivity +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.platform.LocalContext +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import androidx.lifecycle.compose.LocalLifecycleOwner +import to.bitkit.androidServices.NdefTagService +import to.bitkit.nfc.NdefCodec +import to.bitkit.nfc.NfcReadDispatcher +import to.bitkit.nfc.NfcRepeatGuard +import to.bitkit.nfc.NfcTagEmitter +import to.bitkit.nfc.READER_FLAGS +import to.bitkit.nfc.ReaderModeOwner +import to.bitkit.nfc.Type4TagEmulator +import to.bitkit.nfc.nfcPaymentRequest +import to.bitkit.utils.Logger + +private const val TAG = "NfcEffects" +private val NDEF_AIDS = listOf(Type4TagEmulator.NDEF_AID_HEX) + +enum class NfcState { UNAVAILABLE, OFF, ON } + +fun Context.nfcState(): NfcState { + val adapter = NfcAdapter.getDefaultAdapter(this) ?: return NfcState.UNAVAILABLE + return if (adapter.isEnabled) NfcState.ON else NfcState.OFF +} + +fun Context.supportsNfcCardEmulation(): Boolean = + packageManager.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION) + +fun Context.openNfcSettings() { + runCatching { startActivity(Intent(Settings.ACTION_NFC_SETTINGS)) } + .onFailure { Logger.warn("Failed to open NFC settings", it, context = TAG) } +} + +/** Whether this device can offer a payment request to an NFC reader right now. */ +@Composable +fun rememberCanEmitNfc(): Boolean { + val context = LocalContext.current + val nfcState = rememberNfcState() + val supportsCardEmulation = remember(context) { context.supportsNfcCardEmulation() } + return nfcState == NfcState.ON && supportsCardEmulation +} + +/** NFC availability, refreshed every time the screen resumes (e.g. after the user turns NFC on). */ +@Composable +fun rememberNfcState(): NfcState { + val context = LocalContext.current + val lifecycleOwner = LocalLifecycleOwner.current + var state by remember { mutableStateOf(context.nfcState()) } + DisposableEffect(lifecycleOwner) { + val observer = LifecycleEventObserver { _, event -> + if (event == Lifecycle.Event.ON_RESUME) state = context.nfcState() + } + lifecycleOwner.lifecycle.addObserver(observer) + onDispose { lifecycleOwner.lifecycle.removeObserver(observer) } + } + return state +} + +/** + * Reads NDEF tags while the calling screen is resumed and hands over the payment request + * found on the tag. Reader mode keeps the system from opening another app for the tag and + * pauses this phone's own card emulation, so it is only active on scanning screens. + */ +@Composable +fun NfcReaderEffect( + onRead: (String) -> Unit, + onUnreadable: () -> Unit, + enabled: Boolean = true, +) { + val activity = LocalActivity.current ?: return + val lifecycleOwner = LocalLifecycleOwner.current + val currentOnRead by rememberUpdatedState(onRead) + val currentOnUnreadable by rememberUpdatedState(onUnreadable) + + DisposableEffect(activity, lifecycleOwner, enabled) { + val adapter = NfcAdapter.getDefaultAdapter(activity) + if (!enabled || adapter == null) return@DisposableEffect onDispose {} + + val mainHandler = Handler(Looper.getMainLooper()) + val dispatcher = NfcReadDispatcher(onRead = { currentOnRead(it) }, onUnreadable = { currentOnUnreadable() }) + + // 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) + mainHandler.post { + // The tag stays in range after the read; hold reader mode so Android does not deliver it again. + // A read from a closed activation leaves reader mode to whichever scanner owns it now. + if (text != null && dispatcher.isCurrent(activation)) NfcRepeatGuard.engage(activity, tag) + dispatcher.deliver(text, activation) + } + } + + val owner = Any() + + fun enable() = runCatching { + adapter.enableReaderMode(activity, callback(dispatcher.open()), READER_FLAGS, null) + ReaderModeOwner.current = owner + }.onFailure { Logger.warn("Failed to enable NFC reader mode", it, context = TAG) } + + val resume: () -> Unit = { enable() } + + fun disable() { + // A read still in progress, or a callback Android calls after this, posts a closed activation. + dispatcher.close() + if (ReaderModeOwner.resumeScanner === resume) ReaderModeOwner.resumeScanner = null + if (ReaderModeOwner.current !== owner) return + ReaderModeOwner.current = null + runCatching { adapter.disableReaderMode(activity) } + .onFailure { Logger.warn("Failed to disable NFC reader mode", it, context = TAG) } + } + + val observer = LifecycleEventObserver { _, event -> + when (event) { + Lifecycle.Event.ON_RESUME -> { + ReaderModeOwner.resumeScanner = resume + enable() + } + Lifecycle.Event.ON_PAUSE -> disable() + else -> Unit + } + } + lifecycleOwner.lifecycle.addObserver(observer) + if (lifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) { + ReaderModeOwner.resumeScanner = resume + enable() + } + + onDispose { + lifecycleOwner.lifecycle.removeObserver(observer) + disable() + mainHandler.removeCallbacksAndMessages(null) + } + } +} + +private fun readPaymentText(tag: Tag): String? { + val ndef = Ndef.get(tag) ?: return null + val message = runCatching { + ndef.cachedNdefMessage ?: ndef.use { + it.connect() + it.ndefMessage + } + }.onFailure { + Logger.warn("Failed to read NFC tag", it, context = TAG) + }.getOrNull() ?: return null + return NdefCodec.payableText(NdefCodec.decodeTexts(message.toByteArray()))?.let(::nfcPaymentRequest) +} + +/** + * Offers [uri] to NFC readers while the calling screen is resumed, through [NdefTagService]. + * The NDEF tag AID is registered for the service only meanwhile, and the service is made the + * preferred one, so Bitkit does not answer readers elsewhere and another app with the same AID + * does not answer instead. + */ +@Composable +fun NfcEmitterEffect(uri: String?, onFailed: () -> Unit = {}) { + val activity = LocalActivity.current ?: return + val lifecycleOwner = LocalLifecycleOwner.current + val currentOnFailed by rememberUpdatedState(onFailed) + + DisposableEffect(activity, lifecycleOwner, uri) { + val cardEmulation = cardEmulation(activity) + if (uri.isNullOrBlank() || cardEmulation == null) return@DisposableEffect onDispose {} + val service = ComponentName(activity, NdefTagService::class.java) + + var token: Long? = null + + fun start() { + val published = NfcTagEmitter.publish(uri) + token = published + if (registerTagService(cardEmulation, activity, service)) return + // Without the AID no reader reaches the service, so Receive must not say it can be tapped. + token = null + NfcTagEmitter.clear(published) + currentOnFailed() + } + + fun stop() { + val published = token ?: return + token = null + // Another screen may have published since; it then owns the service registration too. + if (!NfcTagEmitter.clear(published)) return + runCatching { + cardEmulation.unsetPreferredService(activity) + cardEmulation.removeAidsForService(service, CardEmulation.CATEGORY_OTHER) + }.onFailure { Logger.warn("Failed to release NFC tag service", it, context = TAG) } + } + + val observer = LifecycleEventObserver { _, event -> + when (event) { + Lifecycle.Event.ON_RESUME -> start() + Lifecycle.Event.ON_PAUSE -> stop() + else -> Unit + } + } + lifecycleOwner.lifecycle.addObserver(observer) + if (lifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) start() + + onDispose { + lifecycleOwner.lifecycle.removeObserver(observer) + stop() + } + } +} + +/** + * Routes the NDEF tag AID to [service] and prefers it. Returns whether both succeeded: without the preference, + * another service holding the same AID can answer the tap, so the AID is released again. + */ +internal fun registerTagService(cardEmulation: CardEmulation, activity: Activity, service: ComponentName): Boolean = + runCatching { + val isRegistered = cardEmulation.registerAidsForService(service, CardEmulation.CATEGORY_OTHER, NDEF_AIDS) + if (!isRegistered) return@runCatching false + if (cardEmulation.setPreferredService(activity, service)) return@runCatching true + cardEmulation.removeAidsForService(service, CardEmulation.CATEGORY_OTHER) + false + }.onFailure { Logger.warn("Failed to register NFC tag service", it, context = TAG) } + .onSuccess { if (!it) Logger.warn("NFC tag service registration was refused", context = TAG) } + .getOrDefault(false) + +private fun cardEmulation(activity: Activity): CardEmulation? { + if (!activity.supportsNfcCardEmulation()) return null + val adapter = NfcAdapter.getDefaultAdapter(activity) ?: return null + return runCatching { CardEmulation.getInstance(adapter) }.getOrNull() +} diff --git a/app/src/main/java/to/bitkit/ui/sheets/NfcIntroSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/NfcIntroSheet.kt new file mode 100644 index 0000000000..454f8fdec2 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/sheets/NfcIntroSheet.kt @@ -0,0 +1,124 @@ +package to.bitkit.ui.sheets + +import androidx.compose.foundation.Image +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import to.bitkit.R +import to.bitkit.ui.components.BodyM +import to.bitkit.ui.components.BottomSheetPreview +import to.bitkit.ui.components.Display +import to.bitkit.ui.components.PrimaryButton +import to.bitkit.ui.components.SecondaryButton +import to.bitkit.ui.components.VerticalSpacer +import to.bitkit.ui.components.settings.SettingsSwitchRow +import to.bitkit.ui.scaffold.SheetTopBar +import to.bitkit.ui.shared.modifiers.sheetHeight +import to.bitkit.ui.shared.util.gradientBackground +import to.bitkit.ui.theme.AppThemeSurface +import to.bitkit.ui.theme.Colors +import to.bitkit.ui.utils.withAccent + +@Composable +fun NfcIntroSheet( + isQuickPayEnabled: Boolean, + onToggleQuickPay: () -> Unit, + onSettings: () -> Unit, + onContinue: () -> Unit, + modifier: Modifier = Modifier, +) { + Column( + modifier = modifier + .sheetHeight(isModal = true) + .fillMaxSize() + .gradientBackground() + .navigationBarsPadding() + .testTag("NfcIntro") + ) { + SheetTopBar(stringResource(R.string.settings__nfc__nav_title)) + + Column(modifier = Modifier.padding(horizontal = 16.dp)) { + Box( + contentAlignment = Alignment.Center, + modifier = Modifier + .fillMaxWidth() + .weight(1f) + ) { + Image( + painter = painterResource(R.drawable.nfc), + contentDescription = null, + contentScale = ContentScale.Fit, + modifier = Modifier + .fillMaxWidth(NFC_IMAGE_WIDTH_FRACTION) + .heightIn(max = 280.dp) + ) + } + + Display( + text = stringResource(R.string.settings__nfc__intro__title).withAccent(accentColor = Colors.Purple), + color = Colors.White, + ) + VerticalSpacer(8.dp) + BodyM( + text = stringResource(R.string.settings__nfc__intro__description), + color = Colors.White64, + ) + VerticalSpacer(16.dp) + SettingsSwitchRow( + title = stringResource(R.string.settings__nfc__intro__quickpay), + isChecked = isQuickPayEnabled, + onClick = onToggleQuickPay, + switchTestTag = "NfcIntroQuickPay", + ) + VerticalSpacer(16.dp) + Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) { + SecondaryButton( + text = stringResource(R.string.settings__settings), + onClick = onSettings, + testTag = "NfcIntroSettings", + modifier = Modifier.weight(1f), + ) + PrimaryButton( + text = stringResource(R.string.settings__nfc__intro__continue), + onClick = onContinue, + modifier = Modifier + .weight(1f) + .testTag("NfcIntroContinue"), + ) + } + VerticalSpacer(16.dp) + } + } +} + +private const val NFC_IMAGE_WIDTH_FRACTION = 0.7f + +@Preview(showSystemUi = true) +@Composable +private fun Preview() { + AppThemeSurface { + BottomSheetPreview { + NfcIntroSheet( + isQuickPayEnabled = true, + onToggleQuickPay = {}, + onSettings = {}, + onContinue = {}, + ) + } + } +} diff --git a/app/src/main/java/to/bitkit/ui/sheets/QrScanningSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/QrScanningSheet.kt index 20bcac4c96..a7e756e154 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/QrScanningSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/QrScanningSheet.kt @@ -16,20 +16,22 @@ fun QrScanningSheet( ) { Content( isPubkyScan = sheet.isPubkyScan, + readsNearby = sheet.readsNearby, onBack = if (sheet.showBackButton) { { appViewModel.hideScannerSheet() } } else { null }, - onScanSuccess = { appViewModel.onScannerSheetResult(it) }, + onScanSuccess = { data, isNearby -> appViewModel.onScannerSheetResult(data, suppressQuickPay = isNearby) }, ) } @Composable private fun Content( isPubkyScan: Boolean, + readsNearby: Boolean, onBack: (() -> Unit)?, - onScanSuccess: (String) -> Unit, + onScanSuccess: (String, Boolean) -> Unit, ) { Column( modifier = Modifier @@ -38,7 +40,8 @@ private fun Content( ) { QrScanningScreen( isPubkyScan = isPubkyScan, - onScanSuccess = { payload -> payload.text?.let(onScanSuccess) }, + readsNearby = readsNearby, + onScanSuccess = { payload -> payload.text?.let { onScanSuccess(it, payload.isNearby) } }, onBack = onBack, ) } diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index d022f04d4c..946b17428a 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -469,11 +469,17 @@ fun SendSheet( } composableWithDefaultTransitions { QrScanningScreen( + readsNearby = true, onBack = { navController.popBackStack() }, onScanSuccess = { payload -> payload.text?.let { navController.popBackStack() - appViewModel.onScanResult(data = it, routePubkyKeys = true) + appViewModel.onScanResult( + data = it, + routePubkyKeys = true, + suppressQuickPay = payload.isNearby, + fromSendScanner = true, + ) } }, ) @@ -730,6 +736,7 @@ fun SendSheet( quickPayData = request.data, isRequestActive = quickPayRequest?.id == request.id, canPayWithoutNode = sparkCanPayQuickPay(request.data, sparkState), + canStart = { appViewModel.canStartQuickPay(request) }, onPaymentComplete = { paymentHash, amountWithFee -> appViewModel.onSendSuccess( NewTransactionSheetDetails( @@ -753,7 +760,7 @@ fun SendSheet( ) }, onFallBackToConfirm = { - appViewModel.resetQuickPay() + appViewModel.fallBackFromQuickPay() navController.navigateTo(SendRoute.Confirm) { popUpTo { inclusive = true } } diff --git a/app/src/main/java/to/bitkit/utils/Errors.kt b/app/src/main/java/to/bitkit/utils/Errors.kt index e722f97e8d..10ddc857cf 100644 --- a/app/src/main/java/to/bitkit/utils/Errors.kt +++ b/app/src/main/java/to/bitkit/utils/Errors.kt @@ -16,6 +16,7 @@ sealed class ServiceError(message: String) : AppError(message) { class NodeNotSetup : ServiceError("Node is not setup") class NodeNotStarted : ServiceError("Node is not started") class PaymentDeadlineExpired : ServiceError("Payment deadline has expired") + class PaymentStoppedAtSubmission : ServiceError("Payment stopped before it was submitted") class MnemonicNotFound : ServiceError("Mnemonic not found") class VssAuthRequired : ServiceError("VSS requires LNURL-auth") class NodeStillRunning : ServiceError("Node is still running") @@ -138,3 +139,7 @@ fun Throwable.asNodeException(): NodeException? = when (this) { // endregion fun Throwable.isTxSyncTimeout(): Boolean = this is NodeException.TxSyncTimeout || cause is NodeException.TxSyncTimeout + +/** Whether this, or an error it wraps, is [ServiceError.PaymentStoppedAtSubmission]: nothing reached the node. */ +fun Throwable.isStoppedAtSubmission(): Boolean = + generateSequence(this) { it.cause }.any { it is ServiceError.PaymentStoppedAtSubmission } diff --git a/app/src/main/java/to/bitkit/utils/timedsheets/sheets/NfcTimedSheet.kt b/app/src/main/java/to/bitkit/utils/timedsheets/sheets/NfcTimedSheet.kt new file mode 100644 index 0000000000..44e2a00eb8 --- /dev/null +++ b/app/src/main/java/to/bitkit/utils/timedsheets/sheets/NfcTimedSheet.kt @@ -0,0 +1,39 @@ +package to.bitkit.utils.timedsheets.sheets + +import android.content.Context +import android.content.pm.PackageManager +import dagger.hilt.android.qualifiers.ApplicationContext +import kotlinx.coroutines.flow.first +import to.bitkit.data.SettingsStore +import to.bitkit.ui.components.TimedSheetType +import to.bitkit.utils.Logger +import to.bitkit.utils.timedsheets.TimedSheetItem +import javax.inject.Inject + +/** Announces NFC payments once, on devices that can read NFC tags. */ +class NfcTimedSheet @Inject constructor( + @ApplicationContext private val context: Context, + private val settingsStore: SettingsStore, +) : TimedSheetItem { + override val type = TimedSheetType.NFC + override val priority = type.priority + + override suspend fun shouldShow(): Boolean { + if (settingsStore.data.first().nfcIntroSeen) return false + return context.packageManager.hasSystemFeature(PackageManager.FEATURE_NFC) + } + + override suspend fun onShown() { + Logger.debug("NFC sheet shown", context = TAG) + } + + override suspend fun onDismissed() { + // The NFC sheet carries the QuickPay toggle, so the separate QuickPay intro is not needed after it. + settingsStore.update { it.copy(nfcIntroSeen = true, quickPayIntroSeen = true) } + Logger.debug("NFC sheet dismissed", context = TAG) + } + + companion object { + private const val TAG = "NfcTimedSheet" + } +} diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index c4fed67217..69e18b6cbd 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -56,6 +56,7 @@ import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.TimeoutCancellationException +import kotlinx.coroutines.asContextElement import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope @@ -176,6 +177,7 @@ import to.bitkit.models.sanitizedQrLogValue import to.bitkit.models.toActivityFilter import to.bitkit.models.toLdkNetwork import to.bitkit.models.toTxType +import to.bitkit.nfc.nfcPaymentRequest import to.bitkit.repositories.ActivityRepo import to.bitkit.repositories.BackupRepo import to.bitkit.repositories.BlocktankRepo @@ -296,6 +298,7 @@ import to.bitkit.utils.timedsheets.sheets.AppUpdateTimedSheet import to.bitkit.utils.timedsheets.sheets.BackupTimedSheet import to.bitkit.utils.timedsheets.sheets.HighBalanceTimedSheet import to.bitkit.utils.timedsheets.sheets.MoveToSparkTimedSheet +import to.bitkit.utils.timedsheets.sheets.NfcTimedSheet import to.bitkit.utils.timedsheets.sheets.NotificationsTimedSheet import to.bitkit.utils.timedsheets.sheets.QuickPayTimedSheet import to.bitkit.utils.timedsheets.sheets.UsdtTimedSheet @@ -365,6 +368,7 @@ class AppViewModel @Inject constructor( private val backupSheet: BackupTimedSheet, private val notificationsSheet: NotificationsTimedSheet, private val quickPaySheet: QuickPayTimedSheet, + private val nfcSheet: NfcTimedSheet, private val usdtSheet: UsdtTimedSheet, private val usdtPreferences: UsdtPreferencesRepo, private val highBalanceSheet: HighBalanceTimedSheet, @@ -426,9 +430,19 @@ class AppViewModel @Inject constructor( if (canPresent()) _mainScreenEffect.emit(effect) } - private suspend fun waitForUsableChannels(walletGeneration: Long? = connectionRecovery.currentGeneration()) { + /** + * Waits for the node's channels before a Lightning send. When Spark covers [amountSats] there is no wait for a + * usable channel: a running node only publishes its current channels, which the send limit reads, and a node not + * running yet is skipped, so a payment opened right after launch does not wait for the node to start. + */ + private suspend fun waitForUsableChannels( + walletGeneration: Long? = connectionRecovery.currentGeneration(), + amountSats: ULong? = null, + ) { requireCurrentPaymentPreparation(walletGeneration) - lightningRepo.waitForUsableChannels() + val isNodeRunning = lightningRepo.lightningState.value.nodeLifecycleState.isRunning() + val sparkCovers = amountSats != null && lightningRepo.canSendWithSpark(amountSats) + if (isNodeRunning || !sparkCovers) lightningRepo.waitForUsableChannels(awaitUsable = !sparkCovers) requireCurrentPaymentPreparation(walletGeneration) walletRepo.refreshMaxSendLightning() requireCurrentPaymentPreparation(walletGeneration) @@ -675,12 +689,36 @@ class AppViewModel @Inject constructor( registerSheet(usdtSheet) registerSheet(backupSheet) registerSheet(notificationsSheet) + // Registered before QuickPay at the same priority: the NFC sheet includes the QuickPay toggle. + registerSheet(nfcSheet) registerSheet(quickPaySheet) registerSheet(highBalanceSheet) } private var isCompletingMigration = false private var isCompletingRestoreHold = false private var addressValidationJob: Job? = null + + /** + * A request read during this Send visit (a nearby read on the recipient screen, or a read from Send's own scanner). + * It is cancelled when Send closes or the user enters a request manually. + */ + private var sendVisitScanJob: Job? = null + + /** + * True on the main thread while a scan job runs, so a scan that closes Send itself (to open LNURL auth, + * withdraw or another sheet) does not cancel itself. Only a dismissal from outside the scan cancels it. + */ + private val isRunningScan = ThreadLocal() + + /** + * Bumped each time the wallet locks (the background lock, a PIN reset or the setter), so a scan that was + * already preparing can tell it crossed a lock. + */ + @Volatile + private var lockGeneration = 0L + + /** [lockGeneration] when the scan now holding [scanMutex] started, or null outside a scan. */ + private var scanLockGeneration: Long? = null private var lastPrivatePaykitContactKeys: Set = emptySet() private val isPaykitEnabled = settingsStore.isPaykitEnabled .map { PaykitFeatureFlags.isUiEnabled(it) } @@ -693,6 +731,7 @@ class AppViewModel @Inject constructor( fun setIsAuthenticated(value: Boolean) { _isAuthenticated.value = value if (!value) { + lockGeneration++ clearPaymentRequestPreparation() return } @@ -3374,7 +3413,7 @@ class AppViewModel @Inject constructor( is SendEvent.AddressChange -> onAddressChange(it.value) SendEvent.AddressReset -> resetAddressInput() - is SendEvent.AddressContinue -> onAddressContinue(it.data) + is SendEvent.AddressContinue -> onAddressContinue(it.data, it.suppressQuickPay, it.isNearbyRead) is SendEvent.AmountChange -> onAmountChange(it.amount) is SendEvent.AmountMax -> onAmountMax(it.amount) @@ -3425,13 +3464,16 @@ class AppViewModel @Inject constructor( SendEvent.ClearPayConfirmation -> _sendUiState.update { s -> s.copy(shouldConfirmPay = false) } SendEvent.BackToAmount -> setSendEffect(SendEffect.PopBack(SendRoute.Amount)) SendEvent.NavToAddress -> setSendEffect(SendEffect.NavigateToAddress) - SendEvent.Contacts -> setSendEffect( - if (isPaykitEnabled.value) { - SendEffect.NavigateToContacts - } else { - SendEffect.NavigateToComingSoon - } - ) + SendEvent.Contacts -> { + cancelSendVisitScan() + setSendEffect( + if (isPaykitEnabled.value) { + SendEffect.NavigateToContacts + } else { + SendEffect.NavigateToComingSoon + }, + ) + } } } catch (_: CancellationException) { currentCoroutineContext().ensureActive() @@ -3445,7 +3487,14 @@ class AppViewModel @Inject constructor( private val activeHardwareWalletId: String? get() = (currentSheet.value as? Sheet.Send)?.hardwareWalletId + /** A request still decoding must not route over the choice the user just made, or after Send closed. */ + private fun cancelSendVisitScan() { + sendVisitScanJob?.cancel() + sendVisitScanJob = null + } + private fun onEnterManuallyClick() { + cancelSendVisitScan() clearActiveContactPaymentContext() resetAddressInput() setSendEffect(SendEffect.NavigateToAddress) @@ -3699,7 +3748,7 @@ class AppViewModel @Inject constructor( ) return@takeIf false } - waitForUsableChannels(walletGeneration) + waitForUsableChannels(walletGeneration, lnInv.amountSatoshis.coerceAtLeast(1u)) val canSend = canSendLightning(lnInv.amountSatoshis.coerceAtLeast(1u)) if (!canSend) { val nodeState = lightningRepo.lightningState.value.nodeLifecycleState @@ -3837,7 +3886,8 @@ class AppViewModel @Inject constructor( } val previousJob = scheduled?.job - val nextJob = viewModelScope.launch(start = CoroutineStart.LAZY) { + val lockAtStart = lockGeneration + val nextJob = viewModelScope.launch(isRunningScan.asContextElement(true), start = CoroutineStart.LAZY) { if (!admission.await() || !canPrepareSend(walletGeneration)) return@launch clearPaymentRequestPreparation(previousPreparation) scanMutex.withLock { @@ -3848,6 +3898,7 @@ class AppViewModel @Inject constructor( if (deferLockedScan(deferrable)) return@withLock prepareContactPaymentContextForScan(normalized, allowPubkyAuth, contactPaymentContext) if (startDelay > Duration.ZERO) delay(startDelay) + scanLockGeneration = lockAtStart handleScan( data, routePubkyKeys, @@ -3857,6 +3908,7 @@ class AppViewModel @Inject constructor( walletGeneration ) } finally { + scanLockGeneration = null hidePubkyAuthWaitToast() } } @@ -4113,9 +4165,26 @@ class AppViewModel @Inject constructor( ) } - private fun onAddressContinue(data: String) { + private fun onAddressContinue(data: String, suppressQuickPay: Boolean, isNearbyRead: Boolean) { + // Bluetooth reads suppress QuickPay; NFC reads come from a tap, like a QR scan or a paste. + val isPassiveRead = isNearbyRead && suppressQuickPay + // A Bluetooth read never replaces a request still preparing: one the user chose, or the strongest receiver + // the scanner read first. A QR, paste or NFC request still replaces a Bluetooth one. + if (isPassiveRead && scheduledScan?.job?.isActive == true) { + Logger.info("Ignoring nearby read while another request is preparing", context = TAG) + return + } clearActiveContactPaymentContext() - launchScan(source = ScanSource.ADDRESS_CONTINUE, data = data, routePubkyKeys = true) + val job = launchScan( + source = ScanSource.ADDRESS_CONTINUE, + data = data, + routePubkyKeys = true, + suppressQuickPay = suppressQuickPay, + ) + // 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 { sendVisitScanJob = it } } fun onUsdtAmountChange(value: String) { @@ -5449,15 +5518,20 @@ class AppViewModel @Inject constructor( routePubkyKeys: Boolean = false, contactPaymentContext: ContactPaymentContext? = null, allowPubkyAuth: Boolean = isMainScanner, + suppressQuickPay: Boolean = false, + fromSendScanner: Boolean = false, ) { - launchScan( + val job = launchScan( source = ScanSource.SCAN_RESULT, data = data, startDelay = startDelay, routePubkyKeys = routePubkyKeys, contactPaymentContext = contactPaymentContext, allowPubkyAuth = allowPubkyAuth, + suppressQuickPay = suppressQuickPay, ) + // A read from Send's own scanner (camera, NFC or Bluetooth) belongs to this Send visit. + if (fromSendScanner) job?.let { sendVisitScanJob = it } } fun openContactPayment( @@ -6414,7 +6488,7 @@ class AppViewModel @Inject constructor( ) if (quickPayHandled) return - waitForUsableChannels(walletGeneration) + waitForUsableChannels(walletGeneration, amount) if (!canSendLightning(amount)) { val maxSendLightning = walletRepo.balanceState.value.maxSendLightningSats val shortfall = amount.safe() - maxSendLightning.safe() @@ -6494,7 +6568,7 @@ class AppViewModel @Inject constructor( } val paymentAmount = incomingAmount ?: displaySats - waitForUsableChannels(walletGeneration) + waitForUsableChannels(walletGeneration, paymentAmount.coerceAtLeast(1u)) if (!canSendLightning(paymentAmount.coerceAtLeast(1u))) { toast( type = Toast.ToastType.WARNING, @@ -6672,6 +6746,10 @@ class AppViewModel @Inject constructor( mainScreenEffect(MainScreenEffect.Navigate(nextRoute)) } + /** Whether the wallet is locked, or locked since the running scan started: whoever unlocked did not confirm it. */ + private fun scanCrossedLock(): Boolean = + !_isAuthenticated.value || scanLockGeneration.let { it != null && it != lockGeneration } + private suspend fun handleQuickPayIfApplicable( amountSats: ULong, fromMainScanner: Boolean, @@ -6681,8 +6759,12 @@ class AppViewModel @Inject constructor( walletGeneration: Long?, ): Boolean { requireCurrentPaymentPreparation(walletGeneration) - if (suppressQuickPay) { - Logger.info("Skipping QuickPay for '$amountSats' sats deferred across the lock", context = TAG) + if (suppressQuickPay || scanCrossedLock()) { + Logger.info( + "Skipping QuickPay for '$amountSats' sats: suppressed for this scan " + + "(deferred across the lock, or read from a nearby device)", + context = TAG, + ) return false } if (hasActiveContactPaymentContext()) return false @@ -6696,6 +6778,8 @@ class AppViewModel @Inject constructor( val canApply = open || canApplyQuickPay(amountSats) requireCurrentPaymentPreparation(walletGeneration) if (!canApply) return false + // Checked again: the wallet can lock while the QuickPay checks above suspend. + if (scanCrossedLock()) return false Logger.info("Using QuickPay for '$amountSats' sats", context = TAG) @@ -6714,7 +6798,11 @@ class AppViewModel @Inject constructor( } _quickPayData.update { - QuickPayRequest(id = quickPayRequestIds.incrementAndGet(), data = quickPayData) + QuickPayRequest( + id = quickPayRequestIds.incrementAndGet(), + data = quickPayData, + lockGeneration = scanLockGeneration ?: lockGeneration, + ) } if (lnurlPay != null) { @@ -8609,6 +8697,24 @@ class AppViewModel @Inject constructor( fun resetQuickPay() = _quickPayData.update { null } + /** + * Leaves QuickPay for the swipe review. QuickPay takes a fixed invoice before the scan marks its amount + * valid, so it is marked here as the fixed LNURL-pay path does: the request sets the amount, and paying + * checks the funds. A check against the spending limit here could run before the node publishes it and + * keep Swipe to Pay disabled. + */ + fun fallBackFromQuickPay() { + resetQuickPay() + _sendUiState.update { it.copy(isAmountInputValid = it.isAmountInputValid || it.amount > 0uL) } + } + + /** + * Whether the QuickPay screen may start paying [request] now: the wallet is unlocked and has not locked since + * the scan that made the request. Otherwise whoever unlocked did not choose the payment, so it goes to review. + */ + fun canStartQuickPay(request: QuickPayRequest): Boolean = + _isAuthenticated.value && request.lockGeneration == lockGeneration + fun navigateToUsdtDeposits() { viewModelScope.launch { hideSheet() @@ -9159,11 +9265,13 @@ class AppViewModel @Inject constructor( Sheet.QrScanner( isPubkyScan = isPubkyScan, showBackButton = showBackButton, + // A caller with its own handler scans for a setting or a contact, not for a payment. + readsNearby = !isPubkyScan && onResult == null, ) ) } - fun onScannerSheetResult(data: String) { + fun onScannerSheetResult(data: String, suppressQuickPay: Boolean = false) { val handler = scanResultHandler val shouldHandleAsProtocol = SamRockSetupRequest.isProtocolUrl(data.removeLightningSchemes()) scanResultHandler = null @@ -9180,6 +9288,7 @@ class AppViewModel @Inject constructor( data = data, startDelay = SCREEN_TRANSITION_DELAY, routePubkyKeys = true, + suppressQuickPay = suppressQuickPay, ) } } @@ -9301,6 +9410,8 @@ class AppViewModel @Inject constructor( clearPaymentRequestPresentationRetry(it.request.id) } if (_currentSheet.value is Sheet.Send) { + // A read still preparing belongs to this Send visit: it must not reopen a sheet or reach QuickPay. + if (isRunningScan.get() != true) cancelSendVisitScan() sendStateGeneration++ // A closed send is over: a swap failing for it later gives no contact back to whatever comes next. sendSession++ @@ -9399,6 +9510,7 @@ class AppViewModel @Inject constructor( private suspend fun resetIsAuthenticatedStateInternal() { val settings = settingsStore.data.first() val needsAuth = settings.isPinEnabled + if (needsAuth) lockGeneration++ _isAuthenticated.value = !needsAuth if (!needsAuth) flushDeferredScan() } @@ -9418,6 +9530,7 @@ class AppViewModel @Inject constructor( if (!isPinEnabled.value) return if (!walletRepo.walletExists()) return if (lightningRepo.isRecoveryMode.value) return + lockGeneration++ _isAuthenticated.update { false } Logger.debug("Locked app on background", context = TAG) } @@ -10245,10 +10358,22 @@ class AppViewModel @Inject constructor( if (intent.action !in DEEPLINK_ACTIONS) return intent.data?.let { uri -> Logger.debug("Received deeplink '${uri.toString().sanitizedDeeplinkLogValue()}'", context = TAG) - processDeeplink(uri) + // A tapped tag goes through the same rewrite and refusal as a scanner read. + val value = if (intent.action == NfcAdapter.ACTION_NDEF_DISCOVERED) { + nfcPaymentRequest(uri.toString()) ?: return showNfcReadError() + } else { + uri.toString() + } + processDeeplink(uri, value) } } + private fun showNfcReadError() = toast( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.other__nfc_read_error_title), + description = context.getString(R.string.other__nfc_read_error_text), + ) + fun onUsbDeviceAttached( deviceId: String? = null, deviceModel: String = "", @@ -10328,9 +10453,9 @@ class AppViewModel @Inject constructor( private fun processDeeplink( uri: Uri, + value: String = uri.toString(), walletGeneration: Long? = connectionRecovery.currentGeneration(), ) = viewModelScope.launch { - val value = uri.toString() val isContactLink = PubkyContactLink.matches(uri) if (SamRockSetupRequest.isProtocolUrl(value)) { if (!walletRepo.walletExists()) return@launch @@ -10890,7 +11015,11 @@ sealed interface SendEvent { data object AddressReset : SendEvent data class AddressChange(val value: String) : SendEvent - data class AddressContinue(val data: String) : SendEvent + data class AddressContinue( + val data: String, + val suppressQuickPay: Boolean = false, + val isNearbyRead: Boolean = false, + ) : SendEvent data object AmountReset : SendEvent data object AmountContinue : SendEvent @@ -10988,6 +11117,8 @@ sealed interface QuickPayData { data class QuickPayRequest( val id: Long, val data: QuickPayData, + /** The wallet's lock count when the scan behind this request started. */ + val lockGeneration: Long, ) // endregion diff --git a/app/src/main/java/to/bitkit/viewmodels/QuickPayViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/QuickPayViewModel.kt index df3993bd46..0c463cc444 100644 --- a/app/src/main/java/to/bitkit/viewmodels/QuickPayViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/QuickPayViewModel.kt @@ -59,10 +59,10 @@ class QuickPayViewModel @Inject constructor( fun acknowledge(session: QuickPaySession) = quickPayRepo.acknowledge(session) - fun pay(session: QuickPaySession, data: QuickPayData) { + fun pay(session: QuickPaySession, data: QuickPayData, canDispatch: () -> Boolean = { true }) { if (isPayRequested || _uiState.value.result != null) return isPayRequested = true - quickPayRepo.pay(session, data.toPayRequest()) + quickPayRepo.pay(session, data.toPayRequest(), canDispatch) } override fun onCleared() { diff --git a/app/src/main/java/to/bitkit/viewmodels/SettingsViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/SettingsViewModel.kt index d88437eb05..b52cb50c3c 100644 --- a/app/src/main/java/to/bitkit/viewmodels/SettingsViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/SettingsViewModel.kt @@ -343,6 +343,16 @@ class SettingsViewModel @Inject constructor( val isQuickpayEnabled = settingsStore.data.map { it.isQuickPayEnabled } .asStateFlow(initialValue = false) + // Off until the saved value loads, so Receive never advertises for a wallet that opted out. + val isNearbyPaymentsEnabled = settingsStore.data.map { it.isNearbyPaymentsEnabled } + .asStateFlow(initialValue = false) + + fun setNearbyPaymentsEnabled(value: Boolean) { + viewModelScope.launch { + settingsStore.update { it.copy(isNearbyPaymentsEnabled = value) } + } + } + val enableSwipeToHideBalance = settingsStore.data.map { it.enableSwipeToHideBalance } .asStateFlow(initialValue = true) diff --git a/app/src/main/res/drawable-nodpi/nfc.png b/app/src/main/res/drawable-nodpi/nfc.png new file mode 100644 index 0000000000..687354a277 Binary files /dev/null and b/app/src/main/res/drawable-nodpi/nfc.png differ diff --git a/app/src/main/res/drawable/ic_bluetooth.xml b/app/src/main/res/drawable/ic_bluetooth.xml new file mode 100644 index 0000000000..09ff8eb62b --- /dev/null +++ b/app/src/main/res/drawable/ic_bluetooth.xml @@ -0,0 +1,30 @@ + + + + + + + + diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 519cc21883..1fcdca483c 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -510,6 +510,11 @@ تم طلب السحب بنجاح. في انتظار الدفع. تم طلب السحب فشل إنشاء ملف السجلات المضغوط + تفعيل البلوتوث + تفعيل NFC + لا تحتوي هذه العلامة على طلب دفع يمكن لـ Bitkit استخدامه. + تعذر قراءة NFC + طلب دفع Bitkit خطأ في البدء: %1$s جارٍ إعداد المحفظة… قيد التشغيل @@ -530,6 +535,12 @@ انتهت صلاحية فاتورة Lightning هذه. لا يستطيع Bitkit قراءة البيانات المقدمة. خطأ في فك التشفير + اسمح بالوصول إلى الكاميرا و Bluetooth و NFC لمسح فواتير Bitcoin والدفع بشكل أسرع. + مسح\n<accent>للدفع</accent> + جارٍ مسح QR + جارٍ مسح QR و Bluetooth + جارٍ مسح QR و NFC + جارٍ مسح QR و NFC و Bluetooth مشاركة رمز QR عبر السفر بلا حدود @@ -791,6 +802,13 @@ عام إعدادات النظام اللغة + اسمح للهواتف القريبة بقراءة طلب الاستلام الخاص بك عبر Bluetooth + المدفوعات القريبة + رائع! + يدعم Bitkit الآن مدفوعات NFC. قرّب هاتفك من جهاز دفع أو هاتف متوافق للدفع فورًا. + استخدم QuickPay للمدفوعات الصغيرة + ادفع\n<accent>بلمسة واحدة فقط</accent> + TapPay (NFC) يجعل Bitkit QuickPay الدفع أسرع من خلال دفع الفواتير الصغيرة تلقائيًا. مدفوعات\n<accent>سلسة</accent> QuickPay @@ -1111,6 +1129,7 @@ تم نسخ الفاتورة إلى الحافظة فاتورة Lightning ملاحظة اختيارية للدافع + امسح أو المس للدفع عرض التفاصيل عرض رمز QR تعديل الفاتورة diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 2c0359bd0c..5287eca9ea 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -517,6 +517,11 @@ Su retiro ha sido solicitado con éxito. Esperando el pago. Retiro solicitado Error al crear el archivo zip de logs + Habilitar Bluetooth + Habilitar NFC + Esta etiqueta no contiene una solicitud de pago que Bitkit pueda usar. + No se puede leer el NFC + Solicitud de pago de Bitkit Error al iniciar: %1$s Configurando billetera... Ejecutándose @@ -537,6 +542,12 @@ Esta factura lightning ha caducado. Bitkit no puede leer los datos proporcionados. Error de descodificación + Permite el acceso a la cámara, Bluetooth y NFC para escanear facturas de bitcoin y pagar más rápido. + Escanea\n<accent>para pagar</accent> + Escaneando QR + Escaneando QR y Bluetooth + Escaneando QR y NFC + Escaneando QR, NFC y Bluetooth Compartir código QR vía Viajes Vive sin fronteras @@ -812,6 +823,13 @@ Geral Ajustes del sistema Idioma + Permite que los teléfonos cercanos lean tu solicitud de Recibir por Bluetooth + Pagos cercanos + ¡Impresionante! + Bitkit ahora admite pagos NFC. Acerca tu teléfono a una terminal de pago o a un teléfono compatible para pagar al instante. + Usa QuickPay para pagos pequeños + Paga con\n<accent>un solo toque</accent> + TapPay (NFC) Bitkit QuickPay agiliza el proceso de pago pagando automáticamente facturas pequeñas. <accent>Pagos</accent>\nsin fricción QuickPay @@ -1141,6 +1159,7 @@ Factura copiada en el portapapeles Factura Lightning Nota opcional para el pagador + Escanea o toca para pagar Ver detalles Mostrar código QR Editar factura diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 745b66514c..c93e5ad07e 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -514,6 +514,11 @@ La teva retirada s\'ha sol·licitat correctament. Esperant el pagament. Retirada sol·licitada Error en crear el fitxer zip de registres + Habilitar Bluetooth + Habilitar NFC + Aquesta etiqueta no conté cap sol·licitud de pagament que Bitkit pugui utilitzar. + No es pot llegir l\'NFC + Sol·licitud de pagament de Bitkit Error en iniciar: %1$s Configurant cartera... Executant @@ -534,6 +539,12 @@ Aquesta factura Lightning ha caducat. Bitkit no pot llegir les dades proporcionades. Error de descodificació + Permet l\'accés a la càmera, el Bluetooth i l\'NFC per escanejar factures de bitcoin i pagar més ràpidament. + Escaneja\n<accent>per pagar</accent> + Escanejant QR + Escanejant QR i Bluetooth + Escanejant QR i NFC + Escanejant QR, NFC i Bluetooth Compartir codi QR via Viatges Sense fronteres @@ -806,6 +817,13 @@ General Configuració del sistema Idioma + Permet que els telèfons propers llegeixin la teva sol·licitud de Rebre per Bluetooth + Pagaments propers + Genial! + Bitkit ara admet pagaments NFC. Apropa el telèfon a un terminal de pagament o a un telèfon compatible per pagar a l\'instant. + Utilitza QuickPay per a pagaments petits + Paga amb\n<accent>només un toc</accent> + TapPay (NFC) Bitkit QuickPay fa que pagar sigui més ràpid pagant automàticament factures petites. <accent>Pagaments</accent>\nsense friccions QuickPay @@ -1135,6 +1153,7 @@ Factura copiada al porta-retalls Factura Lightning Nota opcional per al pagador + Escaneja o toca per pagar Mostrar detalls Mostra el codi QR Editar factura diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 069e3d7aea..4a45fa0c79 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -517,6 +517,11 @@ Váš výběr byl úspěšně vyžádán. Čekání na platbu. Výběr vyžádán Nepodařilo se vytvořit soubor zip s protokoly + Povolit Bluetooth + Povolit NFC + Tento tag neobsahuje žádost o platbu, kterou by Bitkit mohl použít. + Nelze přečíst NFC + Žádost o platbu Bitkit Chyba při spouštění: %1$s Nastavování peněženky… Běží @@ -537,6 +542,12 @@ Platnost lightning faktury vypršela. Bitkit není schopen přečíst zadaná data. Chyba dekódování + Povolte přístup k fotoaparátu, Bluetooth a NFC pro skenování bitcoinových faktur a rychlejší platby. + Naskenujte\n<accent>a zaplaťte</accent> + Skenování QR + Skenování QR a Bluetooth + Skenování QR a NFC + Skenování QR, NFC a Bluetooth Sdílet QR kód pomocí Cestování Žij bez hranic @@ -811,6 +822,13 @@ Obecné Systémové nastavení Jazyk + Umožněte telefonům v okolí načíst vaši žádost Přijmout přes Bluetooth + Platby v okolí + Úžasné! + Bitkit nyní podporuje platby přes NFC. Přiložte telefon ke kompatibilnímu platebnímu terminálu nebo telefonu a zaplaťte okamžitě. + Používejte QuickPay pro malé platby + Plaťte\n<accent>jediným klepnutím</accent> + TapPay (NFC) Bitkit QuickPay urychluje placení automatickou úhradou malých faktur. <accent>Okamžité</accent>\nplatby QuickPay @@ -1139,6 +1157,7 @@ Faktura zkopírovaná do schránky Lightningová faktura Nepovinná poznámka pro plátce + Naskenujte nebo přiložte a zaplaťte Zobrazit podrobnosti Zobrazit QR kód Upravit fakturu diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 0529225082..b4f0be9ce6 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -472,6 +472,11 @@ Um zu\nbeginnen,\n<accent>sende\nBitcoin</accent>\nan dein\nWallet <accent>Achtung:</accent>\nMehrere Geräte Füge deine Wiederherstellungsphrase nicht mehreren Geräten gleichzeitig hinzu, da es zu unwiderruflichen Schäden deiner Daten kommen kann. + Bluetooth aktivieren + NFC aktivieren + Dieses NFC-Tag enthält keine Zahlungsanforderung, die Bitkit verwenden kann. + NFC kann nicht gelesen werden + Bitkit-Zahlungsanforderung QR-Code scannen QR-Code kann nicht gelesen werden Bitkit kann diesen QR-Code nicht lesen. @@ -490,6 +495,12 @@ <accent>Dein Wallet-Kontostand übersteigt $500.</accent>\nZu deiner Sicherheit solltest du einen Teil deiner Ersparnisse in ein Offline-Wallet verschieben. Verstanden Mehr erfahren + Erlaube Kamera-, Bluetooth- und NFC-Zugriff, um Bitcoin-Rechnungen zu scannen und schneller zu bezahlen. + Scannen\n<accent>zum Bezahlen</accent> + Scanne QR + Scanne QR & Bluetooth + Scanne QR & NFC + Scanne QR, NFC & Bluetooth Bitte versuchen Sie es erneut. Kritisches Update Aktualisiere\n<accent>Bitkit jetzt</accent> @@ -677,6 +688,13 @@ Wallet Bitkit wurde zurückgesetzt und alle Wallet-Daten wurden gelöscht. PIN aktivieren + Lass Telefone in der Nähe deine Empfangen-Anfrage über Bluetooth lesen + Zahlungen in der Nähe + Fantastisch! + Bitkit unterstützt jetzt NFC-Zahlungen. Halte dein Telefon an ein kompatibles Zahlungsterminal oder Telefon, um sofort zu bezahlen. + Nutze QuickPay für kleine Zahlungen + Bezahlen mit\n<accent>nur einem Tippen</accent> + TapPay (NFC) Einstellungen Entwickler-Einstellungen aktiviert Entwickler-Einstellungen sind jetzt in der gesamten App aktiviert. @@ -1019,6 +1037,7 @@ Beleg konnte nicht gesendet werden Beleg wird gesendet Beleg gesendet + Scannen oder antippen zum Bezahlen Senden Empfangen Bitcoin senden diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 4e4484778e..d2b474b901 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -510,6 +510,11 @@ Η ανάληψή σου ζητήθηκε επιτυχώς. Αναμονή πληρωμής. Ζητήθηκε ανάληψη Αποτυχία δημιουργίας αρχείου zip καταγραφής + Ενεργοποίηση Bluetooth + Ενεργοποίηση NFC + Αυτή η ετικέτα δεν περιέχει αίτημα πληρωμής που μπορεί να χρησιμοποιήσει το Bitkit. + Αδυναμία ανάγνωσης NFC + Αίτημα πληρωμής Bitkit Σφάλμα εκκίνησης: %1$s Ρύθμιση πορτοφολιού… Εκτελείται @@ -530,6 +535,12 @@ Αυτό το τιμολόγιο Lightning έχει λήξει. Το Bitkit δεν μπορεί να διαβάσει τα παρεχόμενα δεδομένα. Σφάλμα αποκωδικοποίησης + Επίτρεψε την πρόσβαση στην κάμερα, το Bluetooth και το NFC για να σαρώσεις τιμολόγια bitcoin και να πληρώσεις πιο γρήγορα. + Σάρωσε\n<accent>για πληρωμή</accent> + Σάρωση QR + Σάρωση QR και Bluetooth + Σάρωση QR και NFC + Σάρωση QR, NFC και Bluetooth Κοινοποίηση κωδικού QR μέσω Ταξίδια Χωρίς σύνορα @@ -791,6 +802,13 @@ Γενικά Ρυθμίσεις συστήματος Γλώσσα + Επίτρεψε σε κοντινά τηλέφωνα να διαβάζουν το αίτημα Λήψης σου μέσω Bluetooth + Κοντινές πληρωμές + Τέλεια! + Το Bitkit υποστηρίζει πλέον πληρωμές NFC. Φέρε το τηλέφωνό σου κοντά σε ένα συμβατό τερματικό πληρωμών ή τηλέφωνο για να πληρώσεις άμεσα. + Χρησιμοποίησε το QuickPay για μικρές πληρωμές + Πλήρωσε με\n<accent>ένα μόνο άγγιγμα</accent> + TapPay (NFC) Το Bitkit QuickPay κάνει την ολοκλήρωση αγοράς πιο γρήγορη πληρώνοντας αυτόματα μικρά τιμολόγια. <accent>Απρόσκοπτες</accent>\nπληρωμές QuickPay @@ -1116,6 +1134,7 @@ Το τιμολόγιο αντιγράφηκε στο πρόχειρο Τιμολόγιο Lightning Προαιρετική σημείωση προς τον πληρωτή + Σάρωσε ή άγγιξε για πληρωμή Εμφάνιση λεπτομερειών Εμφάνιση κωδικού QR Επεξεργασία τιμολογίου diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 4cffc2f39f..607936166f 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -516,6 +516,11 @@ Tu retiro se ha solicitado correctamente. Esperando el pago. Retirada solicitada Error al crear el archivo zip de registros + Activar Bluetooth + Activar NFC + Esta etiqueta no contiene una solicitud de pago que Bitkit pueda usar. + Incapaz De Leer NFC + Solicitud de pago de Bitkit Error al iniciar: %1$s Configurando monedero… En ejecución @@ -536,6 +541,12 @@ Esta factura Lightning ha expirado. Bitkit no puede leer los datos proporcionados. Error de descodificación + Permite el acceso a la cámara, Bluetooth y NFC para escanear facturas de bitcoin y pagar más rápidamente. + Escanea\n<accent>para pagar</accent> + Escaneando QR + Escaneando QR y Bluetooth + Escaneando QR y NFC + Escaneando QR, NFC y Bluetooth Compartir código QR vía Viajes Sin fronteras @@ -809,6 +820,13 @@ General Ajustes del sistema Idioma + Permite que los teléfonos cercanos lean tu solicitud de Recibir por Bluetooth + Pagos cercanos + ¡Genial! + Bitkit ahora admite pagos NFC. Acerca tu teléfono a un terminal de pago o a un teléfono compatible para pagar al instante. + Usa QuickPay para pagos pequeños + Paga con\n<accent>un solo toque</accent> + TapPay (NFC) Bitkit QuickPay hace que pagar sea más rápido pagando automáticamente facturas pequeñas. Pagos\n<accent>sin fricción</accent> QuickPay @@ -1136,6 +1154,7 @@ Factura copiada al portapapeles Factura Lightning Nota opcional para el pagador + Escanea o toca para pagar Mostrar detalles Mostrar código QR Editar Factura diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 2f69d5c1d2..2203d9e79a 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -469,6 +469,11 @@ Proceder sin respaldo de la copia de seguridad Si anteriormente tenía una copia de seguridad Lightning, ésta se sobrescribirá y se perderá. Esto podría provocar una pérdida de fondos. Para\nempezar\n<accent>envíe\nBitcoin</accent>\na su\nmonedero + Activar Bluetooth + Activar NFC + Esta etiqueta no contiene una solicitud de pago que Bitkit pueda usar. + Incapaz De Leer NFC + Solicitud de pago de Bitkit Escanear código QR Incapaz De Leer QR Bitkit no es capaz de leer este código QR. @@ -484,6 +489,12 @@ <accent>El saldo de su monedero excede $500.</accent>\nPor su seguridad, considere mover parte de sus ahorros a un monedero no conectado a Internet. Entendido Aprender Más + Permite el acceso a la cámara, Bluetooth y NFC para escanear facturas bitcoin y pagar más rápido. + Escanea\n<accent>para pagar</accent> + Escaneando QR + Escaneando QR y Bluetooth + Escaneando QR y NFC + Escaneando QR, NFC y Bluetooth Por favor, intente de nuevo. Actualización Crítica Actualice\n<accent>Bitkit ahora</accent> @@ -674,6 +685,13 @@ Datos de Monedero Borrados Bitkit ha sido restaurado y todos los datos de monedero han sido borrados. Habilitar PIN + Permite que los teléfonos cercanos lean tu solicitud de Recibir por Bluetooth + Pagos cercanos + ¡Genial! + Bitkit ahora admite pagos NFC. Acerca tu teléfono a un terminal de pago o a un teléfono compatible para pagar al instante. + Usa QuickPay para pagos pequeños + Paga con\n<accent>un solo toque</accent> + TapPay (NFC) Ajustes Opciones de desarrollo activadas Las opciones de desarrollo están ahora desactivadas en toda la aplicación. @@ -1016,6 +1034,7 @@ Error al enviar el recibo Enviando recibo Recibo enviado + Escanea o toca para pagar Enviar Recibir Transferencia Entrante: diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 2a8923048c..8da7516932 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -471,6 +471,11 @@ Pour\ncommencer,\n<accent>envoyez\ndu bitcoin</accent>. <accent>Attention :</accent>\nplusieurs appareils N\'installez pas votre phrase de récupération Bitkit sur plusieurs téléphones simultanément, car cela pourrait corrompre vos données. + Activer le Bluetooth + Activer le NFC + Ce tag NFC ne contient aucune demande de paiement utilisable par Bitkit. + Impossible de lire le NFC + Demande de paiement Bitkit Scannez le QR code  Impossible de lire les QR codes Bitkit n\'est pas en mesure de lire ce QR code. @@ -489,6 +494,12 @@ <accent>Le solde de votre portefeuille dépasse 500 $.</accent>\nPour votre sécurité, envisagez de transférer une partie de votre Épargne vers un portefeuille hors ligne. Compris En savoir plus + Autorisez l\'accès à la caméra, au Bluetooth et au NFC pour scanner les factures bitcoin et payer plus rapidement. + Scanner\n<accent>pour payer</accent> + Scan QR + Scan QR et Bluetooth + Scan QR et NFC + Scan QR, NFC et Bluetooth Veuillez réessayer. Mise à jour critique Mettre à jour\n<accent>Bitkit maintenant</accent> @@ -677,6 +688,13 @@ Données du wallet supprimées Bitkit a été réinitialisé et toutes les données du walet ont été supprimées. Activer le PIN + Autorisez les téléphones à proximité à lire votre demande Recevoir via Bluetooth + Paiements à proximité + Génial ! + Bitkit prend désormais en charge les paiements NFC. Approchez votre téléphone d\'un terminal de paiement ou d\'un téléphone compatible pour payer instantanément. + Utilisez QuickPay pour les petits paiements + Payez en\n<accent>un seul geste</accent> + TapPay (NFC) Paramètres Options de développement activées Les options pour les développeurs sont désormais activées dans l\'ensemble de l\'application. @@ -1020,6 +1038,7 @@ Échec de l\'envoi du reçu Envoi du reçu Reçu envoyé + Scannez ou approchez pour payer Envoyer Recevoir Envoyer des bitcoins diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 88a2ba5341..5752c700fc 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -515,6 +515,11 @@ Il tuo prelievo e\' stato richiesto con successo. In attesa del pagamento. Prelievo Richiesto Creazione file zip log non riuscita + Abilita Bluetooth + Abilita NFC + Questo tag non contiene una richiesta di pagamento utilizzabile da Bitkit. + Impossibile leggere NFC + Richiesta di pagamento Bitkit Errore all\'avvio: %1$s Configurazione wallet... In esecuzione @@ -535,6 +540,12 @@ Questa fattura Lightning e\' scaduta. Bitkit non e\' in grado di leggere i dati forniti. Decodificando l\'Errore + Consenti l\'accesso a fotocamera, Bluetooth e NFC per scansionare fatture bitcoin e pagare più velocemente. + Scansiona\n<accent>per pagare</accent> + Scansione QR + Scansione QR e Bluetooth + Scansione QR e NFC + Scansione QR, NFC e Bluetooth Condividi QR Code tramite Viaggi Senza confini @@ -808,6 +819,13 @@ Generale Impostazioni di sistema Lingua + Consenti ai telefoni vicini di leggere la tua richiesta Ricevi tramite Bluetooth + Pagamenti di prossimità + Fantastico! + Bitkit ora supporta i pagamenti NFC. Avvicina il telefono a un terminale di pagamento o a un telefono compatibile per pagare all\'istante. + Usa QuickPay per i piccoli pagamenti + Paga con\n<accent>un solo tocco</accent> + TapPay (NFC) Bitkit QuickPay rende il checkout più veloce pagando automaticamente le fatture di piccolo importo. <accent>Pagamenti</accent>\nsenza attriti QuickPay @@ -1137,6 +1155,7 @@ Fattura copiata negli appunti Lightning invoice Nota opzionale per chi paga + Scansiona o avvicina per pagare Mostra Dettagli Visualizza QR Code Modifica Fattura diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index ccdab9c374..6db293eb99 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -514,6 +514,11 @@ Je opname is succesvol aangevraagd. Wachten op betaling. Opname aangevraagd Log-zipbestand aanmaken mislukt + Bluetooth inschakelen + NFC inschakelen + Deze tag bevat geen betaalverzoek dat Bitkit kan gebruiken. + Kan NFC niet lezen + Bitkit-betaalverzoek Fout bij starten: %1$s Wallet instellen… Actief @@ -534,6 +539,12 @@ Deze Lightning-factuur is verlopen. Bitkit kan de verstrekte gegevens niet lezen. Decoderingsfout + Sta toegang tot camera, Bluetooth en NFC toe om bitcoin-facturen te scannen en sneller te betalen. + Scan\n<accent>om te betalen</accent> + QR scannen + QR & Bluetooth scannen + QR & NFC scannen + QR, NFC & Bluetooth scannen QR-code delen via Reizen Grenzeloos verbonden @@ -806,6 +817,13 @@ Algemeen Systeeminstellingen Taal + Laat telefoons in de buurt je Ontvangen-verzoek via Bluetooth lezen + Betalingen in de buurt + Geweldig! + Bitkit ondersteunt nu NFC-betalingen. Houd je telefoon bij een compatibele betaalterminal of telefoon om direct te betalen. + Gebruik QuickPay voor kleine betalingen + Betaal met\n<accent>één tik</accent> + TapPay (NFC) Bitkit QuickPay maakt afrekenen sneller door kleine facturen automatisch te betalen. <accent>Wrijvingsloze</accent>\nbetalingen QuickPay @@ -1132,6 +1150,7 @@ Factuur gekopieerd naar klembord Lightning-factuur Optionele notitie voor betaler + Scan of tik om te betalen Details tonen QR-code tonen Factuur bewerken diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 7e7eb0c1d8..2a97cf297e 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -473,6 +473,11 @@ Aby\nrozpocząć\n<accent>wyślij\nBitcoin</accent>\nna swój\nportfel <accent>Uwaga:</accent>\nwiele urządzeń Nie instaluj swojej frazy odzyskiwania Bitkit na kilku telefonach jednocześnie, ponieważ może to uszkodzić Twoje dane. + Włącz Bluetooth + Włącz NFC + Ten tag nie zawiera żądania płatności, którego Bitkit może użyć. + Nie można odczytać NFC + Żądanie płatności Bitkit Skanuj kod QR Nie można odczytać kodu QR Bitkit nie jest w stanie odczytać tego kodu QR. @@ -491,6 +496,12 @@ <accent>Twoje saldo portfela przekracza 500$.</accent>\nDla bezpieczeństwa rozważ przeniesienie części oszczędności do portfela offline. Rozumiem Dowiedz się więcej + Zezwól na dostęp do kamery, Bluetooth i NFC, aby skanować faktury Bitcoin i płacić szybciej. + Skanuj\n<accent>i płać</accent> + Skanowanie QR + Skanowanie QR i Bluetooth + Skanowanie QR i NFC + Skanowanie QR, NFC i Bluetooth Spróbuj ponownie. Aktualizacja krytyczna Aktualizuj\n<accent>Bitkit teraz</accent> @@ -680,6 +691,13 @@ Usunięto dane portfela Bitkit został zresetowany, a wszystkie dane portfela zostały usunięte. Włącz PIN + Pozwól pobliskim telefonom odczytać Twoje żądanie Otrzymaj przez Bluetooth + Płatności w pobliżu + Świetnie! + Bitkit obsługuje teraz płatności NFC. Zbliż telefon do kompatybilnego terminala płatniczego lub telefonu, aby natychmiast zapłacić. + Używaj QuickPay do małych płatności + Płać\n<accent>jednym dotknięciem</accent> + TapPay (NFC) Ustawienia Opcje Dev włączone Opcje deweloperskie są teraz dostępne w całej aplikacji. @@ -1022,6 +1040,7 @@ Nie udało się wysłać potwierdzenia Wysyłanie potwierdzenia Potwierdzenie wysłane + Zeskanuj lub zbliż, aby zapłacić Wyślij Otrzymaj Wyślij Bitcoin diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index e117e7bcea..0f4dc482ce 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -518,6 +518,11 @@ Seu saque foi solicitado com sucesso. Aguardando pagamento. Saque solicitado Falha ao criar arquivo zip de logs + Ativar Bluetooth + Ativar NFC + Esta tag não contém uma solicitação de pagamento que a Bitkit possa usar. + Incapaz de Ler o NFC + Solicitação de pagamento Bitkit Erro ao iniciar: %1$s Configurando carteira… Executando @@ -538,6 +543,12 @@ Este invoice lightning expirou. Bitkit não consegue ler os dados fornecidos. Erro de Decodificação + Permita acesso à câmera, Bluetooth e NFC para escanear invoices bitcoin e pagar mais rapidamente. + Escaneie\n<accent>para pagar</accent> + Escaneando QR + Escaneando QR e Bluetooth + Escaneando QR e NFC + Escaneando QR, NFC e Bluetooth Compartilhar QR Code Via Viagem Sem fronteiras @@ -813,6 +824,13 @@ Geral Configurações do sistema Idioma + Permita que celulares próximos leiam sua solicitação de Receber via Bluetooth + Pagamentos por proximidade + Incrível! + A Bitkit agora suporta pagamentos NFC. Aproxime seu celular de um terminal de pagamento ou celular compatível para pagar instantaneamente. + Use o QuickPay para pagamentos pequenos + Pague com\n<accent>apenas um toque</accent> + TapPay (NFC) O Bitkit QuickPay agiliza o pagamento pagando automaticamente pequenas faturas. Pagamentos\n<accent>Sem atrito</accent> QuickPay @@ -1141,6 +1159,7 @@ Invoice copiado para a área de transferência. Invoice Lightning Comentário opcional para o pagador + Escaneie ou aproxime para pagar Mostrar Detalhes Mostrar código QR Editar Invoice diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 7f33fb21a6..ec05faa2dc 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -466,6 +466,11 @@ Para\ncomeçar\n<accent>receba\nBitcoin</accent>\nna sua\ncarteira <accent>Cuidado:</accent>\nvários dispositivos Não instale sua frase de recuperação do Bitkit em vários telefones simultaneamente, isso pode corromper seus dados. + Ativar Bluetooth + Ativar NFC + Esta etiqueta não contém um pedido de pagamento que a Bitkit possa utilizar. + Incapaz de Ler o NFC + Pedido de pagamento Bitkit Escanear o Código QR Incapaz de Ler o QR A Bitkit não consegue ler este código QR. @@ -484,6 +489,12 @@ <accent>O saldo de sua carteira ultrapassa US$ 500.</accent>\nPara sua segurança, considere transferir parte de suas economias para uma carteira offline. Entendido Saiba Mais + Permita o acesso à câmara, ao Bluetooth e ao NFC para ler invoices de bitcoin e pagar mais rapidamente. + Leia\n<accent>para pagar</accent> + A ler QR + A ler QR e Bluetooth + A ler QR e NFC + A ler QR, NFC e Bluetooth Tente novamente. Atualização Crítica Atualize\n<accent>agora</accent> @@ -658,6 +669,13 @@ Dados da Carteira Deletados O Bitkit foi redefinido e todos os dados da carteira foram excluídos. Ativar PIN + Permita que telemóveis próximos leiam o seu pedido de Receber via Bluetooth + Pagamentos por proximidade + Incrível! + A Bitkit suporta agora pagamentos NFC. Aproxime o seu telemóvel de um terminal de pagamento ou telemóvel compatível para pagar instantaneamente. + Utilize o QuickPay para pagamentos pequenos + Pague com\n<accent>apenas um toque</accent> + TapPay (NFC) Ajustes Modo Desenvolvedor Ativado As opções de desenvolvedor estão agora habilitadas em todo o aplicativo. @@ -886,6 +904,7 @@ Falha ao enviar o recibo A enviar recibo Recibo enviado + Leia ou aproxime para pagar Enviar Receber Enviar Bitcoin diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 4440419aab..099c30f1c0 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -528,6 +528,11 @@ Ваш запрос на вывод успешно отправлен. Ожидание платежа. Запрос на Вывод Не удалось создать zip-файл логов + Включить Bluetooth + Включить NFC + Эта метка не содержит запрос на оплату, который может использовать Bitkit. + Не удалось прочитать NFC + Запрос на оплату Bitkit Ошибка запуска: %1$s Настройка кошелька… Работает @@ -548,6 +553,12 @@ Этот Lightning-счёт истёк. Bitkit не может прочитать предоставленные данные. Ошибка Декодирования + Разрешите доступ к камере, Bluetooth и NFC для сканирования биткоин-счетов и более быстрой оплаты. + Сканируйте\n<accent>для оплаты</accent> + Сканирование QR + Сканирование QR и Bluetooth + Сканирование QR и NFC + Сканирование QR, NFC и Bluetooth Поделиться QR-кодом через Путешествия Без границ @@ -824,6 +835,13 @@ Основные Системные настройки Язык + Разрешите телефонам поблизости считывать ваш запрос на получение через Bluetooth + Платежи поблизости + Отлично! + Bitkit теперь поддерживает NFC-платежи. Поднесите телефон к совместимому платёжному терминалу или телефону, чтобы оплатить мгновенно. + Используйте QuickPay для небольших платежей + Оплата\n<accent>одним касанием</accent> + TapPay (NFC) Bitkit QuickPay ускоряет оплату, автоматически оплачивая небольшие счета. <accent>Платежи</accent> без трения @@ -1154,6 +1172,7 @@ Инвойс скопирован в буфер обмена Лайтнинг инвойс Опциональная заметка для плательщика + Сканируйте или приложите для оплаты Показать детали Показать QR-код Редактировать Инвойс diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index aaf1b64921..30fe9d6075 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -640,6 +640,7 @@ Bitkit\n<accent>terms of use</accent> Use Bitkit to pay anyone, anywhere, any time, and spend your bitcoin on the things you value in life. You can ₿ \n<accent>the change</accent> + Enable Bluetooth Choose Exchange Buy some\n<accent>Bitcoin</accent> Don’t have any Bitcoin or need more? @@ -687,6 +688,10 @@ Your withdraw was successfully requested. Waiting for payment. Withdraw Requested Failed to create log zip file + Enable NFC + This tag does not hold a payment request Bitkit can use. + Unable To Read NFC + Bitkit payment request Error starting: %1$s Setting up wallet… Running @@ -709,6 +714,12 @@ This Lightning invoice has expired. Bitkit is unable to read the provided data. Decoding Error + Allow Camera, Bluetooth, and NFC access to scan bitcoin invoices and pay more quickly. + Scan\n<accent>to pay</accent> + Scanning QR + Scanning QR & Bluetooth + Scanning QR & NFC + Scanning QR, NFC & Bluetooth Share QR Code Via Apparel Automobiles @@ -1130,6 +1141,13 @@ Rename Hardware Wallet System Settings Language + Let nearby phones read your Receive request over Bluetooth + Nearby payments + Awesome! + Bitkit now supports NFC payments. Hold your phone near a compatible payment terminal or phone to pay instantly. + Use QuickPay for small payments + Pay with\n<accent>just one tap</accent> + TapPay (NFC) Bitkit QuickPay makes checking out faster by automatically paying small invoices. <accent>Frictionless</accent>\npayments QuickPay @@ -1688,6 +1706,7 @@ Invoice copied to clipboard Lightning invoice Optional note to payer + Scan or tap to pay Show Details QR Code Edit Invoice diff --git a/app/src/main/res/xml/ndef_tag_service.xml b/app/src/main/res/xml/ndef_tag_service.xml new file mode 100644 index 0000000000..1797e01b1a --- /dev/null +++ b/app/src/main/res/xml/ndef_tag_service.xml @@ -0,0 +1,6 @@ + + + + diff --git a/app/src/test/java/to/bitkit/nearby/NearbyAdvertiserTest.kt b/app/src/test/java/to/bitkit/nearby/NearbyAdvertiserTest.kt new file mode 100644 index 0000000000..087afb34fd --- /dev/null +++ b/app/src/test/java/to/bitkit/nearby/NearbyAdvertiserTest.kt @@ -0,0 +1,90 @@ +package to.bitkit.nearby + +import android.bluetooth.BluetoothAdapter +import android.bluetooth.BluetoothGatt +import android.bluetooth.BluetoothGattServer +import android.bluetooth.BluetoothGattServerCallback +import android.bluetooth.BluetoothManager +import android.bluetooth.le.BluetoothLeAdvertiser +import android.content.Context +import android.os.Looper +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import kotlin.test.assertEquals + +@Config(sdk = [34]) +@RunWith(RobolectricTestRunner::class) +class NearbyAdvertiserTest { + private val advertiser = mock() + private val adapter = mock { on { bluetoothLeAdvertiser }.thenReturn(advertiser) } + private val server = mock() + private val manager = mock { on { adapter }.thenReturn(adapter) } + private val context = mock { on { getSystemService(Context.BLUETOOTH_SERVICE) }.thenReturn(manager) } + private var failures = 0 + private lateinit var sut: NearbyAdvertiser + + @Before + fun setUp() { + whenever(manager.openGattServer(any(), any())).thenReturn(server) + whenever(server.addService(any())).thenReturn(true) + sut = NearbyAdvertiser(context) { failures++ } + } + + private fun serverCallback(): BluetoothGattServerCallback { + val captor = argumentCaptor() + verify(manager).openGattServer(any(), captor.capture()) + return captor.lastValue + } + + private fun reportServiceAdded(status: Int) { + serverCallback().onServiceAdded(status, null) + shadowOf(Looper.getMainLooper()).idle() + } + + @Test + fun `advertises only after the service is registered`() { + sut.start(URI) + verify(advertiser, never()).startAdvertising(any(), any(), any()) + + reportServiceAdded(BluetoothGatt.GATT_SUCCESS) + + verify(advertiser).startAdvertising(any(), any(), any()) + assertEquals(0, failures) + } + + @Test + fun `does not advertise when the service is refused`() { + whenever(server.addService(any())).thenReturn(false) + + sut.start(URI) + + verify(advertiser, never()).startAdvertising(any(), any(), any()) + verify(server).close() + assertEquals(1, failures) + } + + @Test + fun `does not advertise when the service registration fails`() { + sut.start(URI) + + reportServiceAdded(BluetoothGatt.GATT_FAILURE) + + verify(advertiser, never()).startAdvertising(any(), any(), any()) + verify(server).close() + assertEquals(1, failures) + } + + private companion object { + const val URI = "bitcoin:bcrt1qs04g2ka4pr9s3mv73nu32tvfy7r3cxd27wkyu8" + } +} diff --git a/app/src/test/java/to/bitkit/nearby/NearbyProtocolTest.kt b/app/src/test/java/to/bitkit/nearby/NearbyProtocolTest.kt new file mode 100644 index 0000000000..b2981746d8 --- /dev/null +++ b/app/src/test/java/to/bitkit/nearby/NearbyProtocolTest.kt @@ -0,0 +1,71 @@ +package to.bitkit.nearby + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.util.UUID + +class NearbyProtocolTest { + @Test + fun `uses the documented UUIDs`() { + assertEquals(UUID.fromString("CB0E128B-1CA5-4959-94DF-A4FE588E3E98"), NearbyProtocol.SERVICE_UUID) + assertEquals(UUID.fromString("69A713E5-B0A7-42F1-8B7F-FA0BDA119C00"), NearbyProtocol.META_UUID) + assertEquals(UUID.fromString("69A713E5-B0A7-42F1-8B7F-FA0BDA119C01"), NearbyProtocol.DATA_UUIDS.first()) + assertEquals(UUID.fromString("69A713E5-B0A7-42F1-8B7F-FA0BDA119C08"), NearbyProtocol.DATA_UUIDS.last()) + assertEquals(8, NearbyProtocol.DATA_UUIDS.size) + } + + @Test + fun `meta holds the version and big-endian length`() { + val request = ByteArray(0x0234) + + assertArrayEquals(byteArrayOf(0x01, 0x02, 0x34), NearbyProtocol.meta(request)) + assertEquals(0x0234, NearbyProtocol.requestLength(NearbyProtocol.meta(request))) + } + + @Test + fun `rejects unknown versions and bad lengths`() { + assertNull(NearbyProtocol.requestLength(byteArrayOf(0x02, 0x00, 0x10))) + assertNull(NearbyProtocol.requestLength(byteArrayOf(0x01, 0x00, 0x00))) + assertNull(NearbyProtocol.requestLength(byteArrayOf(0x01, 0x10, 0x01))) + assertNull(NearbyProtocol.requestLength(byteArrayOf(0x01))) + } + + @Test + fun `splits and reassembles a request across chunks`() { + val request = "bitcoin:bc1qtest?amount=0.001&lightning=" + "lnbc".repeat(200) + val bytes = requireNotNull(NearbyProtocol.encodeRequest(request)) + val length = requireNotNull(NearbyProtocol.requestLength(NearbyProtocol.meta(bytes))) + val chunkCount = NearbyProtocol.chunksFor(length) + + val chunks = (0 until chunkCount).map { NearbyProtocol.chunk(bytes, it) } + + assertEquals(2, chunkCount) + assertEquals(512, chunks[0].size) + assertEquals(request, NearbyProtocol.decode(chunks, length)) + assertTrue(NearbyProtocol.chunk(bytes, 2).isEmpty()) + assertTrue(NearbyProtocol.chunk(bytes, 8).isEmpty()) + } + + @Test + fun `refuses empty and oversized requests`() { + assertNull(NearbyProtocol.encodeRequest("")) + assertNull(NearbyProtocol.encodeRequest("x".repeat(NearbyProtocol.MAX_REQUEST_BYTES + 1))) + } + + @Test + fun `serves reads from an offset`() { + val value = byteArrayOf(1, 2, 3, 4) + + assertArrayEquals(byteArrayOf(3, 4), NearbyProtocol.readAt(value, 2)) + assertArrayEquals(byteArrayOf(), NearbyProtocol.readAt(value, 4)) + assertNull(NearbyProtocol.readAt(value, 5)) + } + + @Test + fun `decode fails when chunks do not match the length`() { + assertNull(NearbyProtocol.decode(listOf("abc".toByteArray()), 4)) + } +} diff --git a/app/src/test/java/to/bitkit/nearby/NearbyRequestFilterTest.kt b/app/src/test/java/to/bitkit/nearby/NearbyRequestFilterTest.kt new file mode 100644 index 0000000000..11dc52e6b6 --- /dev/null +++ b/app/src/test/java/to/bitkit/nearby/NearbyRequestFilterTest.kt @@ -0,0 +1,141 @@ +package to.bitkit.nearby + +import com.synonym.bitkitcore.AddressType +import com.synonym.bitkitcore.NetworkType +import com.synonym.bitkitcore.ValidationResult +import com.synonym.bitkitcore.validateBitcoinAddress +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.mockito.MockedStatic +import org.mockito.Mockito.mockStatic +import to.bitkit.nfc.PosNfcFixtures + +class NearbyRequestFilterTest { + private val invoice = PosNfcFixtures.SQUARE_INVOICE + private val address = "bcrt1q60d6qvf8lufpxpw6pvdnzsplxx4edspe04nyqz" + private val mainnetAddress = "bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq" + private val corruptedAddress = address.dropLast(1) + if (address.last() == 'q') 'p' else 'q' + private lateinit var native: MockedStatic<*> + + /** The filter validates addresses with bitkit-core, whose native library the unit tests stub. */ + @Before + fun setUp() { + native = mockStatic(Class.forName("com.synonym.bitkitcore.Bitkitcore_androidKt")) + for (valid in listOf(address, mainnetAddress)) { + val network = if (valid == mainnetAddress) NetworkType.BITCOIN else NetworkType.REGTEST + native.`when` { validateBitcoinAddress(valid) } + .thenReturn(ValidationResult(valid, network, AddressType.UNKNOWN)) + } + // Like bitkit-core, which reads a bech32 network prefix in lowercase only. + val uppercase = listOf(address.uppercase(), mainnetAddress.uppercase()) + for (invalid in listOf("bcrt1qtest", corruptedAddress, "not-an-address") + uppercase) { + native.`when` { validateBitcoinAddress(invalid) } + .thenThrow(IllegalArgumentException("Invalid address")) + } + } + + @After + fun tearDown() = native.close() + + @Test + fun `accepts the payment requests Bitkit serves`() { + assertTrue(isNearbyPaymentRequest("bitcoin:$address?amount=0.001&lightning=$invoice")) + assertTrue(isNearbyPaymentRequest("BITCOIN:${address.uppercase()}")) + assertTrue(isNearbyPaymentRequest("lightning:$invoice")) + assertTrue(isNearbyPaymentRequest("lightning:${invoice.uppercase()}")) + assertTrue(isNearbyPaymentRequest(" ethereum:0xabc@42161/transfer?address=0xdef ")) + assertTrue(isNearbyPaymentRequest(PosNfcFixtures.SQUARE_URI)) + } + + @Test + fun `refuses everything else the scanner understands`() { + assertFalse(isNearbyPaymentRequest("pubkyauth:///?caps=/pub/:rw&secret=x&relay=https://r")) + assertFalse(isNearbyPaymentRequest("lightning:LNURL1DP68GURN8GHJ7")) + assertFalse(isNearbyPaymentRequest("lnurlw://example.com/withdraw")) + assertFalse(isNearbyPaymentRequest("keyauth://example.com")) + assertFalse(isNearbyPaymentRequest("https://btcpay.example.com/samrock")) + assertFalse(isNearbyPaymentRequest("pk:8pinxxgqs41n4aididenw5apqp1urfmzdztr8jt4abrkdn435ewo")) + assertFalse(isNearbyPaymentRequest("lnbc10u1p")) + assertFalse(isNearbyPaymentRequest("")) + } + + @Test + fun `refuses a non-payment request wrapped in a bitcoin uri`() { + assertNull(nearbyPaymentRequest("bitcoin:?lightning=LNURL1DP68GURN8GHJ7")) + assertNull(nearbyPaymentRequest("BITCOIN:?LIGHTNING=lnurl1dp68gurn8ghj7")) + } + + @Test + fun `refuses a unified uri whose lightning request would be fetched`() { + assertFalse(isNearbyPaymentRequest("bitcoin:$address?lightning=LNURL1DP68GURN8GHJ7")) + assertFalse(isNearbyPaymentRequest("bitcoin:$address?amount=0.001&lightning=lnurl1dp68gurn8ghj7")) + assertTrue(isNearbyPaymentRequest("bitcoin:$address?amount=0.001&lightning=$invoice")) + } + + @Test + fun `refuses a lightning address that starts like an invoice`() { + assertFalse(isNearbyPaymentRequest("lightning:lnsb@example.com")) + assertFalse(isNearbyPaymentRequest("lightning:lnbc1@example.com")) + assertFalse(isNearbyPaymentRequest("bitcoin:$address?lightning=lnsb@example.com")) + assertNull(nearbyPaymentRequest("bitcoin:?lightning=lnsb@example.com")) + } + + @Test + fun `refuses a request with a required parameter`() { + assertFalse(isNearbyPaymentRequest("bitcoin:$address?amount=0.001&req-pop=callback%3a")) + assertFalse(isNearbyPaymentRequest("BITCOIN:${address.uppercase()}?REQ-FOO=bar")) + assertFalse(isNearbyPaymentRequest("bitcoin:$address?lightning=$invoice&req-x")) + assertTrue(isNearbyPaymentRequest("bitcoin:$address?amount=0.001&pop=callback%3a")) + } + + @Test + fun `checks every lightning value of a unified uri`() { + assertFalse(isNearbyPaymentRequest("bitcoin:$address?lightning=$invoice&lightning=LNURL1DP68GURN8GHJ7")) + assertFalse(isNearbyPaymentRequest("bitcoin:$address?lightning=LNURL1DP68GURN8GHJ7&LIGHTNING=$invoice")) + } + + @Test + fun `refuses what the scanner cannot pay`() { + assertFalse(isNearbyPaymentRequest("lightning:lno1qgsq")) + assertNull(nearbyPaymentRequest("bitcoin:?lno=lno1qgsq")) + assertNull(nearbyPaymentRequest("BITCOIN:?amount=0.001")) + } + + @Test + fun `refuses an invoice whose checksum fails`() { + val corrupted = invoice.dropLast(1) + if (invoice.last() == 'q') 'p' else 'q' + assertFalse(isNearbyPaymentRequest("lightning:$corrupted")) + assertFalse(isNearbyPaymentRequest("lightning:lnbc10u1p")) + assertFalse(isNearbyPaymentRequest("lightning:lnbc1" + "q".repeat(60))) + assertFalse(isNearbyPaymentRequest("bitcoin:$address?lightning=$corrupted")) + } + + @Test + fun `refuses a bitcoin uri without an address`() { + assertFalse(isNearbyPaymentRequest("bitcoin:")) + assertFalse(isNearbyPaymentRequest(" BITCOIN: ")) + assertFalse(isNearbyPaymentRequest("bitcoin:not-an-address")) + // An address that only looks right is refused too: the decoder would reject it after Send resets. + assertFalse(isNearbyPaymentRequest("bitcoin:bcrt1qtest")) + assertFalse(isNearbyPaymentRequest("bitcoin:$corruptedAddress?amount=0.001")) + assertNull(nearbyPaymentRequest("bitcoin:")) + } + + @Test + fun `refuses an address for another network`() { + // Tests run the dev build, a regtest wallet. + assertFalse(isNearbyPaymentRequest("bitcoin:$mainnetAddress")) + assertFalse(isNearbyPaymentRequest("BITCOIN:${mainnetAddress.uppercase()}?amount=0.001")) + } + + @Test + fun `hands over the rewritten payment request`() { + assertEquals("lightning:$invoice", nearbyPaymentRequest(PosNfcFixtures.BIP321_URI)) + assertEquals("bitcoin:$address", nearbyPaymentRequest(" bitcoin:$address ")) + } +} diff --git a/app/src/test/java/to/bitkit/nfc/NdefCodecTest.kt b/app/src/test/java/to/bitkit/nfc/NdefCodecTest.kt new file mode 100644 index 0000000000..9d7fd135e5 --- /dev/null +++ b/app/src/test/java/to/bitkit/nfc/NdefCodecTest.kt @@ -0,0 +1,115 @@ +package to.bitkit.nfc + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class NdefCodecTest { + @Test + fun `encodes a short URI record without a prefix code`() { + val message = NdefCodec.encodeUriMessage("lightning:lnbc1") + + val payload = byteArrayOf(0x00) + "lightning:lnbc1".toByteArray() + val expected = byteArrayOf(0xD1.toByte(), 0x01, payload.size.toByte(), 'U'.code.toByte()) + payload + assertArrayEquals(expected, message) + } + + @Test + fun `encodes a long URI record with a 4-byte length`() { + val uri = "bitcoin:bc1q?lightning=" + "x".repeat(400) + + val message = NdefCodec.encodeUriMessage(uri) + + assertEquals(0xC1.toByte(), message[0]) + assertEquals(listOf(uri), NdefCodec.decodeTexts(message)) + } + + @Test + fun `decodes the long URI record a Square Register serves`() { + val message = PosNfcFixtures.squareMessage() + + assertEquals(465, message.size) + assertArrayEquals( + PosNfcFixtures.hex(PosNfcFixtures.SQUARE_MESSAGE_START_HEX), + message.copyOf(18), + ) + assertEquals(listOf(PosNfcFixtures.SQUARE_URI), NdefCodec.decodeTexts(message)) + assertEquals(PosNfcFixtures.SQUARE_URI, NdefCodec.payableText(NdefCodec.decodeTexts(message))) + } + + @Test + fun `encodes a Square-sized request exactly as Square does`() { + assertArrayEquals(PosNfcFixtures.squareMessage(), NdefCodec.encodeUriMessage(PosNfcFixtures.SQUARE_URI)) + } + + @Test + fun `decodes the BIP 321 request Numo serves`() { + val message = PosNfcFixtures.squareMessage(PosNfcFixtures.BIP321_URI) + + assertEquals(listOf(PosNfcFixtures.BIP321_URI), NdefCodec.decodeTexts(message)) + } + + @Test + fun `round trips a URI record`() { + val uri = "bitcoin:BC1QTEST?amount=0.001&lightning=LNBC10U1P" + + assertEquals(listOf(uri), NdefCodec.decodeTexts(NdefCodec.encodeUriMessage(uri))) + } + + @Test + fun `expands URI prefix codes`() { + val payload = byteArrayOf(0x04) + "example.com/lnurlp/alice".toByteArray() + val message = byteArrayOf(0xD1.toByte(), 0x01, payload.size.toByte(), 'U'.code.toByte()) + payload + + assertEquals(listOf("https://example.com/lnurlp/alice"), NdefCodec.decodeTexts(message)) + } + + @Test + fun `decodes a UTF-8 text record`() { + val text = "bitcoin:?lightning=lnbc1&creq=creqA1" + val payload = byteArrayOf(0x02, 'e'.code.toByte(), 'n'.code.toByte()) + text.toByteArray() + val message = byteArrayOf(0xD1.toByte(), 0x01, payload.size.toByte(), 'T'.code.toByte()) + payload + + assertEquals(listOf(text), NdefCodec.decodeTexts(message)) + } + + @Test + fun `decodes a UTF-16 text record`() { + val text = "lnbc1" + val header = byteArrayOf(0x82.toByte(), 'e'.code.toByte(), 'n'.code.toByte()) + val payload = header + text.toByteArray(Charsets.UTF_16) + val message = byteArrayOf(0xD1.toByte(), 0x01, payload.size.toByte(), 'T'.code.toByte()) + payload + + assertEquals(listOf(text), NdefCodec.decodeTexts(message)) + } + + @Test + fun `decodes every record and skips unknown types`() { + val uri = NdefCodec.encodeUriMessage("lightning:lnbc1") + val mime = byteArrayOf(0x52, 0x0A, 0x01) + "text/plain".toByteArray() + byteArrayOf(0x41) + val firstRecord = byteArrayOf((uri[0].toInt() and 0xBF).toByte()) + uri.copyOfRange(1, uri.size) + + assertEquals(listOf("lightning:lnbc1"), NdefCodec.decodeTexts(firstRecord + mime)) + } + + @Test + fun `returns nothing for a truncated message`() { + val message = NdefCodec.encodeUriMessage("lightning:lnbc1") + + assertTrue(NdefCodec.decodeTexts(message.copyOf(message.size - 3)).isEmpty()) + } + + @Test + fun `payable text is the single distinct request`() { + assertEquals("lightning:lnbc1", NdefCodec.payableText(listOf(" lightning:lnbc1 ", "lightning:lnbc1", ""))) + } + + @Test + fun `payable text is null for no or conflicting requests`() { + assertNull(NdefCodec.payableText(emptyList())) + assertNull(NdefCodec.payableText(listOf(" "))) + assertNull(NdefCodec.payableText(listOf("lightning:lnbc1", "lightning:lnbc2"))) + } +} diff --git a/app/src/test/java/to/bitkit/nfc/NfcPaymentUriTest.kt b/app/src/test/java/to/bitkit/nfc/NfcPaymentUriTest.kt new file mode 100644 index 0000000000..fe1d984bfc --- /dev/null +++ b/app/src/test/java/to/bitkit/nfc/NfcPaymentUriTest.kt @@ -0,0 +1,166 @@ +package to.bitkit.nfc + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class NfcPaymentUriTest { + @Test + fun `keeps requests that already have a payment scheme`() { + assertEquals("bitcoin:bc1q?lightning=lnbc1", nfcPaymentUri("bitcoin:bc1q?lightning=lnbc1")) + assertEquals("BITCOIN:BC1Q", nfcPaymentUri("BITCOIN:BC1Q")) + assertEquals("lightning:lnbc1", nfcPaymentUri("lightning:lnbc1")) + assertEquals("ethereum:0xabc@42161/transfer", nfcPaymentUri("ethereum:0xabc@42161/transfer")) + assertEquals("LIGHTNING:LNTBS1P", nfcPaymentUri("LIGHTNING:LNTBS1P")) + } + + @Test + fun `adds lightning to bare lightning requests`() { + assertEquals("lightning:lnbc10u1p", nfcPaymentUri("lnbc10u1p")) + assertEquals("lightning:lnbcrt1p", nfcPaymentUri(" lnbcrt1p ")) + assertEquals("lightning:LNURL1DP68", nfcPaymentUri("LNURL1DP68")) + } + + @Test + fun `adds bitcoin to bare addresses`() { + assertEquals("bitcoin:bc1qxyz", nfcPaymentUri("bc1qxyz")) + } + + @Test + fun `returns null for no request`() { + assertNull(nfcPaymentUri(null)) + assertNull(nfcPaymentUri(" ")) + } + + @Test + fun `keeps a Square request for the scanner`() { + assertEquals(PosNfcFixtures.SQUARE_URI, scannedPaymentRequest(PosNfcFixtures.SQUARE_URI)) + assertEquals("LIGHTNING:LNTBS1P", scannedPaymentRequest(" LIGHTNING:LNTBS1P\n")) + } + + @Test + fun `turns a BIP 321 request without an address into its Lightning request`() { + val invoice = PosNfcFixtures.SQUARE_INVOICE + + assertEquals("lightning:$invoice", scannedPaymentRequest(PosNfcFixtures.BIP321_URI)) + assertEquals("lightning:$invoice", scannedPaymentRequest("BITCOIN:?LIGHTNING=$invoice")) + assertEquals("lightning:$invoice", scannedPaymentRequest("bitcoin:?amount=0.0000799&lightning=$invoice&creq=x")) + } + + @Test + fun `keeps other bitcoin requests unchanged`() { + val unified = "bitcoin:bc1qtest?lightning=lnbc1" + + assertEquals(unified, scannedPaymentRequest(unified)) + assertEquals("bitcoin:?amount=0.001", scannedPaymentRequest("bitcoin:?amount=0.001")) + assertEquals("bitcoin:?lightning=", scannedPaymentRequest("bitcoin:?lightning=")) + assertEquals("bitcoin:?lno=lno1qgsq", scannedPaymentRequest("bitcoin:?lno=lno1qgsq")) + } + + @Test + fun `request repeating a parameter is kept`() { + val invoice = PosNfcFixtures.SQUARE_INVOICE + for (repeated in listOf( + "bitcoin:?lightning=$invoice&amount=0.01&AMOUNT=0.02", + "bitcoin:?lightning=$invoice&lightning=lnbc1other", + "bitcoin:?lightning=$invoice&label=a&label=b", + "bitcoin:?lightning=$invoice&message=a&message=b", + "bitcoin:?lightning=$invoice&amount=0.0000799&amount=0.0000799", + "bitcoin:?lightning=$invoice&pop=a%3a&POP=b%3a", + )) { + assertEquals(repeated, scannedPaymentRequest(repeated)) + } + } + + @Test + fun `request repeating an optional extension is unwrapped`() { + val invoice = PosNfcFixtures.SQUARE_INVOICE + assertEquals( + "lightning:$invoice", + scannedPaymentRequest("bitcoin:?lightning=$invoice&x-shop=a&X-SHOP=b&creq=c&creq=d&lno=lno1a&lno=lno1b"), + ) + } + + @Test + fun `request whose amount the invoice does not carry is kept`() { + val invoice = PosNfcFixtures.SQUARE_INVOICE + assertEquals("lightning:$invoice", scannedPaymentRequest("bitcoin:?amount=0.0000799&lightning=$invoice")) + assertEquals("lightning:$invoice", scannedPaymentRequest("bitcoin:?amount=0.00007990&lightning=$invoice")) + for (kept in listOf( + "bitcoin:?amount=0.0001&lightning=$invoice", + "bitcoin:?amount=0.0001&lightning=lnbcrt1pamountless", + "bitcoin:?amount=abc&lightning=$invoice", + "bitcoin:?amount=0.0000799,50&lightning=$invoice", + "bitcoin:?amount=0.0000799BTC&lightning=$invoice", + "bitcoin:?amount=7.99E-5&lightning=$invoice", + "bitcoin:?amount=+0.0000799&lightning=$invoice", + )) { + assertEquals(kept, scannedPaymentRequest(kept)) + } + } + + @Test + fun `nfc read with a required parameter is refused`() { + assertNull(nfcPaymentRequest("bitcoin:bcrt1qtest?amount=0.001&req-pop=callback%3a")) + assertNull(nfcPaymentRequest("BITCOIN:BCRT1QTEST?REQ-FOO=bar")) + // The scanner strips `lightning:` before decoding, so a wrapped Bitcoin request is checked as one. + assertNull(nfcPaymentRequest("lightning:bitcoin:bcrt1qtest?amount=0.001&req-pop=callback%3a")) + val wrappedInvoice = "LIGHTNING:bitcoin:?lightning=${PosNfcFixtures.SQUARE_INVOICE}&req-pop=callback%3a" + assertNull(nfcPaymentRequest(wrappedInvoice)) + val required = "bitcoin:bcrt1qtest?amount=0.001&req-pop=callback" + for (wrapper in listOf("bitkit://", "bitkit://lightning:", "lightning:lightning:", "lnurl:lightning:")) { + assertNull(nfcPaymentRequest("$wrapper$required")) + } + val wrappedPlain = "bitkit://bitcoin:bcrt1qtest?amount=0.001" + assertEquals(wrappedPlain, nfcPaymentRequest(wrappedPlain)) + val lnurlPay = "https://pay.example.com/lnurlp?req-x=1&lightning=LNURL1DP68GURN8GHJ7" + assertEquals(lnurlPay, nfcPaymentRequest(lnurlPay)) + assertEquals("bitcoin:bcrt1qtest?amount=0.001", nfcPaymentRequest(" bitcoin:bcrt1qtest?amount=0.001 ")) + val invoice = PosNfcFixtures.SQUARE_INVOICE + assertEquals("lightning:$invoice", nfcPaymentRequest("bitcoin:?lightning=$invoice")) + } + + @Test + fun `nfc read with a required parameter behind an inner bitkit scheme is refused`() { + // The decoder deletes every `bitkit://` in a deep link, which can turn a key into `req-`. + val address = "bitkit://bitcoin:bcrt1qtest?amount=0.001" + assertNull(nfcPaymentRequest("$address&bitkit://req-pop=callback")) + assertNull(nfcPaymentRequest("$address&rebitkit://q-pop=callback")) + // The decoder deletes only lowercase `bitkit://`, so a mixed-case one stays part of an optional key. + val mixedCase = "bitkit://bitkit://bitcoin:bcrt1qtest?REBITKIT://Q-POP=callback" + assertEquals(mixedCase, nfcPaymentRequest(mixedCase)) + val optional = "bitkit://bitcoin:bcrt1qtest?amount=0.001&reBitkit://q-x=1" + assertEquals(optional, nfcPaymentRequest(optional)) + // The decoder deletes them again while the text starts with `bitkit://`, so a nested one is removed too. + val required = "bitcoin:bcrt1qtest?amount=0.001&req-pop=x" + assertNull(nfcPaymentRequest("bitkit://bitbitkit://kit://$required")) + assertNull(nfcPaymentRequest("bitkit://lightning:bitbitkit://kit://$required")) + // Once the text starts with `bitcoin:` the decoder deletes nothing more, so this key is not `req-`. + val payable = "bitcoin:bcrt1qtest?amount=0.001&bitbitkit://kit://req-pop=x" + assertEquals(payable, nfcPaymentRequest(payable)) + assertEquals("bitkit://$payable", nfcPaymentRequest("bitkit://$payable")) + // The decoder's trim also removes U+0085 (NEL), which Kotlin's `trim()` keeps. + assertNull(nfcPaymentRequest("\u0085$required")) + assertNull(nfcPaymentRequest("bitkit://\u0085$required")) + } + + @Test + fun `request with an empty amount is kept`() { + val invoice = PosNfcFixtures.SQUARE_INVOICE + for (empty in listOf("bitcoin:?amount=&lightning=$invoice", "bitcoin:?lightning=$invoice&amount")) { + assertEquals(empty, scannedPaymentRequest(empty)) + } + } + + @Test + fun `request with a required parameter is kept`() { + val invoice = PosNfcFixtures.SQUARE_INVOICE + val required = "bitcoin:?lightning=$invoice&req-pop=callback%3a" + assertEquals(required, scannedPaymentRequest(required)) + val uppercase = "BITCOIN:?REQ-FOO=bar&LIGHTNING=$invoice" + assertEquals(uppercase, scannedPaymentRequest(uppercase)) + for (empty in listOf("bitcoin:?lightning=$invoice&req-foo=", "bitcoin:?lightning=$invoice&req-foo")) { + assertEquals(empty, scannedPaymentRequest(empty)) + } + } +} diff --git a/app/src/test/java/to/bitkit/nfc/NfcReadDispatcherTest.kt b/app/src/test/java/to/bitkit/nfc/NfcReadDispatcherTest.kt new file mode 100644 index 0000000000..2062577e14 --- /dev/null +++ b/app/src/test/java/to/bitkit/nfc/NfcReadDispatcherTest.kt @@ -0,0 +1,77 @@ +package to.bitkit.nfc + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class NfcReadDispatcherTest { + private val reads = mutableListOf() + private var unreadable = 0 + private var time = 0L + private val sut = NfcReadDispatcher(onRead = { reads += it }, onUnreadable = { unreadable++ }, now = { time }) + + @Test + fun `delivers a read and reports an unreadable tag`() { + val activation = sut.open() + sut.deliver("lightning:lnbcrt1", activation) + sut.deliver(null, activation) + + assertEquals(listOf("lightning:lnbcrt1"), reads) + assertEquals(1, unreadable) + } + + @Test + fun `drops a repeat of the same request within the window`() { + val activation = sut.open() + sut.deliver("lightning:lnbcrt1", activation) + time += 1_000 + sut.deliver("lightning:lnbcrt1", activation) + sut.deliver("lightning:lnbcrt2", activation) + time += NfcReadDispatcher.DUPLICATE_READ_WINDOW.inWholeMilliseconds + sut.deliver("lightning:lnbcrt2", activation) + + assertEquals(listOf("lightning:lnbcrt1", "lightning:lnbcrt2", "lightning:lnbcrt2"), reads) + } + + @Test + fun `drops a read from a reader that paused or closed`() { + val activation = sut.open() + sut.close() + sut.deliver("lightning:lnbcrt1", activation) + sut.deliver(null, activation) + + assertEquals(emptyList(), reads) + assertEquals(0, unreadable) + } + + @Test + fun `drops a read from an earlier activation after the reader resumed`() { + val paused = sut.open() + sut.close() + val resumed = sut.open() + sut.deliver("lightning:lnbcrt1", paused) + sut.deliver("lightning:lnbcrt2", resumed) + + assertEquals(listOf("lightning:lnbcrt2"), reads) + } + + @Test + fun `drops a read before the reader opens`() { + sut.deliver("lightning:lnbcrt1", 0) + + assertEquals(emptyList(), reads) + } + + @Test + fun `only the open activation is current`() { + assertFalse(sut.isCurrent(0)) + val first = sut.open() + assertTrue(sut.isCurrent(first)) + sut.close() + assertFalse(sut.isCurrent(first)) + val second = sut.open() + assertFalse(sut.isCurrent(first)) + assertTrue(sut.isCurrent(second)) + } +} diff --git a/app/src/test/java/to/bitkit/nfc/NfcTagEmitterTest.kt b/app/src/test/java/to/bitkit/nfc/NfcTagEmitterTest.kt new file mode 100644 index 0000000000..42024e7755 --- /dev/null +++ b/app/src/test/java/to/bitkit/nfc/NfcTagEmitterTest.kt @@ -0,0 +1,35 @@ +package to.bitkit.nfc + +import org.junit.After +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class NfcTagEmitterTest { + private val tokens = mutableListOf() + + @After + fun tearDown() { + tokens.forEach { NfcTagEmitter.clear(it) } + } + + @Test + fun `serves the published request until its owner clears it`() { + val token = NfcTagEmitter.publish("lightning:lnbc1").also(tokens::add) + + assertArrayEquals(NdefCodec.encodeUriMessage("lightning:lnbc1"), NfcTagEmitter.currentMessage()) + assertTrue(NfcTagEmitter.clear(token)) + assertNull(NfcTagEmitter.currentMessage()) + } + + @Test + fun `an older publisher cannot clear a newer request`() { + val first = NfcTagEmitter.publish("lightning:lnbc1").also(tokens::add) + NfcTagEmitter.publish("lightning:lnbc2").also(tokens::add) + + assertFalse(NfcTagEmitter.clear(first)) + assertArrayEquals(NdefCodec.encodeUriMessage("lightning:lnbc2"), NfcTagEmitter.currentMessage()) + } +} diff --git a/app/src/test/java/to/bitkit/nfc/PosNfcFixtures.kt b/app/src/test/java/to/bitkit/nfc/PosNfcFixtures.kt new file mode 100644 index 0000000000..2b75418b5a --- /dev/null +++ b/app/src/test/java/to/bitkit/nfc/PosNfcFixtures.kt @@ -0,0 +1,36 @@ +package to.bitkit.nfc + +import java.nio.ByteBuffer + +/** + * Requests as point-of-sale terminals present them over NFC. + * + * A Square Register (2nd generation) serves `lightning:` and the uppercase BOLT11 invoice from its QR code as + * one long-format NDEF URI record with identifier code 0x00. Numo, and Square in a later release, serve the + * BIP 321 form without an address. [SQUARE_INVOICE] is a real signet invoice of the size Square serves: + * its message is 465 bytes and starts like Square's. + */ +object PosNfcFixtures { + const val SQUARE_INVOICE = + "LNTBS79900N1P4TZWUQD962DCH2CTJV5S9YET8D9EHGETJYP8YVSEQWFJKWUN9WDEKJMMWYPNXJ7R5W4EX2GZNW96KZUN9YPFX2E" + + "MFWD6X2U3QFERYXGRJV4NHYETNWD5K7M3QVE5HSAR4WFJJQ5M3W4SHYEFQ2FJKW6TNW3JHYGZWGEPJQUN9VAEX2UMND9HKUGRXD9" + + "U8GATJV5PP5QURSWPC8QURSWPC8QURSWPC8QURSWPC8QURSWPC8QURSWPC8QURSSP5PYYSJZGFPYYSJZGFPYYSJZGFPYYSJZGFPY" + + "YSJZGFPYYSJZGFPYYS9QRSGQXQ97ZVUQCQZYSKUAHP9D6GKX2H8ERFH5E9NZZ52SY0UFR2F6VGK43QEJ0ZJU7FTYQYJTQE8705R2" + + "KM9QS5NYFM3ZPR330ML3S3HWJP5D0RERD49QGT5CPUXAWEL" + const val SQUARE_URI = "lightning:$SQUARE_INVOICE" + const val BIP321_URI = "bitcoin:?lightning=$SQUARE_INVOICE" + + /** The first bytes of Square's NDEF message: long URI record, 0x1CA-byte payload, code 0x00, `lightning:`. */ + const val SQUARE_MESSAGE_START_HEX = "C1010000 01CA 55 00 6C696768746E696E673A" + + /** Square's NDEF message, built by hand from the record layout rather than by [NdefCodec]. */ + fun squareMessage(uri: String = SQUARE_URI): ByteArray { + val payload = byteArrayOf(0x00) + uri.toByteArray(Charsets.US_ASCII) + val lengthBytes = ByteBuffer.allocate(Int.SIZE_BYTES).putInt(payload.size).array() + val header = byteArrayOf(0xC1.toByte(), 0x01) + lengthBytes + byteArrayOf(0x55) + return header + payload + } + + fun hex(value: String): ByteArray = + value.replace(" ", "").chunked(2).map { it.toInt(16).toByte() }.toByteArray() +} diff --git a/app/src/test/java/to/bitkit/nfc/Type4TagEmulatorTest.kt b/app/src/test/java/to/bitkit/nfc/Type4TagEmulatorTest.kt new file mode 100644 index 0000000000..272d01b831 --- /dev/null +++ b/app/src/test/java/to/bitkit/nfc/Type4TagEmulatorTest.kt @@ -0,0 +1,138 @@ +package to.bitkit.nfc + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Test + +class Type4TagEmulatorTest { + private var message: ByteArray? = NdefCodec.encodeUriMessage("lightning:lnbc1") + private val sut = Type4TagEmulator { message } + + private val selectApp = hex("00A4040007D276000085010100") + private val selectCc = hex("00A4000C02E103") + private val selectNdef = hex("00A4000C02E104") + + @Test + fun `serves the NDEF message through the standard read sequence`() { + assertArrayEquals(Type4TagEmulator.SW_OK, sut.process(selectApp)) + assertArrayEquals(Type4TagEmulator.SW_OK, sut.process(selectCc)) + assertArrayEquals(hex("000F20003B00340406E104100000FF9000"), sut.process(hex("00B000000F"))) + assertArrayEquals(Type4TagEmulator.SW_OK, sut.process(selectNdef)) + + val expected = requireNotNull(message) + val lengthResponse = sut.process(hex("00B0000002")) + assertArrayEquals(byteArrayOf(0x00, expected.size.toByte()) + Type4TagEmulator.SW_OK, lengthResponse) + + val read = readNdef(offset = 2, total = expected.size) + assertArrayEquals(expected, read) + } + + @Test + fun `reads a long message in chunks`() { + message = NdefCodec.encodeUriMessage("bitcoin:bc1q?lightning=" + "x".repeat(700)) + sut.process(selectApp) + sut.process(selectNdef) + + val expected = requireNotNull(message) + assertArrayEquals(expected, readNdef(offset = 2, total = expected.size)) + } + + @Test + fun `serves a Square-sized request to a reader looping over offsets`() { + message = NdefCodec.encodeUriMessage(PosNfcFixtures.SQUARE_URI) + sut.process(selectApp) + sut.process(selectNdef) + + val expected = requireNotNull(message) + assertArrayEquals(hex("01D1") + Type4TagEmulator.SW_OK, sut.process(hex("00B0000002"))) + assertArrayEquals(expected, readNdef(offset = 2, total = expected.size)) + assertArrayEquals(expected, readNdef(offset = 2, total = expected.size, chunk = 0xFF)) + assertEquals(listOf(PosNfcFixtures.SQUARE_URI), NdefCodec.decodeTexts(expected)) + } + + @Test + fun `presents no tag when nothing is published`() { + message = null + + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(selectApp)) + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(selectNdef)) + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(hex("00B0000002"))) + } + + @Test + fun `refuses files before the application is selected`() { + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(selectCc)) + } + + @Test + fun `refuses other applications`() { + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(hex("00A4040007A000000003101000"))) + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(selectCc)) + } + + @Test + fun `keeps serving the message selected for this tap`() { + sut.process(selectApp) + sut.process(selectNdef) + val first = requireNotNull(message) + message = NdefCodec.encodeUriMessage("lightning:lnbc2") + + assertArrayEquals(first, readNdef(offset = 2, total = first.size)) + } + + @Test + fun `stops serving once nothing is published`() { + sut.process(selectApp) + sut.process(selectNdef) + message = null + + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(hex("00B0000002"))) + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(selectNdef)) + } + + @Test + fun `is read-only`() { + sut.process(selectApp) + sut.process(selectNdef) + + assertArrayEquals(Type4TagEmulator.SW_SECURITY_NOT_SATISFIED, sut.process(hex("00D60000020000"))) + } + + @Test + fun `rejects malformed and unsupported commands`() { + assertArrayEquals(Type4TagEmulator.SW_WRONG_LENGTH, sut.process(hex("00A4"))) + assertArrayEquals(Type4TagEmulator.SW_CLA_NOT_SUPPORTED, sut.process(hex("80A4040000"))) + assertArrayEquals(Type4TagEmulator.SW_INS_NOT_SUPPORTED, sut.process(hex("00CA000000"))) + } + + @Test + fun `reset forgets the selection`() { + sut.process(selectApp) + sut.reset() + + assertArrayEquals(Type4TagEmulator.SW_FILE_NOT_FOUND, sut.process(selectNdef)) + } + + private fun readNdef(offset: Int, total: Int, chunk: Int = MAX_READ): ByteArray { + var result = byteArrayOf() + var position = offset + while (result.size < total) { + val length = minOf(chunk, total - result.size) + val response = sut.process( + byteArrayOf(0x00, 0xB0.toByte(), (position shr 8).toByte(), position.toByte(), length.toByte()) + ) + assertArrayEquals(Type4TagEmulator.SW_OK, response.copyOfRange(response.size - 2, response.size)) + val chunk = response.copyOfRange(0, response.size - 2) + assertEquals(length, chunk.size) + result += chunk + position += chunk.size + } + return result + } + + private fun hex(value: String): ByteArray = value.chunked(2).map { it.toInt(16).toByte() }.toByteArray() + + private companion object { + const val MAX_READ = 0x3B + } +} diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 1f83ad43cb..5d43d24d3b 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1246,6 +1246,34 @@ class LightningRepoTest : BaseUnitTest() { verify(sparkRepo).payInvoice(eq("invoice"), eq(1_000uL), eq(deadline), eq(10_000uL), any()) } + @Test + fun `a node send checks its authorization again where it is submitted`() = test { + startNodeForTesting() + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())).thenReturn("hash") + val isAuthorizedAtSubmission = { false } + + sut.payInvoiceAuthorizedAtSubmission("bolt11", 1_000uL, isAuthorizedAtSubmission) { true } + + verify(lightningService).send(eq("bolt11"), eq(1_000uL), anyOrNull(), anyOrNull(), eq(isAuthorizedAtSubmission)) + } + + @Test + fun `a node send stopped at submission keeps an earlier send of the invoice`() = test { + // An earlier node send of this invoice is pending or paid, so its hash is kept. + val cache = AppCacheData(ldkSendHashesSeeded = true, ldkSendHashes = listOf("bolt11")) + val store = CacheStore(InMemoryDataStore(cache)) + sut = repoWith(store) + startNodeForTesting() + whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) + whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenAnswer { throw AppError(ServiceError.PaymentStoppedAtSubmission()) } + + sut.payInvoiceAuthorizedAtSubmission("bolt11", 1_000uL, { false }) { true } + + assertEquals(listOf("bolt11"), store.data.first().ldkSendHashes, "The earlier send's hash must stay") + } + @Test fun `a node-only payment fails instead of falling back to spark`() = test { startNodeForTesting() @@ -2751,6 +2779,21 @@ class LightningRepoTest : BaseUnitTest() { verify(lightningService, never()).balances } + @Test + fun `waitForUsableChannels without awaiting publishes unusable channels and returns`() = test { + val cached = createChannelDetails().copy(isChannelReady = true, isUsable = true) + whenever(lightningService.channels).thenReturn(listOf(cached)) + startNodeForTesting() + val unavailable = cached.copy(isUsable = false) + whenever(lightningService.channels).thenReturn(listOf(unavailable)) + + val wait = async { sut.waitForUsableChannels(awaitUsable = false) } + runCurrent() + + assertTrue(wait.isCompleted) + assertEquals(listOf(unavailable), sut.lightningState.value.channels) + } + @Test fun `waitForUsableChannels waits when a cached usable channel becomes unusable`() = test { val cached = createChannelDetails().copy(isChannelReady = true, isUsable = true) diff --git a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt index 29ddda7818..af3c71bde8 100644 --- a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt @@ -47,6 +47,7 @@ import to.bitkit.test.BaseUnitTest import to.bitkit.test.InMemoryDataStore import to.bitkit.utils.AppError import to.bitkit.utils.LdkError +import to.bitkit.utils.ServiceError import java.math.BigDecimal import java.util.Locale import kotlin.test.assertEquals @@ -384,8 +385,10 @@ class QuickPayRepoTest : BaseUnitTest() { val (bolt11, hash) = testInvoice() val started = CompletableDeferred() val hold = CompletableDeferred>() - whenever { lightningRepo.payInvoice(any(), anyOrNull(), any()) }.doSuspendableAnswer { invocation -> - val onBeforeSend = invocation.getArgument Boolean>(2) + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { invocation -> + val onBeforeSend = invocation.getArgument Boolean>(3) if (!onBeforeSend()) return@doSuspendableAnswer Result.failure(PaymentAbortedBeforeSend()) started.complete(Unit) hold.await() @@ -411,8 +414,10 @@ class QuickPayRepoTest : BaseUnitTest() { val (bolt11, hash) = testInvoice() val started = CompletableDeferred() val hold = CompletableDeferred>() - whenever { lightningRepo.payInvoice(any(), anyOrNull(), any()) }.doSuspendableAnswer { invocation -> - val onBeforeSend = invocation.getArgument Boolean>(2) + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { invocation -> + val onBeforeSend = invocation.getArgument Boolean>(3) if (!onBeforeSend()) return@doSuspendableAnswer Result.failure(PaymentAbortedBeforeSend()) started.complete(Unit) hold.await() @@ -443,8 +448,10 @@ class QuickPayRepoTest : BaseUnitTest() { val (bolt11, hash) = testInvoice() val started = CompletableDeferred() val hold = CompletableDeferred>() - whenever { lightningRepo.payInvoice(any(), anyOrNull(), any()) }.doSuspendableAnswer { invocation -> - val onBeforeSend = invocation.getArgument Boolean>(2) + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { invocation -> + val onBeforeSend = invocation.getArgument Boolean>(3) if (!onBeforeSend()) return@doSuspendableAnswer Result.failure(PaymentAbortedBeforeSend()) started.complete(Unit) hold.await() @@ -503,8 +510,10 @@ class QuickPayRepoTest : BaseUnitTest() { val (bolt11, hash) = testInvoice() val started = CompletableDeferred() val hold = CompletableDeferred>() - whenever { lightningRepo.payInvoice(any(), anyOrNull(), any()) }.doSuspendableAnswer { invocation -> - val onBeforeSend = invocation.getArgument Boolean>(2) + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { invocation -> + val onBeforeSend = invocation.getArgument Boolean>(3) if (!onBeforeSend()) return@doSuspendableAnswer Result.failure(PaymentAbortedBeforeSend()) started.complete(Unit) hold.await() @@ -656,7 +665,7 @@ class QuickPayRepoTest : BaseUnitTest() { val reloaded = repo() assertNull(reloaded.reserveBound("inv", 1000u).getOrThrow()) - verify(lightningRepo, never()).payInvoice(any(), anyOrNull(), any()) + verify(lightningRepo, never()).payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) } @Test @@ -751,8 +760,10 @@ class QuickPayRepoTest : BaseUnitTest() { fun `live record survives day prune then settles`() = test { val (bolt11, hash) = testInvoice() val dispatched = CompletableDeferred() - whenever { lightningRepo.payInvoice(any(), anyOrNull(), any()) }.doSuspendableAnswer { invocation -> - val onBeforeSend = invocation.getArgument Boolean>(2) + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { invocation -> + val onBeforeSend = invocation.getArgument Boolean>(3) if (!onBeforeSend()) return@doSuspendableAnswer Result.failure(PaymentAbortedBeforeSend()) dispatched.complete(Unit) Result.success("pid") @@ -829,7 +840,7 @@ class QuickPayRepoTest : BaseUnitTest() { sut.attach(session) sut.pay(session, QuickPayPayRequest.Bolt11(bolt11 = "lnbcrt1test", amountSats = 500u)) - verify(lightningRepo, never()).payInvoice(any(), anyOrNull(), any()) + verify(lightningRepo, never()).payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) } @Test @@ -925,8 +936,10 @@ class QuickPayRepoTest : BaseUnitTest() { val (bolt11, hash) = testInvoice() val dispatched = CompletableDeferred() val hold = CompletableDeferred>() - whenever { lightningRepo.payInvoice(any(), anyOrNull(), any()) }.doSuspendableAnswer { invocation -> - val onBeforeSend = invocation.getArgument Boolean>(2) + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { invocation -> + val onBeforeSend = invocation.getArgument Boolean>(3) if (!onBeforeSend()) return@doSuspendableAnswer Result.failure(PaymentAbortedBeforeSend()) dispatched.complete(Unit) hold.await() @@ -971,7 +984,7 @@ class QuickPayRepoTest : BaseUnitTest() { sut.payNow(second, QuickPayPayRequest.Bolt11(bolt11 = bolt11, amountSats = 500u)) assertIs(awaitItem()) } - verify(lightningRepo, times(1)).payInvoice(any(), anyOrNull(), any()) + verify(lightningRepo, times(1)).payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) assertEquals(250L, spentCents()) assertEquals(1, cacheStore.data.first().quickPayLedger!!.records.size) } @@ -1004,8 +1017,10 @@ class QuickPayRepoTest : BaseUnitTest() { fun `zombie rescan replays pending after detach timeout`() = test { val (bolt11, hash) = testInvoice() val dispatched = CompletableDeferred() - whenever { lightningRepo.payInvoice(any(), anyOrNull(), any()) }.doSuspendableAnswer { invocation -> - val onBeforeSend = invocation.getArgument Boolean>(2) + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { invocation -> + val onBeforeSend = invocation.getArgument Boolean>(3) if (!onBeforeSend()) return@doSuspendableAnswer Result.failure(PaymentAbortedBeforeSend()) dispatched.complete(Unit) Result.success("pid") @@ -1024,7 +1039,7 @@ class QuickPayRepoTest : BaseUnitTest() { sut.payNow(second, QuickPayPayRequest.Bolt11(bolt11 = bolt11, amountSats = 500u)) assertIs(awaitItem()) } - verify(lightningRepo, times(1)).payInvoice(any(), anyOrNull(), any()) + verify(lightningRepo, times(1)).payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) verify(pendingPaymentRepo).track(hash) assertEquals(250L, spentCents()) assertEquals(1, cacheStore.data.first().quickPayLedger!!.records.size) @@ -1065,8 +1080,10 @@ class QuickPayRepoTest : BaseUnitTest() { val (bolt11, _) = testInvoice() val started = CompletableDeferred() val hold = CompletableDeferred>() - whenever { lightningRepo.payInvoice(any(), anyOrNull(), any()) }.doSuspendableAnswer { invocation -> - val onBeforeSend = invocation.getArgument Boolean>(2) + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { invocation -> + val onBeforeSend = invocation.getArgument Boolean>(3) if (!onBeforeSend()) return@doSuspendableAnswer Result.failure(PaymentAbortedBeforeSend()) started.complete(Unit) hold.await() @@ -1079,7 +1096,7 @@ class QuickPayRepoTest : BaseUnitTest() { started.await() sut.payNow(session, QuickPayPayRequest.Bolt11(bolt11 = bolt11, amountSats = 500u)) - verify(lightningRepo, times(1)).payInvoice(any(), anyOrNull(), any()) + verify(lightningRepo, times(1)).payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) hold.complete(Result.success("pid")) } @@ -1096,7 +1113,7 @@ class QuickPayRepoTest : BaseUnitTest() { assertEquals(hash, pending.paymentHash) } assertEquals(250L, spentCents()) - verify(lightningRepo, never()).payInvoice(any(), anyOrNull(), any()) + verify(lightningRepo, never()).payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) verify(pendingPaymentRepo).track(hash) } @@ -1114,7 +1131,7 @@ class QuickPayRepoTest : BaseUnitTest() { } assertEquals(250L, spentCents()) assertTrue(cacheStore.data.first().quickPayLedger!!.records.isEmpty()) - verify(lightningRepo, never()).payInvoice(any(), anyOrNull(), any()) + verify(lightningRepo, never()).payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) } @Test @@ -1130,7 +1147,7 @@ class QuickPayRepoTest : BaseUnitTest() { } assertEquals(0L, spentCents()) assertTrue(cacheStore.data.first().quickPayLedger?.records.orEmpty().isEmpty()) - verify(lightningRepo, never()).payInvoice(any(), anyOrNull(), any()) + verify(lightningRepo, never()).payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) } @Test @@ -1154,7 +1171,7 @@ class QuickPayRepoTest : BaseUnitTest() { } assertEquals(0L, spentCents()) assertTrue(checkNotNull(cacheStore.data.first().quickPayLedger) { "ledger missing" }.records.isEmpty()) - verify(lightningRepo, never()).payInvoice(any(), anyOrNull(), any()) + verify(lightningRepo, never()).payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) } @Test @@ -1173,7 +1190,7 @@ class QuickPayRepoTest : BaseUnitTest() { assertEquals(hash, pending.paymentHash) } assertEquals(250L, spentCents()) - verify(lightningRepo, never()).payInvoice(any(), anyOrNull(), any()) + verify(lightningRepo, never()).payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) verify(pendingPaymentRepo).track(hash) } @@ -1193,7 +1210,7 @@ class QuickPayRepoTest : BaseUnitTest() { } assertEquals(250L, spentCents()) assertTrue(checkNotNull(cacheStore.data.first().quickPayLedger) { "ledger missing" }.records.isEmpty()) - verify(lightningRepo, never()).payInvoice(any(), anyOrNull(), any()) + verify(lightningRepo, never()).payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) } @Test @@ -1216,7 +1233,7 @@ class QuickPayRepoTest : BaseUnitTest() { } assertEquals(250L, spentCents()) assertTrue(checkNotNull(cacheStore.data.first().quickPayLedger) { "ledger missing" }.records.isEmpty()) - verify(lightningRepo, never()).payInvoice(any(), anyOrNull(), any()) + verify(lightningRepo, never()).payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) } @Test @@ -1237,7 +1254,7 @@ class QuickPayRepoTest : BaseUnitTest() { assertEquals(hash, pending.paymentHash) } assertEquals(250L, spentCents()) - verify(lightningRepo, never()).payInvoice(any(), anyOrNull(), any()) + verify(lightningRepo, never()).payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) verify(pendingPaymentRepo).track(hash) } @@ -1245,8 +1262,10 @@ class QuickPayRepoTest : BaseUnitTest() { fun `disabling quickpay before send aborts the dispatch and falls back to confirm`() = test { val (bolt11, hash) = testInvoice() val proceeded = CompletableDeferred() - whenever { lightningRepo.payInvoice(any(), anyOrNull(), any()) }.doSuspendableAnswer { invocation -> - val onBeforeSend = invocation.getArgument Boolean>(2) + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { invocation -> + val onBeforeSend = invocation.getArgument Boolean>(3) assertEquals(250L, spentCents()) settingsData.value = settingsData.value.copy(isQuickPayEnabled = false) val ok = onBeforeSend() @@ -1263,7 +1282,7 @@ class QuickPayRepoTest : BaseUnitTest() { assertEquals(0L, spentCents()) assertTrue(checkNotNull(cacheStore.data.first().quickPayLedger) { "ledger missing" }.records.isEmpty()) assertFalse(sut.hasOpen(hash)) - verify(lightningRepo, times(1)).payInvoice(any(), anyOrNull(), any()) + verify(lightningRepo, times(1)).payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) } @Test @@ -1364,7 +1383,7 @@ class QuickPayRepoTest : BaseUnitTest() { assertEquals(QuickPaySessionEvent.FallBackToConfirm, awaitItem()) } assertEquals(0L, spentCents()) - verify(lightningRepo, never()).payInvoice(any(), anyOrNull(), any()) + verify(lightningRepo, never()).payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) } @Test @@ -1380,7 +1399,7 @@ class QuickPayRepoTest : BaseUnitTest() { assertIs(error.error) } assertEquals(0L, spentCents()) - verify(lightningRepo, never()).payInvoice(any(), anyOrNull(), any()) + verify(lightningRepo, never()).payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) } @Test @@ -1396,7 +1415,7 @@ class QuickPayRepoTest : BaseUnitTest() { assertEquals(bolt11, error.paymentRequest) } assertEquals(0L, spentCents()) - verify(lightningRepo, never()).payInvoice(any(), anyOrNull(), any()) + verify(lightningRepo, never()).payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) } @Test @@ -1410,14 +1429,16 @@ class QuickPayRepoTest : BaseUnitTest() { assertEquals(QuickPaySessionEvent.FallBackToConfirm, awaitItem()) } verify(lightningRepo, never()).fetchLnurlInvoice(any(), any(), anyOrNull()) - verify(lightningRepo, never()).payInvoice(any(), anyOrNull(), any()) + verify(lightningRepo, never()).payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) } @Test fun `reserve persists before dispatch`() = test { val (bolt11, _) = testInvoice() - whenever { lightningRepo.payInvoice(any(), anyOrNull(), any()) }.doSuspendableAnswer { invocation -> - val onBeforeSend = invocation.getArgument Boolean>(2) + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { invocation -> + val onBeforeSend = invocation.getArgument Boolean>(3) assertEquals(250L, spentCents()) assertEquals(1, cacheStore.data.first().quickPayLedger!!.records.size) if (!onBeforeSend()) return@doSuspendableAnswer Result.failure(PaymentAbortedBeforeSend()) @@ -1434,8 +1455,10 @@ class QuickPayRepoTest : BaseUnitTest() { val entered = CompletableDeferred() val gate = CompletableDeferred() val proceeded = CompletableDeferred() - whenever { lightningRepo.payInvoice(any(), anyOrNull(), any()) }.doSuspendableAnswer { invocation -> - val onBeforeSend = invocation.getArgument Boolean>(2) + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { invocation -> + val onBeforeSend = invocation.getArgument Boolean>(3) entered.complete(Unit) withContext(NonCancellable) { gate.await() @@ -1457,13 +1480,66 @@ class QuickPayRepoTest : BaseUnitTest() { } assertEquals(0L, spentCents()) assertTrue(cacheStore.data.first().quickPayLedger!!.records.isEmpty()) - verify(lightningRepo, times(1)).payInvoice(any(), anyOrNull(), any()) + verify(lightningRepo, times(1)).payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + } + + @Test + fun `authorization lapsing before dispatch falls back to review and releases`() = test { + val (bolt11, _) = testInvoice() + val proceeded = CompletableDeferred() + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { invocation -> + val ok = invocation.getArgument Boolean>(3)() + proceeded.complete(ok) + if (!ok) Result.failure(PaymentAbortedBeforeSend()) else Result.success("pid") + } + val session = QuickPaySession() + sut.attach(session).test { + // The wallet locked while the invoice was being prepared. + sut.payNow(session, QuickPayPayRequest.Bolt11(bolt11 = bolt11, amountSats = 500u), canDispatch = { false }) + assertEquals(false, proceeded.await()) + assertEquals(QuickPaySessionEvent.FallBackToConfirm, awaitItem()) + } + assertEquals(0L, spentCents()) + assertTrue(cacheStore.data.first().quickPayLedger!!.records.isEmpty()) + } + + @Test + fun `authorization lapsing while the node send waits in its queue falls back to review`() = test { + val (bolt11, _) = testInvoice() + var isUnlocked = true + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { invocation -> + val onBeforeSend = invocation.getArgument Boolean>(3) + val isAuthorizedAtSubmission = invocation.getArgument<() -> Boolean>(2) + if (!onBeforeSend()) return@doSuspendableAnswer Result.failure(PaymentAbortedBeforeSend()) + // The wallet locks while the send waits behind a wallet sync on the node's queue. + isUnlocked = false + if (!isAuthorizedAtSubmission()) { + Result.failure(AppError(ServiceError.PaymentStoppedAtSubmission())) + } else { + Result.success("pid") + } + } + val session = QuickPaySession() + sut.attach(session).test { + sut.payNow( + session, + QuickPayPayRequest.Bolt11(bolt11 = bolt11, amountSats = 500u), + canDispatch = { isUnlocked }, + ) + assertEquals(QuickPaySessionEvent.FallBackToConfirm, awaitItem()) + } + assertEquals(0L, spentCents()) + assertTrue(cacheStore.data.first().quickPayLedger!!.records.isEmpty()) } @Test fun `ambiguous failure before dispatch refunds and errors`() = test { val (bolt11, _) = testInvoice() - whenever(lightningRepo.payInvoice(any(), anyOrNull(), any())) + whenever(lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any())) .thenReturn(Result.failure(AppError("Cannot execute 'payInvoice'"))) val session = QuickPaySession() sut.attach(session).test { @@ -1477,7 +1553,7 @@ class QuickPayRepoTest : BaseUnitTest() { @Test fun `ambiguous failure before dispatch refunds even with succeeded ldk row`() = test { val (bolt11, hash) = testInvoice() - whenever(lightningRepo.payInvoice(any(), anyOrNull(), any())) + whenever(lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any())) .thenReturn(Result.failure(AppError("Cannot execute 'payInvoice'"))) paymentRows = listOf(succeededRow(hash)) val session = QuickPaySession() @@ -1520,8 +1596,10 @@ class QuickPayRepoTest : BaseUnitTest() { val (bolt11, hash) = testInvoice() val dispatched = CompletableDeferred() val hold = CompletableDeferred>() - whenever { lightningRepo.payInvoice(any(), anyOrNull(), any()) }.doSuspendableAnswer { invocation -> - val onBeforeSend = invocation.getArgument Boolean>(2) + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { invocation -> + val onBeforeSend = invocation.getArgument Boolean>(3) if (!onBeforeSend()) return@doSuspendableAnswer Result.failure(PaymentAbortedBeforeSend()) dispatched.complete(Unit) hold.await() @@ -1564,8 +1642,10 @@ class QuickPayRepoTest : BaseUnitTest() { } private suspend fun stubPayInvoiceFailure(error: NodeException) { - whenever { lightningRepo.payInvoice(any(), anyOrNull(), any()) }.doSuspendableAnswer { invocation -> - val onBeforeSend = invocation.getArgument Boolean>(2) + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { invocation -> + val onBeforeSend = invocation.getArgument Boolean>(3) if (!onBeforeSend()) return@doSuspendableAnswer Result.failure(PaymentAbortedBeforeSend()) Result.failure(LdkError(error)) } @@ -1573,8 +1653,10 @@ class QuickPayRepoTest : BaseUnitTest() { private fun stubPayInvoiceChangingSettings(change: () -> Unit): CompletableDeferred { val proceeded = CompletableDeferred() - whenever { lightningRepo.payInvoice(any(), anyOrNull(), any()) }.doSuspendableAnswer { invocation -> - val onBeforeSend = invocation.getArgument Boolean>(2) + whenever { + lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any()) + }.doSuspendableAnswer { invocation -> + val onBeforeSend = invocation.getArgument Boolean>(3) val records = checkNotNull(cacheStore.data.first().quickPayLedger) { "ledger missing" }.records assertEquals(1, records.count { it.invoicePaymentHash == TEST_HASH }) change() diff --git a/app/src/test/java/to/bitkit/ui/screens/scanner/NearbyScanSourcesTest.kt b/app/src/test/java/to/bitkit/ui/screens/scanner/NearbyScanSourcesTest.kt new file mode 100644 index 0000000000..bcc868093d --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/screens/scanner/NearbyScanSourcesTest.kt @@ -0,0 +1,22 @@ +package to.bitkit.ui.screens.scanner + +import org.junit.Test +import to.bitkit.R +import to.bitkit.ui.shared.effects.BluetoothState +import to.bitkit.ui.shared.effects.NfcState +import kotlin.test.assertEquals + +class NearbyScanSourcesTest { + private fun sources(isPaused: Boolean) = + NearbyScanSources(NfcState.ON, BluetoothState.ON, onEnableNfc = {}, onEnableBluetooth = {}, isPaused = isPaused) + + @Test + fun `status lists the sources that read`() { + assertEquals(R.string.other__scanner_status_qr_nfc_bluetooth, scannerStatusText(sources(isPaused = false))) + } + + @Test + fun `status lists only the camera while nearby payments pause`() { + assertEquals(R.string.other__scanner_status_qr, scannerStatusText(sources(isPaused = true))) + } +} diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/receive/ReceiveInvoiceUtilsTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/receive/ReceiveInvoiceUtilsTest.kt index d13389dbd6..002fd1f181 100644 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/receive/ReceiveInvoiceUtilsTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/receive/ReceiveInvoiceUtilsTest.kt @@ -2,6 +2,7 @@ package to.bitkit.ui.screens.wallets.receive import org.junit.Test import kotlin.test.assertEquals +import kotlin.test.assertNull class ReceiveInvoiceUtilsTest { @@ -340,4 +341,19 @@ class ReceiveInvoiceUtilsTest { fun `getSavingsCopyText returns fallback address when bip21 is empty`() { assertEquals(testAddress, getSavingsCopyText("", testAddress)) } + + @Test + fun `nearby offers only the request the QR shows`() { + val request = "bitcoin:bcrt1qold?lightning=lnbcrt1old" + for (tab in listOf(ReceiveTab.AUTO, ReceiveTab.SPENDING)) { + assertEquals(request, nearbyReceiveRequest(tab, request, hasInvoiceError = false, isUpdating = false)) + assertNull(nearbyReceiveRequest(tab, request, hasInvoiceError = true, isUpdating = false)) + assertNull(nearbyReceiveRequest(tab, request, hasInvoiceError = false, isUpdating = true)) + } + assertEquals( + "bcrt1qold", + nearbyReceiveRequest(ReceiveTab.SAVINGS, "bcrt1qold", hasInvoiceError = true, isUpdating = true), + ) + assertNull(nearbyReceiveRequest(ReceiveTab.USDT, "ethereum:0xold", hasInvoiceError = false, isUpdating = false)) + } } diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/usdt/UsdtNearbyRequestTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/usdt/UsdtNearbyRequestTest.kt new file mode 100644 index 0000000000..3ef4a73125 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/usdt/UsdtNearbyRequestTest.kt @@ -0,0 +1,30 @@ +package to.bitkit.ui.screens.wallets.usdt + +import org.junit.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +class UsdtNearbyRequestTest { + private val arbitrumUri = "ethereum:0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9@42161/transfer?address=0x1111" + + @Test + fun `offers the arbitrum request when no deposit is shown`() { + assertEquals(arbitrumUri, usdtNearbyRequest(depositUri = null, receiveUri = arbitrumUri)) + } + + @Test + fun `does not offer a tron deposit address`() { + assertNull(usdtNearbyRequest(depositUri = "TJRabPrwbZy45sbavfcjinPJC18kjpRTv8", receiveUri = arbitrumUri)) + } + + @Test + fun `does not offer a deposit on another evm chain`() { + val baseDeposit = "ethereum:0x833589fcd6edb6e08f4c7c32d4f71b54bda02913@8453/transfer?address=0x2222" + assertNull(usdtNearbyRequest(depositUri = baseDeposit, receiveUri = arbitrumUri)) + } + + @Test + fun `offers nothing before the wallet request loads`() { + assertNull(usdtNearbyRequest(depositUri = null, receiveUri = "")) + } +} diff --git a/app/src/test/java/to/bitkit/ui/shared/effects/NearbyPauseTest.kt b/app/src/test/java/to/bitkit/ui/shared/effects/NearbyPauseTest.kt new file mode 100644 index 0000000000..0c95293a6e --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/shared/effects/NearbyPauseTest.kt @@ -0,0 +1,60 @@ +package to.bitkit.ui.shared.effects + +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.test.junit4.createComposeRule +import kotlinx.coroutines.flow.MutableStateFlow +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.kotlin.mock +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import to.bitkit.repositories.ConnectivityState +import to.bitkit.ui.LocalAppViewModel +import to.bitkit.ui.LocalIsAppLocked +import to.bitkit.viewmodels.AppViewModel +import kotlin.test.assertEquals +import kotlin.test.assertNull + +@Config(sdk = [34]) +@RunWith(RobolectricTestRunner::class) +class NearbyPauseTest { + @get:Rule + val composeRule = createComposeRule() + + private val connectivity = MutableStateFlow(ConnectivityState.CONNECTED) + private val app = mock { on { isOnline }.thenReturn(connectivity) } + + private fun isPaused(isLocked: Boolean = false): Boolean { + var paused: Boolean? = null + composeRule.setContent { + CompositionLocalProvider(LocalAppViewModel provides app, LocalIsAppLocked provides isLocked) { + paused = isNearbyPaused() + } + } + composeRule.waitForIdle() + return requireNotNull(paused) + } + + @Test + fun `runs while online and unlocked`() { + assertEquals(false, isPaused()) + } + + @Test + fun `pauses while the connection issues screen is shown`() { + connectivity.value = ConnectivityState.DISCONNECTED + assertEquals(true, isPaused()) + } + + @Test + fun `pauses while the app is locked`() { + assertEquals(true, isPaused(isLocked = true)) + } + + @Test + fun `offers nothing while paused`() { + assertNull(nearbyOfferUri("lnbcrt1p", isPaused = true)) + assertEquals("lightning:lnbcrt1p", nearbyOfferUri("lnbcrt1p", isPaused = false)) + } +} diff --git a/app/src/test/java/to/bitkit/ui/shared/effects/NfcTagServiceRegistrationTest.kt b/app/src/test/java/to/bitkit/ui/shared/effects/NfcTagServiceRegistrationTest.kt new file mode 100644 index 0000000000..bd200c9d2d --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/shared/effects/NfcTagServiceRegistrationTest.kt @@ -0,0 +1,54 @@ +package to.bitkit.ui.shared.effects + +import android.app.Activity +import android.content.ComponentName +import android.nfc.cardemulation.CardEmulation +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class NfcTagServiceRegistrationTest { + private val activity = mock() + private val service = mock() + private val cardEmulation = mock() + + @Test + fun `registered service is preferred and reported`() { + whenever(cardEmulation.registerAidsForService(any(), any(), any())).thenReturn(true) + whenever(cardEmulation.setPreferredService(activity, service)).thenReturn(true) + + assertTrue(registerTagService(cardEmulation, activity, service)) + verify(cardEmulation).setPreferredService(activity, service) + verify(cardEmulation, never()).removeAidsForService(anyOrNull(), anyOrNull()) + } + + @Test + fun `refused preference releases the aid and is reported`() { + whenever(cardEmulation.registerAidsForService(any(), any(), any())).thenReturn(true) + whenever(cardEmulation.setPreferredService(activity, service)).thenReturn(false) + + assertFalse(registerTagService(cardEmulation, activity, service)) + verify(cardEmulation).removeAidsForService(service, CardEmulation.CATEGORY_OTHER) + } + + @Test + fun `refused registration is reported`() { + whenever(cardEmulation.registerAidsForService(any(), any(), any())).thenReturn(false) + + assertFalse(registerTagService(cardEmulation, activity, service)) + verify(cardEmulation, never()).setPreferredService(anyOrNull(), anyOrNull()) + } + + @Test + fun `failed registration is reported`() { + whenever(cardEmulation.registerAidsForService(any(), any(), any())).thenThrow(SecurityException("denied")) + + assertFalse(registerTagService(cardEmulation, activity, service)) + } +} diff --git a/app/src/test/java/to/bitkit/utils/timedsheets/sheets/NfcTimedSheetTest.kt b/app/src/test/java/to/bitkit/utils/timedsheets/sheets/NfcTimedSheetTest.kt new file mode 100644 index 0000000000..bed62b14ed --- /dev/null +++ b/app/src/test/java/to/bitkit/utils/timedsheets/sheets/NfcTimedSheetTest.kt @@ -0,0 +1,73 @@ +package to.bitkit.utils.timedsheets.sheets + +import android.content.Context +import android.content.pm.PackageManager +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever +import to.bitkit.data.SettingsData +import to.bitkit.data.SettingsStore +import to.bitkit.test.BaseUnitTest +import to.bitkit.ui.components.TimedSheetType + +class NfcTimedSheetTest : BaseUnitTest() { + private val packageManager = mock() + private val context = mock() + private val settingsStore = mock() + private val settingsFlow = MutableStateFlow(SettingsData()) + private lateinit var sut: NfcTimedSheet + + @Before + fun setUp() = runBlocking { + whenever(context.packageManager).thenReturn(packageManager) + whenever(packageManager.hasSystemFeature(PackageManager.FEATURE_NFC)).thenReturn(true) + whenever(settingsStore.data).thenReturn(settingsFlow) + whenever(settingsStore.update(any())).then { + val transform = it.getArgument<(SettingsData) -> SettingsData>(0) + settingsFlow.value = transform(settingsFlow.value) + flowOf(settingsFlow.value) + } + sut = NfcTimedSheet(context, settingsStore) + } + + @Test + fun `type is NFC`() { + assertEquals(TimedSheetType.NFC, sut.type) + } + + @Test + fun `shows once on devices with NFC`() = test { + assertTrue(sut.shouldShow()) + } + + @Test + fun `does not show without NFC`() = test { + whenever(packageManager.hasSystemFeature(PackageManager.FEATURE_NFC)).thenReturn(false) + + assertFalse(sut.shouldShow()) + } + + @Test + fun `does not show when already seen`() = test { + settingsFlow.value = SettingsData(nfcIntroSeen = true) + + assertFalse(sut.shouldShow()) + } + + @Test + fun `dismissing marks the NFC and QuickPay intros as seen`() = test { + sut.onDismissed() + + assertTrue(settingsFlow.value.nfcIntroSeen) + assertTrue(settingsFlow.value.quickPayIntroSeen) + assertFalse(sut.shouldShow()) + } +} diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 4a2c1961e9..62e940c693 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -1056,6 +1056,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { backupSheet = backupSheet, notificationsSheet = mock { on { type } doReturn TimedSheetType.NOTIFICATIONS }, quickPaySheet = mock { on { type } doReturn TimedSheetType.QUICK_PAY }, + nfcSheet = mock { on { type } doReturn TimedSheetType.NFC }, usdtSheet = usdtSheet, usdtPreferences = usdtPreferences, @@ -4412,6 +4413,32 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(coreService, never()).decode(any()) } + @Test + fun `nfc tag launch rewrites a bip 321 request without an address`() = test { + val bolt11 = "lnbcrt1nfctap" + stubLightningScan(bolt11 = bolt11, amountSats = 500u) + sut.setIsAuthenticated(true) + + sut.handleDeeplinkIntent(nfcTagIntent("bitcoin:?lightning=$bolt11")) + advanceUntilIdle() + + val decoded = argumentCaptor() + verify(coreService, atLeastOnce()).decode(decoded.capture()) + assertTrue(decoded.allValues.none { it.startsWith("bitcoin:?") }, decoded.allValues.toString()) + } + + @Test + fun `nfc tag launch with a required parameter shows the nfc error without decoding`() = test { + sut.setIsAuthenticated(true) + + sut.handleDeeplinkIntent(nfcTagIntent("bitcoin:$REGTEST_ADDRESS?amount=0.001&req-pop=callback%3a")) + advanceUntilIdle() + + verify(coreService, never()).decode(any()) + verify(toastManager).enqueue(check { assertEquals(Toast.ToastType.ERROR, it.type) }) + assertNull(sut.currentSheet.value) + } + @Test fun `Bitkit SamRock deeplink opens BTCPay connection sheet without core decode`() = test { sut.handleDeeplinkIntent(samRockIntent(samRockDeepLink(SAMROCK_SETUP_URL))) @@ -5359,7 +5386,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { sut.showScannerSheet() advanceUntilIdle() - assertEquals(Sheet.QrScanner(showBackButton = true), sut.currentSheet.value) + assertEquals(Sheet.QrScanner(showBackButton = true, readsNearby = true), sut.currentSheet.value) sut.hideScannerSheet() advanceUntilIdle() @@ -5367,12 +5394,23 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertNull(sut.currentSheet.value) } + @Test + fun `scanner sheet opened for a setting does not read nearby payments`() = test { + sut.showScannerSheet { } + advanceUntilIdle() + assertEquals(Sheet.QrScanner(readsNearby = false), sut.currentSheet.value) + + sut.showScannerSheet(isPubkyScan = true) { } + advanceUntilIdle() + assertEquals(Sheet.QrScanner(isPubkyScan = true, readsNearby = false), sut.currentSheet.value) + } + @Test fun `scanner sheet can hide back button for tab bar entry`() = test { sut.showScannerSheet(showBackButton = false) advanceUntilIdle() - assertEquals(Sheet.QrScanner(showBackButton = false), sut.currentSheet.value) + assertEquals(Sheet.QrScanner(showBackButton = false, readsNearby = true), sut.currentSheet.value) } @Test @@ -6477,7 +6515,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { sut.showScannerSheet() advanceUntilIdle() - assertEquals(Sheet.QrScanner(), sut.currentSheet.value) + assertEquals(Sheet.QrScanner(readsNearby = true), sut.currentSheet.value) sut.onScannerSheetResult(authUrl) advanceUntilIdle() @@ -9775,6 +9813,285 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertFalse(sut.sendUiState.value.isAmountEditable) } + @Test + fun `nearby read still decoding does not route after enter manually`() = test { + val input = stubOnchainAmountScan(amountSats = 10_000u) + val entered = CompletableDeferred() + val release = CompletableDeferred() + whenever(coreService.decode(input)).doSuspendableAnswer { + entered.complete(Unit) + release.await() + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 10_000u, null, null, null)) + } + + sut.showSheet(Sheet.Send()) + advanceUntilIdle() + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AddressContinue(input, suppressQuickPay = true, isNearbyRead = true)) + advanceUntilIdle() + assertTrue(entered.isCompleted) + sut.setSendEvent(SendEvent.EnterManually) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToAddress, awaitItem()) + + release.complete(Unit) + advanceUntilIdle() + + expectNoEvents() + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `duplicate nearby read keeps the decoding read cancellable by enter manually`() = test { + val input = stubOnchainAmountScan(amountSats = 10_000u) + val entered = CompletableDeferred() + val release = CompletableDeferred() + whenever(coreService.decode(input)).doSuspendableAnswer { + entered.complete(Unit) + release.await() + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 10_000u, null, null, null)) + } + + sut.showSheet(Sheet.Send()) + advanceUntilIdle() + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AddressContinue(input, suppressQuickPay = true, isNearbyRead = true)) + advanceUntilIdle() + assertTrue(entered.isCompleted) + sut.setSendEvent(SendEvent.AddressContinue(input, suppressQuickPay = true, isNearbyRead = true)) + advanceUntilIdle() + sut.setSendEvent(SendEvent.EnterManually) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToAddress, awaitItem()) + + release.complete(Unit) + advanceUntilIdle() + + expectNoEvents() + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `nfc read still decoding does not route after enter manually`() = test { + val input = stubOnchainAmountScan(amountSats = 10_000u) + val entered = CompletableDeferred() + val release = CompletableDeferred() + whenever(coreService.decode(input)).doSuspendableAnswer { + entered.complete(Unit) + release.await() + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 10_000u, null, null, null)) + } + + sut.showSheet(Sheet.Send()) + advanceUntilIdle() + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AddressContinue(input, isNearbyRead = true)) + advanceUntilIdle() + assertTrue(entered.isCompleted) + sut.setSendEvent(SendEvent.EnterManually) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToAddress, awaitItem()) + + release.complete(Unit) + advanceUntilIdle() + + expectNoEvents() + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `nearby read still decoding does not route after contacts`() = test { + val input = stubOnchainAmountScan(amountSats = 10_000u) + val entered = CompletableDeferred() + val release = CompletableDeferred() + whenever(coreService.decode(input)).doSuspendableAnswer { + entered.complete(Unit) + release.await() + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 10_000u, null, null, null)) + } + isPaykitEnabled.value = true + + sut.showSheet(Sheet.Send()) + advanceUntilIdle() + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AddressContinue(input, suppressQuickPay = true, isNearbyRead = true)) + advanceUntilIdle() + assertTrue(entered.isCompleted) + sut.setSendEvent(SendEvent.Contacts) + advanceUntilIdle() + assertEquals(SendEffect.NavigateToContacts, awaitItem()) + + release.complete(Unit) + advanceUntilIdle() + + expectNoEvents() + cancelAndIgnoreRemainingEvents() + } + } + + @Test + fun `nfc read still preparing does not reopen send after the sheet closes`() = test { + val input = stubOnchainAmountScan(amountSats = 10_000u) + val entered = CompletableDeferred() + val release = CompletableDeferred() + whenever { blocktankRepo.refreshInfo() }.doSuspendableAnswer { + entered.complete(Unit) + release.await() + Result.success(Unit) + } + + sut.showSheet(Sheet.Send()) + advanceUntilIdle() + sut.setSendEvent(SendEvent.AddressContinue(input, isNearbyRead = true)) + advanceUntilIdle() + assertTrue(entered.isCompleted) + sut.hideSheet() + advanceUntilIdle() + + release.complete(Unit) + advanceUntilIdle() + + assertNull(sut.currentSheet.value) + verify(coreService, never()).decode(input) + } + + @Test + fun `read from the send scanner still preparing does not reopen send after the sheet closes`() = test { + val bolt11 = "lnbcrt1nestedscanner" + enableQuickPay() + stubLightningScan(bolt11 = bolt11, amountSats = 500u) + val entered = CompletableDeferred() + val release = CompletableDeferred() + whenever { blocktankRepo.refreshInfo() }.doSuspendableAnswer { + entered.complete(Unit) + release.await() + Result.success(Unit) + } + + sut.showSheet(Sheet.Send()) + advanceUntilIdle() + sut.onScanResult(bolt11, routePubkyKeys = true, fromSendScanner = true) + advanceUntilIdle() + assertTrue(entered.isCompleted) + sut.hideSheet() + advanceUntilIdle() + + release.complete(Unit) + advanceUntilIdle() + + assertNull(sut.currentSheet.value) + assertNull(sut.quickPayData.value) + verify(coreService, never()).decode(bolt11) + } + + @Test + fun `login request from the send scanner opens its sheet`() = test { + val lnurl = "lnurl1sendscannerauth" + val data = com.synonym.bitkitcore.LnurlAuthData(uri = lnurl, tag = "login", k1 = "k1", domain = "example.com") + // Decoding suspends, as it does on device, so the scan is still running once its handle is kept. + val decoded = CompletableDeferred() + whenever { coreService.decode(lnurl) }.doSuspendableAnswer { + decoded.await() + Scanner.LnurlAuth(data) + } + sut.setIsAuthenticated(true) + advanceUntilIdle() + + sut.showSheet(Sheet.Send()) + advanceUntilIdle() + sut.onScanResult(lnurl, routePubkyKeys = true, fromSendScanner = true) + advanceUntilIdle() + decoded.complete(Unit) + advanceUntilIdle() + + assertEquals(Sheet.LnurlAuth(domain = "example.com", lnurl = lnurl, k1 = "k1"), sut.currentSheet.value) + } + + @Test + fun `existing contact scanned from the send scanner still refreshes its Paykit receivers`() = test { + enablePaykitUi() + pubkyContacts.value = listOf(PubkyProfile.placeholder(testPublicKey)) + var refreshedWhileActive = false + whenever { refreshContactPaykitLink(any()) }.doSuspendableAnswer { + refreshedWhileActive = kotlinx.coroutines.currentCoroutineContext()[Job]?.isActive == true + Result.success(Unit) + } + sut.setIsAuthenticated(true) + sut.showSheet(Sheet.Send()) + advanceUntilIdle() + + // The delay stands in for the suspension before routing, so the scan's handle is kept as on device. + sut.onScanResult(testPublicKey, startDelay = 1.seconds, routePubkyKeys = true, fromSendScanner = true) + advanceUntilIdle() + + assertTrue(refreshedWhileActive) + } + + @Test + fun `second bluetooth read does not replace the first one still preparing`() = test { + val first = stubOnchainAmountScan(amountSats = 10_000u) + val second = "bitcoin:$REGTEST_ADDRESS?amount=0.0002" + val entered = CompletableDeferred() + val release = CompletableDeferred() + whenever(coreService.decode(first)).doSuspendableAnswer { + entered.complete(Unit) + release.await() + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 10_000u, null, null, null)) + } + + sut.showSheet(Sheet.Send()) + advanceUntilIdle() + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AddressContinue(first, suppressQuickPay = true, isNearbyRead = true)) + advanceUntilIdle() + assertTrue(entered.isCompleted) + sut.setSendEvent(SendEvent.AddressContinue(second, suppressQuickPay = true, isNearbyRead = true)) + advanceUntilIdle() + + release.complete(Unit) + advanceUntilIdle() + + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + cancelAndIgnoreRemainingEvents() + } + assertEquals(10_000uL, sut.sendUiState.value.amount) + verify(coreService, never()).decode(second) + } + + @Test + fun `bluetooth read does not replace a scanned request still preparing`() = test { + val scanned = stubOnchainAmountScan(amountSats = 10_000u) + val nearby = "bitcoin:$REGTEST_ADDRESS?amount=0.0002" + val entered = CompletableDeferred() + val release = CompletableDeferred() + whenever(coreService.decode(scanned)).doSuspendableAnswer { + entered.complete(Unit) + release.await() + Scanner.OnChain(OnChainInvoice(REGTEST_ADDRESS, 10_000u, null, null, null)) + } + + sut.showSheet(Sheet.Send()) + advanceUntilIdle() + sut.sendEffect.test { + sut.setSendEvent(SendEvent.AddressContinue(scanned)) + advanceUntilIdle() + assertTrue(entered.isCompleted) + sut.setSendEvent(SendEvent.AddressContinue(nearby, suppressQuickPay = true, isNearbyRead = true)) + advanceUntilIdle() + + release.complete(Unit) + advanceUntilIdle() + + assertEquals(SendEffect.NavigateToConfirm, awaitItem()) + cancelAndIgnoreRemainingEvents() + } + assertEquals(10_000uL, sut.sendUiState.value.amount) + verify(coreService, never()).decode(nearby) + } + @Test fun `hardware send sheet onchain address with payable amount estimates its fee and opens confirm`() = test { val input = stubOnchainAmountScan(amountSats = 10_000u) @@ -10072,6 +10389,47 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(toastManager, never()).enqueue(any()) } + @Test + fun `lightning scan skips the channel wait when spark covers the amount and the node is stopped`() = test { + val input = "lnbcrt1sparkscan" + stubLightningScan(bolt11 = input, amountSats = 500u) + whenever(lightningRepo.canSendWithSpark(500u)).thenReturn(true) + sut.setIsAuthenticated(true) + + sut.onScanResult(input) + advanceUntilIdle() + + verify(lightningRepo, never()).waitForUsableChannels() + } + + @Test + fun `lightning scan refreshes a running node's channels without waiting when spark covers the amount`() = test { + val input = "lnbcrt1runningscan" + stubLightningScan(bolt11 = input, amountSats = 500u) + whenever(lightningRepo.canSendWithSpark(500u)).thenReturn(true) + whenever(lightningRepo.lightningState) + .thenReturn(MutableStateFlow(LightningState(nodeLifecycleState = NodeLifecycleState.Running))) + sut.setIsAuthenticated(true) + + sut.onScanResult(input) + advanceUntilIdle() + + verify(lightningRepo).waitForUsableChannels(awaitUsable = false) + } + + @Test + fun `lightning scan waits for channels when spark does not cover the amount`() = test { + val input = "lnbcrt1ldkscan" + stubLightningScan(bolt11 = input, amountSats = 500u) + whenever(lightningRepo.canSendWithSpark(500u)).thenReturn(false) + sut.setIsAuthenticated(true) + + sut.onScanResult(input) + advanceUntilIdle() + + verify(lightningRepo).waitForUsableChannels() + } + @Test fun `lightning channel wait cannot continue during required recovery`() = test { val input = "lnbcrt1heldscan" @@ -10665,6 +11023,67 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(coreService).decode(bolt11) } + @Test + fun `scan still decoding when the wallet locks does not use QuickPay after unlocking`() = test { + val bolt11 = "lnbcrt1lockedmidscan" + enableQuickPay() + stubLightningScan(bolt11 = bolt11, amountSats = 500u) + val entered = CompletableDeferred() + val release = CompletableDeferred() + whenever { coreService.decode(bolt11) }.doSuspendableAnswer { + entered.complete(Unit) + release.await() + Scanner.Lightning(lightningInvoice(bolt11, 500u)) + } + sut.setIsAuthenticated(true) + advanceUntilIdle() + + sut.showScannerSheet() + sut.onScannerSheetResult(bolt11) + advanceUntilIdle() + assertTrue(entered.isCompleted) + sut.setIsAuthenticated(false) + advanceUntilIdle() + sut.setIsAuthenticated(true) + advanceUntilIdle() + + release.complete(Unit) + advanceUntilIdle() + + assertNull(sut.quickPayData.value) + assertEquals(Sheet.Send(SendRoute.Confirm), sut.currentSheet.value) + } + + @Test + fun `wallet locking during the QuickPay checks does not use QuickPay`() = test { + val bolt11 = "lnbcrt1lockedquickpaycheck" + enableQuickPay() + stubLightningScan(bolt11 = bolt11, amountSats = 500u) + val entered = CompletableDeferred() + val release = CompletableDeferred() + whenever { quickPayRepo.canApply(any()) }.doSuspendableAnswer { + entered.complete(Unit) + release.await() + Result.success(true) + } + sut.setIsAuthenticated(true) + advanceUntilIdle() + + sut.showScannerSheet() + sut.onScannerSheetResult(bolt11) + advanceUntilIdle() + assertTrue(entered.isCompleted) + sut.setIsAuthenticated(false) + advanceUntilIdle() + sut.setIsAuthenticated(true) + advanceUntilIdle() + + release.complete(Unit) + advanceUntilIdle() + + assertNull(sut.quickPayData.value) + } + @Test fun `payment deeplink is queued until authenticated when PIN is enabled`() = test { val bolt11 = "lnbcrt1lockeddeeplink" @@ -10682,6 +11101,87 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(Sheet.Send(SendRoute.Confirm), sut.currentSheet.value) } + @Test + fun `scan still decoding when the app locks on background does not use QuickPay after the PIN`() = test { + val bolt11 = "lnbcrt1backgroundlock" + enableQuickPay() + settingsData.value = settingsData.value.copy(isPinEnabled = true) + stubLightningScan(bolt11 = bolt11, amountSats = 500u) + val entered = CompletableDeferred() + val release = CompletableDeferred() + whenever { coreService.decode(bolt11) }.doSuspendableAnswer { + entered.complete(Unit) + release.await() + Scanner.Lightning(lightningInvoice(bolt11, 500u)) + } + advanceUntilIdle() + sut.setIsAuthenticated(true) + advanceUntilIdle() + + sut.showScannerSheet() + sut.onScannerSheetResult(bolt11) + advanceUntilIdle() + assertTrue(entered.isCompleted) + // The real lock: the app moves to the background, then the PIN screen unlocks it. + sut.lockOnBackground() + assertFalse(sut.isAuthenticated.value) + sut.setIsAuthenticated(true) + advanceUntilIdle() + + release.complete(Unit) + advanceUntilIdle() + + assertNull(sut.quickPayData.value) + assertEquals(Sheet.Send(SendRoute.Confirm), sut.currentSheet.value) + } + + @Test + fun `QuickPay published before the app locks on background does not start after the PIN`() = test { + val bolt11 = "lnbcrt1lockafterpublish" + enableQuickPay() + settingsData.value = settingsData.value.copy(isPinEnabled = true) + stubLightningScan(bolt11 = bolt11, amountSats = 500u) + advanceUntilIdle() + sut.setIsAuthenticated(true) + advanceUntilIdle() + + sut.showScannerSheet() + sut.onScannerSheetResult(bolt11) + advanceUntilIdle() + val request = assertNotNull(sut.quickPayData.value) + assertTrue(sut.canStartQuickPay(request)) + + // The QuickPay screen is still waiting (navigation, funds) when the app locks; the PIN then unlocks it. + sut.lockOnBackground() + assertFalse(sut.canStartQuickPay(request)) + sut.setIsAuthenticated(true) + advanceUntilIdle() + + assertFalse(sut.canStartQuickPay(request)) + } + + @Test + fun `QuickPay falling back to review leaves a fixed invoice ready to swipe`() = test { + val bolt11 = "lnbcrt1fallbacktoreview" + enableQuickPay() + stubLightningScan(bolt11 = bolt11, amountSats = 500u) + // The spending limit may not be published yet when QuickPay falls back. + balanceState.value = BalanceState(maxSendOnchainSats = 100_000u) + advanceUntilIdle() + + sut.showScannerSheet() + sut.onScannerSheetResult(bolt11) + advanceUntilIdle() + assertNotNull(sut.quickPayData.value) + + sut.fallBackFromQuickPay() + advanceUntilIdle() + + assertNull(sut.quickPayData.value) + assertEquals(500uL, sut.sendUiState.value.amount) + assertTrue(sut.sendUiState.value.isAmountInputValid, "Swipe to Pay needs a valid amount") + } + @Test fun `lockOnBackground requires auth when PIN is enabled`() = test { settingsData.value = SettingsData(isPinEnabled = true) @@ -21127,6 +21627,17 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } } + private fun nfcTagIntent(value: String): Intent { + val uri = mock { + on { toString() }.thenReturn(value) + on { scheme }.thenReturn(value.substringBefore(':')) + } + return mock { + on { action }.thenReturn(NfcAdapter.ACTION_NDEF_DISCOVERED) + on { data }.thenReturn(uri) + } + } + private fun samRockIntent(url: String): Intent { val uri = mock { on { toString() }.thenReturn(url) diff --git a/app/src/test/java/to/bitkit/viewmodels/QuickPayViewModelTest.kt b/app/src/test/java/to/bitkit/viewmodels/QuickPayViewModelTest.kt index 8c298a2767..f24e97fb5d 100644 --- a/app/src/test/java/to/bitkit/viewmodels/QuickPayViewModelTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/QuickPayViewModelTest.kt @@ -9,6 +9,7 @@ import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.kotlin.any +import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.times @@ -93,11 +94,13 @@ class QuickPayViewModelTest : BaseUnitTest() { sut.attach(session) val data = QuickPayData.Bolt11(sats = 500u, bolt11 = "lnbcrt1test") - sut.pay(session, data) + val canDispatch = { true } + sut.pay(session, data, canDispatch) verify(quickPayRepo).pay( - session, - QuickPayPayRequest.Bolt11(bolt11 = "lnbcrt1test", amountSats = 500u), + eq(session), + eq(QuickPayPayRequest.Bolt11(bolt11 = "lnbcrt1test", amountSats = 500u)), + eq(canDispatch), ) verify(quickPayRepo, never()).signalCompletion(any(), any(), any(), any(), any()) } @@ -112,7 +115,7 @@ class QuickPayViewModelTest : BaseUnitTest() { sut.pay(session, QuickPayData.Bolt11(sats = 500u, bolt11 = "lnbcrt1test")) sut.pay(session, QuickPayData.Bolt11(sats = 500u, bolt11 = "lnbcrt1test")) - verify(quickPayRepo, never()).pay(any(), any()) + verify(quickPayRepo, never()).pay(any(), any(), any()) } @Test @@ -125,8 +128,9 @@ class QuickPayViewModelTest : BaseUnitTest() { sut.pay(session, data) verify(quickPayRepo, times(1)).pay( - session, - QuickPayPayRequest.Bolt11(bolt11 = "lnbcrt1test", amountSats = 500u), + eq(session), + eq(QuickPayPayRequest.Bolt11(bolt11 = "lnbcrt1test", amountSats = 500u)), + any(), ) } @@ -141,12 +145,14 @@ class QuickPayViewModelTest : BaseUnitTest() { sut.pay(second, data) verify(quickPayRepo, times(1)).pay( - first, - QuickPayPayRequest.Bolt11(bolt11 = "lnbcrt1test", amountSats = 500u), + eq(first), + eq(QuickPayPayRequest.Bolt11(bolt11 = "lnbcrt1test", amountSats = 500u)), + any(), ) verify(quickPayRepo, times(1)).pay( - second, - QuickPayPayRequest.Bolt11(bolt11 = "lnbcrt1test", amountSats = 500u), + eq(second), + eq(QuickPayPayRequest.Bolt11(bolt11 = "lnbcrt1test", amountSats = 500u)), + any(), ) } @@ -178,8 +184,9 @@ class QuickPayViewModelTest : BaseUnitTest() { sut.pay(second, data) verify(quickPayRepo, times(1)).pay( - second, - QuickPayPayRequest.Bolt11(bolt11 = "lnbcrt1test", amountSats = 500u), + eq(second), + eq(QuickPayPayRequest.Bolt11(bolt11 = "lnbcrt1test", amountSats = 500u)), + any(), ) } diff --git a/app/src/test/java/to/bitkit/viewmodels/SettingsViewModelTest.kt b/app/src/test/java/to/bitkit/viewmodels/SettingsViewModelTest.kt index a12851e0a6..3827414161 100644 --- a/app/src/test/java/to/bitkit/viewmodels/SettingsViewModelTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/SettingsViewModelTest.kt @@ -4,6 +4,7 @@ import android.content.Context import app.cash.turbine.test import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.launch @@ -106,6 +107,17 @@ class SettingsViewModelTest : BaseUnitTest() { sut = createViewModel() } + @Test + fun `nearby payments stay off until the saved setting loads`() = test { + whenever(settingsStore.data).thenReturn(MutableSharedFlow()) + val viewModel = createViewModel() + + viewModel.isNearbyPaymentsEnabled.test { + assertFalse(awaitItem()) + cancelAndIgnoreRemainingEvents() + } + } + @Test fun `disabling Paykit clears settings and removes published endpoints`() = test { isPaykitEnabled.value = true diff --git a/app/src/testDebug/java/to/bitkit/ui/utils/SheetDeepLinksTest.kt b/app/src/testDebug/java/to/bitkit/ui/utils/SheetDeepLinksTest.kt index 25dfeb981c..3df5c81b7b 100644 --- a/app/src/testDebug/java/to/bitkit/ui/utils/SheetDeepLinksTest.kt +++ b/app/src/testDebug/java/to/bitkit/ui/utils/SheetDeepLinksTest.kt @@ -90,7 +90,7 @@ class SheetDeepLinksTest : BaseUnitTest() { val qrScanner = SheetDeepLinks.sheetFor(Uri.parse("bitkit://screen/qr-scanner")) assertEquals(Sheet.ActivityTagSelector, tagSelector) - assertEquals(Sheet.QrScanner(), qrScanner) + assertEquals(Sheet.QrScanner(readsNearby = true), qrScanner) } @Test diff --git a/changelog.d/next/1883.added.md b/changelog.d/next/1883.added.md new file mode 100644 index 0000000000..655d6838ad --- /dev/null +++ b/changelog.d/next/1883.added.md @@ -0,0 +1 @@ +Pay by holding your phone near a payment terminal or another phone over NFC, and send or receive with nearby Bitkit wallets over Bluetooth. diff --git a/docs/nearby-payments.md b/docs/nearby-payments.md new file mode 100644 index 0000000000..f91d6f7f77 --- /dev/null +++ b/docs/nearby-payments.md @@ -0,0 +1,53 @@ +# Nearby payments (NFC and Bluetooth) + +Bitkit offers the payment request shown on the Receive screen to nearby phones, and its payment +scanners read requests from nearby phones and payment terminals. Both platforms implement the same +formats so Android and iOS interoperate. + +## NFC + +| Role | Android | iOS | +| --- | --- | --- | +| Read a tag (pay) | Reader mode while a payment scanner is open; `NDEF_DISCOVERED` when the app is closed | Core NFC NDEF session, started from the scanner | +| Be read (receive) | Host card emulation of an NFC Forum Type 4 tag while Receive is in the foreground | Not possible: Apple limits card emulation to licensed payment providers | + +- Tag content: one NDEF message with a single well-known URI record (`U`, identifier code `0x00`). + The URI is the Receive request with a scheme: `bitcoin:…` (BIP21, including `lightning=`), + `lightning:`, or the USDT `ethereum:` (EIP-681) request. +- Readers accept URI, Text (`T`) and absolute-URI records, and use the single distinct value found. +- Type 4 tag: NDEF application AID `D2760000850101`, capability container `E103`, NDEF file `E104`, + read-only. The emulated tag answers only while the Receive screen is in the foreground. +- Compatible tags and terminals: static `lightning:`/`bitcoin:`/LNURL tags, Numo and ZEUS tap-to-pay, + and (inferred, unverified) Square Register 2nd generation. Bolt Card terminals, which read an + `lnurlw` card, are not supported. + +## Bluetooth LE (v1) + +| Role | Android | iOS | +| --- | --- | --- | +| Read a request (pay) | GATT client while a payment scanner is open | CoreBluetooth central while a payment scanner is open | +| Serve a request (receive) | GATT server and advertiser while Receive is in the foreground | CoreBluetooth peripheral while Receive is in the foreground | + +Android and iOS interoperate in both directions; the iOS simulator has no Bluetooth, so iOS needs a device. + +The receiving phone is a GATT server; the paying phone is a central that connects to the closest +advertiser and reads the request. + +- Service UUID: `CB0E128B-1CA5-4959-94DF-A4FE588E3E98`, advertised alone, without a device name. +- Characteristics, all read-only: + - `69A713E5-B0A7-42F1-8B7F-FA0BDA119C00` (meta): 3 bytes, protocol version `0x01` then the + request length in bytes, unsigned 16-bit big-endian. + - `69A713E5-B0A7-42F1-8B7F-FA0BDA119C01` to `…9C08` (data 0 to 7): the UTF-8 request split into + chunks of 512 bytes; chunk `i` is bytes `[512 * i, 512 * (i + 1))`. Unused chunks are empty. + Reads honour the ATT read offset, so long reads return the whole chunk. +- Maximum request size: 4096 bytes. +- The request is the same URI as the NFC tag. +- Advertising runs only while the Receive screen is in the foreground and the nearby setting is on. +- Central: scans for the service UUID while a payment scanner is open, connects to the strongest + advertiser at or above -60 dBm, reads meta and the needed chunks, then disconnects. +- A request received over Bluetooth always opens the normal send review; QuickPay does not apply, + because Bluetooth range lets a device that is not the merchant's answer. +- Only `bitcoin:`, `lightning:` BOLT11 and USDT `ethereum:` requests are taken over Bluetooth. LNURL and + Lightning addresses (also as a unified URI's `lightning` part) are refused, since decoding them contacts + their server before the user picked the request. BOLT12 offers are refused because the decoder does not + read them. diff --git a/journeys/send/scanner-nearby-states.xml b/journeys/send/scanner-nearby-states.xml new file mode 100644 index 0000000000..a8b13603e0 --- /dev/null +++ b/journeys/send/scanner-nearby-states.xml @@ -0,0 +1,20 @@ + + + The Send sheet's scanner names the sources it listens on and offers to turn on the missing ones, + per the Figma "Send Bitcoin" scanner frames. Emulators have no NFC, so the NFC source and button + never appear here; Bluetooth comes from the emulator's virtual controller. Reading a request over + NFC or Bluetooth needs two devices and is a manual test in the PR. + + Precondition: onboarded dev build wallet on an emulator with Bluetooth on, camera and Nearby devices + permissions not yet granted (`adb shell pm revoke to.bitkit.dev android.permission.CAMERA`, + and the same for BLUETOOTH_SCAN, BLUETOOTH_ADVERTISE and BLUETOOTH_CONNECT). Start on the wallet home screen. + + + Tap Send and choose "Don't allow" on the camera permission dialog + Verify the scanner area reads "Scan to pay" and "Allow Camera, Bluetooth, and NFC access to scan bitcoin invoices and pay more quickly.", with a camera button (testTag "ScannerEnableCamera") and a Bluetooth button (testTag "ScannerEnableBluetooth") + Run `adb shell pm grant to.bitkit.dev android.permission.CAMERA`, close the Send sheet and tap Send again + Verify the camera preview shows the Bluetooth button (testTag "ScannerEnableBluetooth") above a pill (testTag "ScannerStatus") reading "Scanning QR" + Tap the Bluetooth button and choose "Allow" on the Nearby devices permission dialog + Verify the Bluetooth button is gone and the pill reads "Scanning QR & Bluetooth" + + diff --git a/journeys/settings/nearby-payments-toggle.xml b/journeys/settings/nearby-payments-toggle.xml new file mode 100644 index 0000000000..561cd98ff0 --- /dev/null +++ b/journeys/settings/nearby-payments-toggle.xml @@ -0,0 +1,16 @@ + + + Settings > General lists "Nearby payments" under Payments, on by default, and the choice survives + leaving Settings. The toggle decides whether Receive offers its request to nearby phones over + Bluetooth; that broadcast needs two Bluetooth devices and is a manual test in the PR. + + Precondition: onboarded dev build wallet that has not changed the setting, start on the wallet home screen. + + + Tap the menu button (testTag "HeaderMenu") and tap Settings + Scroll the General tab to the Payments section and verify the row "Nearby payments" (testTag "NearbyPaymentsSettings") shows its switch (testTag "NearbyPaymentsToggle") on + Tap the "Nearby payments" row and verify the switch turns off + Press back to leave Settings, open Settings again and verify "Nearby payments" is still off + Tap the "Nearby payments" row and verify the switch is on again + +