diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index b33c41b504..5d99d8eba0 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -554,6 +554,13 @@ dependencies {
implementation(libs.camera.view)
// Crypto
implementation(libs.bouncycastle.provider.jdk)
+ // Watch link: the shared protocol, the Wear Data Layer that carries it, and opening the watch app from here.
+ implementation(project(":wearlink"))
+ implementation(libs.play.services.wearable)
+ implementation(libs.wear.remote.interactions)
+ // The debug socket carrier and the in-process fakes; no release variant depends on them.
+ debugImplementation(testFixtures(project(":wearlink")))
+ testImplementation(testFixtures(project(":wearlink")))
testImplementation(libs.bouncycastle.pkix.jdk) // test certificates
implementation(libs.ldk.node.android) { exclude(group = "net.java.dev.jna", module = "jna") }
val localBitkitCoreAar = providers.gradleProperty("bitkitCoreAar").orNull
diff --git a/app/src/debug/java/to/bitkit/di/WatchLinkTransportModule.kt b/app/src/debug/java/to/bitkit/di/WatchLinkTransportModule.kt
new file mode 100644
index 0000000000..600656da85
--- /dev/null
+++ b/app/src/debug/java/to/bitkit/di/WatchLinkTransportModule.kt
@@ -0,0 +1,42 @@
+package to.bitkit.di
+
+import android.content.Context
+import dagger.Module
+import dagger.Provides
+import dagger.hilt.InstallIn
+import dagger.hilt.android.qualifiers.ApplicationContext
+import dagger.hilt.components.SingletonComponent
+import kotlinx.coroutines.CoroutineDispatcher
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.SupervisorJob
+import to.bitkit.utils.Logger
+import to.bitkit.watch.WatchDataLayerTransport
+import to.bitkit.wearlink.LinkTransport
+import to.bitkit.wearlink.testing.SocketLinkTransport
+import java.io.File
+import javax.inject.Singleton
+
+/**
+ * A debug build reaches the watch over the Wear Data Layer too, unless the file `files/wearlink-socket` exists in the
+ * app's data: then it connects to a loopback TCP port instead, which `adb reverse` and `adb forward` bridge to a
+ * watch emulator. That is how two emulators, which cannot pair over the Data Layer without a Google account, run the
+ * pairing journeys; `journeys/wear/README.md` has the setup. The socket carrier is not part of a release build.
+ */
+@Module
+@InstallIn(SingletonComponent::class)
+object WatchLinkTransportModule {
+ private const val TAG = "WatchLinkTransportModule"
+ private const val SOCKET_MARKER = "wearlink-socket"
+
+ @Provides
+ @Singleton
+ fun provideLinkTransport(
+ @ApplicationContext context: Context,
+ @IoDispatcher ioDispatcher: CoroutineDispatcher,
+ dataLayer: WatchDataLayerTransport,
+ ): LinkTransport {
+ if (!File(context.filesDir, SOCKET_MARKER).exists()) return dataLayer
+ Logger.warn("Using the debug socket link transport", context = TAG)
+ return SocketLinkTransport(isServer = false, scope = CoroutineScope(SupervisorJob() + ioDispatcher))
+ }
+}
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 9dbfa70c1d..8a52d967d5 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -94,6 +94,24 @@
android:resource="@xml/ndef_tag_service" />
+
+
+
+
+
+
+
+
+
+
+ /** Resolved at startup when pairing is on, so a settings change reaches the paired watch whoever made it. */
+ @Inject
+ lateinit var watchLinkRepo: Lazy
+
override val workManagerConfiguration
get() = Configuration.Builder()
.setWorkerFactory(workerFactory)
@@ -71,6 +76,7 @@ internal open class App : Application(), Configuration.Provider {
pubkyAuthHandlerRegistrar.start()
subscriptionClockOffsetSync.start()
observeAppForeground()
+ if (Env.isWatchLinkEnabled) watchLinkRepo.get()
}
private fun observeAppForeground() {
diff --git a/app/src/main/java/to/bitkit/data/WatchLinkStore.kt b/app/src/main/java/to/bitkit/data/WatchLinkStore.kt
new file mode 100644
index 0000000000..dd1ee81438
--- /dev/null
+++ b/app/src/main/java/to/bitkit/data/WatchLinkStore.kt
@@ -0,0 +1,73 @@
+package to.bitkit.data
+
+import android.content.Context
+import androidx.datastore.core.DataStore
+import androidx.datastore.dataStore
+import dagger.hilt.android.qualifiers.ApplicationContext
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.map
+import kotlinx.serialization.Serializable
+import to.bitkit.data.serializers.WatchLinkSerializer
+import to.bitkit.wearlink.Handshake
+import to.bitkit.wearlink.LinkRecord
+import to.bitkit.wearlink.LinkRecordStore
+import to.bitkit.wearlink.ThrottleState
+import to.bitkit.wearlink.ThrottleStore
+import java.security.SecureRandom
+import javax.inject.Inject
+import javax.inject.Singleton
+
+private val Context.watchLinkDataStore: DataStore by dataStore(
+ fileName = "watch_link.json",
+ serializer = WatchLinkSerializer,
+)
+
+/**
+ * The phone's note of its paired watch, this install's random id for pairings, and the count of seed transfers that
+ * were started and not finished. It belongs to the install and is in no backup: the link keys are in the Keystore
+ * and cannot be restored, so a restored phone pairs again. Nothing here is secret.
+ */
+@Singleton
+class WatchLinkStore internal constructor(
+ private val store: DataStore,
+) : LinkRecordStore {
+ @Inject
+ constructor(@ApplicationContext context: Context) : this(context.watchLinkDataStore)
+
+ override val record: Flow = store.data.map { it.record }.distinctUntilChanged()
+
+ override suspend fun load(): LinkRecord? = store.data.first().record
+
+ override suspend fun update(transform: (LinkRecord?) -> LinkRecord?): LinkRecord? =
+ store.updateData { it.copy(record = transform(it.record)) }.record
+
+ /** The count of unfinished seed transfers, kept across restarts so a restart does not clear it. */
+ val throttle: ThrottleStore = object : ThrottleStore {
+ override suspend fun load(): ThrottleState = store.data.first().let {
+ ThrottleState(it.transferAttempts, it.transferLockedUntilMs)
+ }
+
+ override suspend fun save(state: ThrottleState) {
+ store.updateData {
+ it.copy(transferAttempts = state.attempts, transferLockedUntilMs = state.lockedUntilMs)
+ }
+ }
+ }
+
+ /** This install's id for pairings, made at first use. */
+ @OptIn(ExperimentalStdlibApi::class)
+ suspend fun installId(): ByteArray = store.updateData {
+ if (it.installId != null) return@updateData it
+ it.copy(installId = ByteArray(Handshake.ID_BYTES).also(SecureRandom()::nextBytes).toHexString())
+ }.installId.orEmpty().hexToByteArray()
+}
+
+@Serializable
+data class WatchLinkData(
+ val record: LinkRecord? = null,
+ val installId: String? = null,
+ val transferAttempts: Int = 0,
+ val transferLockedUntilMs: Long = 0,
+)
diff --git a/app/src/main/java/to/bitkit/data/serializers/WatchLinkSerializer.kt b/app/src/main/java/to/bitkit/data/serializers/WatchLinkSerializer.kt
new file mode 100644
index 0000000000..7711c98fdb
--- /dev/null
+++ b/app/src/main/java/to/bitkit/data/serializers/WatchLinkSerializer.kt
@@ -0,0 +1,27 @@
+package to.bitkit.data.serializers
+
+import androidx.datastore.core.Serializer
+import to.bitkit.data.WatchLinkData
+import to.bitkit.di.json
+import to.bitkit.utils.Logger
+import java.io.InputStream
+import java.io.OutputStream
+
+object WatchLinkSerializer : Serializer {
+ private const val TAG = "WatchLinkSerializer"
+
+ override val defaultValue: WatchLinkData = WatchLinkData()
+
+ override suspend fun readFrom(input: InputStream): WatchLinkData {
+ return runCatching {
+ json.decodeFromString(input.readBytes().decodeToString())
+ }.getOrElse {
+ Logger.error("Failed to deserialize WatchLinkData", it, context = TAG)
+ defaultValue
+ }
+ }
+
+ override suspend fun writeTo(t: WatchLinkData, output: OutputStream) {
+ output.write(json.encodeToString(t).encodeToByteArray())
+ }
+}
diff --git a/app/src/main/java/to/bitkit/di/WatchLinkModule.kt b/app/src/main/java/to/bitkit/di/WatchLinkModule.kt
new file mode 100644
index 0000000000..5eed89d089
--- /dev/null
+++ b/app/src/main/java/to/bitkit/di/WatchLinkModule.kt
@@ -0,0 +1,17 @@
+package to.bitkit.di
+
+import dagger.Binds
+import dagger.Module
+import dagger.hilt.InstallIn
+import dagger.hilt.components.SingletonComponent
+import to.bitkit.watch.KeystoreLinkKeys
+import to.bitkit.wearlink.LinkKeyStore
+import javax.inject.Singleton
+
+@Module
+@InstallIn(SingletonComponent::class)
+abstract class WatchLinkModule {
+ @Binds
+ @Singleton
+ abstract fun bindLinkKeyStore(keys: KeystoreLinkKeys): LinkKeyStore
+}
diff --git a/app/src/main/java/to/bitkit/env/Env.kt b/app/src/main/java/to/bitkit/env/Env.kt
index d3d9b32703..da847dc946 100644
--- a/app/src/main/java/to/bitkit/env/Env.kt
+++ b/app/src/main/java/to/bitkit/env/Env.kt
@@ -28,6 +28,12 @@ internal data class LocalSparkSettings(val configBase64: String, val chainUrl: S
@Suppress("ConstPropertyName", "KotlinConstantConditions", "SimplifyBooleanWithConstants")
internal object Env {
+ /**
+ * Whether the phone offers pairing with a Wear OS watch. Off on mainnet for as long as the watch app is: two live
+ * Spark instances on one seed are not safe until the real-time sync server is on (#2152).
+ */
+ val isWatchLinkEnabled: Boolean get() = network != Network.BITCOIN
+
val isUsdtEnabled: Boolean get() = (network == Network.BITCOIN || isDebug) &&
usdtRpcUrl != null && usdtBundlerUrl.isNotBlank()
val usdtBundlerUrl: String get() = BuildConfig.USDT_BUNDLER_URL
diff --git a/app/src/main/java/to/bitkit/repositories/WatchLinkRepo.kt b/app/src/main/java/to/bitkit/repositories/WatchLinkRepo.kt
new file mode 100644
index 0000000000..950be8bb6f
--- /dev/null
+++ b/app/src/main/java/to/bitkit/repositories/WatchLinkRepo.kt
@@ -0,0 +1,395 @@
+package to.bitkit.repositories
+
+import android.content.Context
+import android.content.pm.PackageManager
+import android.os.Build
+import com.synonym.bitkitcore.mnemonicToSeed
+import dagger.hilt.android.qualifiers.ApplicationContext
+import io.ktor.client.HttpClient
+import io.ktor.client.plugins.timeout
+import io.ktor.client.request.prepareGet
+import io.ktor.client.statement.bodyAsChannel
+import io.ktor.http.contentLength
+import io.ktor.http.isSuccess
+import io.ktor.utils.io.readAvailable
+import kotlinx.coroutines.CoroutineDispatcher
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.CoroutineStart
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.ensureActive
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.collectLatest
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import to.bitkit.data.SettingsData
+import to.bitkit.data.SettingsStore
+import to.bitkit.data.WatchLinkStore
+import to.bitkit.data.keychain.Keychain
+import to.bitkit.di.IoDispatcher
+import to.bitkit.env.Env
+import to.bitkit.ext.nowMs
+import to.bitkit.ext.runSuspendCatching
+import to.bitkit.utils.AppError
+import to.bitkit.utils.Logger
+import to.bitkit.wearlink.AttestationPolicy
+import to.bitkit.wearlink.AttestationStatusList
+import to.bitkit.wearlink.AttestationVerifier
+import to.bitkit.wearlink.LinkCrypto
+import to.bitkit.wearlink.LinkKeyStore
+import to.bitkit.wearlink.LinkNode
+import to.bitkit.wearlink.LinkPacket
+import to.bitkit.wearlink.LinkRecord
+import to.bitkit.wearlink.LinkTransport
+import to.bitkit.wearlink.PairingState
+import to.bitkit.wearlink.PairingThrottle
+import to.bitkit.wearlink.PhoneLink
+import to.bitkit.wearlink.PhonePairing
+import to.bitkit.wearlink.PhonePairingEnv
+import to.bitkit.wearlink.SeedPayload
+import to.bitkit.wearlink.SettingsDoc
+import to.bitkit.wearlink.WalletLink
+import java.io.ByteArrayOutputStream
+import javax.inject.Inject
+import javax.inject.Singleton
+import kotlin.time.Clock
+import kotlin.time.Duration.Companion.seconds
+import kotlin.time.ExperimentalTime
+
+/**
+ * The phone's link to a Wear OS watch running Bitkit: the pairing ceremony's phone side, the settings it pushes to
+ * the paired watch, and removing the watch. The protocol itself is in `:wearlink`; this class gives it the phone's
+ * wallet, Keystore and stores. `docs/wear.md`, Pairing, describes the whole.
+ *
+ * A watch that already holds this wallet pairs by proving it. A watch without a wallet is sent the recovery phrase,
+ * and only after every one of these: the app has a PIN, the watch's key attestation was verified and none of its
+ * certificates is on Google's list of revoked ones (a debug build alone may skip those two, for the emulators), both
+ * users confirmed the same code, and the phone's user passed the app's PIN or biometric check. The phrase is read
+ * from the keychain at that point and not before. A phone without a PIN still pairs with a watch that holds its
+ * wallet and pushes it the settings: nothing secret is sent then.
+ *
+ * The phone's settings are published to the paired watch when the pairing is made and whenever one of them changes.
+ * This is the one place that feeds the watch: a later source of the same state, such as a backup both devices can
+ * read, would publish the same documents without the watch's readers changing.
+ */
+@OptIn(ExperimentalTime::class)
+@Singleton
+class WatchLinkRepo internal constructor(
+ private val ioDispatcher: CoroutineDispatcher,
+ private val transport: LinkTransport,
+ private val keys: LinkKeyStore,
+ private val store: WatchLinkStore,
+ private val keychain: Keychain,
+ private val settingsStore: SettingsStore,
+ private val clock: Clock,
+ private val appId: String,
+ private val signingDigests: () -> Set,
+ private val isUnverifiedTransferAllowed: Boolean,
+ private val toSeed: (String, String?) -> ByteArray,
+ private val fetchStatusList: suspend () -> ByteArray,
+) {
+ companion object {
+ private const val TAG = "WatchLinkRepo"
+
+ /** How long reading Google's attestation status list may take. */
+ private val STATUS_TIMEOUT = 10.seconds
+
+ private const val READ_BUFFER_BYTES = 8 * 1024
+
+ /**
+ * Reads Google's attestation status list: one GET of a public file that is the same for everyone. The
+ * request names no user, wallet or watch. A response longer than the list may be is refused by its
+ * declared length, and otherwise as soon as that much of it was read.
+ */
+ private suspend fun fetchStatusList(httpClient: HttpClient): ByteArray {
+ val request = httpClient.prepareGet(AttestationStatusList.URL) {
+ timeout { requestTimeoutMillis = STATUS_TIMEOUT.inWholeMilliseconds }
+ }
+ return request.execute { response ->
+ if (!response.status.isSuccess()) {
+ throw WatchLinkError.StatusList("Server returned '${response.status}'")
+ }
+ val maxBytes = AttestationStatusList.MAX_BYTES
+ if ((response.contentLength() ?: 0) > maxBytes) throw WatchLinkError.StatusList("Response too long")
+ val channel = response.bodyAsChannel()
+ val body = ByteArrayOutputStream()
+ val buffer = ByteArray(READ_BUFFER_BYTES)
+ while (true) {
+ val read = channel.readAvailable(buffer)
+ if (read < 0) break
+ body.write(buffer, 0, read)
+ if (body.size() > maxBytes) throw WatchLinkError.StatusList("Response too long")
+ }
+ body.toByteArray()
+ }
+ }
+
+ /** The SHA-256 digests of the certificates that signed this app, which also sign the watch app. */
+ @OptIn(ExperimentalStdlibApi::class)
+ private fun signingDigests(context: Context): Set {
+ val flags = PackageManager.GET_SIGNING_CERTIFICATES
+ val signers = context.packageManager.getPackageInfo(context.packageName, flags)
+ .signingInfo?.apkContentsSigners.orEmpty()
+ return signers.map { LinkCrypto.sha256(it.toByteArray()).toHexString() }.toSet()
+ }
+ }
+
+ @Inject
+ constructor(
+ @ApplicationContext context: Context,
+ @IoDispatcher ioDispatcher: CoroutineDispatcher,
+ transport: LinkTransport,
+ keys: LinkKeyStore,
+ store: WatchLinkStore,
+ keychain: Keychain,
+ settingsStore: SettingsStore,
+ clock: Clock,
+ httpClient: HttpClient,
+ ) : this(
+ ioDispatcher = ioDispatcher,
+ transport = transport,
+ keys = keys,
+ store = store,
+ keychain = keychain,
+ settingsStore = settingsStore,
+ clock = clock,
+ appId = context.packageName,
+ signingDigests = { signingDigests(context) },
+ isUnverifiedTransferAllowed = Env.isDebug && Env.isWatchLinkEnabled,
+ toSeed = ::mnemonicToSeed,
+ fetchStatusList = { fetchStatusList(httpClient) },
+ )
+
+ private val scope = CoroutineScope(SupervisorJob() + ioDispatcher)
+
+ private val link = PhoneLink(
+ transport = transport,
+ keys = keys,
+ store = store,
+ onSettingsMissed = { scope.launch { publishSettings(settingsStore.data.first().toWatchSettings()) } },
+ nowMs = { clock.nowMs() },
+ )
+
+ /** The paired watch, or null. */
+ val record: Flow = store.record
+
+ private val _pairing = MutableStateFlow(WatchPairingStatus.Idle)
+ val pairing: StateFlow = _pairing.asStateFlow()
+
+ private val lock = Any()
+ private var job: Job? = null
+ private var session: PhonePairing? = null
+ private var isEnding = false
+ private var isRestartPending = false
+
+ init {
+ transport.attach(::onPacket)
+ scope.launch { publishSettingsOnChange() }
+ }
+
+ /** The watches connected to this phone, with whether each has Bitkit and is reached directly. */
+ suspend fun watches(): Result> = withContext(ioDispatcher) {
+ runSuspendCatching { transport.nodes() }
+ .onFailure { Logger.warn("Failed to list the connected watches", it, context = TAG) }
+ }
+
+ /**
+ * Starts a pairing with the connected watch that has Bitkit and is reached directly, never through the cloud.
+ * One pairing runs at a time; its progress and its end show in [pairing]. While a cancelled one is still ending,
+ * the new one starts as soon as it has, and the cancelled one's end is not shown.
+ */
+ fun startPairing(): Unit = synchronized(lock) {
+ if (job != null && !isEnding) return
+ _pairing.update { WatchPairingStatus.Running(PairingState.Connecting) }
+ if (job != null) {
+ isRestartPending = true
+ return
+ }
+ var status: WatchPairingStatus = WatchPairingStatus.Idle
+ // Started only once it is noted, so a cancel always finds it, also before it found the watch.
+ val pairing = scope.launch(start = CoroutineStart.LAZY) {
+ val result = runSuspendCatching { pair() }
+ result.onFailure { Logger.warn("Failed to pair with the watch", it, context = TAG) }
+ status = result.fold(
+ onSuccess = { WatchPairingStatus.Paired },
+ onFailure = { WatchPairingStatus.Failed(it) },
+ )
+ }
+ job = pairing
+ // Runs however the job ends, also when a cancel overtakes its start and its body never runs.
+ pairing.invokeOnCompletion { onPairingEnd(status) }
+ pairing.start()
+ }
+
+ private suspend fun pair() = coroutineScope {
+ val node = transport.nodes().firstOrNull { it.hasApp && it.isNearby } ?: throw WatchLinkError.NoWatch()
+ val pairing = synchronized(lock) {
+ ensureActive()
+ PhonePairing(transport, link.pairingPackets, node, PairingEnv()).also { session = it }
+ }
+ val progress = launch {
+ pairing.state.collect { state -> showProgress(pairing, state) }
+ }
+ try {
+ link.onPaired(pairing.run())
+ } finally {
+ progress.cancel()
+ }
+ }
+
+ private fun showProgress(pairing: PhonePairing, state: PairingState) = synchronized(lock) {
+ if (session === pairing && !isEnding) _pairing.update { WatchPairingStatus.Running(state) }
+ }
+
+ private fun onPairingEnd(status: WatchPairingStatus) = synchronized(lock) {
+ job = null
+ session = null
+ isEnding = false
+ if (!isRestartPending) {
+ _pairing.update { status }
+ return@synchronized
+ }
+ isRestartPending = false
+ startPairing()
+ }
+
+ /**
+ * The user says [code], the one the sheet showed, matches the watch's. It confirms only the pairing that shows
+ * that code now, so never one the user has not seen. [isAuthenticated] is whether the user just passed the
+ * app's PIN or biometric check; without it no wallet is sent. It only counts on a phone that has a PIN, which
+ * is the one check there is to pass.
+ */
+ suspend fun confirmPairing(code: String, isAuthenticated: Boolean) {
+ val isChecked = isAuthenticated && isPinSet()
+ synchronized(lock) { if (!isEnding) session?.confirm(code, isChecked) }
+ }
+
+ /**
+ * Ends the pairing that runs, as when its screen goes away, and forgets the last one's end. A pairing that has
+ * not found the watch yet ends without opening anything on it.
+ */
+ fun cancelPairing(): Unit = synchronized(lock) {
+ isRestartPending = false
+ val running = job
+ if (running == null) {
+ _pairing.update { WatchPairingStatus.Idle }
+ return
+ }
+ isEnding = true
+ session?.cancel() ?: running.cancel()
+ }
+
+ private suspend fun isPinSet(): Boolean = settingsStore.data.first().isPinEnabled
+
+ /**
+ * Asks the watch to forget this phone, and with [isErase] to delete its wallet. The watch stays listed, marked,
+ * until it acknowledges: an erase is best effort, since a watch that never reconnects never reads it.
+ */
+ suspend fun remove(isErase: Boolean): Result = withContext(ioDispatcher) {
+ runSuspendCatching { link.remove(isErase) }
+ .onFailure { Logger.warn("Failed to remove the watch", it, context = TAG) }
+ }
+
+ /**
+ * Drops the pairing on the phone without waiting for the watch: a removal the user stopped waiting for, or this
+ * phone's wallet being wiped or replaced. The watch is told to unpair; it is never erased by this.
+ */
+ suspend fun forget(): Result = withContext(ioDispatcher) {
+ runSuspendCatching { link.forget() }
+ .onFailure { Logger.warn("Failed to forget the watch", it, context = TAG) }
+ }
+
+ private suspend fun onPacket(packet: LinkPacket) {
+ if (!Env.isWatchLinkEnabled) return
+ runSuspendCatching { link.onPacket(packet) }
+ .onFailure { Logger.debug("Dropped a packet at '${packet.path}': '${it.message}'", context = TAG) }
+ }
+
+ private suspend fun publishSettingsOnChange() {
+ val pairing = store.record.map { record -> record?.pairingId?.takeIf { record.removal == null } }
+ val settings = settingsStore.data.map { it.toWatchSettings() }
+ combine(pairing.distinctUntilChanged(), settings.distinctUntilChanged()) { pairingId, current ->
+ current.takeIf { pairingId != null }
+ }.collectLatest { settings -> settings?.let { publishSettings(it) } }
+ }
+
+ private suspend fun publishSettings(settings: SettingsDoc) {
+ runSuspendCatching { link.publishSettings(settings.copy(changedAtMs = clock.nowMs())) }
+ .onSuccess { Logger.info("Published the settings to the watch", context = TAG) }
+ .onFailure { Logger.warn("Failed to publish the settings to the watch", it, context = TAG) }
+ }
+
+ private fun SettingsData.toWatchSettings() = SettingsDoc(
+ primaryDisplay = primaryDisplay.name,
+ displayUnit = displayUnit.name,
+ selectedCurrency = selectedCurrency,
+ isQuickPayEnabled = isQuickPayEnabled,
+ quickPayAmount = quickPayAmount,
+ quickPayDailyLimitMultiplier = quickPayDailyLimitMultiplier,
+ )
+
+ private inner class PairingEnv : PhonePairingEnv {
+ override val appId: String = this@WatchLinkRepo.appId
+ override val name: String = Build.MODEL.orEmpty()
+ override val verifier = AttestationVerifier(
+ AttestationPolicy(packageName = appId, signingDigests = signingDigests(), nowMs = { clock.nowMs() }),
+ )
+ override val isUnverifiedTransferAllowed: Boolean = this@WatchLinkRepo.isUnverifiedTransferAllowed
+ override val throttle = PairingThrottle(store.throttle) { clock.nowMs() }
+ override val keys: LinkKeyStore = this@WatchLinkRepo.keys
+
+ override suspend fun phoneId(): ByteArray = store.installId()
+
+ override suspend fun isPinSet(): Boolean = this@WatchLinkRepo.isPinSet()
+
+ override suspend fun attestationStatus(): AttestationStatusList? = withContext(ioDispatcher) {
+ runSuspendCatching { AttestationStatusList.parse(fetchStatusList()) }
+ .onFailure { Logger.warn("Failed to read the attestation status list", it, context = TAG) }
+ .getOrNull()
+ }
+
+ override suspend fun walletSecret(): ByteArray = withContext(ioDispatcher) {
+ val seed = toSeed(mnemonic(), passphrase())
+ WalletLink.secret(seed, Env.network.name).also { seed.fill(0) }
+ }
+
+ override suspend fun seed(): SeedPayload = withContext(ioDispatcher) {
+ SeedPayload(Env.network.name, mnemonic(), passphrase())
+ }
+
+ private fun mnemonic(): String =
+ keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name) ?: throw WatchLinkError.NoWallet()
+
+ private fun passphrase(): String? = keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name)
+ }
+}
+
+/** Where the phone's side of a pairing stands. */
+sealed interface WatchPairingStatus {
+ data object Idle : WatchPairingStatus
+
+ data class Running(val state: PairingState) : WatchPairingStatus
+
+ data object Paired : WatchPairingStatus
+
+ data class Failed(val error: Throwable) : WatchPairingStatus
+}
+
+sealed class WatchLinkError(message: String) : AppError(message) {
+ /** No connected watch has Bitkit and is reached directly. */
+ class NoWatch : WatchLinkError("No watch with Bitkit is connected nearby")
+
+ class NoWallet : WatchLinkError("The phone holds no wallet")
+
+ /** Google's attestation status list was not served. */
+ class StatusList(message: String) : WatchLinkError(message)
+}
diff --git a/app/src/main/java/to/bitkit/ui/ContentView.kt b/app/src/main/java/to/bitkit/ui/ContentView.kt
index 8ec94ab942..0b0f1eae6d 100644
--- a/app/src/main/java/to/bitkit/ui/ContentView.kt
+++ b/app/src/main/java/to/bitkit/ui/ContentView.kt
@@ -250,6 +250,7 @@ import to.bitkit.ui.sheets.UpdateSheet
import to.bitkit.ui.sheets.UsdtIntroSheet
import to.bitkit.ui.sheets.WidgetsSheet
import to.bitkit.ui.sheets.hardware.HardwareSheet
+import to.bitkit.ui.sheets.watch.WatchSheet
import to.bitkit.ui.theme.Colors
import to.bitkit.ui.utils.AutoReadClipboardHandler
import to.bitkit.ui.utils.RequestNotificationPermissions
@@ -731,6 +732,7 @@ fun ContentView(
viewModel = hiltViewModel(),
onDismiss = { appViewModel.hideSheet() },
)
+ Sheet.Watch -> WatchSheet(appViewModel)
Sheet.ConnectionClosed -> ConnectionClosedSheet(
onDismiss = { appViewModel.hideSheet() },
)
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 eeb05f9fdc..f504e7b5b0 100644
--- a/app/src/main/java/to/bitkit/ui/components/SheetHost.kt
+++ b/app/src/main/java/to/bitkit/ui/components/SheetHost.kt
@@ -99,6 +99,9 @@ sealed interface Sheet {
data object MoveToSpark : Sheet
data object ConnectionClosed : Sheet
data object TransferUnavailable : Sheet
+
+ /** The Wear OS watch: pairing it, its state, unpairing and erasing it. */
+ data object Watch : Sheet
data class BTCPayConnection(
val setup: SamRockSetupRequest,
val isConnecting: Boolean = false,
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 afce021f0d..e4a5b0f3ef 100644
--- a/app/src/main/java/to/bitkit/ui/settings/SettingsScreen.kt
+++ b/app/src/main/java/to/bitkit/ui/settings/SettingsScreen.kt
@@ -61,6 +61,7 @@ import to.bitkit.ui.screens.wallets.HwWalletViewModel
import to.bitkit.ui.screens.wallets.activity.components.CustomTabRowWithSpacing
import to.bitkit.ui.screens.wallets.activity.components.TabItem
import to.bitkit.ui.settingsViewModel
+import to.bitkit.ui.sheets.watch.WatchSheetViewModel
import to.bitkit.ui.theme.AppThemeSurface
import to.bitkit.ui.utils.rememberBiometricAuthSupported
import to.bitkit.viewmodels.LanguageViewModel
@@ -80,6 +81,7 @@ fun SettingsScreen(
advancedViewModel: AdvancedSettingsViewModel = hiltViewModel(),
languageViewModel: LanguageViewModel = hiltViewModel(),
hwWalletViewModel: HwWalletViewModel = hiltViewModel(),
+ watchViewModel: WatchSheetViewModel? = if (Env.isWatchLinkEnabled) hiltViewModel() else null,
) {
val app = appViewModel ?: return
val settings = settingsViewModel ?: return
@@ -100,6 +102,7 @@ fun SettingsScreen(
val isUsdtEnabled by settings.isUsdtEnabled.collectAsStateWithLifecycle()
val isUpdatingUsdt by settings.isUpdatingUsdt.collectAsStateWithLifecycle()
val hardwareWallets by hwWalletViewModel.wallets.collectAsStateWithLifecycle()
+ val watchState = watchViewModel?.uiState?.collectAsStateWithLifecycle()?.value
val languageUiState by languageViewModel.uiState.collectAsStateWithLifecycle()
// Security tab state
@@ -137,6 +140,7 @@ fun SettingsScreen(
notificationsGranted = notificationsGranted,
isNearbyPaymentsEnabled = isNearbyPaymentsEnabled,
hardwareWalletCount = hardwareWallets.size,
+ pairedWatchName = watchState?.paired?.name,
isUsdtEnabled = isUsdtEnabled,
canDisableUsdt = canDisableUsdt,
isUpdatingUsdt = isUpdatingUsdt,
@@ -180,6 +184,7 @@ fun SettingsScreen(
}
}
SettingsEvent.HardwareWalletsClick -> navController.navigateTo(Routes.HardwareWalletsSettings)
+ SettingsEvent.WatchClick -> app.showSheet(Sheet.Watch)
SettingsEvent.BackupWalletClick -> app.showSheet(Sheet.Backup())
SettingsEvent.DataBackupsClick -> navController.navigateTo(Routes.BackupSettings)
SettingsEvent.ResetWalletClick ->
@@ -382,6 +387,17 @@ private fun GeneralTabContent(
onClick = { onEvent(SettingsEvent.HardwareWalletsClick) },
modifier = Modifier.testTag("HardwareWalletsSettings")
)
+ if (Env.isWatchLinkEnabled) {
+ SettingsButtonRow(
+ title = stringResource(R.string.settings__watch__nav_title),
+ icon = { SettingsIcon(R.drawable.ic_watch) },
+ value = SettingsButtonValue.StringValue(
+ state.pairedWatchName ?: stringResource(R.string.settings__watch__not_paired),
+ ),
+ onClick = { onEvent(SettingsEvent.WatchClick) },
+ modifier = Modifier.testTag("PairedWatchSettings")
+ )
+ }
SettingsSwitchRow(
title = stringResource(R.string.settings__nearby__title),
subtitle = stringResource(R.string.settings__nearby__subtitle),
@@ -695,6 +711,7 @@ sealed interface SettingsEvent {
data object QuickPayClick : SettingsEvent
data object BgPaymentsClick : SettingsEvent
data object HardwareWalletsClick : SettingsEvent
+ data object WatchClick : SettingsEvent
// Security
data object BackupWalletClick : SettingsEvent
@@ -738,6 +755,7 @@ data class GeneralTabState(
val notificationsGranted: Boolean = false,
val isNearbyPaymentsEnabled: Boolean = true,
val hardwareWalletCount: Int = 0,
+ val pairedWatchName: String? = null,
val isUsdtEnabled: Boolean = false,
val canDisableUsdt: Boolean = false,
val isUpdatingUsdt: Boolean = false,
diff --git a/app/src/main/java/to/bitkit/ui/sheets/watch/WatchSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/watch/WatchSheet.kt
new file mode 100644
index 0000000000..75b98112f8
--- /dev/null
+++ b/app/src/main/java/to/bitkit/ui/sheets/watch/WatchSheet.kt
@@ -0,0 +1,494 @@
+package to.bitkit.ui.sheets.watch
+
+import androidx.activity.compose.BackHandler
+import androidx.annotation.DrawableRes
+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.ColumnScope
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.navigationBarsPadding
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+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.text.style.TextAlign
+import androidx.compose.ui.tooling.preview.Preview
+import androidx.compose.ui.unit.dp
+import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.compose.LocalLifecycleOwner
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import androidx.lifecycle.repeatOnLifecycle
+import kotlinx.coroutines.delay
+import to.bitkit.R
+import to.bitkit.ui.components.AuthCheckView
+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.SecondaryButton
+import to.bitkit.ui.components.SheetSize
+import to.bitkit.ui.components.Title
+import to.bitkit.ui.components.VerticalSpacer
+import to.bitkit.ui.scaffold.AppAlertDialog
+import to.bitkit.ui.scaffold.SheetTopBar
+import to.bitkit.ui.settingsViewModel
+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.viewmodels.AppViewModel
+import to.bitkit.wearlink.KeyLevel
+import kotlin.time.Duration.Companion.seconds
+
+/** How often the sheet looks for a connected watch while it has none to pair. */
+private val REFRESH_INTERVAL = 3.seconds
+
+/**
+ * Everything about the Wear OS watch in one sheet, opened from Settings › General › Watch. It shows the connected
+ * watch with Pair, or what is missing; then the pairing: one code on both screens, the app's PIN or biometric check
+ * when confirming sends the watch this phone's wallet, the transfer, and its end; and for a paired watch its state
+ * with Unpair and Erase. A phone without a PIN sends no wallet: that pairing ends on a line that says to set one.
+ * A pairing under way is cancelled when the sheet closes, unless the wallet is already on its way.
+ */
+@Composable
+fun WatchSheet(
+ app: AppViewModel,
+ viewModel: WatchSheetViewModel = hiltViewModel(),
+) {
+ val settings = settingsViewModel ?: return
+ val uiState by viewModel.uiState.collectAsStateWithLifecycle()
+ val isWaitingForWatch = uiState.pairing == null && uiState.paired == null
+
+ LaunchedEffect(viewModel) { viewModel.onSheetOpen() }
+ val lifecycleOwner = LocalLifecycleOwner.current
+ LaunchedEffect(viewModel, isWaitingForWatch, lifecycleOwner) {
+ if (!isWaitingForWatch) return@LaunchedEffect
+ // Only while the app shows: nothing looks for a watch from the background.
+ lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
+ while (true) {
+ delay(REFRESH_INTERVAL)
+ viewModel.refresh()
+ }
+ }
+ }
+ DisposableEffect(viewModel) {
+ onDispose { viewModel.onSheetClose() }
+ }
+
+ Box {
+ Content(
+ uiState = uiState,
+ onPairClick = viewModel::onPairClick,
+ onPairClose = viewModel::onPairClose,
+ onPairConfirm = viewModel::onPairConfirm,
+ onUnpairClick = viewModel::onUnpairClick,
+ onEraseClick = viewModel::onEraseClick,
+ onStopWaitingClick = viewModel::onStopWaitingClick,
+ onDialogConfirm = viewModel::onDialogConfirm,
+ onDialogDismiss = viewModel::onDialogDismiss,
+ onDismiss = { app.hideSheet() },
+ )
+ if (uiState.isAuthShown) {
+ AuthCheckView(
+ appViewModel = app,
+ settingsViewModel = settings,
+ onSuccess = viewModel::onAuthSuccess,
+ onBack = viewModel::onAuthDismiss,
+ )
+ }
+ // Back leaves the check for the code; without this it would close the sheet and cancel the pairing.
+ BackHandler(enabled = uiState.isAuthShown, onBack = viewModel::onAuthDismiss)
+ }
+}
+
+@Suppress("LongParameterList")
+@Composable
+private fun Content(
+ uiState: WatchSheetUiState,
+ modifier: Modifier = Modifier,
+ onPairClick: () -> Unit = {},
+ onPairClose: () -> Unit = {},
+ onPairConfirm: () -> Unit = {},
+ onUnpairClick: () -> Unit = {},
+ onEraseClick: () -> Unit = {},
+ onStopWaitingClick: () -> Unit = {},
+ onDialogConfirm: () -> Unit = {},
+ onDialogDismiss: () -> Unit = {},
+ onDismiss: () -> Unit = {},
+) {
+ val pairing = uiState.pairing
+ val paired = uiState.paired
+ Column(
+ modifier = modifier
+ .sheetHeight(SheetSize.LARGE)
+ .gradientBackground()
+ .navigationBarsPadding()
+ .padding(horizontal = 16.dp)
+ .testTag("PairedWatchSheet")
+ ) {
+ SheetTopBar(
+ titleText = stringResource(
+ if (pairing == null) R.string.settings__watch__nav_title else R.string.settings__watch__pair_title,
+ ),
+ )
+ VerticalSpacer(16.dp)
+ when {
+ pairing != null -> Pairing(step = pairing, onClose = onPairClose, onConfirm = onPairConfirm)
+ paired != null -> Paired(
+ watch = paired,
+ onUnpairClick = onUnpairClick,
+ onEraseClick = onEraseClick,
+ onStopWaitingClick = onStopWaitingClick,
+ onDismiss = onDismiss,
+ )
+ else -> Unpaired(uiState = uiState, onPairClick = onPairClick)
+ }
+ VerticalSpacer(16.dp)
+ }
+
+ uiState.dialog?.let { dialog ->
+ val isErase = dialog == WatchRemoveDialog.Erase
+ AppAlertDialog(
+ title = stringResource(
+ if (isErase) R.string.settings__watch__erase_title else R.string.settings__watch__unpair_title,
+ ),
+ text = stringResource(
+ if (isErase) R.string.settings__watch__erase_text else R.string.settings__watch__unpair_text,
+ ),
+ confirmText = stringResource(
+ if (isErase) R.string.settings__watch__erase_confirm else R.string.settings__watch__unpair,
+ ),
+ confirmTextColor = if (isErase) Colors.Red else Colors.Brand,
+ onConfirm = onDialogConfirm,
+ onDismiss = onDialogDismiss,
+ modifier = Modifier.testTag("PairedWatchRemoveDialog")
+ )
+ }
+}
+
+@Composable
+private fun ColumnScope.Unpaired(
+ uiState: WatchSheetUiState,
+ onPairClick: () -> Unit,
+) {
+ val connected = uiState.connected
+ val text = when {
+ uiState.isLoading -> stringResource(R.string.settings__watch__looking)
+ connected == null -> stringResource(R.string.settings__watch__no_watch)
+ !connected.hasApp -> stringResource(R.string.settings__watch__no_app).replace("{name}", connected.name)
+ !connected.isNearby -> stringResource(R.string.settings__watch__error_unreachable)
+ else -> stringResource(R.string.settings__watch__ready).replace("{name}", connected.name)
+ }
+ BodyM(
+ text = text,
+ color = Colors.White64,
+ modifier = Modifier.testTag("PairedWatchStatus")
+ )
+ Illustration(R.drawable.phone)
+ PrimaryButton(
+ text = stringResource(R.string.settings__watch__pair_button),
+ onClick = onPairClick,
+ enabled = connected?.canPair == true,
+ modifier = Modifier
+ .fillMaxWidth()
+ .testTag("PairedWatchPair")
+ )
+}
+
+@Composable
+private fun ColumnScope.Paired(
+ watch: PairedWatch,
+ onUnpairClick: () -> Unit,
+ onEraseClick: () -> Unit,
+ onStopWaitingClick: () -> Unit,
+ onDismiss: () -> Unit,
+) {
+ Title(text = watch.name, modifier = Modifier.testTag("PairedWatchName"))
+ VerticalSpacer(16.dp)
+ BodyMSB(
+ text = stringResource(R.string.settings__watch__full_wallet),
+ modifier = Modifier.testTag("PairedWatchFullWallet")
+ )
+ VerticalSpacer(8.dp)
+ BodyM(
+ text = stringResource(
+ when (watch.keyLevel) {
+ KeyLevel.StrongBox -> R.string.settings__watch__key_strongbox
+ KeyLevel.TrustedEnvironment -> R.string.settings__watch__key_tee
+ null -> R.string.settings__watch__key_unverified
+ },
+ ),
+ color = Colors.White64,
+ modifier = Modifier.testTag("PairedWatchKeyLevel")
+ )
+ VerticalSpacer(8.dp)
+ BodyM(
+ text = stringResource(
+ if (watch.isSettingsUpToDate) {
+ R.string.settings__watch__settings_synced
+ } else {
+ R.string.settings__watch__settings_pending
+ },
+ ),
+ color = Colors.White64,
+ modifier = Modifier.testTag("PairedWatchSettingsState")
+ )
+ if (watch.isRemoving) {
+ VerticalSpacer(16.dp)
+ BodyM(
+ text = stringResource(
+ if (watch.isErasing) {
+ R.string.settings__watch__erase_pending
+ } else {
+ R.string.settings__watch__unpair_pending
+ },
+ ),
+ color = Colors.White64,
+ modifier = Modifier.testTag("PairedWatchRemovePending")
+ )
+ Illustration(R.drawable.hourglass)
+ SecondaryButton(
+ text = stringResource(R.string.settings__watch__stop_waiting),
+ onClick = onStopWaitingClick,
+ modifier = Modifier.fillMaxWidth(),
+ testTag = "PairedWatchStopWaiting",
+ )
+ return
+ }
+ Illustration(if (watch.keyLevel == null) R.drawable.shield else R.drawable.shield_check)
+ Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {
+ SecondaryButton(
+ text = stringResource(R.string.settings__watch__unpair),
+ onClick = onUnpairClick,
+ fullWidth = false,
+ modifier = Modifier.weight(1f),
+ testTag = "PairedWatchUnpair",
+ )
+ PrimaryButton(
+ text = stringResource(R.string.common__ok),
+ onClick = onDismiss,
+ fullWidth = false,
+ modifier = Modifier
+ .weight(1f)
+ .testTag("PairedWatchClose")
+ )
+ }
+ VerticalSpacer(16.dp)
+ SecondaryButton(
+ text = stringResource(R.string.settings__watch__erase),
+ onClick = onEraseClick,
+ modifier = Modifier.fillMaxWidth(),
+ testTag = "PairedWatchErase",
+ )
+}
+
+@Composable
+private fun ColumnScope.Pairing(
+ step: WatchPairStep,
+ onClose: () -> Unit,
+ onConfirm: () -> Unit,
+) {
+ when (step) {
+ WatchPairStep.Connecting -> {
+ Message(R.string.settings__watch__pair_connecting, "PairedWatchPairConnecting")
+ Illustration(R.drawable.phone)
+ SecondaryButton(
+ text = stringResource(R.string.common__cancel),
+ onClick = onClose,
+ modifier = Modifier.fillMaxWidth(),
+ testTag = "PairedWatchCodeCancel",
+ )
+ }
+ is WatchPairStep.Code -> Code(step = step, onCancel = onClose, onConfirm = onConfirm)
+ WatchPairStep.Sending -> {
+ Message(R.string.settings__watch__pair_sending, "PairedWatchPairSending")
+ Illustration(R.drawable.transfer)
+ }
+ WatchPairStep.Done -> {
+ Message(R.string.settings__watch__pair_done, "PairedWatchPairDone")
+ Illustration(R.drawable.check)
+ CloseButton(onClose)
+ }
+ is WatchPairStep.Failed -> {
+ Message(step.message, "PairedWatchPairError")
+ Illustration(R.drawable.cross)
+ CloseButton(onClose)
+ }
+ }
+}
+
+@Composable
+private fun ColumnScope.Code(
+ step: WatchPairStep.Code,
+ onCancel: () -> Unit,
+ onConfirm: () -> Unit,
+) {
+ BodyM(
+ text = stringResource(R.string.settings__watch__pair_code_text).replace("{name}", step.watchName),
+ color = Colors.White64,
+ )
+ VerticalSpacer(32.dp)
+ Display(
+ text = step.code,
+ textAlign = TextAlign.Center,
+ modifier = Modifier
+ .fillMaxWidth()
+ .testTag("PairedWatchCode")
+ )
+ VerticalSpacer(32.dp)
+ if (step.sendsWallet) {
+ BodyMSB(
+ text = stringResource(R.string.settings__watch__pair_sends_wallet),
+ modifier = Modifier.testTag("PairedWatchSendsWallet")
+ )
+ VerticalSpacer(8.dp)
+ }
+ if (step.sendsWallet && !step.isVerified) {
+ // Only a debug build gets this far with an unverified watch, so the line is not localized.
+ BodyM(
+ text = "Debug build: this watch's secure hardware was not verified.",
+ color = Colors.Red,
+ modifier = Modifier.testTag("PairedWatchUnverified")
+ )
+ VerticalSpacer(8.dp)
+ }
+ if (step.isConfirmed) {
+ BodyM(
+ text = stringResource(R.string.settings__watch__pair_waiting),
+ color = Colors.White64,
+ modifier = Modifier.testTag("PairedWatchPairWaiting")
+ )
+ }
+ Illustration(R.drawable.keyring)
+ Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {
+ SecondaryButton(
+ text = stringResource(R.string.common__cancel),
+ onClick = onCancel,
+ fullWidth = false,
+ modifier = Modifier.weight(1f),
+ testTag = "PairedWatchCodeCancel",
+ )
+ PrimaryButton(
+ text = stringResource(R.string.settings__watch__pair_confirm),
+ onClick = onConfirm,
+ enabled = !step.isConfirmed,
+ fullWidth = false,
+ modifier = Modifier
+ .weight(1f)
+ .testTag("PairedWatchCodeConfirm")
+ )
+ }
+}
+
+@Composable
+private fun CloseButton(onClick: () -> Unit) {
+ PrimaryButton(
+ text = stringResource(R.string.common__ok),
+ onClick = onClick,
+ modifier = Modifier
+ .fillMaxWidth()
+ .testTag("PairedWatchPairClose")
+ )
+}
+
+@Composable
+private fun Message(
+ text: Int,
+ testTag: String,
+) {
+ BodyM(
+ text = stringResource(text),
+ color = Colors.White64,
+ modifier = Modifier.testTag(testTag)
+ )
+}
+
+@Composable
+private fun ColumnScope.Illustration(@DrawableRes image: Int) {
+ Box(
+ contentAlignment = Alignment.Center,
+ modifier = Modifier
+ .fillMaxWidth()
+ .weight(1f)
+ ) {
+ Image(
+ painter = painterResource(image),
+ contentDescription = null,
+ contentScale = ContentScale.Fit,
+ modifier = Modifier.size(200.dp)
+ )
+ }
+}
+
+@Preview(showSystemUi = true)
+@Composable
+private fun PreviewUnpaired() {
+ AppThemeSurface {
+ BottomSheetPreview {
+ Content(
+ uiState = WatchSheetUiState(
+ isLoading = false,
+ connected = ConnectedWatch("Pixel Watch 3", hasApp = true, isNearby = true),
+ ),
+ modifier = Modifier.sheetHeight(),
+ )
+ }
+ }
+}
+
+@Preview(showSystemUi = true)
+@Composable
+private fun PreviewCode() {
+ AppThemeSurface {
+ BottomSheetPreview {
+ Content(
+ uiState = WatchSheetUiState(
+ isLoading = false,
+ pairing = WatchPairStep.Code(
+ code = "048213",
+ watchName = "Pixel Watch 3",
+ sendsWallet = true,
+ isVerified = true,
+ isConfirmed = false,
+ ),
+ ),
+ modifier = Modifier.sheetHeight(),
+ )
+ }
+ }
+}
+
+@Preview(showSystemUi = true)
+@Composable
+private fun PreviewPaired() {
+ AppThemeSurface {
+ BottomSheetPreview {
+ Content(
+ uiState = WatchSheetUiState(
+ isLoading = false,
+ paired = PairedWatch(
+ name = "Pixel Watch 3",
+ keyLevel = KeyLevel.StrongBox,
+ isSettingsUpToDate = false,
+ isRemoving = false,
+ isErasing = false,
+ ),
+ ),
+ modifier = Modifier.sheetHeight(),
+ )
+ }
+ }
+}
diff --git a/app/src/main/java/to/bitkit/ui/sheets/watch/WatchSheetViewModel.kt b/app/src/main/java/to/bitkit/ui/sheets/watch/WatchSheetViewModel.kt
new file mode 100644
index 0000000000..d45e507c77
--- /dev/null
+++ b/app/src/main/java/to/bitkit/ui/sheets/watch/WatchSheetViewModel.kt
@@ -0,0 +1,280 @@
+package to.bitkit.ui.sheets.watch
+
+import androidx.annotation.StringRes
+import androidx.compose.runtime.Immutable
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.viewModelScope
+import dagger.hilt.android.lifecycle.HiltViewModel
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+import to.bitkit.R
+import to.bitkit.repositories.WatchLinkError
+import to.bitkit.repositories.WatchLinkRepo
+import to.bitkit.repositories.WatchPairingStatus
+import to.bitkit.wearlink.AbortReason
+import to.bitkit.wearlink.AttestationFailure
+import to.bitkit.wearlink.AttestationVerdict
+import to.bitkit.wearlink.KeyLevel
+import to.bitkit.wearlink.LinkError
+import to.bitkit.wearlink.LinkRecord
+import to.bitkit.wearlink.PairingMode
+import to.bitkit.wearlink.PairingState
+import to.bitkit.wearlink.Removal
+import to.bitkit.wearlink.StoreFailure
+import javax.inject.Inject
+
+/**
+ * The state of the Watch sheet: the connected watch, the paired watch, and a pairing while one runs. A pairing
+ * starts on the user's tap and is cancelled when the sheet closes, whoever owns this view model.
+ *
+ * It also decides when the app's PIN or biometric check is asked for: always before a confirmation that sends the
+ * wallet to a watch, and never for a watch that already holds it. The repository is only told the check was passed
+ * from [onAuthSuccess], which does nothing unless that check is the one this view model asked for.
+ */
+@HiltViewModel
+class WatchSheetViewModel @Inject constructor(
+ private val watchLinkRepo: WatchLinkRepo,
+) : ViewModel() {
+ private val _uiState = MutableStateFlow(WatchSheetUiState())
+ val uiState: StateFlow = _uiState.asStateFlow()
+
+ private var refreshJob: Job? = null
+ private var isTransferLeft = false
+
+ init {
+ viewModelScope.launch {
+ watchLinkRepo.record.collect { record ->
+ _uiState.update {
+ // The record is rewritten whenever the watch reports; only another watch, or none, ends a dialog.
+ val isSameWatch = record != null && record.pairingId == it.pairingId
+ it.copy(
+ paired = record?.toPairedWatch(),
+ pairingId = record?.pairingId,
+ dialog = it.dialog.takeIf { isSameWatch },
+ )
+ }
+ }
+ }
+ viewModelScope.launch {
+ watchLinkRepo.pairing.collect { status ->
+ _uiState.update { if (it.pairing == null) it else it.withStep(step(status)) }
+ }
+ }
+ }
+
+ /**
+ * The sheet came up: looks for a connected watch from scratch, and shows a pairing that is still sending the
+ * wallet from before the sheet was closed, or how that one failed meanwhile. One that paired shows as the
+ * paired watch.
+ */
+ fun onSheetOpen() {
+ // Only a transfer outlives the sheet; whatever else still shows there was cancelled and is ending.
+ val shown = when (val status = watchLinkRepo.pairing.value) {
+ is WatchPairingStatus.Running if status.state == PairingState.Transferring -> step(status)
+ is WatchPairingStatus.Failed if isTransferLeft -> step(status)
+ else -> null
+ }
+ isTransferLeft = false
+ _uiState.update { it.copy(isLoading = true, connected = null, pairing = shown, isAuthShown = false) }
+ lookForWatch()
+ }
+
+ /** Looks for a connected watch again, as while the sheet waits for one, unless a look is still under way. */
+ fun refresh() {
+ if (refreshJob?.isActive == true) return
+ lookForWatch()
+ }
+
+ private fun lookForWatch() {
+ refreshJob?.cancel()
+ refreshJob = viewModelScope.launch {
+ val watches = watchLinkRepo.watches().getOrDefault(emptyList())
+ val watch = watches.firstOrNull { it.hasApp && it.isNearby }
+ ?: watches.firstOrNull { it.hasApp }
+ ?: watches.firstOrNull()
+ val connected = watch?.let { ConnectedWatch(it.name, hasApp = it.hasApp, isNearby = it.isNearby) }
+ _uiState.update { it.copy(isLoading = false, connected = connected) }
+ }
+ }
+
+ /** Starts a pairing with the connected watch. */
+ fun onPairClick() {
+ watchLinkRepo.cancelPairing()
+ _uiState.update { it.copy(pairing = WatchPairStep.Connecting, isAuthShown = false) }
+ watchLinkRepo.startPairing()
+ }
+
+ /**
+ * The user says the codes match. A confirmation that sends the wallet first asks for the app's PIN or
+ * biometric check; one for a watch that already holds the wallet goes through as it is.
+ */
+ fun onPairConfirm() {
+ val step = _uiState.value.pairing as? WatchPairStep.Code ?: return
+ if (step.sendsWallet) {
+ _uiState.update { it.copy(isAuthShown = true) }
+ return
+ }
+ viewModelScope.launch { watchLinkRepo.confirmPairing(step.code, isAuthenticated = false) }
+ }
+
+ /** The user passed the check that [onPairConfirm] asked for. */
+ fun onAuthSuccess() {
+ val state = _uiState.value
+ val step = state.pairing as? WatchPairStep.Code ?: return
+ if (!state.isAuthShown) return
+ _uiState.update { it.copy(isAuthShown = false) }
+ viewModelScope.launch { watchLinkRepo.confirmPairing(step.code, isAuthenticated = true) }
+ }
+
+ /** The user left the check: back to the code, with nothing confirmed. */
+ fun onAuthDismiss() = _uiState.update { it.copy(isAuthShown = false) }
+
+ /** Ends the pairing that runs, or leaves the end of the last one, back to the watch's state. */
+ fun onPairClose() {
+ watchLinkRepo.cancelPairing()
+ _uiState.update { it.copy(pairing = null, isAuthShown = false) }
+ lookForWatch()
+ }
+
+ /**
+ * The sheet went away: a pairing under way is cancelled, except while the wallet is on its way to the watch,
+ * which is left to finish so that the phone and the watch agree on how it ended.
+ */
+ fun onSheetClose() {
+ refreshJob?.cancel()
+ isTransferLeft = _uiState.value.pairing == WatchPairStep.Sending
+ if (!isTransferLeft) watchLinkRepo.cancelPairing()
+ _uiState.update { it.copy(pairing = null, isAuthShown = false, dialog = null) }
+ }
+
+ fun onUnpairClick() = _uiState.update { it.copy(dialog = WatchRemoveDialog.Unpair) }
+
+ fun onEraseClick() = _uiState.update { it.copy(dialog = WatchRemoveDialog.Erase) }
+
+ fun onDialogDismiss() = _uiState.update { it.copy(dialog = null) }
+
+ fun onDialogConfirm() {
+ val dialog = _uiState.value.dialog ?: return
+ _uiState.update { it.copy(dialog = null) }
+ viewModelScope.launch { watchLinkRepo.remove(isErase = dialog == WatchRemoveDialog.Erase) }
+ }
+
+ /** Drops a watch whose removal was never acknowledged. */
+ fun onStopWaitingClick() {
+ viewModelScope.launch { watchLinkRepo.forget() }
+ }
+
+ private fun LinkRecord.toPairedWatch() = PairedWatch(
+ name = peerName,
+ keyLevel = keyLevel,
+ isSettingsUpToDate = isSettingsUpToDate,
+ isRemoving = removal != null,
+ isErasing = removal == Removal.Erase,
+ )
+
+ private fun WatchSheetUiState.withStep(step: WatchPairStep) =
+ copy(pairing = step, isAuthShown = isAuthShown && step is WatchPairStep.Code)
+
+ private fun step(status: WatchPairingStatus): WatchPairStep = when (status) {
+ WatchPairingStatus.Idle -> WatchPairStep.Connecting
+ WatchPairingStatus.Paired -> WatchPairStep.Done
+ is WatchPairingStatus.Failed -> WatchPairStep.Failed(message(status.error))
+ is WatchPairingStatus.Running -> when (val state = status.state) {
+ PairingState.Connecting -> WatchPairStep.Connecting
+ PairingState.Transferring -> WatchPairStep.Sending
+ is PairingState.Code -> WatchPairStep.Code(
+ code = state.code,
+ watchName = state.peerName,
+ sendsWallet = state.mode == PairingMode.Transfer,
+ isVerified = state.attestation is AttestationVerdict.Verified,
+ isConfirmed = state.isConfirmed,
+ )
+ }
+ }
+
+ @StringRes
+ private fun message(error: Throwable): Int = when (error) {
+ is LinkError.Cancelled -> R.string.settings__watch__error_cancelled
+ is LinkError.Timeout -> R.string.settings__watch__error_timeout
+ is LinkError.DifferentWallet -> R.string.settings__watch__error_different_wallet
+ is LinkError.UpdateRequired -> R.string.settings__watch__error_update
+ is LinkError.AttestationFailed if error.failure == AttestationFailure.StatusUnknown ->
+ R.string.settings__watch__error_status
+ is LinkError.AttestationFailed -> R.string.settings__watch__error_unverified
+ is LinkError.PinRequired -> R.string.settings__watch__error_pin
+ is LinkError.Throttled -> R.string.settings__watch__error_throttled
+ is LinkError.Unreachable, is WatchLinkError.NoWatch -> R.string.settings__watch__error_unreachable
+ is LinkError.TransferFailed -> when (error.reason) {
+ StoreFailure.InsecureKey -> R.string.settings__watch__error_insecure
+ else -> R.string.settings__watch__error_store
+ }
+ is LinkError.PeerAborted -> when (error.reason) {
+ AbortReason.Cancelled -> R.string.settings__watch__error_cancelled_watch
+ AbortReason.DifferentWallet -> R.string.settings__watch__error_different_wallet
+ AbortReason.UpdateRequired -> R.string.settings__watch__error_update
+ else -> R.string.settings__watch__error_failed
+ }
+ else -> R.string.settings__watch__error_failed
+ }
+}
+
+/**
+ * [pairing] is the step of the pairing the user started from the sheet, or null while none shows. [isAuthShown]
+ * while the app's PIN or biometric check covers the code, before a confirmation that sends the wallet.
+ */
+@Immutable
+data class WatchSheetUiState(
+ val isLoading: Boolean = true,
+ val connected: ConnectedWatch? = null,
+ val paired: PairedWatch? = null,
+ val pairingId: String? = null,
+ val pairing: WatchPairStep? = null,
+ val isAuthShown: Boolean = false,
+ val dialog: WatchRemoveDialog? = null,
+)
+
+/** A watch connected to this phone, with whether it has Bitkit and whether it is reached directly. */
+@Immutable
+data class ConnectedWatch(val name: String, val hasApp: Boolean, val isNearby: Boolean) {
+ val canPair: Boolean get() = hasApp && isNearby
+}
+
+/** [keyLevel] is where the watch's attested key lives, or null when its attestation was not verified. */
+@Immutable
+data class PairedWatch(
+ val name: String,
+ val keyLevel: KeyLevel?,
+ val isSettingsUpToDate: Boolean,
+ val isRemoving: Boolean,
+ val isErasing: Boolean,
+)
+
+enum class WatchRemoveDialog { Unpair, Erase }
+
+sealed interface WatchPairStep {
+ /** Waiting for the watch to answer. */
+ data object Connecting : WatchPairStep
+
+ /**
+ * The code to compare with the watch's. [sendsWallet] when the watch holds no wallet and confirming sends it
+ * this phone's; [isVerified] whether the watch's secure hardware was verified.
+ */
+ data class Code(
+ val code: String,
+ val watchName: String,
+ val sendsWallet: Boolean,
+ val isVerified: Boolean,
+ val isConfirmed: Boolean,
+ ) : WatchPairStep
+
+ /** The wallet is on its way to the watch. */
+ data object Sending : WatchPairStep
+
+ data object Done : WatchPairStep
+
+ data class Failed(@StringRes val message: Int) : WatchPairStep
+}
diff --git a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt
index ef1abdcbac..a340778cd9 100644
--- a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt
+++ b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt
@@ -22,6 +22,7 @@ import to.bitkit.repositories.PubkyRepo
import to.bitkit.repositories.PubkySwapsRouteRepo
import to.bitkit.repositories.UsdtRepo
import to.bitkit.repositories.WakeRepo
+import to.bitkit.repositories.WatchLinkRepo
import to.bitkit.repositories.WatchOnlyAccountRepo
import to.bitkit.services.CoreService
import to.bitkit.services.MigrationService
@@ -60,6 +61,7 @@ class WipeWalletUseCase @Inject constructor(
private val connectionRecovery: WalletConnectionRecovery,
private val wakeRepo: WakeRepo,
private val moveToSparkManager: Provider,
+ private val watchLinkRepo: Provider,
) {
private val wipeMutex = Mutex()
@@ -105,6 +107,9 @@ class WipeWalletUseCase @Inject constructor(
step("remove Bitkit payment endpoints") { pubkyRepo.removeBitkitPaymentEndpoints() }
step("close Paykit SDK") { privatePaykitRepo.get().closeAndClear() }
step("unregister wake device") { wakeRepo.unregister() }
+ // The paired watch is told to unpair while the link keys exist. It keeps its own wallet: it is never erased
+ // because the phone's wallet went.
+ step("unpair watch") { watchLinkRepo.get().forget() }
}
private suspend fun wipeLocal(walletIndex: Int, resetWalletState: () -> Unit): Result {
diff --git a/app/src/main/java/to/bitkit/watch/KeystoreLinkKeys.kt b/app/src/main/java/to/bitkit/watch/KeystoreLinkKeys.kt
new file mode 100644
index 0000000000..634f44ac7c
--- /dev/null
+++ b/app/src/main/java/to/bitkit/watch/KeystoreLinkKeys.kt
@@ -0,0 +1,96 @@
+package to.bitkit.watch
+
+import android.content.Context
+import android.content.pm.PackageManager
+import android.os.Build
+import android.security.keystore.KeyProperties
+import android.security.keystore.KeyProtection
+import dagger.hilt.android.qualifiers.ApplicationContext
+import to.bitkit.wearlink.LinkError
+import to.bitkit.wearlink.LinkKeyStore
+import java.security.KeyStore
+import javax.crypto.AEADBadTagException
+import javax.crypto.Cipher
+import javax.crypto.SecretKey
+import javax.crypto.spec.GCMParameterSpec
+import javax.crypto.spec.SecretKeySpec
+import javax.inject.Inject
+import javax.inject.Singleton
+
+/**
+ * The link keys as AES-256-GCM keys imported into AndroidKeyStore: StrongBox when the phone has one that takes the
+ * key (Android 12 and later), else the trusted execution environment. Once imported a key cannot be read back.
+ * Unlike the seed key they are not bound to an unlocked phone, so the watch's status can be read while it is locked;
+ * they protect settings and commands, never funds. The watch app's `KeystoreLinkKeys` is the same class but for
+ * that API check.
+ */
+@Singleton
+class KeystoreLinkKeys @Inject constructor(
+ @ApplicationContext private val context: Context,
+) : LinkKeyStore {
+ private companion object {
+ const val KEYSTORE = "AndroidKeyStore"
+ const val TRANSFORMATION = "AES/GCM/NoPadding"
+ const val ALIAS_PREFIX = "wearlink."
+ const val IV_BYTES = 12
+ const val TAG_BITS = 128
+ }
+
+ private val keyStore: KeyStore by lazy { KeyStore.getInstance(KEYSTORE).apply { load(null) } }
+
+ override fun import(alias: String, key: ByteArray) = guarded {
+ val entry = KeyStore.SecretKeyEntry(SecretKeySpec(key, KeyProperties.KEY_ALGORITHM_AES))
+ // Importing into StrongBox needs API 31; an older phone keeps the keys in the trusted environment.
+ val hasStrongBox = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S &&
+ context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
+ if (hasStrongBox && runCatching { keyStore.setEntry(alias, entry, protection(isStrongBox = true)) }.isSuccess) {
+ return@guarded
+ }
+ keyStore.setEntry(alias, entry, protection(isStrongBox = false))
+ }
+
+ override fun encrypt(alias: String, plaintext: ByteArray, aad: ByteArray): ByteArray = guarded {
+ val cipher = Cipher.getInstance(TRANSFORMATION)
+ cipher.init(Cipher.ENCRYPT_MODE, key(alias))
+ cipher.updateAAD(aad)
+ val ciphertext = cipher.doFinal(plaintext)
+ check(cipher.iv.size == IV_BYTES) { "Unexpected IV size" }
+ cipher.iv + ciphertext
+ }
+
+ override fun decrypt(alias: String, blob: ByteArray, aad: ByteArray): ByteArray = guarded {
+ if (blob.size <= IV_BYTES) throw LinkError.Rejected("too short")
+ val cipher = Cipher.getInstance(TRANSFORMATION)
+ cipher.init(Cipher.DECRYPT_MODE, key(alias), GCMParameterSpec(TAG_BITS, blob, 0, IV_BYTES))
+ cipher.updateAAD(aad)
+ cipher.doFinal(blob, IV_BYTES, blob.size - IV_BYTES)
+ }
+
+ override fun delete(alias: String) = guarded { keyStore.deleteEntry(alias) }
+
+ override fun clear() = guarded {
+ keyStore.aliases().toList().filter { it.startsWith(ALIAS_PREFIX) }.forEach(keyStore::deleteEntry)
+ }
+
+ private fun key(alias: String): SecretKey =
+ keyStore.getKey(alias, null) as? SecretKey ?: throw LinkError.KeyFailure()
+
+ private fun protection(isStrongBox: Boolean) =
+ KeyProtection.Builder(KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
+ .setRandomizedEncryptionRequired(true)
+ .apply { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) setIsStrongBoxBacked(isStrongBox) }
+ .build()
+
+ private inline fun guarded(block: () -> T): T = runCatching(block).getOrElse {
+ val causes = generateSequence(it) { error -> error.cause }.take(MAX_CAUSE_DEPTH)
+ throw when {
+ it is LinkError -> it
+ causes.any { cause -> cause is AEADBadTagException } -> LinkError.Rejected("not authentic")
+ else -> LinkError.KeyFailure(it)
+ }
+ }
+}
+
+private const val MAX_CAUSE_DEPTH = 8
diff --git a/app/src/main/java/to/bitkit/watch/WatchDataLayerTransport.kt b/app/src/main/java/to/bitkit/watch/WatchDataLayerTransport.kt
new file mode 100644
index 0000000000..4a10465e61
--- /dev/null
+++ b/app/src/main/java/to/bitkit/watch/WatchDataLayerTransport.kt
@@ -0,0 +1,104 @@
+package to.bitkit.watch
+
+import android.content.Context
+import android.content.Intent
+import android.net.Uri
+import androidx.core.net.toUri
+import androidx.wear.remote.interactions.RemoteActivityHelper
+import com.google.android.gms.tasks.Task
+import com.google.android.gms.wearable.CapabilityClient
+import com.google.android.gms.wearable.PutDataRequest
+import com.google.android.gms.wearable.Wearable
+import dagger.hilt.android.qualifiers.ApplicationContext
+import kotlinx.coroutines.suspendCancellableCoroutine
+import to.bitkit.wearlink.LinkError
+import to.bitkit.wearlink.LinkNode
+import to.bitkit.wearlink.LinkPacket
+import to.bitkit.wearlink.LinkTransport
+import java.util.concurrent.Executor
+import javax.inject.Inject
+import javax.inject.Singleton
+import kotlin.coroutines.resume
+import kotlin.coroutines.resumeWithException
+
+/**
+ * [LinkTransport] over the Wear Data Layer, and the only file besides [WatchLinkListenerService] that names its
+ * classes. One-shot messages go through `MessageClient`, which stores nothing: the handshake and the wallet seed
+ * only ever travel there. State documents, which the link has encrypted, go through `DataClient`, which delivers the
+ * latest after a reconnect. The Data Layer only connects apps with the same application id and signing certificate.
+ * What arrives comes in through [WatchLinkListenerService].
+ */
+@Singleton
+class WatchDataLayerTransport @Inject constructor(
+ @ApplicationContext private val context: Context,
+) : LinkTransport {
+ companion object {
+ /** The capability the watch app declares in its `wear.xml`. */
+ const val WATCH_CAPABILITY = "bitkit_watch_v1"
+ private const val WEAR_SCHEME = "wear"
+ }
+
+ private val nodeClient by lazy { Wearable.getNodeClient(context) }
+ private val capabilityClient by lazy { Wearable.getCapabilityClient(context) }
+ private val messageClient by lazy { Wearable.getMessageClient(context) }
+ private val dataClient by lazy { Wearable.getDataClient(context) }
+ private val remoteActivityHelper by lazy { RemoteActivityHelper(context) }
+
+ @Volatile
+ private var receiver: (suspend (LinkPacket) -> Unit)? = null
+
+ override suspend fun nodes(): List {
+ val withApp = capabilityClient.getCapability(WATCH_CAPABILITY, CapabilityClient.FILTER_REACHABLE).await()
+ .nodes.map { it.id }.toSet()
+ return nodeClient.connectedNodes.await().map { LinkNode(it.id, it.displayName, it.isNearby, it.id in withApp) }
+ }
+
+ override suspend fun send(nodeId: String, path: String, payload: ByteArray) {
+ runCatching { messageClient.sendMessage(nodeId, path, payload).await() }
+ .getOrElse { throw LinkError.Unreachable(it) }
+ }
+
+ override suspend fun putState(path: String, payload: ByteArray) {
+ val request = PutDataRequest.create(path).setData(payload).setUrgent()
+ dataClient.putDataItem(request).await()
+ }
+
+ override suspend fun deleteState(path: String) {
+ val uri = Uri.Builder().scheme(WEAR_SCHEME).path(path).build()
+ dataClient.deleteDataItems(uri).await()
+ }
+
+ /** Brings the watch app to the front with [uri]; a listener service on the watch may not start an activity. */
+ override suspend fun open(nodeId: String, uri: String): Unit = suspendCancellableCoroutine { continuation ->
+ val intent = Intent(Intent.ACTION_VIEW, uri.toUri()).addCategory(Intent.CATEGORY_BROWSABLE)
+ val future = remoteActivityHelper.startRemoteActivity(intent, nodeId)
+ future.addListener(
+ {
+ runCatching { future.get() }
+ .onSuccess { continuation.resume(Unit) }
+ .onFailure { continuation.resumeWithException(LinkError.Unreachable(it)) }
+ },
+ DirectExecutor,
+ )
+ }
+
+ override fun attach(receiver: suspend (LinkPacket) -> Unit) {
+ this.receiver = receiver
+ }
+
+ /** Hands [packet], which the listener service received, to the link. */
+ suspend fun deliver(packet: LinkPacket) {
+ receiver?.invoke(packet)
+ }
+
+ private object DirectExecutor : Executor {
+ override fun execute(command: Runnable) = command.run()
+ }
+}
+
+/** Waits for a Play services task without a coroutines adapter library. */
+internal suspend fun Task.await(): T = suspendCancellableCoroutine { continuation ->
+ addOnSuccessListener { continuation.resume(it) }
+ addOnFailureListener { continuation.resumeWithException(it) }
+ addOnCanceledListener { continuation.cancel() }
+}
diff --git a/app/src/main/java/to/bitkit/watch/WatchLinkListenerService.kt b/app/src/main/java/to/bitkit/watch/WatchLinkListenerService.kt
new file mode 100644
index 0000000000..262cdcfb4b
--- /dev/null
+++ b/app/src/main/java/to/bitkit/watch/WatchLinkListenerService.kt
@@ -0,0 +1,42 @@
+package to.bitkit.watch
+
+import com.google.android.gms.wearable.DataEvent
+import com.google.android.gms.wearable.DataEventBuffer
+import com.google.android.gms.wearable.MessageEvent
+import com.google.android.gms.wearable.WearableListenerService
+import dagger.hilt.android.AndroidEntryPoint
+import kotlinx.coroutines.runBlocking
+import to.bitkit.repositories.WatchLinkRepo
+import to.bitkit.wearlink.LinkPacket
+import javax.inject.Inject
+
+/**
+ * Receives what the paired watch sends over the Data Layer, also while the app is closed. Play services binds it, so
+ * it is exported; what it receives is trusted only as far as the link authenticates it. It only writes the link's own
+ * store: it never starts the Lightning node or Spark. Each callback runs on the service's own background thread and
+ * is handled to its end before it returns, since the process may be stopped right after.
+ */
+@AndroidEntryPoint
+class WatchLinkListenerService : WearableListenerService() {
+ /** Injected so the link is attached to the transport before anything is delivered. */
+ @Inject
+ lateinit var watchLinkRepo: WatchLinkRepo
+
+ @Inject
+ lateinit var transport: WatchDataLayerTransport
+
+ override fun onMessageReceived(event: MessageEvent) {
+ deliver(LinkPacket(event.sourceNodeId, event.path, event.data))
+ }
+
+ override fun onDataChanged(events: DataEventBuffer) {
+ val packets = events.filter { it.type == DataEvent.TYPE_CHANGED }.mapNotNull { event ->
+ val item = event.dataItem
+ val data = item.data ?: return@mapNotNull null
+ LinkPacket(item.uri.host.orEmpty(), item.uri.path.orEmpty(), data)
+ }
+ packets.forEach(::deliver)
+ }
+
+ private fun deliver(packet: LinkPacket) = runBlocking { transport.deliver(packet) }
+}
diff --git a/app/src/main/res/drawable/ic_watch.xml b/app/src/main/res/drawable/ic_watch.xml
new file mode 100644
index 0000000000..daf0d7889a
--- /dev/null
+++ b/app/src/main/res/drawable/ic_watch.xml
@@ -0,0 +1,9 @@
+
+
+
diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml
index 552859a4ed..c1f0ec4f52 100644
--- a/app/src/main/res/values-ar/strings.xml
+++ b/app/src/main/res/values-ar/strings.xml
@@ -889,6 +889,50 @@
فشل الإرسال
Bitkit من تصميم Synonym Software, S.A. DE C.V. ©2025. جميع الحقوق محفوظة.
الدعم
+ إلغاء الإقران ومسح الساعة
+ مسح
+ في انتظار أن تمسح الساعة محفظتها. الساعة التي لا تعاود الاتصال أبدًا تحتفظ بها.
+ ستنسى الساعة هذا الهاتف وتحذف محفظتها عند اتصالها في المرة القادمة. الساعة التي لا تعاود الاتصال أبدًا تحتفظ بالمحفظة، لذا انقل أموالك إلى محفظة جديدة إذا فُقدت الساعة.
+ مسح الساعة؟
+ تم إلغاء الإقران.
+ تم إلغاء الإقران من الساعة.
+ الساعة تحتوي على محفظة مختلفة.
+ فشل الإقران. يرجى المحاولة مرة أخرى.
+ لا تحتوي هذه الساعة على عتاد آمن لحفظ محفظة.
+ عيّن رمز PIN في Bitkit أولًا، ثم أقرن ساعتك.
+ تعذّر التحقق من العتاد الآمن للساعة. اتصل بالإنترنت وحاول مرة أخرى.
+ تعذّر على الساعة حفظ المحفظة.
+ محاولات كثيرة جدًا. حاول مرة أخرى لاحقًا.
+ انتهت مهلة الإقران.
+ تعذّر الوصول إلى ساعتك. أبقِها قريبة مع تشغيل Bluetooth.
+ تعذّر التحقق من العتاد الآمن لهذه الساعة، لذا لم تُرسَل محفظتك.
+ حدّث Bitkit على هاتفك وساعتك.
+ هذه الساعة تحتوي على محفظتك الكاملة ويمكنها الإنفاق منها.
+ تم التحقق من مفاتيح الساعة في StrongBox.
+ تم التحقق من مفاتيح الساعة في العتاد الآمن.
+ لم يتم التحقق من العتاد الآمن للساعة.
+ جارٍ البحث عن ساعتك…
+ الساعة
+ ثبّت Bitkit على {name} لإقرانها.
+ لا توجد ساعة متصلة. وصّل ساعة Wear OS بهذا الهاتف أولًا.
+ غير مقترنة
+ إقران الساعة
+ تأكد من أن {name} تعرض هذا الرمز.
+ إقران
+ افتح Bitkit على ساعتك.
+ تم إقران ساعتك.
+ جارٍ إرسال محفظتك إلى الساعة…
+ لا توجد محفظة على هذه الساعة. الإقران يرسل إليها عبارة الاسترداد الخاصة بك، فتصبح حاملة لمحفظتك الكاملة.
+ إقران الساعة
+ أكّد الرمز على ساعتك.
+ {name} جاهزة للإقران.
+ الإعدادات ليست على الساعة بعد.
+ إعدادات الساعة محدّثة.
+ إيقاف الانتظار
+ إلغاء الإقران
+ في انتظار إلغاء إقران الساعة.
+ ستنسى الساعة هذا الهاتف. تبقى المحفظة على الساعة.
+ إلغاء إقران الساعة؟
الأدوات
الأدوات
إعادة تعيين بطاقات الاقتراحات
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 c1306b8f56..cd413c39be 100644
--- a/app/src/main/res/values-b+es+419/strings.xml
+++ b/app/src/main/res/values-b+es+419/strings.xml
@@ -910,6 +910,50 @@
Fallo en el envío
Bitkit fue creado por Synonym Software, S.A. DE C.V. ©2025. Todos los derechos reservados.
Soporte
+ Desvincular y borrar el reloj
+ Borrar
+ Esperando a que el reloj borre la billetera. Un reloj que no vuelva a conectarse la conservará.
+ El reloj olvidará este teléfono y eliminará la billetera la próxima vez que se conecte. Un reloj que no vuelva a conectarse conservará la billetera, así que mueva sus fondos a una billetera nueva si pierde el reloj.
+ ¿Borrar el reloj?
+ Vinculación cancelada.
+ La vinculación se canceló en el reloj.
+ El reloj contiene una billetera distinta.
+ La vinculación falló. Inténtelo de nuevo.
+ Este reloj no tiene hardware seguro para guardar una billetera.
+ Primero configure un PIN en Bitkit y luego vincule su reloj.
+ No se pudo comprobar el hardware seguro del reloj. Conéctese a internet e inténtelo de nuevo.
+ El reloj no pudo guardar la billetera.
+ Demasiados intentos. Inténtelo de nuevo más tarde.
+ Se agotó el tiempo de vinculación.
+ No se puede acceder a su reloj. Manténgalo cerca y con el Bluetooth activado.
+ No se pudo verificar el hardware seguro de este reloj, por lo que no se envió su billetera.
+ Actualice Bitkit en su teléfono y en su reloj.
+ Este reloj contiene su billetera completa y puede gastar sus fondos.
+ Claves del reloj verificadas en StrongBox.
+ Claves del reloj verificadas en hardware seguro.
+ Hardware seguro del reloj no verificado.
+ Buscando su reloj…
+ Reloj
+ Instale Bitkit en {name} para vincularlo.
+ No hay ningún reloj conectado. Conecte primero un reloj Wear OS a este teléfono.
+ No vinculado
+ Vincular reloj
+ Verifique que {name} muestra este código.
+ Vincular
+ Abra Bitkit en su reloj.
+ Su reloj está vinculado.
+ Enviando su billetera al reloj…
+ Este reloj no tiene billetera. Al vincularlo se le envía su frase de recuperación, por lo que contendrá su billetera completa.
+ Vincular reloj
+ Confirme el código en su reloj.
+ {name} está listo para vincularse.
+ Los ajustes aún no están en el reloj.
+ Ajustes del reloj actualizados.
+ Dejar de esperar
+ Desvincular
+ Esperando a que el reloj se desvincule.
+ El reloj olvidará este teléfono. La billetera permanece en el reloj.
+ ¿Desvincular el reloj?
Widgets
Widgets
Incapaz de pagar a Contacto
diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml
index d831a98a93..2ba3dd584b 100644
--- a/app/src/main/res/values-ca/strings.xml
+++ b/app/src/main/res/values-ca/strings.xml
@@ -904,6 +904,50 @@
Error en enviar
Bitkit ha estat creat per Synonym Software, S.A. DE C.V. ©2025. Tots els drets reservats.
Suport
+ Desvincular i esborrar el rellotge
+ Esborrar
+ S\'està esperant que el rellotge esborri la seva cartera. Un rellotge que no es torni a connectar la conservarà.
+ El rellotge oblidarà aquest telèfon i eliminarà la seva cartera la pròxima vegada que es connecti. Un rellotge que no es torni a connectar conservarà la cartera, així que mou els teus fons a una cartera nova si perds el rellotge.
+ Esborrar el rellotge?
+ Vinculació cancel·lada.
+ La vinculació s\'ha cancel·lat al rellotge.
+ El rellotge conté una cartera diferent.
+ La vinculació ha fallat. Torna-ho a provar.
+ Aquest rellotge no té maquinari segur per guardar una cartera.
+ Primer defineix un PIN a Bitkit i després vincula el rellotge.
+ No s\'ha pogut comprovar el maquinari segur del rellotge. Connecta\'t a internet i torna-ho a provar.
+ El rellotge no ha pogut desar la cartera.
+ Massa intents. Torna-ho a provar més tard.
+ S\'ha esgotat el temps de vinculació.
+ No es pot accedir al teu rellotge. Mantén-lo a prop amb el Bluetooth activat.
+ No s\'ha pogut verificar el maquinari segur d\'aquest rellotge, de manera que la teva cartera no s\'ha enviat.
+ Actualitza Bitkit al telèfon i al rellotge.
+ Aquest rellotge conté la teva cartera completa i en pot gastar els fons.
+ Claus del rellotge verificades a StrongBox.
+ Claus del rellotge verificades al maquinari segur.
+ Maquinari segur del rellotge no verificat.
+ S\'està cercant el teu rellotge…
+ Rellotge
+ Instal·la Bitkit a {name} per vincular-lo.
+ No hi ha cap rellotge connectat. Connecta primer un rellotge Wear OS a aquest telèfon.
+ No vinculat
+ Vincular rellotge
+ Comprova que {name} mostra aquest codi.
+ Vincular
+ Obre Bitkit al teu rellotge.
+ El teu rellotge està vinculat.
+ S\'està enviant la teva cartera al rellotge…
+ Aquest rellotge no té cartera. En vincular-lo se li envia la teva frase de recuperació, de manera que contindrà la teva cartera completa.
+ Vincular rellotge
+ Confirma el codi al teu rellotge.
+ {name} està a punt per vincular.
+ La configuració encara no és al rellotge.
+ Configuració del rellotge actualitzada.
+ Deixar d\'esperar
+ Desvincular
+ S\'està esperant que el rellotge es desvinculi.
+ El rellotge oblidarà aquest telèfon. La cartera es queda al rellotge.
+ Desvincular el rellotge?
Ginys
Ginys
No s\'ha pogut pagar el contacte.
diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml
index 01133e01b1..da41b94409 100644
--- a/app/src/main/res/values-cs/strings.xml
+++ b/app/src/main/res/values-cs/strings.xml
@@ -909,6 +909,50 @@
Odeslání se nezdařilo
Bitkit vytvořila společnost Synonym Software, S.A. DE C.V. ©2025. Všechna práva vyhrazena.
Podpora
+ Zrušit spárování a vymazat hodinky
+ Vymazat
+ Čeká se, až hodinky vymažou svou peněženku. Hodinky, které se už nepřipojí, si ji ponechají.
+ Hodinky zapomenou tento telefon a při příštím připojení smažou svou peněženku. Hodinky, které se už nepřipojí, si peněženku ponechají, proto při ztrátě hodinek přesuňte prostředky do nové peněženky.
+ Vymazat hodinky?
+ Párování zrušeno.
+ Párování bylo zrušeno na hodinkách.
+ Hodinky obsahují jinou peněženku.
+ Párování se nezdařilo. Zkuste to prosím znovu.
+ Tyto hodinky nemají bezpečný hardware pro uložení peněženky.
+ Nejprve si v aplikaci Bitkit nastavte PIN a potom hodinky spárujte.
+ Bezpečný hardware hodinek se nepodařilo zkontrolovat. Připojte se k internetu a zkuste to znovu.
+ Hodinky nemohly peněženku uložit.
+ Příliš mnoho pokusů. Zkuste to znovu později.
+ Časový limit párování vypršel.
+ Hodinky nejsou dostupné. Mějte je poblíž se zapnutým Bluetooth.
+ Bezpečný hardware těchto hodinek se nepodařilo ověřit, proto vaše peněženka nebyla odeslána.
+ Aktualizujte Bitkit v telefonu i v hodinkách.
+ Tyto hodinky obsahují vaši celou peněženku a mohou z ní utrácet.
+ Klíče hodinek ověřeny ve StrongBox.
+ Klíče hodinek ověřeny v bezpečném hardwaru.
+ Bezpečný hardware hodinek nebyl ověřen.
+ Hledání hodinek…
+ Hodinky
+ Pro spárování nainstalujte Bitkit do zařízení {name}.
+ Nejsou připojeny žádné hodinky. Nejprve k tomuto telefonu připojte hodinky s Wear OS.
+ Nespárováno
+ Spárovat hodinky
+ Zkontrolujte, že zařízení {name} zobrazuje tento kód.
+ Spárovat
+ Otevřete Bitkit v hodinkách.
+ Hodinky jsou spárovány.
+ Odesílání peněženky do hodinek…
+ Tyto hodinky nemají peněženku. Spárováním se do nich odešle vaše fráze pro obnovení, takže budou obsahovat vaši celou peněženku.
+ Spárovat hodinky
+ Potvrďte kód na hodinkách.
+ Zařízení {name} je připraveno ke spárování.
+ Nastavení zatím není v hodinkách.
+ Nastavení hodinek je aktuální.
+ Přestat čekat
+ Zrušit spárování
+ Čeká se na zrušení spárování hodinek.
+ Hodinky zapomenou tento telefon. Peněženka v hodinkách zůstane.
+ Zrušit spárování hodinek?
Widgety
Widgety
Není možné zaplatit kontaktu
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
index e6666288e8..80b190f8c3 100644
--- a/app/src/main/res/values-de/strings.xml
+++ b/app/src/main/res/values-de/strings.xml
@@ -746,6 +746,50 @@
Früher verwendete Tags
Oberfläche
Zahlungen
+ Entkoppeln und Uhr löschen
+ Löschen
+ Warte darauf, dass die Uhr ihr Wallet löscht. Eine Uhr, die sich nie wieder verbindet, behält es.
+ Die Uhr vergisst dieses Telefon und löscht ihr Wallet, sobald sie sich das nächste Mal verbindet. Eine Uhr, die sich nie wieder verbindet, behält das Wallet. Verschiebe dein Guthaben daher in ein neues Wallet, falls die Uhr verloren geht.
+ Uhr löschen?
+ Kopplung abgebrochen.
+ Die Kopplung wurde auf der Uhr abgebrochen.
+ Auf der Uhr befindet sich ein anderes Wallet.
+ Kopplung fehlgeschlagen. Bitte versuche es erneut.
+ Diese Uhr hat keine sichere Hardware, um ein Wallet aufzubewahren.
+ Lege zuerst eine PIN in Bitkit fest und kopple dann deine Uhr.
+ Die sichere Hardware der Uhr konnte nicht geprüft werden. Verbinde dich mit dem Internet und versuche es erneut.
+ Die Uhr konnte das Wallet nicht speichern.
+ Zu viele Versuche. Versuche es später erneut.
+ Zeitüberschreitung bei der Kopplung.
+ Deine Uhr ist nicht erreichbar. Halte sie in der Nähe und lasse Bluetooth eingeschaltet.
+ Die sichere Hardware dieser Uhr konnte nicht verifiziert werden, daher wurde dein Wallet nicht gesendet.
+ Aktualisiere Bitkit auf deinem Telefon und deiner Uhr.
+ Diese Uhr enthält dein vollständiges Wallet und kann daraus Zahlungen senden.
+ Schlüssel der Uhr in StrongBox verifiziert.
+ Schlüssel der Uhr in sicherer Hardware verifiziert.
+ Sichere Hardware der Uhr nicht verifiziert.
+ Suche nach deiner Uhr…
+ Uhr
+ Installiere Bitkit auf {name}, um die Uhr zu koppeln.
+ Keine Uhr verbunden. Verbinde zuerst eine Wear OS-Uhr mit diesem Telefon.
+ Nicht gekoppelt
+ Uhr koppeln
+ Prüfe, ob {name} diesen Code anzeigt.
+ Koppeln
+ Öffne Bitkit auf deiner Uhr.
+ Deine Uhr ist gekoppelt.
+ Dein Wallet wird an die Uhr gesendet…
+ Diese Uhr hat kein Wallet. Beim Koppeln wird deine Wiederherstellungsphrase an sie gesendet, sodass sie dein vollständiges Wallet enthält.
+ Uhr koppeln
+ Bestätige den Code auf deiner Uhr.
+ {name} ist bereit zum Koppeln.
+ Einstellungen noch nicht auf der Uhr.
+ Einstellungen der Uhr sind aktuell.
+ Nicht mehr warten
+ Entkoppeln
+ Warte darauf, dass die Uhr entkoppelt wird.
+ Die Uhr vergisst dieses Telefon. Das Wallet bleibt auf der Uhr.
+ Uhr entkoppeln?
Widgets
Widgets
Kontakt konnte nicht bezahlt werden
diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml
index fee81da7a5..12973abf61 100644
--- a/app/src/main/res/values-el/strings.xml
+++ b/app/src/main/res/values-el/strings.xml
@@ -889,6 +889,50 @@
Αποτυχία αποστολής
Το Bitkit δημιουργήθηκε από τη Synonym Software, S.A. DE C.V. ©2025. Με επιφύλαξη παντός δικαιώματος.
Υποστήριξη
+ Αποσύζευξη και διαγραφή ρολογιού
+ Διαγραφή
+ Αναμονή για τη διαγραφή του πορτοφολιού από το ρολόι. Ένα ρολόι που δεν συνδεθεί ποτέ ξανά το διατηρεί.
+ Το ρολόι θα ξεχάσει αυτό το τηλέφωνο και θα διαγράψει το πορτοφόλι του την επόμενη φορά που θα συνδεθεί. Ένα ρολόι που δεν συνδεθεί ποτέ ξανά διατηρεί το πορτοφόλι, γι\' αυτό μετάφερε τα χρήματά σου σε νέο πορτοφόλι αν το ρολόι χαθεί.
+ Διαγραφή ρολογιού;
+ Η σύζευξη ακυρώθηκε.
+ Η σύζευξη ακυρώθηκε στο ρολόι.
+ Το ρολόι περιέχει διαφορετικό πορτοφόλι.
+ Η σύζευξη απέτυχε. Δοκίμασε ξανά.
+ Αυτό το ρολόι δεν διαθέτει ασφαλές υλικό για τη φύλαξη πορτοφολιού.
+ Όρισε πρώτα ένα PIN στο Bitkit και μετά κάνε σύζευξη του ρολογιού.
+ Δεν ήταν δυνατός ο έλεγχος του ασφαλούς υλικού του ρολογιού. Συνδέσου στο διαδίκτυο και δοκίμασε ξανά.
+ Το ρολόι δεν μπόρεσε να αποθηκεύσει το πορτοφόλι.
+ Πάρα πολλές προσπάθειες. Δοκίμασε ξανά αργότερα.
+ Το χρονικό όριο της σύζευξης έληξε.
+ Το ρολόι σου δεν είναι προσβάσιμο. Κράτησέ το κοντά με το Bluetooth ενεργό.
+ Το ασφαλές υλικό αυτού του ρολογιού δεν μπόρεσε να επαληθευτεί, οπότε το πορτοφόλι σου δεν στάλθηκε.
+ Ενημέρωσε το Bitkit στο τηλέφωνο και στο ρολόι σου.
+ Αυτό το ρολόι περιέχει ολόκληρο το πορτοφόλι σου και μπορεί να ξοδέψει από αυτό.
+ Τα κλειδιά του ρολογιού επαληθεύτηκαν στο StrongBox.
+ Τα κλειδιά του ρολογιού επαληθεύτηκαν σε ασφαλές υλικό.
+ Το ασφαλές υλικό του ρολογιού δεν επαληθεύτηκε.
+ Αναζήτηση του ρολογιού σου…
+ Ρολόι
+ Εγκατάστησε το Bitkit στο {name} για σύζευξη.
+ Δεν υπάρχει συνδεδεμένο ρολόι. Σύνδεσε πρώτα ένα ρολόι Wear OS σε αυτό το τηλέφωνο.
+ Χωρίς σύζευξη
+ Σύζευξη ρολογιού
+ Έλεγξε ότι το {name} εμφανίζει αυτόν τον κωδικό.
+ Σύζευξη
+ Άνοιξε το Bitkit στο ρολόι σου.
+ Το ρολόι σου έχει συζευχθεί.
+ Αποστολή του πορτοφολιού σου στο ρολόι…
+ Αυτό το ρολόι δεν έχει πορτοφόλι. Η σύζευξη του στέλνει τη φράση ανάκτησής σου, οπότε θα περιέχει ολόκληρο το πορτοφόλι σου.
+ Σύζευξη ρολογιού
+ Επιβεβαίωσε τον κωδικό στο ρολόι σου.
+ Το {name} είναι έτοιμο για σύζευξη.
+ Οι ρυθμίσεις δεν είναι ακόμη στο ρολόι.
+ Οι ρυθμίσεις του ρολογιού είναι ενημερωμένες.
+ Διακοπή αναμονής
+ Αποσύζευξη
+ Αναμονή για την αποσύζευξη του ρολογιού.
+ Το ρολόι θα ξεχάσει αυτό το τηλέφωνο. Το πορτοφόλι παραμένει στο ρολόι.
+ Αποσύζευξη ρολογιού;
Widgets
Widgets
Επαναφορά καρτών προτάσεων
diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml
index 29e2727911..ea84475100 100644
--- a/app/src/main/res/values-es-rES/strings.xml
+++ b/app/src/main/res/values-es-rES/strings.xml
@@ -907,6 +907,50 @@
Error al enviar
Bitkit fue creado por Synonym Software, S.A. DE C.V. ©2025. Todos los derechos reservados.
Soporte
+ Desvincular y borrar el reloj
+ Borrar
+ Esperando a que el reloj borre la cartera. Un reloj que no vuelva a conectarse la conservará.
+ El reloj olvidará este teléfono y eliminará la cartera la próxima vez que se conecte. Un reloj que no vuelva a conectarse conservará la cartera, así que mueve tus fondos a una cartera nueva si pierdes el reloj.
+ ¿Borrar el reloj?
+ Vinculación cancelada.
+ La vinculación se canceló en el reloj.
+ El reloj contiene una cartera distinta.
+ La vinculación ha fallado. Inténtalo de nuevo.
+ Este reloj no tiene hardware seguro para guardar una cartera.
+ Primero configura un PIN en Bitkit y luego vincula tu reloj.
+ No se pudo comprobar el hardware seguro del reloj. Conéctate a internet e inténtalo de nuevo.
+ El reloj no pudo guardar la cartera.
+ Demasiados intentos. Inténtalo de nuevo más tarde.
+ Se agotó el tiempo de vinculación.
+ No se puede acceder a tu reloj. Mantenlo cerca y con el Bluetooth activado.
+ No se pudo verificar el hardware seguro de este reloj, por lo que no se envió tu cartera.
+ Actualiza Bitkit en tu teléfono y en tu reloj.
+ Este reloj contiene tu cartera completa y puede gastar tus fondos.
+ Claves del reloj verificadas en StrongBox.
+ Claves del reloj verificadas en hardware seguro.
+ Hardware seguro del reloj no verificado.
+ Buscando tu reloj…
+ Reloj
+ Instala Bitkit en {name} para vincularlo.
+ No hay ningún reloj conectado. Conecta primero un reloj Wear OS a este teléfono.
+ No vinculado
+ Vincular reloj
+ Comprueba que {name} muestra este código.
+ Vincular
+ Abre Bitkit en tu reloj.
+ Tu reloj está vinculado.
+ Enviando tu cartera al reloj…
+ Este reloj no tiene cartera. Al vincularlo se le envía tu frase de recuperación, por lo que contendrá tu cartera completa.
+ Vincular reloj
+ Confirma el código en tu reloj.
+ {name} está listo para vincularse.
+ Los ajustes aún no están en el reloj.
+ Ajustes del reloj actualizados.
+ Dejar de esperar
+ Desvincular
+ Esperando a que el reloj se desvincule.
+ El reloj olvidará este teléfono. La cartera permanece en el reloj.
+ ¿Desvincular el reloj?
Widgets
Widgets
Restablecer tarjetas de sugerencias
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index c713dae08e..b24fd0f4f0 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -743,6 +743,50 @@
Etiquetas utilizadas anteriormente
Interfaz
Pagos
+ Desvincular y borrar el reloj
+ Borrar
+ Esperando a que el reloj borre la cartera. Un reloj que no vuelva a conectarse la conservará.
+ El reloj olvidará este teléfono y eliminará la cartera la próxima vez que se conecte. Un reloj que no vuelva a conectarse conservará la cartera, así que mueva sus fondos a una cartera nueva si pierde el reloj.
+ ¿Borrar el reloj?
+ Vinculación cancelada.
+ La vinculación se canceló en el reloj.
+ El reloj contiene una cartera distinta.
+ La vinculación ha fallado. Inténtelo de nuevo.
+ Este reloj no tiene hardware seguro para guardar una cartera.
+ Primero configure un PIN en Bitkit y luego vincule su reloj.
+ No se pudo comprobar el hardware seguro del reloj. Conéctese a internet e inténtelo de nuevo.
+ El reloj no pudo guardar la cartera.
+ Demasiados intentos. Inténtelo de nuevo más tarde.
+ Se agotó el tiempo de vinculación.
+ No se puede acceder a su reloj. Manténgalo cerca y con el Bluetooth activado.
+ No se pudo verificar el hardware seguro de este reloj, por lo que no se envió su cartera.
+ Actualice Bitkit en su teléfono y en su reloj.
+ Este reloj contiene su cartera completa y puede gastar sus fondos.
+ Claves del reloj verificadas en StrongBox.
+ Claves del reloj verificadas en hardware seguro.
+ Hardware seguro del reloj no verificado.
+ Buscando su reloj…
+ Reloj
+ Instale Bitkit en {name} para vincularlo.
+ No hay ningún reloj conectado. Conecte primero un reloj Wear OS a este teléfono.
+ No vinculado
+ Vincular reloj
+ Compruebe que {name} muestra este código.
+ Vincular
+ Abra Bitkit en su reloj.
+ Su reloj está vinculado.
+ Enviando su cartera al reloj…
+ Este reloj no tiene cartera. Al vincularlo se le envía su frase de recuperación, por lo que contendrá su cartera completa.
+ Vincular reloj
+ Confirme el código en su reloj.
+ {name} está listo para vincularse.
+ Los ajustes aún no están en el reloj.
+ Ajustes del reloj actualizados.
+ Dejar de esperar
+ Desvincular
+ Esperando a que el reloj se desvincule.
+ El reloj olvidará este teléfono. La cartera permanece en el reloj.
+ ¿Desvincular el reloj?
Widgets
Widgets
Cancelar
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index d1cd1f6577..032ffb21e3 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -746,6 +746,50 @@
Étiquettes précédemment utilisées
Interface
Paiements
+ Dissocier et effacer la montre
+ Effacer
+ En attente de l\'effacement du portefeuille par la montre. Une montre qui ne se reconnecte jamais le conserve.
+ La montre oubliera ce téléphone et supprimera son portefeuille à sa prochaine connexion. Une montre qui ne se reconnecte jamais conserve le portefeuille : transférez donc vos fonds vers un nouveau portefeuille si la montre est perdue.
+ Effacer la montre ?
+ Association annulée.
+ L\'association a été annulée sur la montre.
+ La montre contient un autre portefeuille.
+ L\'association a échoué. Veuillez réessayer.
+ Cette montre n\'a pas de matériel sécurisé pour conserver un portefeuille.
+ Définissez d\'abord un code PIN dans Bitkit, puis associez votre montre.
+ Impossible de vérifier le matériel sécurisé de la montre. Connectez-vous à Internet et réessayez.
+ La montre n\'a pas pu enregistrer le portefeuille.
+ Trop de tentatives. Réessayez plus tard.
+ L\'association a expiré.
+ Votre montre est injoignable. Gardez-la à proximité avec le Bluetooth activé.
+ Le matériel sécurisé de cette montre n\'a pas pu être vérifié, votre portefeuille n\'a donc pas été envoyé.
+ Mettez à jour Bitkit sur votre téléphone et votre montre.
+ Cette montre contient votre portefeuille complet et peut dépenser vos fonds.
+ Clés de la montre vérifiées dans StrongBox.
+ Clés de la montre vérifiées dans le matériel sécurisé.
+ Matériel sécurisé de la montre non vérifié.
+ Recherche de votre montre…
+ Montre
+ Installez Bitkit sur {name} pour l\'associer.
+ Aucune montre connectée. Connectez d\'abord une montre Wear OS à ce téléphone.
+ Non associée
+ Associer la montre
+ Vérifiez que {name} affiche ce code.
+ Associer
+ Ouvrez Bitkit sur votre montre.
+ Votre montre est associée.
+ Envoi de votre portefeuille à la montre…
+ Cette montre n\'a pas de portefeuille. L\'association lui envoie votre phrase de récupération : elle contiendra donc votre portefeuille complet.
+ Associer la montre
+ Confirmez le code sur votre montre.
+ Vous pouvez associer {name}.
+ Paramètres pas encore sur la montre.
+ Paramètres de la montre à jour.
+ Ne plus attendre
+ Dissocier
+ En attente de la dissociation de la montre.
+ La montre oubliera ce téléphone. Le portefeuille reste sur la montre.
+ Dissocier la montre ?
Widgets
Widgets
Incapable de payer le contact
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index 618774ccb9..e767df0977 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -906,6 +906,50 @@
Impossibile inviare
Bitkit è stato realizzato da Synonym Software, S.A. DE C.V. ©2025. Tutti i diritti riservati.
Supporto
+ Dissocia e Cancella Orologio
+ Cancella
+ In attesa che l\'orologio cancelli il suo wallet. Un orologio che non si riconnette mai lo conserva.
+ L\'orologio dimenticherà questo telefono ed eliminerà il suo wallet alla prossima connessione. Un orologio che non si riconnette mai conserva il wallet, quindi sposta i tuoi fondi su un nuovo wallet se l\'orologio viene smarrito.
+ Cancellare l\'Orologio?
+ Associazione annullata.
+ L\'associazione è stata annullata sull\'orologio.
+ L\'orologio contiene un wallet diverso.
+ Associazione non riuscita. Riprova.
+ Questo orologio non ha un hardware sicuro per custodire un wallet.
+ Imposta prima un PIN in Bitkit, poi associa l\'orologio.
+ Non è stato possibile controllare l\'hardware sicuro dell\'orologio. Connettiti a internet e riprova.
+ L\'orologio non è riuscito a salvare il wallet.
+ Troppi tentativi. Riprova più tardi.
+ Associazione scaduta.
+ Il tuo orologio non è raggiungibile. Tienilo vicino con il Bluetooth attivo.
+ Non è stato possibile verificare l\'hardware sicuro di questo orologio, quindi il tuo wallet non è stato inviato.
+ Aggiorna Bitkit sul telefono e sull\'orologio.
+ Questo orologio contiene il tuo wallet completo e può spenderne i fondi.
+ Chiavi dell\'orologio verificate in StrongBox.
+ Chiavi dell\'orologio verificate nell\'hardware sicuro.
+ Hardware sicuro dell\'orologio non verificato.
+ Ricerca del tuo orologio…
+ Orologio
+ Installa Bitkit su {name} per associarlo.
+ Nessun orologio connesso. Connetti prima un orologio Wear OS a questo telefono.
+ Non associato
+ Associa Orologio
+ Controlla che {name} mostri questo codice.
+ Associa
+ Apri Bitkit sul tuo orologio.
+ Il tuo orologio è associato.
+ Invio del tuo wallet all\'orologio…
+ Questo orologio non ha un wallet. L\'associazione gli invia la tua frase di ripristino, quindi conterrà il tuo wallet completo.
+ Associa Orologio
+ Conferma il codice sul tuo orologio.
+ {name} è pronto per l\'associazione.
+ Impostazioni non ancora sull\'orologio.
+ Impostazioni dell\'orologio aggiornate.
+ Smetti di Attendere
+ Dissocia
+ In attesa che l\'orologio venga dissociato.
+ L\'orologio dimenticherà questo telefono. Il wallet resta sull\'orologio.
+ Dissociare l\'Orologio?
Widget
Widget
Impossibile pagare questo contatto
diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml
index 22e2d1d8a7..3c85fff08d 100644
--- a/app/src/main/res/values-nl/strings.xml
+++ b/app/src/main/res/values-nl/strings.xml
@@ -904,6 +904,50 @@
Verzenden mislukt
Bitkit is gemaakt door Synonym Software, S.A. DE C.V. ©2025. Alle rechten voorbehouden.
Ondersteuning
+ Ontkoppelen en horloge wissen
+ Wissen
+ Wachten tot het horloge zijn wallet wist. Een horloge dat nooit meer verbinding maakt, behoudt de wallet.
+ Het horloge vergeet deze telefoon en verwijdert zijn wallet zodra het weer verbinding maakt. Een horloge dat nooit meer verbinding maakt, behoudt de wallet. Verplaats je geld dus naar een nieuwe wallet als je het horloge kwijt bent.
+ Horloge wissen?
+ Koppelen geannuleerd.
+ Het koppelen is op het horloge geannuleerd.
+ Het horloge bevat een andere wallet.
+ Koppelen mislukt. Probeer het opnieuw.
+ Dit horloge heeft geen veilige hardware om een wallet te bewaren.
+ Stel eerst een PIN in Bitkit in en koppel daarna je horloge.
+ De veilige hardware van het horloge kon niet worden gecontroleerd. Maak verbinding met internet en probeer het opnieuw.
+ Het horloge kon de wallet niet opslaan.
+ Te veel pogingen. Probeer het later opnieuw.
+ Time-out bij het koppelen.
+ Je horloge is niet bereikbaar. Houd het in de buurt met Bluetooth aan.
+ De veilige hardware van dit horloge kon niet worden geverifieerd, dus je wallet is niet verzonden.
+ Werk Bitkit bij op je telefoon en je horloge.
+ Dit horloge bevat je volledige wallet en kan ermee betalen.
+ Sleutels van het horloge geverifieerd in StrongBox.
+ Sleutels van het horloge geverifieerd in veilige hardware.
+ Veilige hardware van het horloge niet geverifieerd.
+ Je horloge zoeken…
+ Horloge
+ Installeer Bitkit op {name} om te koppelen.
+ Geen horloge verbonden. Verbind eerst een Wear OS-horloge met deze telefoon.
+ Niet gekoppeld
+ Horloge koppelen
+ Controleer of {name} deze code toont.
+ Koppelen
+ Open Bitkit op je horloge.
+ Je horloge is gekoppeld.
+ Je wallet naar het horloge verzenden…
+ Dit horloge heeft geen wallet. Bij het koppelen wordt je herstelzin ernaartoe gestuurd, zodat het je volledige wallet bevat.
+ Horloge koppelen
+ Bevestig de code op je horloge.
+ {name} is klaar om te koppelen.
+ Instellingen nog niet op het horloge.
+ Horloge-instellingen zijn up-to-date.
+ Stoppen met wachten
+ Ontkoppelen
+ Wachten tot het horloge is ontkoppeld.
+ Het horloge vergeet deze telefoon. De wallet blijft op het horloge.
+ Horloge ontkoppelen?
Widgets
Widgets
Suggestiekaarten resetten
diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml
index 907e06e657..ef62f31260 100644
--- a/app/src/main/res/values-pl/strings.xml
+++ b/app/src/main/res/values-pl/strings.xml
@@ -747,6 +747,50 @@
Poprzednio używane tagi
Interfejs
Płatności
+ Anuluj sparowanie i wyczyść zegarek
+ Wyczyść
+ Czekam, aż zegarek usunie swój portfel. Zegarek, który nigdy więcej się nie połączy, zachowa go.
+ Zegarek zapomni ten telefon i usunie swój portfel przy następnym połączeniu. Zegarek, który nigdy więcej się nie połączy, zachowa portfel, więc jeśli zegarek zaginie, przenieś środki do nowego portfela.
+ Wyczyścić zegarek?
+ Parowanie anulowane.
+ Parowanie zostało anulowane na zegarku.
+ Na zegarku jest inny portfel.
+ Parowanie nie powiodło się. Spróbuj ponownie.
+ Ten zegarek nie ma bezpiecznego sprzętu do przechowywania portfela.
+ Najpierw ustaw kod PIN w Bitkit, a potem sparuj zegarek.
+ Nie udało się sprawdzić bezpiecznego sprzętu zegarka. Połącz się z internetem i spróbuj ponownie.
+ Zegarek nie mógł zapisać portfela.
+ Zbyt wiele prób. Spróbuj ponownie później.
+ Upłynął czas parowania.
+ Twój zegarek jest nieosiągalny. Trzymaj go w pobliżu z włączonym Bluetooth.
+ Nie udało się zweryfikować bezpiecznego sprzętu tego zegarka, więc Twój portfel nie został wysłany.
+ Zaktualizuj Bitkit na telefonie i zegarku.
+ Ten zegarek przechowuje Twój pełny portfel i może wydawać z niego środki.
+ Klucze zegarka zweryfikowane w StrongBox.
+ Klucze zegarka zweryfikowane w bezpiecznym sprzęcie.
+ Bezpieczny sprzęt zegarka niezweryfikowany.
+ Szukam Twojego zegarka…
+ Zegarek
+ Zainstaluj Bitkit na {name}, aby go sparować.
+ Brak połączonego zegarka. Najpierw połącz zegarek z Wear OS z tym telefonem.
+ Nie sparowano
+ Sparuj zegarek
+ Sprawdź, czy {name} pokazuje ten kod.
+ Sparuj
+ Otwórz Bitkit na zegarku.
+ Twój zegarek jest sparowany.
+ Wysyłam Twój portfel do zegarka…
+ Ten zegarek nie ma portfela. Parowanie wyśle do niego Twoją frazę odzyskiwania, więc będzie przechowywał Twój pełny portfel.
+ Sparuj zegarek
+ Potwierdź kod na zegarku.
+ {name} jest gotowy do sparowania.
+ Ustawień nie ma jeszcze na zegarku.
+ Ustawienia zegarka są aktualne.
+ Przestań czekać
+ Anuluj sparowanie
+ Czekam na anulowanie sparowania zegarka.
+ Zegarek zapomni ten telefon. Portfel pozostanie na zegarku.
+ Anulować sparowanie zegarka?
Widgety
Widgety
Brak możliwości zapłaty Kontaktowi
diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml
index c00aefadf8..e6c3bb4597 100644
--- a/app/src/main/res/values-pt-rBR/strings.xml
+++ b/app/src/main/res/values-pt-rBR/strings.xml
@@ -911,6 +911,50 @@
Falha no Envio
Bitkit foi criado pela Synonym Software, S.A. DE C.V. ©2025. Todos os direitos reservados.
Suporte
+ Desparear e Apagar Relógio
+ Apagar
+ Aguardando o relógio apagar a carteira. Um relógio que nunca se reconectar continuará com ela.
+ O relógio vai esquecer este telefone e excluir a carteira na próxima vez que se conectar. Um relógio que nunca se reconectar continuará com a carteira, então mova seus fundos para uma nova carteira se o relógio for perdido.
+ Apagar Relógio?
+ Pareamento cancelado.
+ O pareamento foi cancelado no relógio.
+ O relógio contém uma carteira diferente.
+ O pareamento falhou. Tente novamente.
+ Este relógio não tem hardware seguro para guardar uma carteira.
+ Primeiro defina um PIN na Bitkit e depois pareie o relógio.
+ Não foi possível verificar o hardware seguro do relógio. Conecte-se à internet e tente novamente.
+ O relógio não conseguiu armazenar a carteira.
+ Muitas tentativas. Tente novamente mais tarde.
+ O pareamento expirou.
+ Seu relógio está inacessível. Mantenha-o por perto com o Bluetooth ativado.
+ Não foi possível verificar o hardware seguro deste relógio, então sua carteira não foi enviada.
+ Atualize a Bitkit no telefone e no relógio.
+ Este relógio contém sua carteira completa e pode gastar seus fundos.
+ Chaves do relógio verificadas no StrongBox.
+ Chaves do relógio verificadas em hardware seguro.
+ Hardware seguro do relógio não verificado.
+ Procurando seu relógio…
+ Relógio
+ Instale a Bitkit em {name} para parear.
+ Nenhum relógio conectado. Primeiro conecte um relógio Wear OS a este telefone.
+ Não pareado
+ Parear Relógio
+ Verifique se {name} mostra este código.
+ Parear
+ Abra a Bitkit no seu relógio.
+ Seu relógio está pareado.
+ Enviando sua carteira para o relógio…
+ Este relógio não tem carteira. O pareamento envia sua frase de recuperação para ele, que passará a conter sua carteira completa.
+ Parear Relógio
+ Confirme o código no seu relógio.
+ {name} está pronto para parear.
+ Os ajustes ainda não estão no relógio.
+ Ajustes do relógio atualizados.
+ Parar de Esperar
+ Desparear
+ Aguardando o relógio ser despareado.
+ O relógio vai esquecer este telefone. A carteira permanece no relógio.
+ Desparear Relógio?
Widgets
Widgets
Não foi Possível Pagar Contato
diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml
index 4a6bc4563a..a86f2e8e92 100644
--- a/app/src/main/res/values-pt/strings.xml
+++ b/app/src/main/res/values-pt/strings.xml
@@ -725,6 +725,50 @@
Tags usadas anteriormente
Interface
Pagamentos
+ Desemparelhar e apagar relógio
+ Apagar
+ A aguardar que o relógio apague a carteira. Um relógio que nunca volte a ligar-se mantém-na.
+ O relógio vai esquecer este telemóvel e eliminar a carteira na próxima vez que se ligar. Um relógio que nunca volte a ligar-se mantém a carteira, por isso mova os seus fundos para uma nova carteira se o relógio for perdido.
+ Apagar relógio?
+ Emparelhamento cancelado.
+ O emparelhamento foi cancelado no relógio.
+ O relógio contém uma carteira diferente.
+ O emparelhamento falhou. Tente novamente.
+ Este relógio não tem hardware seguro para guardar uma carteira.
+ Primeiro defina um PIN na Bitkit e depois emparelhe o relógio.
+ Não foi possível verificar o hardware seguro do relógio. Ligue-se à internet e tente novamente.
+ O relógio não conseguiu guardar a carteira.
+ Demasiadas tentativas. Tente novamente mais tarde.
+ O emparelhamento expirou.
+ O seu relógio não está acessível. Mantenha-o por perto com o Bluetooth ligado.
+ Não foi possível verificar o hardware seguro deste relógio, por isso a sua carteira não foi enviada.
+ Atualize a Bitkit no telemóvel e no relógio.
+ Este relógio contém a sua carteira completa e pode gastar os seus fundos.
+ Chaves do relógio verificadas no StrongBox.
+ Chaves do relógio verificadas em hardware seguro.
+ Hardware seguro do relógio não verificado.
+ A procurar o seu relógio…
+ Relógio
+ Instale a Bitkit em {name} para o emparelhar.
+ Nenhum relógio ligado. Ligue primeiro um relógio Wear OS a este telemóvel.
+ Não emparelhado
+ Emparelhar relógio
+ Verifique se {name} mostra este código.
+ Emparelhar
+ Abra a Bitkit no seu relógio.
+ O seu relógio está emparelhado.
+ A enviar a sua carteira para o relógio…
+ Este relógio não tem carteira. O emparelhamento envia-lhe a sua frase de recuperação, pelo que ficará com a sua carteira completa.
+ Emparelhar relógio
+ Confirme o código no seu relógio.
+ {name} está pronto para emparelhar.
+ Os ajustes ainda não estão no relógio.
+ Ajustes do relógio atualizados.
+ Parar de esperar
+ Desemparelhar
+ A aguardar que o relógio seja desemparelhado.
+ O relógio vai esquecer este telemóvel. A carteira permanece no relógio.
+ Desemparelhar relógio?
Widgets
Widgets
Cancelar
diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml
index f6c914f3db..2c1f4ce0c1 100644
--- a/app/src/main/res/values-ru/strings.xml
+++ b/app/src/main/res/values-ru/strings.xml
@@ -923,6 +923,50 @@
Не Удалось Отправить
Bitkit создан компанией Synonym Software, S.A. DE C.V. ©2025. Все права защищены.
Поддержка
+ Отменить Сопряжение И Стереть Часы
+ Стереть
+ Ожидаем, пока часы сотрут свой кошелёк. Если часы больше не подключатся, кошелёк останется на них.
+ Часы забудут этот телефон и удалят свой кошелёк при следующем подключении. Если часы больше не подключатся, кошелёк останется на них, поэтому переведите средства в новый кошелёк, если часы утеряны.
+ Стереть Часы?
+ Сопряжение отменено.
+ Сопряжение было отменено на часах.
+ На часах другой кошелёк.
+ Не удалось выполнить сопряжение. Пожалуйста, попробуйте снова.
+ В этих часах нет защищённого модуля для хранения кошелька.
+ Сначала установите PIN-код в Bitkit, затем выполните сопряжение часов.
+ Не удалось проверить защищённый модуль часов. Подключитесь к интернету и попробуйте снова.
+ Часам не удалось сохранить кошелёк.
+ Слишком много попыток. Попробуйте позже.
+ Время сопряжения истекло.
+ Часы недоступны. Держите их рядом с включённым Bluetooth.
+ Не удалось проверить защищённый модуль этих часов, поэтому ваш кошелёк не был отправлен.
+ Обновите Bitkit на телефоне и на часах.
+ На этих часах хранится ваш кошелёк целиком, и с них можно тратить средства.
+ Ключи часов проверены в StrongBox.
+ Ключи часов проверены в защищённом модуле.
+ Защищённый модуль часов не проверен.
+ Поиск ваших часов…
+ Часы
+ Установите Bitkit на {name}, чтобы выполнить сопряжение.
+ Часы не подключены. Сначала подключите часы Wear OS к этому телефону.
+ Нет сопряжения
+ Сопрячь Часы
+ Убедитесь, что {name} показывает этот код.
+ Сопрячь
+ Откройте Bitkit на часах.
+ Часы сопряжены.
+ Отправка кошелька на часы…
+ На этих часах нет кошелька. При сопряжении на них отправляется ваша фраза восстановления, поэтому на них будет храниться ваш кошелёк целиком.
+ Сопряжение Часов
+ Подтвердите код на часах.
+ Устройство {name} готово к сопряжению.
+ Настройки ещё не переданы на часы.
+ Настройки часов актуальны.
+ Не Ждать
+ Отменить Сопряжение
+ Ожидаем отмены сопряжения на часах.
+ Часы забудут этот телефон. Кошелёк останется на часах.
+ Отменить Сопряжение?
Виджеты
Виджеты
Невозможно Заплатить Контакту
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index b42b86792e..864c33d60c 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -1247,6 +1247,50 @@
Sent Successfully
Failed To Send
Support
+ Unpair and Erase Watch
+ Erase
+ Waiting for the watch to erase its wallet. A watch that never reconnects keeps it.
+ The watch will forget this phone and delete its wallet the next time it connects. A watch that never reconnects keeps the wallet, so move your funds to a new wallet if the watch is lost.
+ Erase Watch?
+ Pairing cancelled.
+ Pairing was cancelled on the watch.
+ The watch holds a different wallet.
+ Pairing failed. Please try again.
+ This watch has no secure hardware to keep a wallet.
+ Set a PIN in Bitkit first, then pair your watch.
+ Could not check the watch\'s secure hardware. Connect to the internet and try again.
+ The watch could not store the wallet.
+ Too many attempts. Try again later.
+ Pairing timed out.
+ Your watch is not reachable. Keep it nearby with Bluetooth on.
+ This watch\'s secure hardware could not be verified, so your wallet was not sent.
+ Update Bitkit on your phone and your watch.
+ This watch holds your full wallet and can spend from it.
+ Watch keys verified in StrongBox.
+ Watch keys verified in secure hardware.
+ Watch secure hardware not verified.
+ Looking for your watch…
+ Watch
+ Install Bitkit on {name} to pair it.
+ No watch connected. Connect a Wear OS watch to this phone first.
+ Not paired
+ Pair Watch
+ Check that {name} shows this code.
+ Pair
+ Open Bitkit on your watch.
+ Your watch is paired.
+ Sending your wallet to the watch…
+ This watch has no wallet. Pairing sends it your recovery phrase, so it will hold your full wallet.
+ Pair Watch
+ Confirm the code on your watch.
+ {name} is ready to pair.
+ Settings not on watch yet.
+ Watch settings up to date.
+ Stop Waiting
+ Unpair
+ Waiting for the watch to unpair.
+ The watch will forget this phone. Its wallet stays on the watch.
+ Unpair Watch?
Widgets
Reset Suggestions Cards
Reset Widgets
diff --git a/app/src/main/res/values/wear.xml b/app/src/main/res/values/wear.xml
new file mode 100644
index 0000000000..17b4ffc8fd
--- /dev/null
+++ b/app/src/main/res/values/wear.xml
@@ -0,0 +1,9 @@
+
+
+
+
+ - bitkit_phone_v1
+
+
diff --git a/app/src/release/java/to/bitkit/di/WatchLinkTransportModule.kt b/app/src/release/java/to/bitkit/di/WatchLinkTransportModule.kt
new file mode 100644
index 0000000000..9e19470302
--- /dev/null
+++ b/app/src/release/java/to/bitkit/di/WatchLinkTransportModule.kt
@@ -0,0 +1,18 @@
+package to.bitkit.di
+
+import dagger.Binds
+import dagger.Module
+import dagger.hilt.InstallIn
+import dagger.hilt.components.SingletonComponent
+import to.bitkit.watch.WatchDataLayerTransport
+import to.bitkit.wearlink.LinkTransport
+import javax.inject.Singleton
+
+/** A release build reaches the watch over the Wear Data Layer and has no other carrier. */
+@Module
+@InstallIn(SingletonComponent::class)
+abstract class WatchLinkTransportModule {
+ @Binds
+ @Singleton
+ abstract fun bindLinkTransport(transport: WatchDataLayerTransport): LinkTransport
+}
diff --git a/app/src/test/java/to/bitkit/repositories/WatchLinkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/WatchLinkRepoTest.kt
new file mode 100644
index 0000000000..d826121ce3
--- /dev/null
+++ b/app/src/test/java/to/bitkit/repositories/WatchLinkRepoTest.kt
@@ -0,0 +1,614 @@
+package to.bitkit.repositories
+
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.async
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.test.StandardTestDispatcher
+import kotlinx.coroutines.test.TestScope
+import kotlinx.coroutines.test.runCurrent
+import org.junit.Test
+import org.mockito.kotlin.mock
+import org.mockito.kotlin.never
+import org.mockito.kotlin.verify
+import org.mockito.kotlin.whenever
+import to.bitkit.data.SettingsData
+import to.bitkit.data.SettingsStore
+import to.bitkit.data.WatchLinkData
+import to.bitkit.data.WatchLinkStore
+import to.bitkit.data.keychain.Keychain
+import to.bitkit.test.BaseUnitTest
+import to.bitkit.test.InMemoryDataStore
+import to.bitkit.wearlink.AttestationFailure
+import to.bitkit.wearlink.Handshake
+import to.bitkit.wearlink.LinkError
+import to.bitkit.wearlink.LinkNode
+import to.bitkit.wearlink.LinkPaths
+import to.bitkit.wearlink.LinkTransport
+import to.bitkit.wearlink.PairingState
+import to.bitkit.wearlink.PairingThrottle
+import to.bitkit.wearlink.Removal
+import to.bitkit.wearlink.SeedPayload
+import to.bitkit.wearlink.SeedStoreResult
+import to.bitkit.wearlink.SettingsDoc
+import to.bitkit.wearlink.WalletLink
+import to.bitkit.wearlink.WatchInfo
+import to.bitkit.wearlink.WatchLink
+import to.bitkit.wearlink.WatchLinkListener
+import to.bitkit.wearlink.WatchPairing
+import to.bitkit.wearlink.WatchPairingEnv
+import to.bitkit.wearlink.testing.FakeLinkNetwork
+import to.bitkit.wearlink.testing.InMemoryLinkKeyStore
+import to.bitkit.wearlink.testing.InMemoryRecordStore
+import to.bitkit.wearlink.testing.SoftwareAgreementKey
+import kotlin.test.assertEquals
+import kotlin.test.assertFalse
+import kotlin.test.assertIs
+import kotlin.test.assertNotNull
+import kotlin.test.assertNull
+import kotlin.test.assertTrue
+import kotlin.time.Clock
+import kotlin.time.ExperimentalTime
+import kotlin.time.Instant
+
+/**
+ * The phone's link repository against the real protocol, with the watch's side played by `:wearlink`'s own watch
+ * classes over the in-process carrier.
+ */
+@OptIn(ExperimentalCoroutinesApi::class, ExperimentalTime::class)
+class WatchLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) {
+ private companion object {
+ const val APP_ID = "to.bitkit.dev"
+ const val NOW = 1_800_000_000_000L
+ const val MNEMONIC = "abandon abandon about"
+ const val PASSPHRASE = "pass"
+
+ /** The network name of this build, as `Env.network` gives it. */
+ const val NETWORK = "REGTEST"
+
+ fun toSeed(mnemonic: String, passphrase: String?) = "$mnemonic|${passphrase.orEmpty()}".encodeToByteArray()
+ }
+
+ private val phoneKeys = InMemoryLinkKeyStore()
+ private val watchKeys = InMemoryLinkKeyStore()
+ private val watchStore = InMemoryRecordStore()
+ private val keychain = mock()
+ private val settingsStore = mock()
+ private val settings =
+ MutableStateFlow(SettingsData(isQuickPayEnabled = true, quickPayAmount = 10, isPinEnabled = true))
+
+ /** What reading Google's status list gives, and how often it was read. */
+ private var statusList: suspend () -> String = { """{"entries":{}}""" }
+ private var statusReads = 0
+
+ /** Holds the phone's search for the watch until completed, as the Data Layer's query takes its time. */
+ private var nodesGate: CompletableDeferred? = null
+ private val appliedSettings = mutableListOf()
+ private val storedSeeds = mutableListOf()
+ private var erases = 0
+ private var nowMs = NOW
+ private val clock = object : Clock {
+ override fun now(): Instant = Instant.fromEpochMilliseconds(nowMs)
+ }
+
+ /** Whether the watch holds the phone's wallet; without one it is sent the seed. */
+ private var hasWatchWallet = true
+
+ private lateinit var network: FakeLinkNetwork
+ private lateinit var store: WatchLinkStore
+ private lateinit var watchLink: WatchLink
+ private lateinit var sut: WatchLinkRepo
+
+ private fun TestScope.setUp(isUnverifiedTransferAllowed: Boolean = true) {
+ network = FakeLinkNetwork(backgroundScope)
+ store = WatchLinkStore(InMemoryDataStore(WatchLinkData()))
+ whenever(keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(MNEMONIC)
+ whenever(keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name)).thenReturn(PASSPHRASE)
+ whenever(settingsStore.data).thenReturn(settings)
+ watchLink = WatchLink(
+ transport = network.watch,
+ keys = watchKeys,
+ store = watchStore,
+ listener = object : WatchLinkListener {
+ override suspend fun applySettings(settings: SettingsDoc) {
+ appliedSettings += settings
+ }
+
+ override suspend fun prepareErase() = Unit
+
+ override suspend fun erase() {
+ erases++
+ }
+
+ override suspend fun onUnpaired() = Unit
+ },
+ info = { WatchInfo("1.0", isLockSet = false) },
+ nowMs = { nowMs },
+ )
+ network.watch.attach { packet -> runCatching { watchLink.onPacket(packet) } }
+ sut = WatchLinkRepo(
+ ioDispatcher = testDispatcher,
+ transport = object : LinkTransport by network.phone {
+ override suspend fun nodes(): List {
+ nodesGate?.await()
+ return network.phone.nodes()
+ }
+ },
+ keys = phoneKeys,
+ store = store,
+ keychain = keychain,
+ settingsStore = settingsStore,
+ clock = clock,
+ appId = APP_ID,
+ signingDigests = { setOf("00") },
+ isUnverifiedTransferAllowed = isUnverifiedTransferAllowed,
+ toSeed = ::toSeed,
+ fetchStatusList = {
+ statusReads++
+ statusList().encodeToByteArray()
+ },
+ )
+ }
+
+ private fun watchSession() = WatchPairing(network.watch, watchLink.pairingPackets, watchEnv)
+
+ private suspend fun awaitCode(): String {
+ val status = sut.pairing.first { (it as? WatchPairingStatus.Running)?.state is PairingState.Code }
+ return ((status as WatchPairingStatus.Running).state as PairingState.Code).code
+ }
+
+ private suspend fun WatchPairing.confirmShown() =
+ confirm((state.first { it is PairingState.Code } as PairingState.Code).code)
+
+ private val watchEnv = object : WatchPairingEnv {
+ override val appId = APP_ID
+ override val name = "Pixel Watch"
+ override val agreementKey = SoftwareAgreementKey()
+ override val keys = watchKeys
+
+ override suspend fun watchId() = ByteArray(Handshake.ID_BYTES) { 2 }
+
+ override suspend fun isLockSet() = false
+
+ override suspend fun walletSecret() =
+ if (hasWatchWallet) WalletLink.secret(toSeed(MNEMONIC, PASSPHRASE), NETWORK) else null
+
+ override suspend fun storeSeed(seed: SeedPayload): SeedStoreResult {
+ storedSeeds += seed
+ return SeedStoreResult.Stored(WalletLink.secret(toSeed(seed.mnemonic, seed.passphrase), seed.network))
+ }
+ }
+
+ /** Runs a pairing from the repository against a watch, confirming on both sides. */
+ private suspend fun TestScope.pair(isAuthenticated: Boolean = true): WatchPairingStatus {
+ val session = watchSession()
+ val watch = async { runCatching { session.run() } }
+ sut.startPairing()
+ val confirming = async {
+ session.confirmShown()
+ sut.confirmPairing(awaitCode(), isAuthenticated)
+ }
+ val result = watch.await()
+ confirming.cancel()
+ runCurrent()
+ result.onSuccess { watchLink.onPaired(it) }
+ runCurrent()
+ return sut.pairing.value
+ }
+
+ private fun failure(status: WatchPairingStatus) = (status as WatchPairingStatus.Failed).error
+
+ @Test
+ fun `a watch that holds this wallet pairs without the recovery phrase being sent`() = test {
+ setUp()
+
+ assertEquals(WatchPairingStatus.Paired, pair())
+
+ val record = assertNotNull(store.load())
+ assertEquals("Pixel Watch", record.peerName)
+ assertFalse(record.isSeedTransferred)
+ assertTrue(storedSeeds.isEmpty())
+ }
+
+ @Test
+ fun `pairing pushes the phone's settings to the watch at once`() = test {
+ setUp()
+
+ pair()
+
+ val applied = appliedSettings.single()
+ assertEquals(true, applied.isQuickPayEnabled)
+ assertEquals(10, applied.quickPayAmount)
+ assertEquals("USD", applied.selectedCurrency)
+ assertTrue(applied.changedAtMs >= NOW)
+ assertTrue(assertNotNull(store.load()).isSettingsUpToDate)
+ }
+
+ @Test
+ fun `turning QuickPay off on the phone reaches the paired watch`() = test {
+ setUp()
+ pair()
+ nowMs += 5_000
+
+ settings.update { it.copy(isQuickPayEnabled = false) }
+ runCurrent()
+
+ assertEquals(listOf(true, false), appliedSettings.map { it.isQuickPayEnabled })
+ assertEquals(NOW + 5_000, appliedSettings.last().changedAtMs)
+ }
+
+ @Test
+ fun `a setting the watch does not adopt is not pushed`() = test {
+ setUp()
+ pair()
+
+ settings.update { it.copy(hideBalance = true) }
+ runCurrent()
+
+ assertEquals(1, appliedSettings.size)
+ }
+
+ @Test
+ fun `a change made while the watch is away shows as not on the watch until it returns`() = test {
+ setUp()
+ pair()
+ network.isConnected = false
+
+ settings.update { it.copy(isQuickPayEnabled = false) }
+ runCurrent()
+ assertFalse(assertNotNull(store.load()).isSettingsUpToDate)
+
+ network.reconnect()
+ runCurrent()
+
+ assertEquals(false, appliedSettings.last().isQuickPayEnabled)
+ assertTrue(assertNotNull(store.load()).isSettingsUpToDate)
+ }
+
+ @Test
+ fun `nothing is pushed without a pairing`() = test {
+ setUp()
+
+ settings.update { it.copy(isQuickPayEnabled = false) }
+ runCurrent()
+
+ assertTrue(network.sent.isEmpty())
+ }
+
+ @Test
+ fun `a watch without a wallet is sent the phrase from the keychain after an authenticated confirmation`() = test {
+ hasWatchWallet = false
+ setUp()
+
+ assertEquals(WatchPairingStatus.Paired, pair())
+
+ val seed = storedSeeds.single()
+ assertEquals(MNEMONIC, seed.mnemonic)
+ assertEquals(PASSPHRASE, seed.passphrase)
+ assertEquals(NETWORK, seed.network)
+ assertTrue(assertNotNull(store.load()).isSeedTransferred)
+ assertNull(assertNotNull(store.load()).keyLevel)
+ }
+
+ @Test
+ fun `a confirmation without the phone's authentication sends no phrase`() = test {
+ hasWatchWallet = false
+ setUp()
+
+ assertIs(failure(pair(isAuthenticated = false)))
+
+ assertTrue(storedSeeds.isEmpty())
+ assertNull(store.load())
+ }
+
+ @Test
+ fun `a build that requires attestation refuses to send the phrase to an unattested watch`() = test {
+ hasWatchWallet = false
+ setUp(isUnverifiedTransferAllowed = false)
+
+ val error = assertIs(failure(pair()))
+
+ assertEquals(AttestationFailure.NoChain, error.failure)
+ assertTrue(storedSeeds.isEmpty())
+ assertNull(store.load())
+ }
+
+ @Test
+ fun `unfinished transfers are counted in the store and lock the next one out`() = test {
+ hasWatchWallet = false
+ setUp()
+ repeat(PairingThrottle.MAX_ATTEMPTS) { pair(isAuthenticated = false) }
+
+ assertIs(failure(pair()))
+ assertEquals(PairingThrottle.MAX_ATTEMPTS, store.throttle.load().attempts)
+ assertTrue(storedSeeds.isEmpty())
+ }
+
+ @Test
+ fun `no connected watch with bitkit nearby fails the pairing`() = test {
+ setUp()
+ network.isWatchNearby = false
+
+ sut.startPairing()
+ runCurrent()
+
+ assertIs(failure(sut.pairing.value))
+ }
+
+ @Test
+ fun `a phone without a PIN sends no phrase, and says a PIN is needed`() = test {
+ hasWatchWallet = false
+ setUp()
+ settings.update { it.copy(isPinEnabled = false) }
+
+ assertIs(failure(pair()))
+
+ assertTrue(storedSeeds.isEmpty())
+ assertTrue(network.sent.none { it.path == LinkPaths.REVEAL || it.path == LinkPaths.SEED })
+ verify(keychain, never()).loadString(Keychain.Key.BIP39_MNEMONIC.name)
+ assertNull(store.load())
+ }
+
+ @Test
+ fun `a phone without a PIN pairs with a watch that holds its wallet, and pushes its settings`() = test {
+ setUp()
+ settings.update { it.copy(isPinEnabled = false) }
+
+ assertEquals(WatchPairingStatus.Paired, pair(isAuthenticated = false))
+
+ assertTrue(storedSeeds.isEmpty())
+ assertEquals(1, appliedSettings.size)
+ }
+
+ @Test
+ fun `a check claimed on a phone whose PIN is gone sends no phrase`() = test {
+ // The PIN is removed after the code came up: nothing was there to check, whatever the caller says.
+ hasWatchWallet = false
+ setUp()
+ val session = watchSession()
+ val watch = async { runCatching { session.run() } }
+ sut.startPairing()
+ val code = awaitCode()
+ settings.update { it.copy(isPinEnabled = false) }
+
+ session.confirmShown()
+ sut.confirmPairing(code, isAuthenticated = true)
+ watch.await()
+ runCurrent()
+
+ assertIs(failure(sut.pairing.value))
+ assertTrue(storedSeeds.isEmpty())
+ }
+
+ @Test
+ fun `the status list is not read for a watch whose key was not verified`() = test {
+ hasWatchWallet = false
+ setUp()
+
+ assertEquals(WatchPairingStatus.Paired, pair())
+
+ assertEquals(0, statusReads)
+ }
+
+ // region cancel
+
+ @Test
+ fun `a cancel before the watch was found starts no ceremony and opens nothing on the watch`() = test {
+ hasWatchWallet = false
+ setUp()
+ nodesGate = CompletableDeferred()
+ sut.startPairing()
+ runCurrent()
+ assertEquals(WatchPairingStatus.Running(PairingState.Connecting), sut.pairing.value)
+
+ sut.cancelPairing()
+ nodesGate?.complete(Unit)
+ runCurrent()
+
+ assertEquals(WatchPairingStatus.Idle, sut.pairing.value)
+ assertTrue(network.opened.isEmpty())
+ assertTrue(network.sent.isEmpty())
+ assertEquals(0, store.throttle.load().attempts)
+ }
+
+ @Test
+ fun `a cancel that overtakes the start of a pairing leaves the next one free to run`() = test {
+ setUp()
+ sut.startPairing()
+ sut.cancelPairing()
+ runCurrent()
+
+ assertEquals(WatchPairingStatus.Idle, sut.pairing.value)
+ assertTrue(network.opened.isEmpty())
+
+ val session = watchSession()
+ val watch = async { runCatching { session.run() } }
+ sut.startPairing()
+ awaitCode()
+ sut.cancelPairing()
+ watch.await()
+ }
+
+ @Test
+ fun `a confirmation of another code than the one that shows confirms nothing`() = test {
+ hasWatchWallet = false
+ setUp()
+ val session = watchSession()
+ val watch = async { runCatching { session.run() } }
+ sut.startPairing()
+ val code = awaitCode()
+ session.confirmShown()
+
+ sut.confirmPairing(if (code == "000000") "000001" else "000000", isAuthenticated = true)
+ runCurrent()
+
+ val shown = (sut.pairing.value as WatchPairingStatus.Running).state as PairingState.Code
+ assertFalse(shown.isConfirmed)
+ assertTrue(storedSeeds.isEmpty())
+ sut.cancelPairing()
+ watch.await()
+ }
+
+ @Test
+ fun `a cancel while the phone waits for the watch to answer ends the pairing`() = test {
+ setUp()
+ sut.startPairing()
+ runCurrent()
+ assertTrue(network.sent.any { it.path == LinkPaths.HELLO })
+
+ sut.cancelPairing()
+ runCurrent()
+
+ assertIs(failure(sut.pairing.value))
+ assertEquals(LinkPaths.ABORT, network.sent.last().path)
+ }
+
+ @Test
+ fun `a cancel at the code ends both sides and sends no phrase`() = test {
+ hasWatchWallet = false
+ setUp()
+ val session = watchSession()
+ val watch = async { runCatching { session.run() } }
+ sut.startPairing()
+ awaitCode()
+
+ sut.cancelPairing()
+
+ assertIs(watch.await().exceptionOrNull())
+ runCurrent()
+ assertIs(failure(sut.pairing.value))
+ assertTrue(storedSeeds.isEmpty())
+ assertNull(store.load())
+ }
+
+ @Test
+ fun `a cancel after the phone's user confirmed, while the watch has not, sends no phrase`() = test {
+ hasWatchWallet = false
+ setUp()
+ val session = watchSession()
+ val watch = async { runCatching { session.run() } }
+ sut.startPairing()
+ sut.confirmPairing(awaitCode(), isAuthenticated = true)
+ runCurrent()
+
+ sut.cancelPairing()
+
+ assertIs(watch.await().exceptionOrNull())
+ runCurrent()
+ assertIs(failure(sut.pairing.value))
+ assertTrue(storedSeeds.isEmpty())
+ }
+
+ @Test
+ fun `a cancel with no pairing running forgets the last one's end`() = test {
+ setUp()
+ network.isWatchNearby = false
+ sut.startPairing()
+ runCurrent()
+ assertIs(sut.pairing.value)
+
+ sut.cancelPairing()
+
+ assertEquals(WatchPairingStatus.Idle, sut.pairing.value)
+ }
+
+ @Test
+ fun `a watch pairs after an earlier pairing was cancelled`() = test {
+ setUp()
+ nodesGate = CompletableDeferred()
+ sut.startPairing()
+ runCurrent()
+ sut.cancelPairing()
+ nodesGate?.complete(Unit)
+ runCurrent()
+ nodesGate = null
+
+ assertEquals(WatchPairingStatus.Paired, pair())
+ assertNotNull(store.load())
+ }
+
+ @Test
+ fun `a pairing started while the cancelled one is still ending runs, and the old end never shows`() = test {
+ setUp()
+ val first = watchSession()
+ val firstWatch = async { runCatching { first.run() } }
+ sut.startPairing()
+ awaitCode()
+ val shown = mutableListOf()
+ val collecting = async { sut.pairing.collect { shown += it } }
+
+ // The sheet's Pair tap: it cancels what runs, then starts.
+ sut.cancelPairing()
+ sut.startPairing()
+ assertEquals(WatchPairingStatus.Running(PairingState.Connecting), sut.pairing.value)
+ assertIs(firstWatch.await().exceptionOrNull())
+ val second = watchSession()
+ val secondWatch = async { runCatching { second.run() } }
+ second.confirmShown()
+ sut.confirmPairing(awaitCode(), isAuthenticated = false)
+ secondWatch.await().onSuccess { watchLink.onPaired(it) }
+ runCurrent()
+ collecting.cancel()
+
+ assertEquals(WatchPairingStatus.Paired, sut.pairing.value)
+ assertTrue(shown.none { it is WatchPairingStatus.Failed })
+ }
+
+ // endregion
+
+ @Test
+ fun `unpair waits for the watch and then forgets it`() = test {
+ setUp()
+ pair()
+ network.isConnected = false
+
+ sut.remove(isErase = false).getOrThrow()
+ assertEquals(Removal.Unpair, assertNotNull(store.load()).removal)
+
+ network.reconnect()
+ runCurrent()
+
+ assertNull(store.load())
+ assertNull(watchStore.load())
+ assertEquals(0, erases)
+ assertTrue(phoneKeys.keys.isEmpty())
+ }
+
+ @Test
+ fun `erase deletes the wallet on the watch and forgets it once acknowledged`() = test {
+ setUp()
+ pair()
+
+ sut.remove(isErase = true).getOrThrow()
+ runCurrent()
+
+ assertEquals(1, erases)
+ assertNull(store.load())
+ }
+
+ @Test
+ fun `forgetting the watch, as when the phone's wallet is wiped, unpairs and never erases`() = test {
+ setUp()
+ pair()
+
+ sut.forget().getOrThrow()
+ runCurrent()
+
+ assertNull(store.load())
+ assertNull(watchStore.load())
+ assertEquals(0, erases)
+ verify(keychain, never()).wipe()
+ }
+
+ @Test
+ fun `the install id is made once and kept`() = test {
+ setUp()
+
+ val first = store.installId()
+
+ assertEquals(Handshake.ID_BYTES, first.size)
+ assertTrue(first.contentEquals(store.installId()))
+ }
+}
diff --git a/app/src/test/java/to/bitkit/ui/sheets/watch/WatchSheetViewModelTest.kt b/app/src/test/java/to/bitkit/ui/sheets/watch/WatchSheetViewModelTest.kt
new file mode 100644
index 0000000000..514cfd5370
--- /dev/null
+++ b/app/src/test/java/to/bitkit/ui/sheets/watch/WatchSheetViewModelTest.kt
@@ -0,0 +1,518 @@
+package to.bitkit.ui.sheets.watch
+
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.update
+import org.junit.Before
+import org.junit.Test
+import org.mockito.kotlin.any
+import org.mockito.kotlin.atLeast
+import org.mockito.kotlin.doSuspendableAnswer
+import org.mockito.kotlin.eq
+import org.mockito.kotlin.inOrder
+import org.mockito.kotlin.mock
+import org.mockito.kotlin.never
+import org.mockito.kotlin.times
+import org.mockito.kotlin.verify
+import org.mockito.kotlin.whenever
+import to.bitkit.R
+import to.bitkit.repositories.WatchLinkError
+import to.bitkit.repositories.WatchLinkRepo
+import to.bitkit.repositories.WatchPairingStatus
+import to.bitkit.test.BaseUnitTest
+import to.bitkit.wearlink.AbortReason
+import to.bitkit.wearlink.AttestationFailure
+import to.bitkit.wearlink.AttestationVerdict
+import to.bitkit.wearlink.KeyLevel
+import to.bitkit.wearlink.LinkError
+import to.bitkit.wearlink.LinkNode
+import to.bitkit.wearlink.LinkRecord
+import to.bitkit.wearlink.PairingMode
+import to.bitkit.wearlink.PairingState
+import to.bitkit.wearlink.Removal
+import to.bitkit.wearlink.StoreFailure
+import kotlin.test.assertEquals
+import kotlin.test.assertFalse
+import kotlin.test.assertNull
+import kotlin.test.assertTrue
+
+class WatchSheetViewModelTest : BaseUnitTest() {
+ private val repo = mock()
+ private val record = MutableStateFlow(null)
+ private val pairing = MutableStateFlow(WatchPairingStatus.Idle)
+
+ @Before
+ fun setUp() {
+ whenever(repo.record).thenReturn(record)
+ whenever(repo.pairing).thenReturn(pairing)
+ whenever { repo.watches() }.thenReturn(Result.success(emptyList()))
+ }
+
+ private val transferCode = PairingState.Code(
+ code = "048213",
+ mode = PairingMode.Transfer,
+ peerName = "Pixel Watch",
+ attestation = AttestationVerdict.Verified(KeyLevel.TrustedEnvironment),
+ )
+ private val proofCode = transferCode.copy(mode = PairingMode.Proof)
+
+ private fun record(removal: Removal? = null, settingsSent: Long = 0) = LinkRecord(
+ pairingId = "0102030405060708",
+ peerId = "aa",
+ peerNodeId = "node",
+ peerName = "Pixel Watch",
+ pairedAtMs = 1,
+ keyLevel = KeyLevel.StrongBox,
+ removal = removal,
+ settingsSent = settingsSent,
+ )
+
+ // region settings
+
+ @Test
+ fun `a connected watch with bitkit nearby can be paired`() = test {
+ val watch = LinkNode("n", "Pixel Watch", isNearby = true, hasApp = true)
+ whenever { repo.watches() }.thenReturn(Result.success(listOf(watch)))
+ val sut = WatchSheetViewModel(repo)
+
+ sut.refresh()
+
+ assertEquals(ConnectedWatch("Pixel Watch", hasApp = true, isNearby = true), sut.uiState.value.connected)
+ assertTrue(sut.uiState.value.connected?.canPair == true)
+ assertFalse(sut.uiState.value.isLoading)
+ }
+
+ @Test
+ fun `a watch without bitkit, or reached through the cloud, cannot be paired, and each says why`() = test {
+ val sut = WatchSheetViewModel(repo)
+ whenever { repo.watches() }.thenReturn(Result.success(listOf(LinkNode("n", "Watch", true, hasApp = false))))
+ sut.refresh()
+ assertEquals(ConnectedWatch("Watch", hasApp = false, isNearby = true), sut.uiState.value.connected)
+ assertFalse(sut.uiState.value.connected?.canPair == true)
+
+ whenever { repo.watches() }.thenReturn(Result.success(listOf(LinkNode("n", "Watch", false, hasApp = true))))
+ sut.refresh()
+ assertEquals(ConnectedWatch("Watch", hasApp = true, isNearby = false), sut.uiState.value.connected)
+ assertFalse(sut.uiState.value.connected?.canPair == true)
+ }
+
+ @Test
+ fun `of several watches the one that can pair is named, then one that has bitkit`() = test {
+ val bare = LinkNode("a", "Bare", isNearby = true, hasApp = false)
+ val away = LinkNode("b", "Away", isNearby = false, hasApp = true)
+ val ready = LinkNode("c", "Ready", isNearby = true, hasApp = true)
+ val sut = WatchSheetViewModel(repo)
+
+ whenever { repo.watches() }.thenReturn(Result.success(listOf(bare, away, ready)))
+ sut.refresh()
+ assertEquals("Ready", sut.uiState.value.connected?.name)
+
+ whenever { repo.watches() }.thenReturn(Result.success(listOf(bare, away)))
+ sut.refresh()
+ assertEquals("Away", sut.uiState.value.connected?.name)
+ }
+
+ @Test
+ fun `opening the sheet again looks from scratch instead of showing the last watch found`() = test {
+ val watch = LinkNode("n", "Pixel Watch", isNearby = true, hasApp = true)
+ whenever { repo.watches() }.thenReturn(Result.success(listOf(watch)))
+ val sut = WatchSheetViewModel(repo)
+ sut.onSheetOpen()
+ assertTrue(sut.uiState.value.connected?.canPair == true)
+ sut.onSheetClose()
+
+ whenever { repo.watches() }.thenReturn(Result.success(emptyList()))
+ sut.onSheetOpen()
+
+ assertNull(sut.uiState.value.connected)
+ assertFalse(sut.uiState.value.isLoading)
+ }
+
+ @Test
+ fun `a watch that connects while the sheet is open shows on the next look`() = test {
+ val sut = WatchSheetViewModel(repo)
+ sut.onSheetOpen()
+ assertNull(sut.uiState.value.connected)
+
+ val watch = LinkNode("n", "Pixel Watch", isNearby = true, hasApp = true)
+ whenever { repo.watches() }.thenReturn(Result.success(listOf(watch)))
+ sut.refresh()
+
+ assertTrue(sut.uiState.value.connected?.canPair == true)
+ }
+
+ @Test
+ fun `a look that is still under way is not started again, and closing the sheet drops its result`() = test {
+ val gate = CompletableDeferred()
+ val watch = LinkNode("n", "Pixel Watch", isNearby = true, hasApp = true)
+ whenever { repo.watches() }.doSuspendableAnswer {
+ gate.await()
+ Result.success(listOf(watch))
+ }
+ val sut = WatchSheetViewModel(repo)
+ sut.onSheetOpen()
+
+ sut.refresh()
+ sut.refresh()
+ verify(repo, times(1)).watches()
+
+ sut.onSheetClose()
+ gate.complete(Unit)
+
+ assertNull(sut.uiState.value.connected)
+ assertTrue(sut.uiState.value.isLoading)
+ }
+
+ @Test
+ fun `closing the end of a failed pairing looks for the watch again`() = test {
+ val sut = WatchSheetViewModel(repo).apply { onSheetOpen() }
+ sut.onPairClick()
+ pairing.update { WatchPairingStatus.Failed(LinkError.Timeout()) }
+ val watch = LinkNode("n", "Pixel Watch", isNearby = true, hasApp = true)
+ whenever { repo.watches() }.thenReturn(Result.success(listOf(watch)))
+
+ sut.onPairClose()
+
+ assertNull(sut.uiState.value.pairing)
+ assertTrue(sut.uiState.value.connected?.canPair == true)
+ }
+
+ @Test
+ fun `no watch, or no wearable service, shows as none connected`() = test {
+ whenever { repo.watches() }.thenReturn(Result.failure(IllegalStateException("no api")))
+ val sut = WatchSheetViewModel(repo)
+
+ sut.refresh()
+
+ assertNull(sut.uiState.value.connected)
+ assertFalse(sut.uiState.value.isLoading)
+ }
+
+ @Test
+ fun `the paired watch shows its key level and whether the settings reached it`() = test {
+ val sut = WatchSheetViewModel(repo)
+
+ record.update { record(settingsSent = 3) }
+
+ val paired = sut.uiState.value.paired
+ assertEquals("Pixel Watch", paired?.name)
+ assertEquals(KeyLevel.StrongBox, paired?.keyLevel)
+ assertEquals(false, paired?.isSettingsUpToDate)
+ assertEquals(false, paired?.isRemoving)
+ }
+
+ @Test
+ fun `unpair and erase each ask first and act only on confirm`() = test {
+ whenever { repo.remove(isErase = true) }.thenReturn(Result.success(Unit))
+ whenever { repo.remove(isErase = false) }.thenReturn(Result.success(Unit))
+ val sut = WatchSheetViewModel(repo)
+ record.update { record() }
+
+ sut.onEraseClick()
+ assertEquals(WatchRemoveDialog.Erase, sut.uiState.value.dialog)
+ sut.onDialogDismiss()
+ verify(repo, never()).remove(isErase = true)
+
+ sut.onEraseClick()
+ sut.onDialogConfirm()
+ verify(repo).remove(isErase = true)
+
+ sut.onUnpairClick()
+ sut.onDialogConfirm()
+ verify(repo).remove(isErase = false)
+ assertNull(sut.uiState.value.dialog)
+ }
+
+ @Test
+ fun `a dialog stays open while the same watch reports, and closes when the watch is gone`() = test {
+ val sut = WatchSheetViewModel(repo)
+ record.update { record() }
+ sut.onEraseClick()
+
+ record.update { record(settingsSent = 4) }
+ assertEquals(WatchRemoveDialog.Erase, sut.uiState.value.dialog)
+
+ record.update { null }
+ assertNull(sut.uiState.value.dialog)
+ }
+
+ @Test
+ fun `a dialog closes when another watch takes the place of the one it was about`() = test {
+ val sut = WatchSheetViewModel(repo)
+ record.update { record() }
+ sut.onUnpairClick()
+
+ record.update { record().copy(pairingId = "0807060504030201") }
+
+ assertNull(sut.uiState.value.dialog)
+ }
+
+ @Test
+ fun `a removal that waits shows as pending and can be dropped`() = test {
+ whenever { repo.forget() }.thenReturn(Result.success(Unit))
+ val sut = WatchSheetViewModel(repo)
+ record.update { record(removal = Removal.Erase) }
+
+ assertTrue(sut.uiState.value.paired?.isRemoving == true)
+ assertTrue(sut.uiState.value.paired?.isErasing == true)
+
+ sut.onStopWaitingClick()
+
+ verify(repo).forget()
+ }
+
+ // endregion
+
+ // region pair
+
+ private fun step(sut: WatchSheetViewModel, status: WatchPairingStatus): WatchPairStep {
+ pairing.update { status }
+ return checkNotNull(sut.uiState.value.pairing)
+ }
+
+ private fun message(sut: WatchSheetViewModel, error: Throwable) =
+ (step(sut, WatchPairingStatus.Failed(error)) as WatchPairStep.Failed).message
+
+ @Test
+ fun `a pairing starts on the tap and is cancelled when the sheet closes`() = test {
+ val sut = WatchSheetViewModel(repo)
+ assertNull(sut.uiState.value.pairing)
+ verify(repo, never()).startPairing()
+
+ sut.onPairClick()
+
+ verify(repo).startPairing()
+ assertEquals(WatchPairStep.Connecting, sut.uiState.value.pairing)
+
+ sut.onSheetClose()
+
+ verify(repo, atLeast(2)).cancelPairing()
+ assertNull(sut.uiState.value.pairing)
+ }
+
+ @Test
+ fun `the end of an earlier pairing does not show until a pairing is started`() = test {
+ val sut = WatchSheetViewModel(repo)
+
+ pairing.update { WatchPairingStatus.Failed(LinkError.Timeout()) }
+
+ assertNull(sut.uiState.value.pairing)
+ }
+
+ @Test
+ fun `the code step says when confirming sends the wallet and whether the watch is verified`() = test {
+ val sut = WatchSheetViewModel(repo).apply { onPairClick() }
+ val verified = AttestationVerdict.Verified(KeyLevel.TrustedEnvironment)
+ val transfer = PairingState.Code("048213", PairingMode.Transfer, "Pixel Watch", verified)
+
+ assertEquals(
+ WatchPairStep.Code("048213", "Pixel Watch", sendsWallet = true, isVerified = true, isConfirmed = false),
+ step(sut, WatchPairingStatus.Running(transfer)),
+ )
+ val unverified = AttestationVerdict.Unverified(AttestationFailure.UntrustedRoot)
+ val proof = PairingState.Code("048213", PairingMode.Proof, "Pixel Watch", unverified, isConfirmed = true)
+ assertEquals(
+ WatchPairStep.Code("048213", "Pixel Watch", sendsWallet = false, isVerified = false, isConfirmed = true),
+ step(sut, WatchPairingStatus.Running(proof)),
+ )
+ assertEquals(WatchPairStep.Sending, step(sut, WatchPairingStatus.Running(PairingState.Transferring)))
+ assertEquals(WatchPairStep.Done, step(sut, WatchPairingStatus.Paired))
+ }
+
+ @Test
+ fun `confirming for a watch that is sent the wallet asks for the phone's check first`() = test {
+ val sut = WatchSheetViewModel(repo).apply { onPairClick() }
+ step(sut, WatchPairingStatus.Running(transferCode))
+
+ sut.onPairConfirm()
+
+ assertTrue(sut.uiState.value.isAuthShown)
+ verify(repo, never()).confirmPairing(any(), any())
+ }
+
+ @Test
+ fun `the wallet is confirmed as checked only once the check was passed`() = test {
+ val sut = WatchSheetViewModel(repo).apply { onPairClick() }
+ step(sut, WatchPairingStatus.Running(transferCode))
+ sut.onPairConfirm()
+
+ sut.onAuthSuccess()
+
+ verify(repo).confirmPairing("048213", true)
+ verify(repo, never()).confirmPairing(any(), eq(false))
+ assertFalse(sut.uiState.value.isAuthShown)
+ }
+
+ @Test
+ fun `leaving the check goes back to the code with nothing confirmed`() = test {
+ val sut = WatchSheetViewModel(repo).apply { onPairClick() }
+ step(sut, WatchPairingStatus.Running(transferCode))
+ sut.onPairConfirm()
+
+ sut.onAuthDismiss()
+
+ assertFalse(sut.uiState.value.isAuthShown)
+ assertEquals("048213", (sut.uiState.value.pairing as WatchPairStep.Code).code)
+ verify(repo, never()).confirmPairing(any(), any())
+ verify(repo, times(1)).cancelPairing()
+ }
+
+ @Test
+ fun `a watch that already holds the wallet is confirmed without a check, and never as checked`() = test {
+ val sut = WatchSheetViewModel(repo).apply { onPairClick() }
+ step(sut, WatchPairingStatus.Running(proofCode))
+
+ sut.onPairConfirm()
+
+ assertFalse(sut.uiState.value.isAuthShown)
+ verify(repo).confirmPairing("048213", false)
+ verify(repo, never()).confirmPairing(any(), eq(true))
+ }
+
+ @Test
+ fun `a passed check that nothing asked for confirms nothing`() = test {
+ val sut = WatchSheetViewModel(repo).apply { onPairClick() }
+
+ sut.onAuthSuccess()
+ step(sut, WatchPairingStatus.Running(transferCode))
+ sut.onAuthSuccess()
+ step(sut, WatchPairingStatus.Running(proofCode))
+ sut.onAuthSuccess()
+
+ verify(repo, never()).confirmPairing(any(), any())
+ }
+
+ @Test
+ fun `the check goes away when the pairing ends under it, and passing it then confirms nothing`() = test {
+ val sut = WatchSheetViewModel(repo).apply { onPairClick() }
+ step(sut, WatchPairingStatus.Running(transferCode))
+ sut.onPairConfirm()
+
+ step(sut, WatchPairingStatus.Failed(LinkError.PeerAborted(AbortReason.Cancelled)))
+
+ assertFalse(sut.uiState.value.isAuthShown)
+ sut.onAuthSuccess()
+ verify(repo, never()).confirmPairing(any(), any())
+ }
+
+ @Test
+ fun `confirming without a code on screen does nothing`() = test {
+ val sut = WatchSheetViewModel(repo).apply { onPairClick() }
+
+ sut.onPairConfirm()
+
+ assertFalse(sut.uiState.value.isAuthShown)
+ verify(repo, never()).confirmPairing(any(), any())
+ }
+
+ @Test
+ fun `closing the sheet while the wallet is on its way lets the transfer finish`() = test {
+ val sut = WatchSheetViewModel(repo).apply { onPairClick() }
+ step(sut, WatchPairingStatus.Running(PairingState.Transferring))
+
+ sut.onSheetClose()
+
+ verify(repo, times(1)).cancelPairing()
+ assertNull(sut.uiState.value.pairing)
+
+ sut.onSheetOpen()
+ assertEquals(WatchPairStep.Sending, sut.uiState.value.pairing)
+ }
+
+ @Test
+ fun `a transfer that failed while the sheet was closed says so when the sheet opens again`() = test {
+ val sut = WatchSheetViewModel(repo).apply { onPairClick() }
+ step(sut, WatchPairingStatus.Running(PairingState.Transferring))
+ sut.onSheetClose()
+ pairing.update { WatchPairingStatus.Failed(LinkError.TransferFailed(StoreFailure.Failed)) }
+
+ sut.onSheetOpen()
+
+ assertEquals(WatchPairStep.Failed(R.string.settings__watch__error_store), sut.uiState.value.pairing)
+
+ sut.onSheetClose()
+ sut.onSheetOpen()
+ assertNull(sut.uiState.value.pairing)
+ }
+
+ @Test
+ fun `a transfer that paired while the sheet was closed shows as the paired watch`() = test {
+ val sut = WatchSheetViewModel(repo).apply { onPairClick() }
+ step(sut, WatchPairingStatus.Running(PairingState.Transferring))
+ sut.onSheetClose()
+ pairing.update { WatchPairingStatus.Paired }
+
+ sut.onSheetOpen()
+
+ assertNull(sut.uiState.value.pairing)
+ }
+
+ @Test
+ fun `reopening the sheet does not show a cancelled pairing that is still ending`() = test {
+ val sut = WatchSheetViewModel(repo).apply { onPairClick() }
+ step(sut, WatchPairingStatus.Running(transferCode))
+ sut.onSheetClose()
+
+ sut.onSheetOpen()
+ assertNull(sut.uiState.value.pairing)
+
+ pairing.update { WatchPairingStatus.Failed(LinkError.Cancelled()) }
+ assertNull(sut.uiState.value.pairing)
+ }
+
+ @Test
+ fun `tapping pair cancels what still runs before it starts, so a pairing that is ending is replaced`() = test {
+ val sut = WatchSheetViewModel(repo)
+
+ sut.onPairClick()
+
+ inOrder(repo) {
+ verify(repo).cancelPairing()
+ verify(repo).startPairing()
+ }
+ }
+
+ @Test
+ fun `each failure gets its line, and a refused attestation says the wallet was not sent`() = test {
+ val sut = WatchSheetViewModel(repo).apply { onPairClick() }
+
+ assertEquals(
+ R.string.settings__watch__error_unverified,
+ message(sut, LinkError.AttestationFailed(AttestationFailure.SoftwareKey)),
+ )
+ assertEquals(R.string.settings__watch__error_different_wallet, message(sut, LinkError.DifferentWallet()))
+ assertEquals(
+ R.string.settings__watch__error_different_wallet,
+ message(sut, LinkError.PeerAborted(AbortReason.DifferentWallet)),
+ )
+ assertEquals(
+ R.string.settings__watch__error_cancelled_watch,
+ message(sut, LinkError.PeerAborted(AbortReason.Cancelled)),
+ )
+ assertEquals(R.string.settings__watch__error_timeout, message(sut, LinkError.Timeout()))
+ assertEquals(R.string.settings__watch__error_throttled, message(sut, LinkError.Throttled(1)))
+ assertEquals(R.string.settings__watch__error_unreachable, message(sut, LinkError.Unreachable()))
+ assertEquals(R.string.settings__watch__error_unreachable, message(sut, WatchLinkError.NoWatch()))
+ assertEquals(R.string.settings__watch__error_update, message(sut, LinkError.UpdateRequired()))
+ assertEquals(
+ R.string.settings__watch__error_insecure,
+ message(sut, LinkError.TransferFailed(StoreFailure.InsecureKey)),
+ )
+ assertEquals(
+ R.string.settings__watch__error_store,
+ message(sut, LinkError.TransferFailed(StoreFailure.InvalidPhrase)),
+ )
+ assertEquals(R.string.settings__watch__error_failed, message(sut, LinkError.NotAuthorized()))
+ assertEquals(R.string.settings__watch__error_pin, message(sut, LinkError.PinRequired()))
+ assertEquals(
+ R.string.settings__watch__error_status,
+ message(sut, LinkError.AttestationFailed(AttestationFailure.StatusUnknown)),
+ )
+ assertEquals(
+ R.string.settings__watch__error_unverified,
+ message(sut, LinkError.AttestationFailed(AttestationFailure.Revoked)),
+ )
+ }
+
+ // endregion
+}
diff --git a/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt b/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt
index ffcaebbf5c..5490c07ccb 100644
--- a/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt
+++ b/app/src/test/java/to/bitkit/usecases/WipeWalletUseCaseTest.kt
@@ -36,6 +36,7 @@ import to.bitkit.repositories.PubkyRepo
import to.bitkit.repositories.PubkySwapsRouteRepo
import to.bitkit.repositories.UsdtRepo
import to.bitkit.repositories.WakeRepo
+import to.bitkit.repositories.WatchLinkRepo
import to.bitkit.repositories.WatchOnlyAccountRepo
import to.bitkit.services.CoreService
import to.bitkit.services.MigrationService
@@ -76,6 +77,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() {
private val paykitSdkService = PaykitSdkService(mock(), keychain, mock(), settingsStore = mock()) { mock() }
private val privatePaykitRepoProvider = Provider { privatePaykitRepo }
private val moveToSparkManager = mock()
+ private val watchLinkRepo = mock()
private lateinit var sut: WipeWalletUseCase
@@ -125,6 +127,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() {
connectionRecovery = connectionRecoveryFixture(settingsStore),
wakeRepo = wakeRepo,
moveToSparkManager = Provider { moveToSparkManager },
+ watchLinkRepo = Provider { watchLinkRepo },
)
}
@@ -158,6 +161,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() {
migrationService,
wakeRepo,
moveToSparkManager,
+ watchLinkRepo,
)
inOrder.verify(backupRepo).setWiping(true)
inOrder.verify(lightningRepo).setWiping(true)
@@ -167,6 +171,7 @@ class WipeWalletUseCaseTest : BaseUnitTest() {
inOrder.verify(pubkyRepo).removeBitkitPaymentEndpoints()
inOrder.verify(privatePaykitRepo).closeAndClear()
inOrder.verify(wakeRepo).unregister()
+ inOrder.verify(watchLinkRepo).forget()
inOrder.verify(lightningRepo).wipeStorage(0)
inOrder.verify(pubkySwapsRouteRepo).resetForWipe()
inOrder.verify(migrationService).setNeedsPostMigrationSync(false)
diff --git a/app/src/test/java/to/bitkit/watch/WatchLinkSourcesTest.kt b/app/src/test/java/to/bitkit/watch/WatchLinkSourcesTest.kt
new file mode 100644
index 0000000000..12ad2b4590
--- /dev/null
+++ b/app/src/test/java/to/bitkit/watch/WatchLinkSourcesTest.kt
@@ -0,0 +1,89 @@
+package to.bitkit.watch
+
+import org.junit.Test
+import java.io.File
+import kotlin.test.assertEquals
+import kotlin.test.assertTrue
+
+/**
+ * What the watch link's safety rests on in the phone app's structure, pinned so a later change cannot loosen it
+ * unnoticed: where the Wear Data Layer is named, how the seed may travel, and that nothing logs it.
+ */
+class WatchLinkSourcesTest {
+ private companion object {
+ const val DATA_LAYER_PACKAGE = "com.google.android.gms.wearable"
+ }
+
+ private val root: File by lazy {
+ generateSequence(File("").absoluteFile) { it.parentFile }.first { File(it, "wearlink/src/main").isDirectory }
+ }
+
+ private fun sources(path: String): List =
+ File(root, path).walkTopDown().filter { it.isFile && it.extension == "kt" }.toList()
+
+ @Test
+ fun `only the transport and its listener service name the wear data layer`() {
+ val naming = (sources("app/src/main") + sources("app/src/release"))
+ .filter { DATA_LAYER_PACKAGE in it.readText() }
+ .map { it.name }
+
+ assertEquals(setOf("WatchDataLayerTransport.kt", "WatchLinkListenerService.kt"), naming.toSet())
+ }
+
+ @Test
+ fun `one-shot messages, which carry the handshake and the seed, never go through the data client`() {
+ val transport = sources("app/src/main").single { it.name == "WatchDataLayerTransport.kt" }.readText()
+ val send = transport.substringAfter("override suspend fun send(")
+ .substringBefore("override suspend fun putState(")
+
+ assertTrue("messageClient.sendMessage" in send)
+ assertTrue("dataClient" !in send)
+ }
+
+ @Test
+ fun `the protocol sends the seed only as a one-shot message`() {
+ val protocol = sources("wearlink/src/main")
+ val sendingSeed = protocol.filter { "LinkPaths.SEED" in it.readText() }.map { it.name }.toSet()
+ val phone = protocol.single { it.name == "PhonePairing.kt" }.readText()
+
+ assertEquals(setOf("PhonePairing.kt", "WatchPairing.kt"), sendingSeed)
+ assertTrue("send(LinkPaths.SEED, sealed)" in phone)
+ // The pairing sessions have no way to store a document: only the endpoints after pairing do.
+ val storing = protocol.filter { "putState(" in it.readText() }.map { it.name }.toSet()
+ assertEquals(setOf("LinkEndpoints.kt", "LinkTransport.kt"), storing)
+ }
+
+ @Test
+ fun `the protocol module logs nothing and prints no secret`() {
+ val protocol = sources("wearlink/src/main")
+
+ val logging = Regex("\\b(println|Logger\\.|System\\.out)")
+ assertEquals(emptyList(), protocol.filter { logging.containsMatchIn(it.readText()) })
+ val handshake = protocol.single { it.name == "Handshake.kt" }.readText()
+ assertTrue("override fun toString(): String = \"SeedPayload(***)\"" in handshake)
+ }
+
+ @Test
+ fun `no main or release source names the debug socket carrier or the test fixtures`() {
+ val naming = (sources("app/src/main") + sources("app/src/release") + sources("wearlink/src/main"))
+ .filter { "wearlink.testing" in it.readText() }
+ .map { it.name }
+
+ assertEquals(emptyList(), naming)
+ }
+
+ @Test
+ fun `the link's log lines never include the recovery phrase, a key or a code`() {
+ val logging = listOf(
+ "app/src/main/java/to/bitkit/repositories/WatchLinkRepo.kt",
+ "wear/src/main/java/to/bitkit/wear/repositories/PhoneLinkRepo.kt",
+ "wear/src/main/java/to/bitkit/wear/link/KeystoreAgreementKey.kt",
+ ).map { File(root, it).readText() }
+ val call = Regex("Logger\\.\\w+\\(\\s*\"([^\"]*)\"")
+ val logged = logging.flatMap { source -> call.findAll(source).map { it.groupValues[1] } }
+
+ assertTrue(logged.isNotEmpty())
+ val secrets = Regex("mnemonic|passphrase|seed\\.|secret|\\.code|payload", RegexOption.IGNORE_CASE)
+ assertEquals(emptyList(), logged.filter { secrets.containsMatchIn(it) })
+ }
+}
diff --git a/build.gradle.kts b/build.gradle.kts
index db2d4ea7bd..606140d9e3 100644
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ -4,6 +4,7 @@ plugins {
alias(libs.plugins.compose.compiler) apply false
alias(libs.plugins.compose.stability.analyzer) apply false
alias(libs.plugins.google.services) apply false
+ alias(libs.plugins.kotlin.jvm) apply false
alias(libs.plugins.hilt.android) apply false // https://github.com/google/dagger/releases/
alias(libs.plugins.kotlin.serialization) apply false
alias(libs.plugins.ksp) apply false // https://github.com/google/ksp/releases
diff --git a/docs/screens-map.md b/docs/screens-map.md
index 3f09d7f30a..30ea2388bc 100644
--- a/docs/screens-map.md
+++ b/docs/screens-map.md
@@ -373,6 +373,10 @@ Amount entry stays in dollars with a BTC equivalent; QR and shared payment amoun
`MoveToSparkSheet.kt` implements [Modal Update Spending Balance](https://www.figma.com/design/ltqvnKiejWj0JQiqtDf2JJ/Bitkit-Wallet?node-id=52052-404808) and [Spending Balance Updated](https://www.figma.com/design/ltqvnKiejWj0JQiqtDf2JJ/Bitkit-Wallet?node-id=52052-409823) in Wallet Lightning - Transfer to Spending Balance. Its in-flight and failed states have no frame and keep their earlier copy in the same sheet. Covered by `journeys/transfer/move-to-spark.xml`; the update before a payment is covered by `journeys/send/update-spending-balance-payment.xml`.
+### Watch pairing
+
+`WatchSheet.kt` (Settings › General › Watch) pairs a Wear OS watch and shows the paired one; see `docs/wear.md`, Pairing. No design exists yet. Covered by `journeys/settings/watch-no-watch-connected.xml` and `journeys/wear/pair-*.xml`.
+
## Wear OS
The watch app's screens, under `wear/src/main/java/to/bitkit/wear`. None has a design yet. `HomeScreen.kt`, `SettingsScreen.kt`, `ActivityDetailScreen.kt` and `ReceiveQrScreen.kt` share their file names with phone screens and have their own rows here.
@@ -406,6 +410,12 @@ Layout scaffolds that other screens build on, not screens of their own.
| - | - |
| OnboardingScreen.kt | `todo` |
+### ui/screens/pair
+
+| Android | Figma |
+| - | - |
+| PairScreen.kt | `todo` |
+
### ui/screens/receive
| Android | Figma |
diff --git a/docs/wear.md b/docs/wear.md
index c8b06098eb..775872d99c 100644
--- a/docs/wear.md
+++ b/docs/wear.md
@@ -4,7 +4,8 @@
The `:wear` module is a standalone Wear OS app (issue #2105, epic #2077). It runs its own Spark wallet through the
Breez SDK, with no LDK node, no Room database and no Firebase. It needs no phone nearby: it adopts the phone's
-settings by reading the phone's backup (see Settings sync).
+settings by reading the phone's backup (see Settings sync). A watch that is paired with the phone also gets them
+pushed live, and can be set up, unpaired and erased from the phone (see Pairing).
## Module overview
@@ -48,7 +49,7 @@ settings by reading the phone's backup (see Settings sync).
components into the manifest: three activities and two services, one of them exported
(`RevocationBoundService`). The watch app uses none of them, so its manifest removes them
(`tools:node="remove"`), and the merged manifest lists only `MainActivity`, the balance tile's service, the NFC
- tag service and the androidx startup and profile components. The libraries themselves stay on the classpath, since Breez's classes load them.
+ tag service, the phone link's listener service and the androidx startup and profile components. The libraries themselves stay on the classpath, since Breez's classes load them.
- **Main thread.** Nothing reads the disk, the network or a system service on the main thread at launch or while
a screen composes. `NetworkMonitor`, `DeviceLock` and `NfcMonitor` are created empty and register with the system
on the IO dispatcher; the HTTP client, the settings file and the seed directory are opened on first use there.
@@ -89,11 +90,16 @@ settings by reading the phone's backup (see Settings sync).
tap, one request; `ui/LaunchGate` asks the filter and `SendMonitor` for the whole process). See NFC below.
- `tile`: `BalanceTileService` (the balance tile), `TileState` (what it shows) and `TileUpdates` (asks the system
to draw it again). See Tile below.
+- `link`: the watch's adapters for the phone link, whose protocol is the shared `:wearlink` module:
+ `DataLayerTransport` and `LinkListenerService` (the Wear Data Layer), `KeystoreAgreementKey` and `KeystoreLinkKeys`
+ (AndroidKeyStore) and `WatchLinkStore` (the pairing's record, in the settings file). `PhoneLinkRepo` in
+ `repositories` runs the pairing and takes what the paired phone sends; `PhoneStateSink` in `data` is where the
+ phone's state lands, whichever way it travelled. See Pairing below.
- `models`: among others `PhoneSettingsParser`, the reader of the phone's settings backup.
- `ui`: one `MainActivity` with `testTagsAsResourceId`, a `SwipeDismissableNavHost` with the routes Onboarding,
- the Restore graph, Wallet removed, Home, About, Receive QR, Send, Activity detail and Not supported, and the M3
+ the Restore graph, Pair, Wallet removed, Home, About, Receive QR, Send, Activity detail and Not supported, and the M3
Expressive theme (black background, Brand orange, Inter Tight). `LaunchRequest` reads what an intent asks for
- beyond opening the app: a payment link, a tapped NFC tag or the tile's Receive. The splash screen stays while the first screen is picked, for at most about a second;
+ beyond opening the app: a payment link, a tapped NFC tag, the tile's Receive or the phone's pair link. The splash screen stays while the first screen is picked, for at most about a second;
after that the loading ring shows until it is. When the wallet storage cannot be recovered at launch, the start
error (`WatchStartError` with `WatchStartRetry`) shows instead of a first screen.
@@ -190,9 +196,10 @@ On-screen copy stays short: a title or one line of at most about six words per s
a payer who scanned the earlier QR gets the check too. An
invoice shows for at least 30 s, also when the watch's clock runs ahead. Paid, the QR turns into a
check with the amount (`WatchReceivePaid`, `WatchReceivePaidAmount`) and a firm click (the `LongPress` haptic), unlike
- the confirm pattern that ends a send; a tap on the check shows a new invoice. In ambient mode the QR is replaced by
- a dimmed QR icon (`WatchReceiveHidden`), and an invoice paid meanwhile shows the check dimmed and without the
- amount, with the same haptic, so the always-on screen shows no amount; the amount shows once the watch wakes. Debug builds log each invoice shown (`Showing invoice`), which is how the
+ the confirm pattern that ends a send. The check is a status and takes no tap: the `EdgeButton` below it, "New
+ invoice" (`WatchReceiveNew`), shows a new invoice. In ambient mode the QR is replaced by
+ a dimmed QR icon (`WatchReceiveHidden`), and an invoice paid meanwhile shows the check dimmed, without the
+ amount and without the button, with the same haptic, so the always-on screen shows no amount; the amount shows once the watch wakes. Debug builds log each invoice shown (`Showing invoice`), which is how the
journeys read it. While the QR shows, the watch also offers the invoice as an NFC tag, with the NFC hint below the
QR (`WatchReceiveNfc`, or `WatchReceiveNfcOff` with NFC off): see NFC › Receive by tap.
- **Tile.** The Bitkit tile (`BalanceTileService`) uses the tiles and ProtoLayout Material 3 libraries: a primary
@@ -291,7 +298,8 @@ On-screen copy stays short: a title or one line of at most about six words per s
import, or after the phone's backup was found missing or unreadable; it moves on every minute while the page is
open), and a tap imports them now under the loading ring. An import from the tap that fails shows one line under
the row (`WatchSettingsSyncFailed`). Tapping the balance still swaps which unit shows first, and the choice is kept across restarts until the
- phone's own setting changes. Remove wallet asks with a one-line title and the two round ✕/✓ buttons.
+ phone's own setting changes. Remove wallet asks with a one-line title above one `EdgeButton` in the error colours
+ that says "Remove" (`WatchSettingsRemoveConfirm`); swiping the dialog away cancels.
- **Loading.** Every wait shows `BezelLoading`: an indeterminate ring around the screen edge (test tag
`BezelLoading`), with the screen's content readable inside it. It covers connecting and syncing on Balance, saving
the restored wallet, removing the wallet, importing the phone's settings from the Settings page, making an
@@ -302,7 +310,11 @@ On-screen copy stays short: a title or one line of at most about six words per s
rings, such as hold-to-pay.
- **Style.** Black background; Brand orange only on the one primary action (an `EdgeButton`) and accents; Inter
Tight; content centered inside the round screen and clear of the time; icons rather than labels where the icon is
- clear; no stacked button lists. Icon and text buttons morph their shape on press and the theme uses the expressive
+ clear; no stacked button lists. A check icon is a success status (Sent, Paid, Paired) and never a screen's
+ button, anywhere on the watch: a confirm action is a short text `EdgeButton` named by what it does ("Match",
+ "OK", "Remove", "Unpair", "New invoice"), and cancelling is the watch's swipe-to-dismiss.
+ The two questions asked in a dialog (Remove wallet, Unpair phone) are the platform's alert dialog with that one
+ button. Icon and text buttons morph their shape on press and the theme uses the expressive
(spring) motion scheme. Icons are vector drawables in `res/drawable`, with no icon library.
## Payments
@@ -796,9 +808,14 @@ from VSS and never writes there.
debug dex. It ships its own R8 rules, and `:wear:minifyDevReleaseWithR8` passes with it.
- **Checked on the emulator.** On the API 37 emulator a dev build signed in to the staging VSS and imported the
settings backup of its restored wallet 1.8 s after the wallet synced (2026-11-28).
-- **Known gap: a stale backup.** The watch sees a change only once the phone uploaded it. A phone that is offline,
- or whose backup fails, leaves the old settings on VSS, and the watch keeps following them.
-- **Later.** Pairing (a later PR) adds a live push from the phone over the Data Layer and the watch-specific limits.
+- **Known gap: a stale backup.** An unpaired watch sees a change only once the phone uploaded it. A phone that is
+ offline, or whose backup fails, leaves the old settings on VSS, and the watch keeps following them. A paired watch
+ does not depend on the backup: the phone pushes each change to it (see Pairing › Settings push), and a backup
+ older than the last push is not applied.
+- **One sink.** The import does not write the settings itself: it hands what it read to `PhoneStateSink`, as the
+ paired phone's push does. The sink decides which version holds, and whatever reads the settings afterwards never
+ learns where they came from.
+- **Later.** The watch-specific limits come with a later part of the pairing work.
### Self-send guard
@@ -829,6 +846,362 @@ unpaired watch has no way to learn the phone's invoices. The watch runs the guar
wallet is ready then, and always before a send is priced, also on the invoice an LNURL service returns; a guard
that cannot tell refuses the send.
+## Pairing
+
+The phone app and the watch app can be linked. Pairing does three things: it lets the phone set a watch up by
+sending it the wallet, it gives the phone a live, authenticated way to push its settings to the watch, and it lets
+the phone unpair the watch or erase its wallet. The watch still works without it, by the backup import above.
+
+This is part 1 of the pairing work. Parts 2 and 3 are later PRs and are named where they attach: part 2 shares the
+self-send guard's invoice hashes, the QuickPay counts and the send records; part 3 adds watch-specific limits, a
+payment handed from the phone to the watch and the prompt to install the watch app.
+
+- **Off on mainnet.** `Env.isWatchLinkEnabled` is false on mainnet for as long as the watch app is (#2152). The
+ phone's Watch row is then not shown, the link repository is not created at startup or by Settings, and the
+ listener service, which is in every flavor's manifest, drops every packet it is handed. A debug build on mainnet
+ sends no wallet to an unverified watch either. The watch's own switch is `Env.IS_MAINNET_ENABLED`.
+- **One watch.** The phone keeps one paired watch and the watch one paired phone. Pairing again replaces the
+ earlier pairing and deletes its keys.
+
+### Where the code is
+
+- **`:wearlink`** is a plain JVM module with no Android, no UI and no Play services, used by both apps. It holds
+ the whole protocol: the handshake of both roles (`PhonePairing`, `WatchPairing`), the key schedule, the key
+ attestation check (`AttestationVerifier`), the envelope every later message travels in (`LinkChannel`), the
+ documents, and both ends after pairing (`PhoneLink`, `WatchLink`). One copy means a phone and a watch can never
+ disagree about a byte, and its tests run the phone's side against the watch's in one process.
+- **Seams.** The module reaches the outside through four interfaces: `LinkTransport` (the carrier),
+ `LinkKeyStore` (the two long-term keys), `WatchAgreementKey` (the watch's key agreement key) and
+ `LinkRecordStore` (the pairing's record). Each app supplies the Android side: the Wear Data Layer, AndroidKeyStore
+ and a DataStore. The module's test fixtures supply in-memory ones, and the debug socket carrier.
+- **Phone:** `WatchLinkRepo`, `WatchLinkStore`, the `watch` package (`WatchDataLayerTransport`,
+ `WatchLinkListenerService`, `KeystoreLinkKeys`) and `ui/sheets/watch`.
+- **Watch:** `PhoneLinkRepo`, the `link` package and `ui/screens/pair`.
+- **Crypto.** Everything is the platform's or BouncyCastle's: P-256 key agreement (`KeyAgreement`), AES-256-GCM
+ (`Cipher`), HMAC-SHA256 and SHA-256 from the platform; HKDF-SHA256 and the ASN.1 reader of the attestation record
+ from BouncyCastle (`bcprov-jdk18on`, which the phone already shipped and the watch now ships too). Nothing
+ implements an algorithm. `LinkCryptoTest` holds RFC 5869's HKDF vectors and one vector of the key schedule that
+ was computed independently of the module.
+
+### The carrier
+
+- **Wear Data Layer.** Each app declares one capability in `res/values/wear.xml`: the phone `bitkit_phone_v1`,
+ the watch `bitkit_watch_v1`. The phone lists the connected nodes and those with the watch's capability; a node
+ without it is a watch without Bitkit. Only a node the Data Layer reports as nearby, so not one reached through
+ the cloud, is offered for pairing. The Data Layer itself only connects apps with the same application id and
+ signing certificate.
+- **Untrusted.** The link treats the carrier as a relay that can read, drop, delay, repeat, reorder and alter
+ everything. Nothing the listener services receive is trusted until the link has authenticated it.
+- **Two kinds of delivery, one rule.** One-shot messages (`MessageClient`) are never stored and only arrive while
+ the two are connected. State documents (`DataClient`) are stored and replicated by Play services, and delivered
+ after a reconnect. The handshake and the wallet seed only ever travel as one-shot messages. `DataClient` only
+ carries documents the link has encrypted, and never a seed. In the code the pairing sessions can only call the
+ transport's send; `WatchLinkSourcesTest` and `LinkSourcesTest` pin that, and that only two files in each app
+ name the Data Layer's classes.
+- **Listener services.** Each app has one `WearableListenerService`, exported because Play services binds it,
+ filtered to the `wear` scheme and the `/bitkit/v1` path prefix. It handles each event to its end on its own
+ thread, so a command also lands while the app is closed. The phone's only writes the link's store and starts
+ neither the Lightning node nor Spark.
+- **Release build.** The watch's release build shrinks resources, and nothing in the code refers to the
+ capability array, so `res/raw/keep.xml` keeps it; without that rule the capability would vanish from release
+ builds only. The phone's release build does not shrink resources.
+- **Opening the watch app.** The phone opens the watch's Pair screen with a `bitkitwear://pair` link through
+ `RemoteActivityHelper`, since a listener service may not start an activity on Wear OS. The wearer can also open
+ it from the watch's settings or onboarding. The link only shows a screen, so any app may send it.
+- **Debug socket.** Two emulators cannot pair over the Data Layer without a Google account. A debug build
+ therefore swaps the carrier for one TCP connection on the loopback interface when the file `wearlink-socket`
+ exists in its files directory: the watch listens, the phone connects, and `adb forward` with `adb reverse`
+ bridge the two on the host (`journeys/wear/README.md` has the commands). The class lives in `:wearlink`'s test
+ fixtures, which only the debug variants and the tests depend on, and the transport binding lives in each app's
+ `debug` and `release` source sets, so no release build contains it. The protocol above the carrier is unchanged
+ and trusts the socket no more than the Data Layer.
+
+### The ceremony
+
+Both ways of pairing run the same handshake. Which one follows is decided by one bit in the watch's reply: whether
+it holds a wallet.
+
+1. **Hello** (phone to watch, in clear). The phone makes a fresh P-256 key pair and sends its install id, a nonce,
+ its name and a commitment: the hash of its public key and a nonce. It repeats the hello every 2 s until a reply
+ arrives. The watch answers only while its Pair screen is up.
+2. **Reply** (watch to phone, in clear). The watch's Keystore generates a P-256 key for this handshake whose only
+ purpose is a key agreement, attested with a challenge that is the hash of the hello. The watch sends its
+ install id, a nonce, its model name, whether it holds a wallet, the key and the attestation's certificate chain.
+3. **Attestation check.** The phone verifies the chain and, for a chain that passes, reads Google's list of
+ revoked attestation certificates (see Key attestation). For a watch without a wallet, which is to receive the
+ seed, a failed check, a listed certificate or a list that cannot be read ends the pairing here: before the
+ phone has revealed its key, and long before any seed is read. A debug build alone goes on, and says so in the
+ sheet. A phone whose app has no PIN ends here too, for such a watch: see The phone's check.
+4. **Reveal** (phone to watch, in clear). The phone sends the public key it committed to. The watch checks the
+ commitment, so a relay cannot have picked the phone's key after seeing the watch's.
+5. **Keys.** Both run the key agreement and derive, with HKDF-SHA256 over the shared secret, salted with the hash
+ of the three messages above exactly as sent: two handshake keys (one per direction), a confirmation key, the
+ two long-term link keys, the pairing id and a 6-digit code.
+6. **Proofs.** Each side proves it derived the same keys. A watch that holds a wallet must also prove it is the
+ phone's, and the phone proves the same to it first: an HMAC keyed from the wallet's link secret over the
+ transcript and the role. The link secret is an HMAC-SHA256 of a label and the network name, keyed with the
+ BIP39 seed, as `SparkSendKey.secret` is under another label. A watch with another wallet ends here with
+ "Different wallet" on both screens.
+7. **The code on both screens.** Each user confirms that the two codes match, and each confirmation sends an
+ encrypted accept. Nothing more happens until both arrived.
+8. **Only for a watch without a wallet: the seed.** The phone's Pair button first runs the app's PIN or
+ biometric check. Then the phone reads the recovery phrase and passphrase from its keychain, encrypts them with
+ AES-256-GCM under its handshake key with the transcript as associated data, and sends that one message. The
+ watch decrypts it, checks the network and the BIP39 checksum, stores it through `WalletRepo.restore`, which is
+ the door a typed phrase goes through (`KeystoreSeedStore`), and answers with a proof made from the stored
+ wallet's link secret. The phone checks that proof: the wallet that landed is the one it sent.
+9. **Stored.** Both import the two link keys into their Keystore and write their record. The phone pushes its
+ settings at once.
+
+A ceremony lasts at most 90 s. Either side can cancel at any step, which tells the other; the other shows one line.
+On the phone a cancel also ends a pairing that is still looking for the watch, before anything was opened or sent
+on it, and one that waits for Google's list. A pairing started while the cancelled one is still ending (its abort
+is on its way) starts as soon as that has ended, and the cancelled one's end is never shown; `WatchLinkRepo` and
+`PhoneLinkRepo` both keep this under one lock.
+
+**What the code is for.** Between two holders of one wallet (step 6) the code is not what keeps a stranger out:
+without the seed nobody passes the proof. It tells each user which device answered. For a watch without a wallet
+the code is what tells the watch from a relay in the middle: a relay that runs its own key agreement with each
+side makes the two screens show different codes, except by a chance of one in a million per try.
+
+**Tries are counted.** `PairingThrottle` counts every seed transfer when it starts, before the reveal, and only a
+finished transfer clears the count. After three unfinished ones nothing starts for 10 minutes; the sheet says to
+try again later. The count is in
+the phone's link store, so a restart does not clear it.
+
+### Seed transfer: the controls
+
+Sending the seed is the one step whose failure costs the wallet, so each control is enforced in the code and has a
+test.
+
+| Control | Where | Test |
+|---|---|---|
+| Both users confirm one code before anything is sent | `PairingSession.exchangeAccepts`; the phone reads the seed only after both accepts | `PairingTest`: "no seed is read or sent before the watch confirmed", "…before the phone's user confirmed" |
+| The watch's key is attested before any seed leaves | `PhonePairing`, before the reveal | `PairingTest`: "an unverified attestation refuses the transfer before the phone reveals its key", and one test per reason; `AttestationVerifierTest` |
+| No certificate of the chain is revoked | `PhonePairing.checkStatus`, before the reveal, against `AttestationStatusList` read by `WatchLinkRepo` | `PairingTest`: revoked, suspended, a status this version does not know, and a list that cannot be read each refuse the transfer; `AttestationStatusListTest` |
+| A release build never sends to an unverified watch | `WatchLinkRepo` passes a debug build off mainnet as the only exception | `WatchLinkRepoTest`: "a build that requires attestation refuses…" |
+| The seed is encrypted to a key that exists only in the watch's Keystore | The watch's half of the key agreement is `KeystoreAgreementKey`: generated in StrongBox or the TEE, agreement-only, not extractable, deleted when the ceremony ends | The attestation check requires exactly that key; on-device behaviour is a manual test |
+| Never in the Data Layer's storage | The sessions can only send one-shot messages | `PairingTest`: "the seed never crosses the carrier in clear, and never as a stored document"; `WatchLinkSourcesTest` |
+| The app's PIN or biometric check first | `WatchSheetViewModel` decides to ask and only `onAuthSuccess` reports a pass; `WatchLinkRepo.confirmPairing` counts it only while a PIN is set; without it the session ends | `WatchSheetViewModelTest`: the check is asked before a wallet is sent, never for a watch that holds it, and a pass nothing asked for confirms nothing; `PairingTest` and `WatchLinkRepoTest`: "a confirmation without the phone's authentication sends no seed", "a check claimed on a phone whose PIN is gone sends no phrase" |
+| A confirmation counts only for the code the user saw | `PairingSession.confirm` takes the code and does nothing unless the session shows that code; `WatchLinkRepo.confirmPairing` and `PhoneLinkRepo.confirmPairing` pass the code their screen showed | `PairingTest`: "a confirmation made before the code shows, or of another code, sends no seed"; `WatchLinkRepoTest`: "a confirmation of another code than the one that shows confirms nothing" |
+| A phone without a PIN sends no seed | `PhonePairing`, before the reveal (`PhonePairingEnv.isPinSet`) | `PairingTest`: "a phone without a PIN sends no seed, and ends before it reveals its key"; `WatchLinkRepoTest`: "a phone without a PIN sends no phrase, and says a PIN is needed" |
+| Not in logs | `:wearlink` logs nothing; `SeedPayload.toString` prints nothing; the apps log event names | `WatchLinkSourcesTest` |
+| Stored through the seed store | `PhoneLinkRepo.storeSeed` calls `WalletRepo.restore` | `PhoneLinkRepoTest`: stored through the restore; invalid checksum, other network and insecure key refused |
+| One use | Keys are per handshake; a seed message of another handshake does not open | `PairingTest`: "a seed message of an earlier transfer is not taken by a later one" |
+| A watch with a wallet is never sent one | The watch's reply decides, and the transcript binds it | `PairingTest`: "two holders of one wallet pair without the seed being sent" |
+
+Everything fails closed: a message that is malformed, altered, early, repeated or from another device ends the
+ceremony or is dropped, and no partial pairing is kept.
+
+**The phone's check.** Sending the wallet needs the app's PIN to be set. The sheet's view model asks for the check
+the app's other protected actions use (`AuthCheckView`: biometrics when they are on and available, else the PIN
+pad) and tells the repository the check was passed only from its success. A phone without a PIN has no check to
+run, so it sends no wallet: the pairing with a watch that holds none ends before the reveal with "Set a PIN in
+Bitkit first, then pair your watch." Such a phone still pairs with a watch that already holds its wallet, and
+pushes it the settings, since neither sends anything secret: the wallet proof shows the watch has the seed
+already, and the settings are display values and the QuickPay limits.
+
+**Zeroing.** The shared secret, the session keys, the link secret and the encoded seed are byte arrays and are
+zeroed after use. The recovery phrase itself is a `String` on both sides, as in the rest of both apps (#2179).
+
+### Key attestation
+
+The phone accepts the watch's key agreement key as hardware-held only when all of this holds
+(`AttestationVerifier`):
+
+- each certificate of the chain is valid now and signed by the next, every certificate but the first is a CA whose
+ key usage, when it names one, allows signing certificates, and none but the first carries an attestation
+ record, so a key attested for signing cannot issue a forged record below itself;
+- the last certificate's public key is one of Google's two hardware attestation roots, pinned by key hash (the RSA
+ root and the P-384 root that replaces it; read from Google's published list on 2026-11-28, and kept equal to it
+ by a test over the two published certificates);
+- the attested key is the key the watch offered, on P-256;
+- the record's challenge is the hash of this handshake's hello;
+- both the attestation and the key are in the TEE or StrongBox, the key was generated there, and its only purpose
+ is a key agreement;
+- the device is locked with a verified boot state;
+- the app is Bitkit's package, signed with the certificate that signed the phone app.
+
+**Revocation.** Attestation keys leak from devices, and a leaked one attests anything. Google lists the serial
+numbers of the certificates it has revoked or suspended at `https://android.googleapis.com/attestation/status`.
+For a chain that passed the checks above, the phone reads that list (`WatchLinkRepo`, with the app's own HTTP
+client, at most 10 s; `AttestationStatusList` in `:wearlink` parses it) and looks up every certificate of the
+chain. A listed certificate, whatever its status, makes the watch unverified. So does a list that cannot be
+fetched or read, since a response that is not the list is never taken for an empty one: a release build then
+sends no wallet and says "Could not check the watch's secure hardware. Connect to the internet and try again.",
+and a debug build goes on, logs it and shows the watch as unverified. The request is one GET of a public file that
+is the same for everyone and names no user, wallet or watch. The list is read once per pairing and not kept; no
+snapshot is bundled, as it would be out of date by the first release.
+
+**Limits.** An emulator's Keystore attests with a software root, so a release build never sends a seed to one, and
+the list is not read for it. Between two wallet holders the verdict is shown and stored, and refuses nothing: a
+seed holder is trusted already. A watch whose list could not be read then shows as "secure hardware not
+verified".
+
+### Keys and records
+
+| What | Phone | Watch |
+|---|---|---|
+| Two AES-256-GCM link keys | AndroidKeyStore, imported, not extractable; StrongBox when it takes them (Android 12 and later), else the TEE | AndroidKeyStore, imported, not extractable; StrongBox when it takes them, else the TEE |
+| Pairing record | `watch_link.json`, device-local, in no backup: a restored phone pairs again | The settings file, which the wallet's wipe clears |
+| Install id | The same file | The settings file |
+| Count of unfinished transfers | The same file | — |
+| Seed | Unchanged | Unchanged (`KeystoreSeedStore`) |
+
+The link keys are not bound to an unlocked device, unlike the seed key, so an erase command can be read on a
+locked, lost watch. They protect settings and commands, never funds. Link keys that no record owns, as after a
+wipe took the record with the settings, are deleted when the watch app starts.
+
+### After pairing: envelopes and documents
+
+Everything after the handshake travels in an envelope: a header in clear (magic, version, the writer's role, the
+pairing id, a counter) and the body under the writer's link key, with the header and the Data Layer path as
+associated data. One key per direction, so a message cannot be sent back to its writer.
+
+- **Order and replay.** The writer stores its counter before it uses it. At each path the reader takes only a
+ counter higher than the last one it applied, so an old "QuickPay on" never replaces a newer "QuickPay off",
+ whatever the carrier does. The reader records a counter after it applied the body, so a document whose effect a
+ crash cut short is applied again when it is delivered again.
+- **Documents**, each a full snapshot with one writer: `p2w/control` (paired, revoked, erase), `p2w/settings`
+ (the six settings and the phone's time of the change) and `w2p/status` (the settings counter the watch applied,
+ whether it still holds the pairing). Each is stored for delivery after a reconnect and also sent at once.
+- **A new pairing** has new keys and a new id, so nothing of an earlier one opens.
+
+### Settings push
+
+- The phone publishes the six settings the watch adopts when the pairing is made, at each app start and whenever
+ one of them changes, with the phone's time of the change, made strictly later than the last one sent.
+- The phone finishes a pairing a moment before the watch has noted it, so the watch may drop that first push. Its
+ first status then says it has applied none, and the phone publishes again; this happens at most once per pairing.
+- The watch applies a push through the same rules as a backup (`PhoneSettingsParser.fromPush`: a value the phone
+ cannot have is dropped, QuickPay values outside the phone's sliders turn QuickPay off), also while its app is
+ closed, and reports the counter it applied.
+- The phone's Watch sheet shows "Settings not on watch yet" until that report covers the last push.
+- **Push against import.** Both feed `PhoneStateSink`. A push always holds: the link has put pushes in order. A
+ backup holds only when the phone wrote it after the last push the watch applied, by the phone's own clock on
+ both, so an older backup never undoes a change that already arrived live. The push's time the watch keeps is
+ never more than 5 minutes ahead of the watch's own clock: a push from a phone whose clock ran ahead is still
+ adopted, and does not shadow the backups that phone writes later, as it would once the phone lost the pairing.
+ The limit of that cap: the watch cannot tell a phone that runs ahead from its own clock running behind. On a
+ watch whose clock is more than 5 minutes behind the phone's, a push is kept as older than it is, so a backup
+ the phone wrote in between, before the push, can pass as newer and bring the older settings back until the
+ next push or the phone's next backup. Watches take their time from the phone, so this needs a watch whose
+ clock is off. A backup that is missing or unreadable
+ does not turn QuickPay off while a push holds. When the pairing ends, the import holds again.
+- **A seam for another source.** The Data Layer is how the phone's state reaches the watch today. The watch may one
+ day read it from VSS instead, which is not possible yet. The sink is the seam for that: the settings now, and in
+ part 2 the invoice hashes, the QuickPay counts and the send records, land in the watch's stores through it, and
+ the guards read the stores. A source can be added or replaced without touching a guard. On the phone,
+ `WatchLinkRepo` is the one place that publishes them. The watch stays read-only on VSS.
+
+### Unpair, erase and wipe
+
+- **Unpair from the phone.** The phone publishes "revoked" and marks its record. The watch forgets the phone,
+ deletes its link keys and answers; the phone then deletes its record and keys. The wallet stays on the watch.
+- **Erase from the phone.** The phone publishes "erase" and keeps that command stored until the watch
+ acknowledges. The watch first writes the wipe's note to disk (`WalletRepo.noteEraseByPhone`), then acknowledges
+ while its keys still exist, then runs the wallet's own wipe (`WalletRepo.eraseByPhone`), which leaves the Wallet
+ removed notice and takes the pairing's record with the settings. From the note on, the wipe is finished when the
+ app's process next starts at the latest, whatever starts it (`PhoneLinkRepo` runs `WalletRepo.recover` at its
+ start when the note exists, so a message from the phone, the tile or a tap on the app all do), so the phone is
+ never told "erased" about a wallet that stays. A note that cannot be
+ written, or a watch that dies before it, acknowledges nothing: the command is still stored and is delivered
+ again. A watch that dies between the note and the acknowledgement finishes the wipe at its next process start, which
+ takes the link keys with it, so the phone is not told and keeps showing the erase as waiting until the user
+ stops waiting. The command is authenticated by the link key and its counter: one from an earlier pairing does
+ nothing. It is best effort, and the phone says so: a watch that never reconnects keeps its wallet.
+- **Stop waiting.** A removal the watch never acknowledged stays listed with "Stop Waiting", which drops the
+ record and keys on the phone. The stored command stays, so a watch that returns later still reads it.
+- **Unpair from the watch**, from the Phone row in its settings: it tells the phone and forgets it.
+- **Removing the wallet on the watch** tells the phone first; the wipe then clears the record.
+- **Wiping or replacing the wallet on the phone** (`WipeWalletUseCase`) tells the watch to unpair and forgets it.
+ The watch is never erased by this: it holds its wallet in its own right.
+
+### Screens
+
+Phone: Settings › General has one row, Watch (`PairedWatchSettings`), after Hardware Wallets, with the paired
+watch's name or "Not paired". It opens one bottom sheet (`WatchSheet`; its container's tag `PairedWatchSheet` has no
+text, so `android layout` does not list it), in the app's sheet host
+like Send and Receive, that holds the whole flow:
+
+- **Watch found.** One line about the connected watch (`PairedWatchStatus`): ready to pair, Bitkit missing on it,
+ has Bitkit but is not reached directly ("Keep it nearby with Bluetooth on"), or none connected; and Pair Watch
+ (`PairedWatchPair`), disabled unless a watch with Bitkit is nearby. Of several watches the one that can pair is
+ named, then one that has Bitkit. Each opening looks from scratch, and while the sheet shows this state and the
+ app is on screen it looks again every 3 s, so a watch that connects later shows up. One look runs at a time,
+ and closing the sheet drops the one under way.
+- **Code.** The six digits (`PairedWatchCode`), the warning that confirming sends the wallet
+ (`PairedWatchSendsWallet`), Cancel and Pair (`PairedWatchCodeCancel`, `PairedWatchCodeConfirm`), and "Confirm
+ the code on your watch" once the phone confirmed (`PairedWatchPairWaiting`).
+- **Authenticate.** When confirming sends the wallet, the app's PIN pad or biometric prompt covers the sheet
+ first. Leaving it, by its back arrow or the system Back, returns to the code with nothing sent and the pairing
+ still running. It goes away by itself when the pairing ends under it.
+- **Transfer and end.** "Sending your wallet…" (`PairedWatchPairSending`), then `PairedWatchPairDone` or one line
+ (`PairedWatchPairError`), each with OK (`PairedWatchPairClose`), which returns to the watch's state. A phone
+ without a PIN gets its line here: "Set a PIN in Bitkit first, then pair your watch."
+- **Paired watch.** Its name (`PairedWatchName`), "holds your full wallet" (`PairedWatchFullWallet`), its key's
+ verdict (`PairedWatchKeyLevel`), the settings state (`PairedWatchSettingsState`), Unpair (`PairedWatchUnpair`),
+ OK (`PairedWatchClose`) and Unpair and Erase Watch (`PairedWatchErase`), each removal behind a dialog
+ (`DialogConfirm`, `DialogCancel`); or a pending removal (`PairedWatchRemovePending`, `PairedWatchStopWaiting`).
+ A watch whose secure hardware was not verified shows a plain shield instead of the checked one. A dialog stays
+ open while the watch's reports rewrite its record, and closes when that watch is gone.
+
+Closing the sheet cancels a pairing under way, at any step, except while the wallet is on its way to the watch:
+that transfer is left to finish, so the two devices agree on how it ended, and the sheet shows it again when
+reopened: still sending, the line that says why it failed, or the paired watch.
+
+The phone's tags start with `PairedWatch` because the watch app's own start with `Watch`.
+
+Watch:
+
+- **Pair** (`PairScreen`, `WatchPairScreen`): "Start on phone" (`WatchPairWaiting`), then the phone's name
+ (`WatchPairPhone`), the code (`WatchPairCode`) and one `EdgeButton` that says "Match" (`WatchPairConfirm`), then
+ the ring, then a check with "Paired" (`WatchPairDone`) or one line (`WatchPairError`). There is no cancel
+ button: swiping the screen away cancels, at every step. The code and the button are hidden in ambient mode, and
+ the code from screenshots in release builds. The pairing is cancelled when the screen closes or the app leaves
+ the screen. A Pair screen opened while a cancelled pairing is still ending waits anew and never shows that one's code. The end of
+ a failed pairing shows for 3 s; when the phone starts another pairing meanwhile, the screen stays and waits
+ anew, so the phone's retry is answered. A request that comes while a pairing runs past the phone's hello never
+ interrupts it; it is kept, and when that pairing fails or the phone aborts it the screen waits anew. It is
+ dropped when the wearer swipes the pairing away or it pairs.
+- **Onboarding** has a second way in, "From phone" (`WatchOnboardingFromPhone`), which opens Pair.
+- **Settings** has a row: "Pair phone" (`WatchSettingsPair`), or "Phone" with the phone's name
+ (`WatchSettingsPaired`, `WatchSettingsPairedName`), whose tap asks "Unpair phone?" above one `EdgeButton` that
+ says "Unpair" (`WatchPhoneUnpairConfirm`); swiping the dialog away cancels. An unpair that fails shows one line
+ under the row (`WatchPhoneUnpairFailed`) while the phone stays paired; the line goes when the pairing changes.
+
+### Checked where
+
+- **Unit tests**, both roles in one process over an in-process carrier that drops, alters and replays
+ (`:wearlink`): every step of the ceremony, every refusal, the attestation check against test certificate chains,
+ replay and rollback of documents, unpair, erase and the settings push. `WatchLinkRepoTest` (phone) and
+ `PhoneLinkRepoTest` (watch) run each app's repository against the other role.
+- **Two emulators** over the debug socket: the journeys named in `journeys/wear/README.md`.
+- **Driven on the two emulators** (API 36 phone, API 37 watch, debug socket, 2026-11-28): pairing by proof with the
+ same code on both screens, the settings push arriving on the watch, erase from the phone ending on Wallet removed
+ with the seed file gone, a watch without a wallet receiving the phone's through the watch's real Keystore
+ agreement key (unattested there, so the debug-only path) and opening Home, cancel on the watch, unpair from the
+ phone and from the watch, and the phone's sheet through each of those. PlayStore-less emulators make no Google
+ attestation, so the verified path and the release-build refusal were not run.
+- **Not checked without physical devices:** the Data Layer carrier itself, discovery by capability and `isNearby`,
+ the remote launch of the Pair screen, delivery to a closed app and a locked watch, the Keystore's agreement key
+ and its attestation on real hardware, and so the whole release-build seed transfer. These are manual tests.
+
+### Known gaps
+
+- Key attestation revocation needs the internet on the phone: without it a release build sends no wallet. The
+ list is Google's alone; a leaked key Google has not listed yet still passes.
+- A watch that dies between noting an erase and acknowledging it erases at its next launch without telling the
+ phone, which shows the erase as waiting until the user stops waiting.
+- An abort tells the other side why in clear, and nothing authenticates it: a relay can end a ceremony or change
+ the line shown, and nothing else.
+- When the watch stored the seed and its answer is lost, the phone reports a failure while the watch holds the
+ wallet. Pairing again then succeeds by proof.
+- The phone publishes its settings to the watch; the wearer's own unit swap still lasts only until the phone's
+ setting changes, as for the import.
+- Not in this part: the shared invoice hashes, QuickPay counts and send records (part 2); watch-specific limits,
+ the payment handoff and the install prompt (part 3). Until part 3 the watch's QuickPay follows the phone's.
+
## Seed storage
The watch holds the full recovery phrase and passphrase, because Breez needs them to open the wallet.
@@ -938,8 +1311,9 @@ still works if it ever happens.
## Restoring with a recovery phrase
-Onboarding leads to the length choice (12 or 24 words), then one screen per word, the checksum check, the optional
-passphrase and Home.
+Onboarding's Restore leads to the length choice (12 or 24 words), then one screen per word, the checksum check, the
+optional passphrase and Home. Its other way in, From phone, receives the wallet from the paired phone instead (see
+Pairing).
- The length is one control: tapping 12 or 24 starts typing.
- Each word screen shows the progress, such as 3/12, and a text field. After two letters up to six wordlist words
@@ -964,9 +1338,9 @@ passphrase and Home.
- While the wallet is saved, the passphrase screen cannot be left by a swipe or the back button, so the wearer
never lands on an earlier screen with a wallet stored behind it. Onboarding checks for a stored wallet each time
it comes on screen and opens Home when there is one, as after a save that finished while the wearer was away.
-- The word and passphrase screens set `FLAG_SECURE` while shown, in debug builds too (the phone's
- `BlockScreenshots` exempts debug builds). Screenshots and screen recordings of them come out black, so journeys
- check these screens with `android layout` only.
+- The word and passphrase screens set `FLAG_SECURE` while shown, in release builds only, as the phone's
+ `BlockScreenshots` does. Screenshots and screen recordings of them come out black there; debug builds capture
+ them, so journeys can screenshot them, and never with a recovery phrase on screen.
- The text fields ask the keyboard for plain text without suggestions, personalized learning or dictation. A keyboard
may ignore these hints: the Wear OS keyboard on the API 37 emulator still shows its own dictionary strip and
microphone key. A password input type would silence it, but Wear OS apps must not show password fields (lint
@@ -1042,5 +1416,9 @@ Measured on the emulator (Wear OS 7, API 37, 454×454 round, x86_64) unless note
exists.
- Whether Wear OS watches read NFC tags and dispatch them with the screen on, which Pay by tap counts on: see NFC ›
Open questions.
+- Pairing on physical devices: whether `isNearby` excludes a cloud-routed node, whether a Wear OS Keystore makes an
+ attested key-agreement key in StrongBox or only in the TEE, how long a Data Layer state document waits for a watch
+ that is away, and whether the listener service is started on a locked watch.
+- Whether the phone should keep more than one paired watch.
- Whether bitkit-ios writes all three QuickPay keys into its settings backup: the watch needs all three and leaves
QuickPay off when one is missing.
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index 1d0dc2ec12..b37e649aa3 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -63,7 +63,10 @@ hilt-work = { module = "androidx.hilt:hilt-work", version.ref = "hiltAndroidx" }
jna = { module = "net.java.dev.jna:jna", version = "5.19.1" }
kotlin-bom = { module = "org.jetbrains.kotlin:kotlin-bom", version.ref = "kotlin" }
kotlinx-collections-immutable = { module = "org.jetbrains.kotlinx:kotlinx-collections-immutable", version = "0.5.2" }
+kotlinx-coroutines-bom = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-bom", version = "1.11.0" }
+kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core" }
kotlinx-datetime = { module = "org.jetbrains.kotlinx:kotlinx-datetime", version = "0.8.0" }
+kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version = "1.11.0" }
ktor-client-cio = { module = "io.ktor:ktor-client-cio", version.ref = "ktor" }
ktor-client-content-negotiation = { module = "io.ktor:ktor-client-content-negotiation", version.ref = "ktor" }
ktor-client-core = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }
@@ -81,6 +84,7 @@ lifecycle-viewmodel-savedstate = { module = "androidx.lifecycle:lifecycle-viewmo
material = { module = "com.google.android.material:material", version = "1.14.0" }
navigation-compose = { module = "androidx.navigation:navigation-compose", version.ref = "navCompose" }
navigation-testing = { module = "androidx.navigation:navigation-testing", version.ref = "navCompose" }
+play-services-wearable = { module = "com.google.android.gms:play-services-wearable", version = "20.0.1" }
room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "room" }
room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = "room" }
room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "room" }
@@ -106,6 +110,7 @@ wear-compose-foundation = { module = "androidx.wear.compose:compose-foundation",
wear-compose-material3 = { module = "androidx.wear.compose:compose-material3", version.ref = "wearCompose" }
wear-compose-navigation = { module = "androidx.wear.compose:compose-navigation", version.ref = "wearCompose" }
wear-tooling-preview = { module = "androidx.wear:wear-tooling-preview", version = "1.0.0" }
+wear-remote-interactions = { module = "androidx.wear:wear-remote-interactions", version = "1.2.0" }
wear-tiles = { module = "androidx.wear.tiles:tiles", version = "1.6.2" }
wear-protolayout = { module = "androidx.wear.protolayout:protolayout", version.ref = "wearProtolayout" }
wear-protolayout-material3 = { module = "androidx.wear.protolayout:protolayout-material3", version.ref = "wearProtolayout" }
@@ -118,6 +123,7 @@ haze = { module = "dev.chrisbanes.haze:haze", version.ref = "haze" }
haze-materials = { module = "dev.chrisbanes.haze:haze-materials", version.ref = "haze" }
[plugins]
+kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" }
android-application = { id = "com.android.application", version.ref = "agp" }
compose-compiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
compose-stability-analyzer = { id = "com.github.skydoves.compose.stability.analyzer", version = "0.7.5" }
diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml
index 12061cc024..1fcf4fa3c8 100644
--- a/gradle/verification-metadata.xml
+++ b/gradle/verification-metadata.xml
@@ -2654,6 +2654,14 @@
+
+
+
+
+
+
+
+
@@ -2662,6 +2670,14 @@
+
+
+
+
+
+
+
+
@@ -3592,6 +3608,14 @@
+
+
+
+
+
+
+
+
@@ -3608,6 +3632,14 @@
+
+
+
+
+
+
+
+
@@ -3656,6 +3688,14 @@
+
+
+
+
+
+
+
+
@@ -5156,6 +5196,19 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -6851,6 +6904,14 @@
+
+
+
+
+
+
+
+
@@ -7066,6 +7127,14 @@
+
+
+
+
+
+
+
+
@@ -7074,6 +7143,14 @@
+
+
+
+
+
+
+
+
@@ -7183,6 +7260,38 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -7455,6 +7564,11 @@
+
+
+
+
+
diff --git a/journeys/README.md b/journeys/README.md
index 1d03a38d3e..5e79d56d35 100644
--- a/journeys/README.md
+++ b/journeys/README.md
@@ -140,6 +140,7 @@ journey PR, which is what made this file conflict on every merge.
| A watch to run the Wear OS app on | a Wear OS watch emulator (`Wear_Large_Round_API37`, `Wear_Small_Round_API34`), or a physical watch over Wi-Fi debugging — [wear](wear/README.md) |
| Watch gestures: pager swipes, swipe-to-dismiss, rotary crown, ambient mode | `adb shell input swipe`, `adb shell input rotaryencoder scroll --axis SCROLL,` and `KEYCODE_SLEEP`/`KEYCODE_WAKEUP` on the emulator; the real crown, bezel and wrist on a physical watch — [wear](wear/README.md#watch-gestures) |
| The phone's settings on the watch (units, currency, QuickPay) | a phone dev build with the same private settings wallet (the test phrase with a passphrase kept on this machine), never the public test phrase alone, writes them to the hosted staging VSS, and the watch imports them; nothing runs locally — [wear](wear/README.md#phone-settings-on-vss) |
+| A phone and a watch that reach each other, for pairing | a phone emulator (`Bitkit_Phone_API36`) and a watch emulator with debug builds of both apps, joined by the debug socket carrier over `adb forward` and `adb reverse`; the Wear Data Layer itself, the watch's hardware Keystore and its attestation, and so a release-build seed transfer, are not covered — [wear](wear/README.md#phone-and-watch-over-the-debug-socket) |
| Typing on the watch keyboard | `adb shell input text` after closing the Wear OS keyboard with Back, which otherwise swallows the input — [wear](wear/README.md#typing) |
## Cross-platform
@@ -220,6 +221,7 @@ Known differences in the corpus, as of the iOS port (synonymdev/bitkit-ios#691):
| `settings/quickpay-payment-pin.xml` | same file and steps, paired with synonymdev/bitkit-ios#1326 — on iOS the PIN pad is a sheet whose back control is `NavigationBack`, and a failed biometric check counts as not approved instead of falling back to the PIN pad |
| — | `hardware-wallet/transfer-to-spending-over-max.xml` exists only on iOS |
| `wear/*` | not ported — Android only for now; bitkit-ios has no watch app yet, and the watch journeys port with that follow-up |
+| `settings/watch-no-watch-connected.xml` | not ported — Android only for now; bitkit-ios has no watch pairing. The phone's pairing tags are `PairedWatch…`, since the watch app's own start with `Watch…`; an iOS twin takes the same names |
### Running one on iOS
diff --git a/journeys/settings/watch-no-watch-connected.xml b/journeys/settings/watch-no-watch-connected.xml
new file mode 100644
index 0000000000..0bbc5705a2
--- /dev/null
+++ b/journeys/settings/watch-no-watch-connected.xml
@@ -0,0 +1,19 @@
+
+
+ A phone with no watch connected offers nothing to pair: Settings › General has the Watch row reading "Not
+ paired", and the sheet it opens says no watch is connected, with Pair Watch disabled. One phone emulator, with no Wear OS
+ watch connected to it and without the debug socket file (journeys/wear/README.md › Phone and watch over the
+ debug socket). Android only: bitkit-ios has no watch app yet. A mainnet build hides the row (unit of
+ `Env.isWatchLinkEnabled`), which no dev build can show.
+
+ Precondition: a dev build with a wallet, on Home.
+
+
+ Open Settings from the drawer (tag "HeaderMenu", then "DrawerSettings")
+ On the General tab, scroll to Watch (tag "PairedWatchSettings") and verify its value reads "Not paired"
+ Tap "PairedWatchSettings" and verify the Watch sheet opens: "PairedWatchStatus" is listed
+ Wait up to 10 s until "PairedWatchStatus" reads "No watch connected. Connect a Wear OS watch to this phone first."
+ Tap Pair Watch (tag "PairedWatchPair") and verify nothing starts: "PairedWatchPairConnecting" is not listed
+ Press Back and verify the sheet closes: "PairedWatchStatus" is not listed and "PairedWatchSettings" is
+
+
diff --git a/journeys/wear/README.md b/journeys/wear/README.md
index 5c1cec7811..2a13f06544 100644
--- a/journeys/wear/README.md
+++ b/journeys/wear/README.md
@@ -21,8 +21,9 @@ What `android layout` misses on the watch, verified on the API 37 emulator:
text node at the same `center`. A chip below the screen edge is not listed until the screen scrolls.
- **The keyboard.** The Wear OS keyboard is a full-screen window that `android layout` does not show. It lists the
app's screen underneath, so a tap you aim at a tag lands on a key instead. See [Typing](#typing).
-- **Screens with `FLAG_SECURE`.** The word and passphrase screens come out black in a screenshot and a screen
- recording. `android layout` still lists their tags, so check them there.
+- **Screens with `FLAG_SECURE`.** The word, passphrase and Pair screens block screenshots and screen recordings in
+ release builds only, as on the phone; debug builds capture them. Never capture the word or passphrase screens with
+ a recovery phrase on them.
## Emulators
@@ -113,7 +114,6 @@ the command line. Run `receive-paid.xml` first: it funds the wallet the send jou
| `background-disconnects-spark.xml` | hosted | yes |
| `nfc-hint-states.xml` | hosted, physical watch only | yes |
| `nfc-pay-background.xml` | local | yes, 2 000 sats |
-| `screenshot-blocked.xml` | none | no |
| `receive-qr.xml` | local | no |
| `receive-qr-rests.xml` | local | no |
| `receive-paid.xml` | local | no, it funds the wallet with 50 000 sats |
@@ -384,6 +384,54 @@ day.
**Never install the phone app on the watch or the watch app on the phone:** they share one application id.
`just install` and `just wear-install` each pick a device by `ANDROID_SERIAL`; set it before every install.
+### Phone and watch over the debug socket
+
+The `pair-*.xml` journeys run the phone app and the watch app against each other. Two emulators cannot pair over
+the Wear Data Layer without a Google account, so debug builds can carry the same protocol over one TCP connection
+instead (Pairing › The carrier in [docs/wear.md](../../docs/wear.md)). The watch listens on port 47115 and the
+phone connects to it through the host.
+
+1. Build both apps first, one Gradle build at a time and with no emulator running if memory is short:
+ `./gradlew :app:assembleDevDebug`, then `./gradlew :wear:assembleDevDebug`.
+2. Start the phone emulator (`Bitkit_Phone_API36`) and the watch emulator (`Wear_Large_Round_API37`), and note
+ their serials as `PHONE` and `WATCH`. Never install one app on the other device: the two share an application
+ id, so `adb install` would replace the app that is there.
+3. Install each app on its own device, open each once so its files directory exists, then turn the socket on and
+ bridge the port:
+
+```bash
+adb -s $PHONE install -r app/build/outputs/bitkit/devDebug/
+adb -s $WATCH install -r wear/build/outputs/apk/dev/debug/wear-dev-x86_64-debug.apk
+adb -s $PHONE shell run-as to.bitkit.dev touch files/wearlink-socket
+adb -s $WATCH shell run-as to.bitkit.dev touch files/wearlink-socket
+adb -s $WATCH forward tcp:47115 tcp:47115 # host port -> the watch's listener
+adb -s $PHONE reverse tcp:47115 tcp:47115 # the phone's loopback -> host port
+adb -s $PHONE shell am force-stop to.bitkit.dev
+adb -s $WATCH shell am force-stop to.bitkit.dev
+```
+
+4. Start the watch app, then the phone app. Both log `Using the debug socket link transport` (the watch under
+ `BitkitWear`, the phone in its app log). The sheet behind the phone's Settings › General › Watch then names the watch
+ "Debug socket" as ready to pair.
+
+Notes:
+
+- `adb forward` and `adb reverse` are lost when an emulator restarts; run those two lines again. `pm clear` deletes
+ the `wearlink-socket` file with the rest of the app's data, so [Fresh app](#fresh-app) needs the `touch` again
+ after the app was opened once.
+- The phone needs a wallet: create one in the app's onboarding. It needs no funds for the pairing journeys.
+- The phone needs a PIN to send its wallet to a watch (Settings › Security › PIN Code; the journeys use 1111, with
+ biometrics off). Without one that pairing ends on "Set a PIN in Bitkit first, then pair your watch."
+ (`pair-receive-wallet-no-pin.xml`). Pairing with a watch that already holds the wallet needs none.
+- The watch's code screen has one button, Match (`WatchPairConfirm`). It has no cancel button: swipe the screen
+ away (Watch gestures, swipe-to-dismiss).
+- An emulator's Keystore cannot be attested against Google's roots, so the phone's Watch sheet shows
+ `PairedWatchUnverified` when it is about to send the wallet. A release build refuses there. Google's list of
+ revoked attestation certificates is only read for a watch whose attestation was verified, so never here.
+- The socket stands in for the carrier only. Everything above it is the real protocol, with the real Keystore
+ keys of each emulator.
+- To go back to the Data Layer, delete the file on both devices and restart both apps.
+
### Restart
The journeys restart the app with:
@@ -588,8 +636,8 @@ adb shell rm /sdcard/.mp4
grep -q moov .mp4 || echo ".mp4 has no moov atom: record it again"
```
-The word and passphrase screens record as black frames (`FLAG_SECURE`), which is what `screenshot-blocked.xml`
-checks.
+Debug builds record every screen. Release builds record the word, passphrase and Pair screens as black frames
+(`FLAG_SECURE`); manual test 8 under [Manual tests on a physical watch](#manual-tests-on-a-physical-watch) checks it.
## On a physical watch
@@ -625,8 +673,8 @@ Every journey here runs on a real watch; none needs an emulator-only command.
screen lock.
- **Network.** An LTE watch reaches hosted regtest without Wi-Fi or the phone; one without LTE goes through Wi-Fi or
the phone's Bluetooth proxy, which makes the first sync slower.
-- **Screenshots and screen recordings** work over adb as on the emulator, and the secure screens come out black the
- same way.
+- **Screenshots and screen recordings** work over adb as on the emulator. In a release build the secure screens
+ come out black.
## Offline
@@ -760,3 +808,69 @@ same wallet the phone's invoice would be the watch's own. Debug builds log the t
- Expected: the first time TalkBack says "Sent" as the line changes; the second time it says "Sent, ₿ 1 000"
once as the check appears, and nothing of the screen beneath can be focused meanwhile. Cancelling in place of
claiming gives "Payment failed" and "Payment failed, ₿ 1 000". Not run yet.
+8. **Release builds block screenshots.** It needs a release build, which is built for ARM only, so a physical watch:
+ install a release-signed build, tap Restore, then 12, and take a screenshot of the word entry screen. Swipe back
+ and take another.
+ - Expected: the first is entirely black, and `android layout` still lists `RestoreWordInput`; the second shows
+ "How many words?". The Pair screen's code is black the same way. A debug build captures all three.
+
+## Manual tests for pairing
+
+These need capabilities the journey environment lacks: a watch paired with the phone over the Wear Data Layer,
+which needs the companion app and a Google account, and a watch with a hardware Keystore. Run them with a phone
+and a physical Wear OS watch that are paired in the system, both with builds of the same flavor signed with the
+same key. Tests 1 to 8 use dev builds without the `wearlink-socket` file; tests 3a and 9 need release-signed
+builds (`assembleDevRelease` of both apps with a local keystore).
+
+1. **Discovery.** With the watch connected and Bitkit installed on it, open Settings › General › Watch on the phone.
+ - Expected: the line names the watch as ready to pair and Pair is enabled.
+ - 1a. With Bitkit not installed on the watch: the line asks to install Bitkit on it and Pair is disabled.
+ - 1b. With the watch out of Bluetooth range but online over Wi-Fi: the line says the watch is not reachable and
+ to keep it nearby with Bluetooth on, never to install Bitkit, and Pair is disabled. Note whether the Data
+ Layer reports the node at all.
+ - 1c. Open the sheet with the watch disconnected, then connect it: within a few seconds the line names it as
+ ready, without reopening the sheet.
+2. **Pair two holders of one wallet.** Restore the phone's wallet on the watch by typing the phrase. Tap Pair on
+ the phone.
+ - Expected: the watch app comes to the front on its Pair screen by itself; both screens show the same six
+ digits; after Match on the watch and Pair on the phone both say paired; the phone shows the watch's name, "holds
+ your full wallet" and its key's verdict.
+ - 2a. Note the verdict (StrongBox, secure hardware or not verified) per watch model.
+ - 2b. With the watch app closed before tapping Pair: it opens on the Pair screen.
+3. **Set a watch up from the phone.** Remove the wallet from the watch. Tap From phone on the watch, then Pair on
+ the phone. Set a PIN on the phone first.
+ - Expected: the phone warns that pairing sends the recovery phrase; Pair asks for the PIN; the watch opens Home
+ with the phone's balance after its first sync.
+ - 3a. Release-signed builds on a watch with a locked bootloader: the same, and the phone's Watch screen shows
+ the key verified in StrongBox or secure hardware. This is the only check of the attestation on real hardware.
+ - 3b. Dev builds on a watch emulator connected to a physical phone, or any watch with an unlocked bootloader,
+ with a release-signed phone build: the phone says the watch's secure hardware could not be verified and that
+ the wallet was not sent, and the watch stays without a wallet.
+ - 3c. Cancel the PIN: nothing is sent and the watch keeps waiting.
+ - 3d. Release-signed builds, the phone in airplane mode with Bluetooth back on: the phone says it could not
+ check the watch's secure hardware and to connect to the internet, and the watch stays without a wallet.
+ Online again, the same pairing sends the wallet.
+ - 3e. Without a PIN on the phone: the phone says to set a PIN in Bitkit first, and nothing is sent.
+ - 3f. Tap Pair on the phone and Cancel at once, three times in a row: the watch's Pair screen does not open by
+ itself with a code nobody confirms, and a fourth try is not refused with "Too many attempts".
+4. **Different wallet.** Restore another wallet on the watch and pair: both say "different wallet".
+5. **Erase a watch that is away.** Paired, close the watch app and lock the watch. On the phone tap Unpair and
+ Erase Watch.
+ - Expected: within seconds the watch's wallet is gone; opening the app shows Wallet removed; the phone's row
+ reads Not paired.
+ - 5a. With the watch switched off: the phone shows the pending removal; switch the watch on and it erases
+ itself once it reconnects, without the app being opened.
+ - 5b. Tap Stop Waiting before switching the watch on: the phone forgets the watch, and the watch still erases
+ itself when it reconnects.
+ - 5c. Force-stop the watch app the moment the phone's erase is confirmed (`adb shell am force-stop`): at its
+ next launch the watch shows Wallet removed. The phone never reads "Not paired" while the watch still holds
+ its wallet; it may keep showing the erase as waiting, which Stop Waiting ends.
+6. **Settings push.** Paired, turn QuickPay off on the phone with the watch connected.
+ - Expected: a small invoice on the watch asks for the hold within seconds; the phone shows the watch's settings
+ as up to date.
+ - 6a. With the watch out of range: the phone shows "Settings not on watch yet"; back in range the watch follows
+ without either app being opened.
+7. **Unpair from each side**, and removing the wallet on the watch: the other side shows not paired each time.
+8. **Wipe the phone's wallet** (Settings › Reset): the watch shows not paired and keeps its wallet.
+9. **Release build has no socket.** With the `wearlink-socket` file created by hand in a release-signed build's
+ data (rooted device or emulator): the app still uses the Data Layer, and nothing listens on port 47115.
diff --git a/journeys/wear/pair-cancel-on-watch.xml b/journeys/wear/pair-cancel-on-watch.xml
new file mode 100644
index 0000000000..05e0e9e5a3
--- /dev/null
+++ b/journeys/wear/pair-cancel-on-watch.xml
@@ -0,0 +1,20 @@
+
+
+ The wearer cancels at the code by swiping the Pair screen away, as it has no cancel button: the screen closes,
+ the phone says the pairing was cancelled on the watch, and nothing is paired. Two emulators over the debug
+ socket.
+
+ Precondition: journeys/wear/README.md › Phone and watch over the debug socket. The watch holds the phone's
+ wallet and is not paired, as for pair-same-wallet.xml. Watch: on the Settings page. Phone: on Home.
+
+
+ On the watch, tap Pair phone (tag "WatchSettingsPair")
+ On the phone, open Settings, tap Watch (tag "PairedWatchSettings"), then "PairedWatchPair"
+ Wait up to 15 s until the watch lists "WatchPairCode"
+ Verify the watch lists the Match button (tag "WatchPairConfirm") and no "WatchPairCancel"
+ On the watch, swipe the screen away (README › Watch gestures, swipe-to-dismiss)
+ Verify the watch lists "WatchSettingsPair" within 5 s
+ Wait up to 5 s until the phone lists "PairedWatchPairError" reading "Pairing was cancelled on the watch."
+ On the phone, tap OK (tag "PairedWatchPairClose") and verify "PairedWatchPair" is listed
+
+
diff --git a/journeys/wear/pair-different-wallet.xml b/journeys/wear/pair-different-wallet.xml
new file mode 100644
index 0000000000..bc50612aeb
--- /dev/null
+++ b/journeys/wear/pair-different-wallet.xml
@@ -0,0 +1,20 @@
+
+
+ A watch that holds another wallet than the phone's does not pair: both screens say so, and nothing is paired.
+ Two emulators over the debug socket.
+
+ Precondition: journeys/wear/README.md › Phone and watch over the debug socket. Watch: Restored wallet (the
+ public test phrase), on the Balance page. Phone: a dev build with a wallet of its own, not the test phrase, on
+ Home.
+
+
+ On the watch, swipe left three times to the Settings page (README › Watch gestures)
+ Tap Pair phone (tag "WatchSettingsPair") and verify "WatchPairWaiting" is listed
+ On the phone, open Settings, tap Watch (tag "PairedWatchSettings"), then "PairedWatchPair"
+ Wait up to 15 s until the phone lists "PairedWatchPairError"
+ Verify "PairedWatchPairError" reads "The watch holds a different wallet."
+ Verify the watch lists "WatchPairError" reading "Different wallet", or already "WatchSettingsPair" again
+ On the phone, tap OK (tag "PairedWatchPairClose") and verify "PairedWatchPair" is listed, not "PairedWatchName"
+ Verify the watch lists "WatchSettingsPair" within 5 s: it is not paired
+
+
diff --git a/journeys/wear/pair-erase-from-phone.xml b/journeys/wear/pair-erase-from-phone.xml
new file mode 100644
index 0000000000..32900357dd
--- /dev/null
+++ b/journeys/wear/pair-erase-from-phone.xml
@@ -0,0 +1,22 @@
+
+
+ Unpair and Erase on the phone deletes the wallet from the paired watch: the watch shows Wallet removed, then
+ onboarding, and its encrypted seed is gone. With the watch app open; an erase that reaches a closed app or a
+ locked watch needs the Data Layer (manual test 5 in journeys/wear/README.md › Manual tests for pairing). Two
+ emulators over the debug socket.
+
+ Precondition: journeys/wear/README.md › Phone and watch over the debug socket, paired. Watch: on the Balance
+ page. Phone: on Home. The journey leaves no wallet on the watch.
+
+
+ Run `adb -s $WATCH shell run-as to.bitkit.dev ls no_backup/seed` and verify it lists one file
+ On the phone, open Settings and tap Watch (tag "PairedWatchSettings")
+ Tap Unpair and Erase Watch (tag "PairedWatchErase")
+ Verify the dialog says a watch that never reconnects keeps the wallet, then tap Erase (tag "DialogConfirm")
+ Wait up to 15 s until the watch lists "WalletRemovedTitle"
+ Verify the phone lists "PairedWatchPair" and no "PairedWatchName"
+ On the watch, tap OK (tag "WalletRemovedConfirm") and verify "WatchOnboardingRestore" is listed
+ Run `adb -s $WATCH shell run-as to.bitkit.dev ls no_backup/seed` and verify it lists no seed file
+ Restart the watch app (README › Restart) and verify "WatchOnboardingRestore" is listed again
+
+
diff --git a/journeys/wear/pair-receive-wallet-no-pin.xml b/journeys/wear/pair-receive-wallet-no-pin.xml
new file mode 100644
index 0000000000..d5a1930d98
--- /dev/null
+++ b/journeys/wear/pair-receive-wallet-no-pin.xml
@@ -0,0 +1,20 @@
+
+
+ A phone without a PIN sends no wallet to a watch: its user cannot be checked first. The pairing ends before the
+ code with one line that says to set a PIN, the watch says it could not pair, and the watch stays without a
+ wallet. Two emulators over the debug socket.
+
+ Precondition: journeys/wear/README.md › Phone and watch over the debug socket. Phone: a dev build with a wallet
+ and no PIN (Settings › Security shows PIN Code as disabled), on Home. Watch: Fresh app, on onboarding. WATCH is
+ the watch's serial.
+
+
+ On the watch, tap From phone (tag "WatchOnboardingFromPhone") and verify "WatchPairWaiting" is listed
+ On the phone, open Settings, tap Watch (tag "PairedWatchSettings"), then "PairedWatchPair"
+ Wait up to 15 s until the phone lists "PairedWatchPairError" reading "Set a PIN in Bitkit first, then pair your watch."
+ Verify the phone never listed "PairedWatchCode"
+ Verify the watch lists "WatchPairError" reading "Couldn't pair", or already "WatchOnboardingFromPhone" again
+ Run `adb -s $WATCH shell run-as to.bitkit.dev ls no_backup/seed` and verify it lists no seed file
+ On the phone, tap OK (tag "PairedWatchPairClose") and verify "PairedWatchPair" is listed, not "PairedWatchName"
+
+
diff --git a/journeys/wear/pair-receive-wallet-pin.xml b/journeys/wear/pair-receive-wallet-pin.xml
new file mode 100644
index 0000000000..1f0f86785e
--- /dev/null
+++ b/journeys/wear/pair-receive-wallet-pin.xml
@@ -0,0 +1,28 @@
+
+
+ Sending the wallet to a watch asks for the phone's PIN first. Leaving the PIN screen, by the system Back or by
+ its back arrow, sends nothing and returns to the code with the pairing still running: the watch keeps waiting
+ and stays without a wallet. Entering the PIN sends it. Two emulators over the debug socket.
+
+ Precondition: journeys/wear/README.md › Phone and watch over the debug socket. Phone: a dev build with a wallet
+ and the PIN 1111 set with biometrics off (Settings › Security › PIN Code), so the check is the PIN pad and not
+ the fingerprint prompt, on Home. Watch: Fresh app, on onboarding.
+
+ Timing: a pairing lasts at most 90 s from the phone's Pair Watch tap, and everything up to the PIN entry runs
+ inside one. Read each screen once and move on; a run that was too slow ends on "Pairing timed out."
+ (`PairedWatchPairError`) and is started again from a Fresh app on the watch.
+
+
+ On the watch, tap From phone (tag "WatchOnboardingFromPhone")
+ On the phone, open Settings, tap Watch (tag "PairedWatchSettings"), then "PairedWatchPair"
+ Wait up to 15 s until the phone lists "PairedWatchCode", then tap Match on the watch (tag "WatchPairConfirm")
+ On the phone, tap Pair (tag "PairedWatchCodeConfirm") and verify the PIN pad is listed (tag "N1")
+ Press Back on the phone and verify "PairedWatchCode" is listed again, and neither "PairedWatchPairDone" nor "PairedWatchPairError"
+ On the phone, tap Pair (tag "PairedWatchCodeConfirm") again, then the PIN pad's back arrow (tag "NavigationBack"), and verify "PairedWatchCode" is listed again
+ Run `adb -s $WATCH shell run-as to.bitkit.dev ls no_backup/seed` and verify it lists no seed file
+ On the phone, tap Pair (tag "PairedWatchCodeConfirm") again
+ Enter the PIN: tap "N1" four times
+ Wait up to 20 s until the phone lists "PairedWatchPairDone"
+ Wait up to 15 s until the watch lists "WatchHomePager"
+
+
diff --git a/journeys/wear/pair-receive-wallet.xml b/journeys/wear/pair-receive-wallet.xml
new file mode 100644
index 0000000000..047efdf2c2
--- /dev/null
+++ b/journeys/wear/pair-receive-wallet.xml
@@ -0,0 +1,29 @@
+
+
+ A watch without a wallet is set up from the phone: both screens show one code, each confirms it, and the phone
+ sends the watch its wallet. The watch then opens Home and holds an encrypted seed. Two emulators over the debug
+ socket, whose Keystore cannot be attested, so the phone's Watch sheet says the watch is not verified; a release
+ build refuses here (manual test 3 in journeys/wear/README.md › Manual tests for pairing). The phone needs a
+ PIN to send its wallet: pair-receive-wallet-pin.xml covers leaving that check, and
+ pair-receive-wallet-no-pin.xml a phone without one.
+
+ Precondition: journeys/wear/README.md › Phone and watch over the debug socket. Phone: a dev build with a wallet
+ and the PIN 1111 set (Settings › Security › PIN Code), biometrics off, on Home. Watch: Fresh app, on onboarding.
+ PHONE and WATCH are the two serials.
+
+
+ On the watch, tap From phone (tag "WatchOnboardingFromPhone") and verify "WatchPairWaiting" is listed
+ On the phone, open Settings and tap Watch (tag "PairedWatchSettings")
+ Wait up to 10 s until "PairedWatchStatus" names the watch as ready to pair (the sheet looks again every 3 s), then tap "PairedWatchPair"
+ Wait up to 15 s until the phone lists "PairedWatchCode" and note its six digits
+ Verify the watch lists "WatchPairCode" with the same six digits
+ Verify the phone lists "PairedWatchSendsWallet" and "PairedWatchUnverified"
+ On the watch, tap Match (tag "WatchPairConfirm")
+ On the phone, tap Pair (tag "PairedWatchCodeConfirm") and verify the PIN pad is listed (tag "N1")
+ Enter the PIN: tap "N1" four times
+ Wait up to 20 s until the phone lists "PairedWatchPairDone"
+ Wait up to 15 s until the watch lists "WatchHomePager"
+ Run `adb -s $WATCH shell run-as to.bitkit.dev ls no_backup/seed` and verify it lists one file, the encrypted seed
+ On the phone, tap OK (tag "PairedWatchPairClose") and verify "PairedWatchName" and "PairedWatchFullWallet" are listed
+
+
diff --git a/journeys/wear/pair-retry-after-cancel.xml b/journeys/wear/pair-retry-after-cancel.xml
new file mode 100644
index 0000000000..17db155240
--- /dev/null
+++ b/journeys/wear/pair-retry-after-cancel.xml
@@ -0,0 +1,27 @@
+
+
+ The phone's user cancels at the code and taps Pair Watch again at once, while the watch still shows
+ "Cancelled" for its 3 s: the watch's Pair screen stays and waits anew instead of dropping the phone's request,
+ and the new pairing goes through. Two emulators over the debug socket.
+
+ Precondition: journeys/wear/README.md › Phone and watch over the debug socket. The watch holds the phone's
+ wallet and is not paired, as for pair-same-wallet.xml. Watch: on the Settings page. Phone: on Home.
+
+ Timing: the second Pair Watch tap must land within 3 s of the Cancel tap. Pair Watch comes back where it was,
+ so note the `center` of "PairedWatchPair" before the first tap and of "PairedWatchCodeCancel" at the code, and
+ send the two taps in one command: `adb -s $PHONE shell "input tap <cancel> && input tap <pair>"`.
+
+
+ On the watch, tap Pair phone (tag "WatchSettingsPair")
+ On the phone, open Settings, tap Watch (tag "PairedWatchSettings"), note the center of "PairedWatchPair", then tap it
+ Wait up to 15 s until the phone lists "PairedWatchCode" and the watch lists "WatchPairCode"
+ On the phone, tap Cancel (tag "PairedWatchCodeCancel") and Pair Watch right after it, in one command as in the description
+ Wait up to 5 s until the watch lists "WatchPairWaiting" or "WatchPairCode", and verify it still lists "WatchPairScreen" and no longer lists "WatchPairError"
+ About 4 s after the taps, verify the watch still lists "WatchPairScreen"
+ Wait up to 15 s until the phone lists "PairedWatchCode" and note its six digits
+ Verify the watch lists "WatchPairCode" with the same six digits
+ On the phone, tap Pair (tag "PairedWatchCodeConfirm"), then on the watch tap Match (tag "WatchPairConfirm")
+ Wait up to 10 s until the phone lists "PairedWatchPairDone"
+ Wait up to 5 s until the watch lists "WatchSettingsPaired"
+
+
diff --git a/journeys/wear/pair-same-wallet.xml b/journeys/wear/pair-same-wallet.xml
new file mode 100644
index 0000000000..a356bcdfc4
--- /dev/null
+++ b/journeys/wear/pair-same-wallet.xml
@@ -0,0 +1,23 @@
+
+
+ A watch that already holds the phone's wallet pairs by proving it: the same code on both screens, no warning
+ about sending the wallet, and the watch stays on its wallet. Two emulators over the debug socket.
+
+ Precondition: journeys/wear/README.md › Phone and watch over the debug socket. The watch holds the phone's
+ wallet and is not paired: run pair-receive-wallet.xml, then pair-unpair-from-phone.xml. Watch: on the Balance
+ page. Phone: on Home.
+
+
+ On the watch, swipe left three times to the Settings page (README › Watch gestures)
+ Tap Pair phone (tag "WatchSettingsPair") and verify "WatchPairWaiting" is listed
+ On the phone, open Settings, tap Watch (tag "PairedWatchSettings"), then "PairedWatchPair"
+ Wait up to 15 s until the phone lists "PairedWatchCode" and note its six digits
+ Verify the watch lists "WatchPairCode" with the same six digits and "WatchPairPhone" with the phone's model name
+ Verify the phone does not list "PairedWatchSendsWallet"
+ On the phone, tap Pair (tag "PairedWatchCodeConfirm") and verify "PairedWatchPairWaiting" is listed and no PIN pad (tag "N1"): nothing is sent, so nothing is asked
+ On the watch, tap Match (tag "WatchPairConfirm")
+ Wait up to 10 s until the phone lists "PairedWatchPairDone"
+ Wait up to 5 s until the watch lists "WatchSettingsPaired": the Pair screen closed by itself
+ Verify "WatchSettingsPairedName" reads the phone's model name
+
+
diff --git a/journeys/wear/pair-settings-push.xml b/journeys/wear/pair-settings-push.xml
new file mode 100644
index 0000000000..405fe4c98b
--- /dev/null
+++ b/journeys/wear/pair-settings-push.xml
@@ -0,0 +1,21 @@
+
+
+ A paired watch gets the phone's settings the moment one changes, with no backup in between: switching the
+ phone's local currency reaches the watch within seconds, and the phone shows that the watch has it. Two
+ emulators over the debug socket. The same push carries QuickPay; unit tests cover its values.
+
+ Precondition: journeys/wear/README.md › Phone and watch over the debug socket, paired by pair-receive-wallet.xml
+ or pair-same-wallet.xml. Phone: Local Currency USD, on Home. Watch: on the Balance page.
+
+
+ Run `adb -s $WATCH logcat -c`
+ On the phone, open Settings and tap Local Currency (tag "CurrenciesSettings")
+ Tap EUR in the list
+ Wait up to 10 s until `adb -s $WATCH logcat -d -s BitkitWear` lists "Applied the settings the phone pushed"
+ On the phone, go back to Settings and tap Watch (tag "PairedWatchSettings")
+ Verify "PairedWatchSettingsState" reads "Watch settings up to date.", then tap OK (tag "PairedWatchClose")
+ On the watch, tap "WatchHomeBalanceToggle" until "WatchHomeBalanceSymbol" is a fiat symbol, and verify it reads "€"
+ On the phone, set Local Currency back to USD
+ Wait up to 10 s until "WatchHomeBalanceSymbol" on the watch reads "$"
+
+
diff --git a/journeys/wear/pair-unpair-from-phone.xml b/journeys/wear/pair-unpair-from-phone.xml
new file mode 100644
index 0000000000..e3169e8c26
--- /dev/null
+++ b/journeys/wear/pair-unpair-from-phone.xml
@@ -0,0 +1,19 @@
+
+
+ Unpair on the phone asks first, then ends the pairing on both devices. The watch keeps its wallet. Two emulators
+ over the debug socket.
+
+ Precondition: journeys/wear/README.md › Phone and watch over the debug socket, paired. Phone: on Home. Watch:
+ on the Settings page, which lists "WatchSettingsPaired".
+
+
+ On the phone, open Settings and tap Watch (tag "PairedWatchSettings")
+ Tap Unpair (tag "PairedWatchUnpair")
+ Tap Cancel in the dialog (tag "DialogCancel") and verify "PairedWatchName" is still listed
+ Tap Unpair (tag "PairedWatchUnpair") again, then Unpair in the dialog (tag "DialogConfirm")
+ Wait up to 10 s until the phone lists "PairedWatchPair" and no "PairedWatchName"
+ Verify the watch lists "WatchSettingsPair" and no "WatchSettingsPaired"
+ On the watch, swipe right three times and verify "WatchHomeBalance" is listed: the wallet is still there
+ Run `adb -s $WATCH shell run-as to.bitkit.dev ls no_backup/seed` and verify it lists one file
+
+
diff --git a/journeys/wear/pair-unpair-from-watch.xml b/journeys/wear/pair-unpair-from-watch.xml
new file mode 100644
index 0000000000..6f948fec49
--- /dev/null
+++ b/journeys/wear/pair-unpair-from-watch.xml
@@ -0,0 +1,17 @@
+
+
+ Unpair on the watch asks first, with one button that says Unpair and swipe-to-dismiss to cancel, then ends the
+ pairing on both devices. Two emulators over the debug socket.
+
+ Precondition: journeys/wear/README.md › Phone and watch over the debug socket, paired. Watch: on the Settings
+ page. Phone: the Watch sheet open (Settings › General › Watch), listing "PairedWatchName".
+
+
+ On the watch, tap Phone (tag "WatchSettingsPaired")
+ Verify the dialog: the text "Unpair phone?" above one button that reads "Unpair" (tag "WatchPhoneUnpairConfirm"), and no "WatchPhoneUnpairCancel"
+ Swipe the dialog away (README › Watch gestures, swipe-to-dismiss) and verify "WatchPhoneUnpairConfirm" is not listed and "WatchSettingsPaired" still is
+ Tap Phone (tag "WatchSettingsPaired") again, then Unpair (tag "WatchPhoneUnpairConfirm")
+ Verify the watch lists "WatchSettingsPair" within 5 s
+ Wait up to 10 s until the phone lists "PairedWatchPair" and no "PairedWatchName"
+
+
diff --git a/journeys/wear/receive-paid-ambient.xml b/journeys/wear/receive-paid-ambient.xml
index bd5c7a00eb..a840c75c44 100644
--- a/journeys/wear/receive-paid-ambient.xml
+++ b/journeys/wear/receive-paid-ambient.xml
@@ -16,8 +16,9 @@
Wait up to 5 s until "WatchReceiveHidden" is listed
Run `../bitkit-docker/spark pay <invoice> 1000` from this repo's parent checkout
Wait up to 20 s until "WatchReceivePaid" is listed
- Verify "WatchReceivePaidAmount" is not listed
+ Verify neither "WatchReceivePaidAmount" nor "WatchReceiveNew" is listed
Run `adb shell input keyevent KEYCODE_WAKEUP`
Wait up to 5 s until "WatchReceivePaidAmount" reads "1 000"
+ Verify "WatchReceiveNew" is listed
diff --git a/journeys/wear/receive-paid.xml b/journeys/wear/receive-paid.xml
index 72d42d017b..550474df55 100644
--- a/journeys/wear/receive-paid.xml
+++ b/journeys/wear/receive-paid.xml
@@ -1,7 +1,7 @@
- Paying the receive QR's invoice turns the QR into a check with the amount, with a firm haptic; a tap on the check
- shows a new invoice. This also funds the wallet for the send journeys. Emulator and physical watch.
+ Paying the receive QR's invoice turns the QR into a check with the amount, with a firm haptic; the check takes
+ no tap, and the New invoice button below it shows a new invoice. This also funds the wallet for the send journeys. Emulator and physical watch.
Precondition: a wallet restored on the local ./spark stack, see journeys/wear/README.md › Local ./spark stack: the
Restored wallet (README › Restored wallet), or the Private settings wallet (README › Private settings wallet)
@@ -19,7 +19,9 @@
Run `../bitkit-docker/spark pay <invoice> 50000` from this repo's parent checkout
Wait up to 20 s until "WatchReceivePaid" is listed
Verify "WatchReceivePaidAmount" reads "50 000"
- Tap "WatchReceivePaid"
+ Verify the button below the check reads "New invoice" (tag "WatchReceiveNew")
+ Tap the check (tag "WatchReceivePaid") and verify "WatchReceivePaid" is still listed 2 s later: the check is no button
+ Tap New invoice (tag "WatchReceiveNew")
Wait up to 10 s until `adb shell uiautomator dump` lists "WatchReceiveQr"
Read the invoice from the log again as <next>
Verify <next> differs from <invoice>
diff --git a/journeys/wear/remove-wallet-cancel.xml b/journeys/wear/remove-wallet-cancel.xml
index aca3ef3fcc..2a287af8b6 100644
--- a/journeys/wear/remove-wallet-cancel.xml
+++ b/journeys/wear/remove-wallet-cancel.xml
@@ -1,6 +1,7 @@
- Cancelling Remove wallet keeps the wallet: the dialog closes, and after a restart the watch still opens on Balance
+ Cancelling Remove wallet, by swiping its dialog away as it has no cancel button, keeps the wallet: the dialog
+ closes, and after a restart the watch still opens on Balance
with a balance, not on onboarding. Emulator and physical watch.
Precondition: Restored wallet, see journeys/wear/README.md › Restored wallet. Backend: hosted regtest. The test
@@ -12,9 +13,9 @@
Swipe the pager left: on a 454 px screen `adb shell input swipe 400 227 60 227 300`, on a 384 px screen `adb shell input swipe 340 192 50 192 300`
Tap Remove wallet (tag "WatchSettingsRemoveWallet")
- Verify the dialog: the text "Remove wallet?" with ✕ (tag "WatchSettingsRemoveCancel")
- Tap ✕ (tag "WatchSettingsRemoveCancel")
- Verify the dialog is gone: "WatchSettingsRemoveCancel" is not listed
+ Verify the dialog: the text "Remove wallet?" above one button that reads "Remove" (tag "WatchSettingsRemoveConfirm"), and no "WatchSettingsRemoveCancel"
+ Swipe the dialog away (README › Watch gestures, swipe-to-dismiss)
+ Verify the dialog is gone: "WatchSettingsRemoveConfirm" is not listed, and "WatchSettingsRemoveWallet" is
Restart the app (README › Restart)
Dump `android layout` every 5 s until it lists "WatchHomeBalance", for up to 1 minute
Verify "WatchHomeBalance" reads a number above 0
diff --git a/journeys/wear/remove-wallet.xml b/journeys/wear/remove-wallet.xml
index 2c21f6bbf0..72b65e8263 100644
--- a/journeys/wear/remove-wallet.xml
+++ b/journeys/wear/remove-wallet.xml
@@ -14,7 +14,8 @@
Run `adb shell run-as to.bitkit.dev ls no_backup/seed` and verify it lists one file, the encrypted seed
Swipe the pager left: on a 454 px screen `adb shell input swipe 400 227 60 227 300`, on a 384 px screen `adb shell input swipe 340 192 50 192 300`
Tap Remove wallet (tag "WatchSettingsRemoveWallet")
- Tap ✓ (tag "WatchSettingsRemoveConfirm")
+ Verify the dialog: the text "Remove wallet?" above one button that reads "Remove" (tag "WatchSettingsRemoveConfirm"), and no "WatchSettingsRemoveCancel"
+ Tap Remove (tag "WatchSettingsRemoveConfirm")
Verify onboarding: "WatchOnboardingRestore" is listed
Restart the app (README › Restart)
Verify onboarding again: "WatchOnboardingRestore" is listed
diff --git a/journeys/wear/screenshot-blocked.xml b/journeys/wear/screenshot-blocked.xml
deleted file mode 100644
index 4bff7939ed..0000000000
--- a/journeys/wear/screenshot-blocked.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
- The word entry screen blocks screenshots and screen recordings (FLAG_SECURE, debug builds included), while
- `android layout` still lists its tags; the screen before it can be captured. Emulator and physical watch.
-
- Precondition: Fresh app, see journeys/wear/README.md › Fresh app. Backend: none. Read the screen
- size once with `adb shell wm size` and use the swipe written for it: 454 px (`Wear_Large_Round_API37`) or 384 px
- (`Wear_Small_Round_API34`); for another size scale it as in README › What differs.
-
-
- Tap Restore (tag "WatchOnboardingRestore")
- Tap 12 (tag "RestoreWords12")
- Verify `android layout` lists "RestoreWordInput"
- Run `adb shell input keyevent KEYCODE_BACK` to close the keyboard
- Take a screenshot and verify it is entirely black
- Swipe to dismiss from the left edge: on a 454 px screen `adb shell input swipe 20 227 400 227 300`, on a 384 px screen `adb shell input swipe 15 192 340 192 300`
- Verify the title (tag "RestoreTitle") reads "How many words?"
- Take a screenshot and verify it shows "How many words?" with the 12 and 24 buttons, not a black frame
-
-
diff --git a/settings.gradle.kts b/settings.gradle.kts
index 425b869f80..0e0b1a92c5 100644
--- a/settings.gradle.kts
+++ b/settings.gradle.kts
@@ -104,3 +104,4 @@ dependencyResolutionManagement {
rootProject.name = "bitkit-android"
include(":app")
include(":wear")
+include(":wearlink")
diff --git a/wear/build.gradle.kts b/wear/build.gradle.kts
index 85d12e9b6c..de7cc21443 100644
--- a/wear/build.gradle.kts
+++ b/wear/build.gradle.kts
@@ -249,6 +249,12 @@ dependencies {
implementation(libs.wear.compose.material3)
implementation(libs.wear.compose.navigation)
implementation(libs.wear.tooling.preview)
+ // Phone link: the shared protocol (which brings BouncyCastle for HKDF) and the Wear Data Layer that carries it.
+ implementation(project(":wearlink"))
+ implementation(libs.play.services.wearable)
+ // The debug socket carrier and the in-process fakes; no release variant depends on them.
+ debugImplementation(testFixtures(project(":wearlink")))
+ testImplementation(testFixtures(project(":wearlink")))
// Tile
implementation(libs.wear.tiles)
implementation(libs.wear.protolayout)
diff --git a/wear/src/debug/java/to/bitkit/wear/di/LinkTransportModule.kt b/wear/src/debug/java/to/bitkit/wear/di/LinkTransportModule.kt
new file mode 100644
index 0000000000..abbda48dfd
--- /dev/null
+++ b/wear/src/debug/java/to/bitkit/wear/di/LinkTransportModule.kt
@@ -0,0 +1,73 @@
+package to.bitkit.wear.di
+
+import android.annotation.SuppressLint
+import android.content.Context
+import android.content.Intent
+import android.os.StrictMode
+import androidx.core.net.toUri
+import dagger.Module
+import dagger.Provides
+import dagger.hilt.InstallIn
+import dagger.hilt.android.qualifiers.ApplicationContext
+import dagger.hilt.components.SingletonComponent
+import kotlinx.coroutines.CoroutineDispatcher
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.SupervisorJob
+import to.bitkit.wear.link.DataLayerTransport
+import to.bitkit.wear.ui.MainActivity
+import to.bitkit.wear.utils.Logger
+import to.bitkit.wearlink.LinkTransport
+import to.bitkit.wearlink.testing.SocketLinkTransport
+import java.io.File
+import javax.inject.Singleton
+
+/**
+ * A debug build reaches the phone over the Wear Data Layer too, unless the file `files/wearlink-socket` exists in the
+ * app's data: then it listens on a loopback TCP port instead, which `adb forward` bridges to a phone emulator. That
+ * is how two emulators, which cannot pair over the Data Layer without a Google account, run the pairing journeys;
+ * `journeys/wear/README.md` has the setup. The socket carrier is not part of a release build.
+ */
+@Module
+@InstallIn(SingletonComponent::class)
+object LinkTransportModule {
+ private const val TAG = "LinkTransportModule"
+ private const val SOCKET_MARKER = "wearlink-socket"
+
+ @Provides
+ @Singleton
+ fun provideLinkTransport(
+ @ApplicationContext context: Context,
+ @IoDispatcher ioDispatcher: CoroutineDispatcher,
+ dataLayer: DataLayerTransport,
+ ): LinkTransport {
+ if (!hasSocketMarker(context)) return dataLayer
+ Logger.warn("Using the debug socket link transport", context = TAG)
+ return SocketLinkTransport(
+ isServer = true,
+ scope = CoroutineScope(SupervisorJob() + ioDispatcher),
+ onOpen = { uri -> open(context, uri) },
+ )
+ }
+
+ /**
+ * Stands in for the phone's remote launch of the Pair screen. It starts from the application context, which
+ * needs its own task flag; the activity is `singleTask`, so Recents still shows the app once.
+ */
+ @SuppressLint("WearRecents")
+ private fun open(context: Context, uri: String) {
+ val intent = Intent(Intent.ACTION_VIEW, uri.toUri(), context, MainActivity::class.java)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ runCatching { context.startActivity(intent) }
+ .onFailure { Logger.warn("Failed to open '$uri' for the debug socket", it, context = TAG) }
+ }
+
+ /** Looks for the marker file where it is asked, which may be the main thread at launch: one `stat`. */
+ private fun hasSocketMarker(context: Context): Boolean {
+ val policy = StrictMode.allowThreadDiskReads()
+ return try {
+ File(context.filesDir, SOCKET_MARKER).exists()
+ } finally {
+ StrictMode.setThreadPolicy(policy)
+ }
+ }
+}
diff --git a/wear/src/main/AndroidManifest.xml b/wear/src/main/AndroidManifest.xml
index e094432335..80bb872103 100644
--- a/wear/src/main/AndroidManifest.xml
+++ b/wear/src/main/AndroidManifest.xml
@@ -95,6 +95,17 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
{
+ val latestMs = syncedAtMs + MAX_PUSH_AHEAD.inWholeMilliseconds
+ settingsStore.applyPushedSettings(settings, syncedAtMs, source.changedAtMs.coerceAtMost(latestMs))
+ }
+ is PhoneStateSource.Backup -> {
+ val pushedAtMs = settingsStore.pushedSettingsAtMs()
+ if (pushedAtMs != null && (source.createdAtMs ?: 0) <= pushedAtMs) return false
+ settingsStore.applyPhoneSettings(settings, syncedAtMs)
+ }
+ }
+ return true
+ }
+
+ override suspend fun onSettingsMissing(source: PhoneStateSource) {
+ if (settingsStore.pushedSettingsAtMs() != null) return
+ settingsStore.clearQuickPay()
+ }
+
+ override suspend fun onPushSourceGone() = settingsStore.clearPushedSettingsAt()
+}
diff --git a/wear/src/main/java/to/bitkit/wear/data/SettingsStore.kt b/wear/src/main/java/to/bitkit/wear/data/SettingsStore.kt
index b14363bd5f..2aaad3d2e4 100644
--- a/wear/src/main/java/to/bitkit/wear/data/SettingsStore.kt
+++ b/wear/src/main/java/to/bitkit/wear/data/SettingsStore.kt
@@ -53,6 +53,7 @@ class SettingsStore @Inject constructor(
private val quickPayAmountKey = intPreferencesKey("quickpay_amount_usd")
private val quickPayMultiplierKey = intPreferencesKey("quickpay_daily_multiplier")
private val phoneSyncedAtKey = longPreferencesKey("phone_settings_synced_at")
+ private val phonePushedAtKey = longPreferencesKey("phone_settings_pushed_at")
val data: Flow = dataStore.data.map { prefs ->
WatchSettings(
@@ -81,23 +82,44 @@ class SettingsStore @Inject constructor(
* is off when the backup's values cannot be read.
*/
suspend fun applyPhoneSettings(settings: PhoneSettings, syncedAtMs: Long) {
+ dataStore.edit { it.adopt(settings, syncedAtMs) }
+ }
+
+ /**
+ * Adopts [settings] as [applyPhoneSettings] does, for settings the paired phone pushed, and notes the phone's
+ * time of the change, [changedAtMs]: see [PhoneStateSink] for what that time decides.
+ */
+ suspend fun applyPushedSettings(settings: PhoneSettings, syncedAtMs: Long, changedAtMs: Long) {
dataStore.edit { prefs ->
- settings.primaryDisplay?.let {
- if (prefs[phonePrimaryDisplayKey] != it.name) prefs[primaryDisplayKey] = it.name
- prefs[phonePrimaryDisplayKey] = it.name
- }
- settings.displayUnit?.let { prefs[displayUnitKey] = it.name }
- settings.selectedCurrency?.let { prefs[selectedCurrencyKey] = it }
- val quickPay = settings.quickPay
- if (quickPay == null) {
- prefs.clearQuickPay()
- } else {
- prefs[quickPayEnabledKey] = quickPay.isEnabled
- prefs[quickPayAmountKey] = quickPay.amountUsd
- prefs[quickPayMultiplierKey] = quickPay.dailyMultiplier
- }
- prefs[phoneSyncedAtKey] = syncedAtMs
+ prefs.adopt(settings, syncedAtMs)
+ prefs[phonePushedAtKey] = changedAtMs
+ }
+ }
+
+ /** The phone's time of the last pushed settings the watch applied, or null when none holds. */
+ suspend fun pushedSettingsAtMs(): Long? = dataStore.data.first()[phonePushedAtKey]
+
+ /** Forgets that pushed settings hold, as when the pairing ends. The settings themselves stay. */
+ suspend fun clearPushedSettingsAt() {
+ dataStore.edit { it.remove(phonePushedAtKey) }
+ }
+
+ private fun MutablePreferences.adopt(settings: PhoneSettings, syncedAtMs: Long) {
+ settings.primaryDisplay?.let {
+ if (this[phonePrimaryDisplayKey] != it.name) this[primaryDisplayKey] = it.name
+ this[phonePrimaryDisplayKey] = it.name
+ }
+ settings.displayUnit?.let { this[displayUnitKey] = it.name }
+ settings.selectedCurrency?.let { this[selectedCurrencyKey] = it }
+ val quickPay = settings.quickPay
+ if (quickPay == null) {
+ clearQuickPay()
+ } else {
+ this[quickPayEnabledKey] = quickPay.isEnabled
+ this[quickPayAmountKey] = quickPay.amountUsd
+ this[quickPayMultiplierKey] = quickPay.dailyMultiplier
}
+ this[phoneSyncedAtKey] = syncedAtMs
}
/**
@@ -121,8 +143,14 @@ class SettingsStore @Inject constructor(
suspend fun clearPhoneSettings() {
dataStore.edit { prefs ->
prefs.clearQuickPay()
- listOf(phoneSyncedAtKey, phonePrimaryDisplayKey, primaryDisplayKey, displayUnitKey, selectedCurrencyKey)
- .forEach { prefs.remove(it) }
+ listOf(
+ phoneSyncedAtKey,
+ phonePushedAtKey,
+ phonePrimaryDisplayKey,
+ primaryDisplayKey,
+ displayUnitKey,
+ selectedCurrencyKey,
+ ).forEach { prefs.remove(it) }
}
}
diff --git a/wear/src/main/java/to/bitkit/wear/di/SecurityModule.kt b/wear/src/main/java/to/bitkit/wear/di/SecurityModule.kt
index c50325e683..2fff8bacb9 100644
--- a/wear/src/main/java/to/bitkit/wear/di/SecurityModule.kt
+++ b/wear/src/main/java/to/bitkit/wear/di/SecurityModule.kt
@@ -21,15 +21,19 @@ import to.bitkit.wear.data.ForegroundMonitor
import to.bitkit.wear.data.NetworkMonitor
import to.bitkit.wear.data.NfcMonitor
import to.bitkit.wear.data.OwnInvoiceStore
+import to.bitkit.wear.data.PhoneStateSink
import to.bitkit.wear.data.ProcessForegroundMonitor
import to.bitkit.wear.data.QuickPaySpendStore
import to.bitkit.wear.data.SettingsOwnInvoiceStore
+import to.bitkit.wear.data.SettingsPhoneStateSink
import to.bitkit.wear.data.SettingsQuickPaySpendStore
import to.bitkit.wear.data.SettingsUncertainSendStore
import to.bitkit.wear.data.UncertainSendStore
import to.bitkit.wear.data.WipeMarker
import to.bitkit.wear.data.settingsDataStore
import to.bitkit.wear.env.Env
+import to.bitkit.wear.link.KeystoreAgreementKey
+import to.bitkit.wear.link.KeystoreLinkKeys
import to.bitkit.wear.security.AndroidKeystoreSeedKey
import to.bitkit.wear.security.Bip39
import to.bitkit.wear.security.CoreBip39
@@ -44,6 +48,8 @@ import to.bitkit.wear.services.PhoneBackupReader
import to.bitkit.wear.services.SelfSendGuard
import to.bitkit.wear.services.VssPhoneBackupReader
import to.bitkit.wear.services.WalletSelfSendGuard
+import to.bitkit.wearlink.LinkKeyStore
+import to.bitkit.wearlink.WatchAgreementKey
import java.io.File
import javax.inject.Singleton
@@ -98,6 +104,18 @@ abstract class SecurityModule {
@Singleton
abstract fun bindPhoneBackupReader(reader: VssPhoneBackupReader): PhoneBackupReader
+ @Binds
+ @Singleton
+ abstract fun bindPhoneStateSink(sink: SettingsPhoneStateSink): PhoneStateSink
+
+ @Binds
+ @Singleton
+ abstract fun bindLinkKeyStore(keys: KeystoreLinkKeys): LinkKeyStore
+
+ @Binds
+ @Singleton
+ abstract fun bindWatchAgreementKey(key: KeystoreAgreementKey): WatchAgreementKey
+
companion object {
private const val SEED_DIR = "seed"
private const val SETTINGS_NAME = "settings"
diff --git a/wear/src/main/java/to/bitkit/wear/link/DataLayerTransport.kt b/wear/src/main/java/to/bitkit/wear/link/DataLayerTransport.kt
new file mode 100644
index 0000000000..a340e4cb1b
--- /dev/null
+++ b/wear/src/main/java/to/bitkit/wear/link/DataLayerTransport.kt
@@ -0,0 +1,83 @@
+package to.bitkit.wear.link
+
+import android.content.Context
+import android.net.Uri
+import com.google.android.gms.tasks.Task
+import com.google.android.gms.wearable.CapabilityClient
+import com.google.android.gms.wearable.PutDataRequest
+import com.google.android.gms.wearable.Wearable
+import dagger.hilt.android.qualifiers.ApplicationContext
+import kotlinx.coroutines.suspendCancellableCoroutine
+import to.bitkit.wearlink.LinkError
+import to.bitkit.wearlink.LinkNode
+import to.bitkit.wearlink.LinkPacket
+import to.bitkit.wearlink.LinkTransport
+import javax.inject.Inject
+import javax.inject.Singleton
+import kotlin.coroutines.resume
+import kotlin.coroutines.resumeWithException
+
+/**
+ * [LinkTransport] over the Wear Data Layer, and the only file besides [LinkListenerService] that names its classes.
+ * One-shot messages go through `MessageClient`, which stores nothing; state documents, which the link has encrypted,
+ * through `DataClient`, which delivers the latest after a reconnect. The Data Layer only connects apps with the same
+ * application id and signing certificate. What arrives comes in through [LinkListenerService].
+ */
+@Singleton
+class DataLayerTransport @Inject constructor(
+ @ApplicationContext private val context: Context,
+) : LinkTransport {
+ companion object {
+ /** The capability the phone app declares in its `wear.xml`. */
+ const val PHONE_CAPABILITY = "bitkit_phone_v1"
+ private const val WEAR_SCHEME = "wear"
+ }
+
+ private val nodeClient by lazy { Wearable.getNodeClient(context) }
+ private val capabilityClient by lazy { Wearable.getCapabilityClient(context) }
+ private val messageClient by lazy { Wearable.getMessageClient(context) }
+ private val dataClient by lazy { Wearable.getDataClient(context) }
+
+ @Volatile
+ private var receiver: (suspend (LinkPacket) -> Unit)? = null
+
+ override suspend fun nodes(): List {
+ val withApp = capabilityClient.getCapability(PHONE_CAPABILITY, CapabilityClient.FILTER_REACHABLE).await()
+ .nodes.map { it.id }.toSet()
+ return nodeClient.connectedNodes.await().map { LinkNode(it.id, it.displayName, it.isNearby, it.id in withApp) }
+ }
+
+ override suspend fun send(nodeId: String, path: String, payload: ByteArray) {
+ runCatching { messageClient.sendMessage(nodeId, path, payload).await() }
+ .getOrElse { throw LinkError.Unreachable(it) }
+ }
+
+ override suspend fun putState(path: String, payload: ByteArray) {
+ val request = PutDataRequest.create(path).setData(payload).setUrgent()
+ dataClient.putDataItem(request).await()
+ }
+
+ override suspend fun deleteState(path: String) {
+ val uri = Uri.Builder().scheme(WEAR_SCHEME).path(path).build()
+ dataClient.deleteDataItems(uri).await()
+ }
+
+ /** The watch opens nothing on the phone. */
+ override suspend fun open(nodeId: String, uri: String) = throw LinkError.Unreachable()
+
+ override fun attach(receiver: suspend (LinkPacket) -> Unit) {
+ this.receiver = receiver
+ }
+
+ /** Hands [packet], which the listener service received, to the link. */
+ suspend fun deliver(packet: LinkPacket) {
+ receiver?.invoke(packet)
+ }
+}
+
+/** Waits for a Play services task without a coroutines adapter library. */
+internal suspend fun Task.await(): T = suspendCancellableCoroutine { continuation ->
+ addOnSuccessListener { continuation.resume(it) }
+ addOnFailureListener { continuation.resumeWithException(it) }
+ addOnCanceledListener { continuation.cancel() }
+}
diff --git a/wear/src/main/java/to/bitkit/wear/link/KeystoreAgreementKey.kt b/wear/src/main/java/to/bitkit/wear/link/KeystoreAgreementKey.kt
new file mode 100644
index 0000000000..e0fde437a0
--- /dev/null
+++ b/wear/src/main/java/to/bitkit/wear/link/KeystoreAgreementKey.kt
@@ -0,0 +1,90 @@
+package to.bitkit.wear.link
+
+import android.content.Context
+import android.content.pm.PackageManager
+import android.security.keystore.KeyGenParameterSpec
+import android.security.keystore.KeyProperties
+import dagger.hilt.android.qualifiers.ApplicationContext
+import to.bitkit.wear.utils.Logger
+import to.bitkit.wearlink.LinkError
+import to.bitkit.wearlink.WatchAgreementKey
+import java.security.KeyFactory
+import java.security.KeyPairGenerator
+import java.security.KeyStore
+import java.security.PrivateKey
+import java.security.spec.ECGenParameterSpec
+import java.security.spec.X509EncodedKeySpec
+import javax.crypto.KeyAgreement
+import javax.inject.Inject
+import javax.inject.Singleton
+
+/**
+ * The pairing's key agreement key in AndroidKeyStore: a P-256 key generated inside StrongBox when the watch has one
+ * that makes it, else inside the trusted execution environment, whose only purpose is a key agreement. Its private
+ * half cannot leave the secure hardware. It is attested with the handshake's challenge, so the phone can check all
+ * of that before it encrypts a seed to the agreed secret. A Keystore that cannot attest, as on some emulators, still
+ * makes the key, without a certificate chain: the phone then never sends a seed from a release build.
+ */
+@Singleton
+class KeystoreAgreementKey @Inject constructor(
+ @ApplicationContext private val context: Context,
+) : WatchAgreementKey {
+ private companion object {
+ const val TAG = "KeystoreAgreementKey"
+ const val KEYSTORE = "AndroidKeyStore"
+ const val ALIAS = "wearlink_agreement"
+ const val CURVE = "secp256r1"
+ }
+
+ private val keyStore: KeyStore by lazy { KeyStore.getInstance(KEYSTORE).apply { load(null) } }
+
+ override fun create(challenge: ByteArray): WatchAgreementKey.Attested = guarded {
+ val hasStrongBox = context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
+ val attempts = listOfNotNull(
+ Attempt(isStrongBox = true, challenge).takeIf { hasStrongBox },
+ Attempt(isStrongBox = false, challenge),
+ Attempt(isStrongBox = false, challenge = null),
+ )
+ val made = attempts.firstOrNull { attempt ->
+ keyStore.deleteEntry(ALIAS)
+ runCatching { generate(attempt) }
+ .onFailure { Logger.warn("Failed to make the agreement key in '$attempt'", it, context = TAG) }
+ .isSuccess
+ } ?: throw LinkError.KeyFailure()
+ val publicKey = keyStore.getCertificate(ALIAS).publicKey.encoded
+ val chain = if (made.challenge == null) emptyList() else keyStore.getCertificateChain(ALIAS).map { it.encoded }
+ WatchAgreementKey.Attested(publicKey, chain)
+ }
+
+ override fun agree(peerPublicKey: ByteArray): ByteArray = guarded {
+ val privateKey = keyStore.getKey(ALIAS, null) as? PrivateKey ?: throw LinkError.KeyFailure()
+ val peer = KeyFactory.getInstance(KeyProperties.KEY_ALGORITHM_EC)
+ .generatePublic(X509EncodedKeySpec(peerPublicKey))
+ KeyAgreement.getInstance("ECDH", KEYSTORE).run {
+ init(privateKey)
+ doPhase(peer, true)
+ generateSecret()
+ }
+ }
+
+ override fun delete() = guarded { keyStore.deleteEntry(ALIAS) }
+
+ private fun generate(attempt: Attempt) {
+ val spec = KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_AGREE_KEY)
+ .setAlgorithmParameterSpec(ECGenParameterSpec(CURVE))
+ .setIsStrongBoxBacked(attempt.isStrongBox)
+ .apply { attempt.challenge?.let(::setAttestationChallenge) }
+ .build()
+ KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, KEYSTORE).run {
+ initialize(spec)
+ generateKeyPair()
+ }
+ }
+
+ private inline fun guarded(block: () -> T): T =
+ runCatching(block).getOrElse { throw it as? LinkError ?: LinkError.KeyFailure(it) }
+
+ private class Attempt(val isStrongBox: Boolean, val challenge: ByteArray?) {
+ override fun toString(): String = "strongBox=$isStrongBox attested=${challenge != null}"
+ }
+}
diff --git a/wear/src/main/java/to/bitkit/wear/link/KeystoreLinkKeys.kt b/wear/src/main/java/to/bitkit/wear/link/KeystoreLinkKeys.kt
new file mode 100644
index 0000000000..ce58ed93cd
--- /dev/null
+++ b/wear/src/main/java/to/bitkit/wear/link/KeystoreLinkKeys.kt
@@ -0,0 +1,92 @@
+package to.bitkit.wear.link
+
+import android.content.Context
+import android.content.pm.PackageManager
+import android.security.keystore.KeyProperties
+import android.security.keystore.KeyProtection
+import dagger.hilt.android.qualifiers.ApplicationContext
+import to.bitkit.wearlink.LinkError
+import to.bitkit.wearlink.LinkKeyStore
+import java.security.KeyStore
+import javax.crypto.AEADBadTagException
+import javax.crypto.Cipher
+import javax.crypto.SecretKey
+import javax.crypto.spec.GCMParameterSpec
+import javax.crypto.spec.SecretKeySpec
+import javax.inject.Inject
+import javax.inject.Singleton
+
+/**
+ * The link keys as AES-256-GCM keys imported into AndroidKeyStore: StrongBox when the watch has one that takes the
+ * key, else the trusted execution environment. Once imported a key cannot be read back. Unlike the seed key they are
+ * not bound to an unlocked watch, so the phone's erase command can be read on a locked one; they protect settings
+ * and commands, never funds. The phone's `KeystoreLinkKeys` is the same class.
+ */
+@Singleton
+class KeystoreLinkKeys @Inject constructor(
+ @ApplicationContext private val context: Context,
+) : LinkKeyStore {
+ private companion object {
+ const val KEYSTORE = "AndroidKeyStore"
+ const val TRANSFORMATION = "AES/GCM/NoPadding"
+ const val ALIAS_PREFIX = "wearlink."
+ const val IV_BYTES = 12
+ const val TAG_BITS = 128
+ }
+
+ private val keyStore: KeyStore by lazy { KeyStore.getInstance(KEYSTORE).apply { load(null) } }
+
+ override fun import(alias: String, key: ByteArray) = guarded {
+ val entry = KeyStore.SecretKeyEntry(SecretKeySpec(key, KeyProperties.KEY_ALGORITHM_AES))
+ val hasStrongBox = context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
+ if (hasStrongBox && runCatching { keyStore.setEntry(alias, entry, protection(isStrongBox = true)) }.isSuccess) {
+ return@guarded
+ }
+ keyStore.setEntry(alias, entry, protection(isStrongBox = false))
+ }
+
+ override fun encrypt(alias: String, plaintext: ByteArray, aad: ByteArray): ByteArray = guarded {
+ val cipher = Cipher.getInstance(TRANSFORMATION)
+ cipher.init(Cipher.ENCRYPT_MODE, key(alias))
+ cipher.updateAAD(aad)
+ val ciphertext = cipher.doFinal(plaintext)
+ check(cipher.iv.size == IV_BYTES) { "Unexpected IV size" }
+ cipher.iv + ciphertext
+ }
+
+ override fun decrypt(alias: String, blob: ByteArray, aad: ByteArray): ByteArray = guarded {
+ if (blob.size <= IV_BYTES) throw LinkError.Rejected("too short")
+ val cipher = Cipher.getInstance(TRANSFORMATION)
+ cipher.init(Cipher.DECRYPT_MODE, key(alias), GCMParameterSpec(TAG_BITS, blob, 0, IV_BYTES))
+ cipher.updateAAD(aad)
+ cipher.doFinal(blob, IV_BYTES, blob.size - IV_BYTES)
+ }
+
+ override fun delete(alias: String) = guarded { keyStore.deleteEntry(alias) }
+
+ override fun clear() = guarded {
+ keyStore.aliases().toList().filter { it.startsWith(ALIAS_PREFIX) }.forEach(keyStore::deleteEntry)
+ }
+
+ private fun key(alias: String): SecretKey =
+ keyStore.getKey(alias, null) as? SecretKey ?: throw LinkError.KeyFailure()
+
+ private fun protection(isStrongBox: Boolean) =
+ KeyProtection.Builder(KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
+ .setRandomizedEncryptionRequired(true)
+ .setIsStrongBoxBacked(isStrongBox)
+ .build()
+
+ private inline fun guarded(block: () -> T): T = runCatching(block).getOrElse {
+ val causes = generateSequence(it) { error -> error.cause }.take(MAX_CAUSE_DEPTH)
+ throw when {
+ it is LinkError -> it
+ causes.any { cause -> cause is AEADBadTagException } -> LinkError.Rejected("not authentic")
+ else -> LinkError.KeyFailure(it)
+ }
+ }
+}
+
+private const val MAX_CAUSE_DEPTH = 8
diff --git a/wear/src/main/java/to/bitkit/wear/link/LinkListenerService.kt b/wear/src/main/java/to/bitkit/wear/link/LinkListenerService.kt
new file mode 100644
index 0000000000..94f1c1ab3f
--- /dev/null
+++ b/wear/src/main/java/to/bitkit/wear/link/LinkListenerService.kt
@@ -0,0 +1,42 @@
+package to.bitkit.wear.link
+
+import com.google.android.gms.wearable.DataEvent
+import com.google.android.gms.wearable.DataEventBuffer
+import com.google.android.gms.wearable.MessageEvent
+import com.google.android.gms.wearable.WearableListenerService
+import dagger.hilt.android.AndroidEntryPoint
+import kotlinx.coroutines.runBlocking
+import to.bitkit.wear.repositories.PhoneLinkRepo
+import to.bitkit.wearlink.LinkPacket
+import javax.inject.Inject
+
+/**
+ * Receives what the phone sends over the Data Layer, also while the app is closed and the watch is locked, which is
+ * how an erase command reaches a lost watch. Play services binds it, so it is exported; what it receives is trusted
+ * only as far as the link authenticates it. Each callback runs on the service's own background thread and is handled
+ * to its end before it returns, since the process may be stopped right after.
+ */
+@AndroidEntryPoint
+class LinkListenerService : WearableListenerService() {
+ /** Injected so the link is attached to the transport before anything is delivered. */
+ @Inject
+ lateinit var phoneLinkRepo: PhoneLinkRepo
+
+ @Inject
+ lateinit var transport: DataLayerTransport
+
+ override fun onMessageReceived(event: MessageEvent) {
+ deliver(LinkPacket(event.sourceNodeId, event.path, event.data))
+ }
+
+ override fun onDataChanged(events: DataEventBuffer) {
+ val packets = events.filter { it.type == DataEvent.TYPE_CHANGED }.mapNotNull { event ->
+ val item = event.dataItem
+ val data = item.data ?: return@mapNotNull null
+ LinkPacket(item.uri.host.orEmpty(), item.uri.path.orEmpty(), data)
+ }
+ packets.forEach(::deliver)
+ }
+
+ private fun deliver(packet: LinkPacket) = runBlocking { transport.deliver(packet) }
+}
diff --git a/wear/src/main/java/to/bitkit/wear/link/WatchLinkStore.kt b/wear/src/main/java/to/bitkit/wear/link/WatchLinkStore.kt
new file mode 100644
index 0000000000..9fed5a22fb
--- /dev/null
+++ b/wear/src/main/java/to/bitkit/wear/link/WatchLinkStore.kt
@@ -0,0 +1,49 @@
+package to.bitkit.wear.link
+
+import androidx.datastore.core.DataStore
+import androidx.datastore.preferences.core.Preferences
+import androidx.datastore.preferences.core.edit
+import androidx.datastore.preferences.core.stringPreferencesKey
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.map
+import to.bitkit.wearlink.Handshake
+import to.bitkit.wearlink.LinkRecord
+import to.bitkit.wearlink.LinkRecordStore
+import java.security.SecureRandom
+import javax.inject.Inject
+import javax.inject.Singleton
+
+/**
+ * The watch's note of its paired phone and this install's random id, in the settings file, which a wallet wipe
+ * clears: a wallet that is removed leaves no pairing behind. Nothing here is secret; the link keys are in the
+ * Keystore.
+ */
+@Singleton
+class WatchLinkStore @Inject constructor(
+ private val dataStore: DataStore,
+) : LinkRecordStore {
+ private val recordKey = stringPreferencesKey("phone_link")
+ private val installIdKey = stringPreferencesKey("link_install_id")
+
+ override val record: Flow = dataStore.data.map { it.record() }.distinctUntilChanged()
+
+ override suspend fun load(): LinkRecord? = dataStore.data.first().record()
+
+ override suspend fun update(transform: (LinkRecord?) -> LinkRecord?): LinkRecord? =
+ dataStore.edit { prefs ->
+ val updated = transform(prefs.record())
+ if (updated == null) prefs.remove(recordKey) else prefs[recordKey] = updated.encode()
+ }.record()
+
+ /** This install's id for pairings, made at first use. */
+ @OptIn(ExperimentalStdlibApi::class)
+ suspend fun installId(): ByteArray = dataStore.edit { prefs ->
+ if (prefs[installIdKey] == null) {
+ prefs[installIdKey] = ByteArray(Handshake.ID_BYTES).also(SecureRandom()::nextBytes).toHexString()
+ }
+ }[installIdKey].orEmpty().hexToByteArray()
+
+ private fun Preferences.record(): LinkRecord? = this[recordKey]?.let(LinkRecord::decode)
+}
diff --git a/wear/src/main/java/to/bitkit/wear/models/PhoneSettings.kt b/wear/src/main/java/to/bitkit/wear/models/PhoneSettings.kt
index 1f24a57271..ef325183ca 100644
--- a/wear/src/main/java/to/bitkit/wear/models/PhoneSettings.kt
+++ b/wear/src/main/java/to/bitkit/wear/models/PhoneSettings.kt
@@ -6,6 +6,7 @@ import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.intOrNull
+import kotlinx.serialization.json.longOrNull
import to.bitkit.wear.utils.AppError
/**
@@ -41,6 +42,12 @@ data class PhoneSettings(
val quickPay: QuickPayLimits?,
)
+/** A settings backup as read: its [settings], and when the phone wrote it, by its clock, when the backup says. */
+data class PhoneSettingsBackup(
+ val settings: PhoneSettings,
+ val createdAtMs: Long?,
+)
+
sealed class PhoneSettingsError(message: String, cause: Throwable? = null) : AppError(message, cause) {
/** The backup is not the JSON envelope the phone writes. */
class Unreadable(cause: Throwable? = null) : PhoneSettingsError("The settings backup cannot be read", cause)
@@ -63,7 +70,10 @@ object PhoneSettingsParser {
private val json = Json { isLenient = true }
/** Fails with a [PhoneSettingsError]. */
- fun parse(bytes: ByteArray): PhoneSettings {
+ fun parse(bytes: ByteArray): PhoneSettings = parseBackup(bytes).settings
+
+ /** [parse] with the backup's own time, the envelope's `createdAt`. Fails with a [PhoneSettingsError]. */
+ fun parseBackup(bytes: ByteArray): PhoneSettingsBackup {
if (bytes.size > MAX_BYTES) throw PhoneSettingsError.Unreadable()
val root = runCatching { json.parseToJsonElement(bytes.decodeToString()) as JsonObject }
.getOrElse { throw PhoneSettingsError.Unreadable(it) }
@@ -74,18 +84,43 @@ object PhoneSettingsParser {
if (version > SCHEMA_VERSION) throw PhoneSettingsError.NewerSchema(version)
if (version < 1) throw PhoneSettingsError.Unreadable()
val settings = root["settings"] as? JsonObject ?: throw PhoneSettingsError.Unreadable()
- return PhoneSettings(
+ val adopted = PhoneSettings(
primaryDisplay = settings["primaryDisplay"].enumOrNull(),
displayUnit = settings["displayUnit"].enumOrNull(),
selectedCurrency = settings["selectedCurrency"].stringOrNull()?.takeIf { CURRENCY_CODE.matches(it) },
quickPay = quickPay(settings),
)
+ val createdAtMs = (root["createdAt"] as? JsonPrimitive)?.takeIf { !it.isString }?.longOrNull
+ return PhoneSettingsBackup(adopted, createdAtMs)
}
+ /**
+ * The same settings as the paired phone pushes them over the link, held to the same rules as a backup: a value
+ * that is not one the phone can have is dropped, and QuickPay values outside the phone's sliders turn it off.
+ */
+ @Suppress("LongParameterList")
+ fun fromPush(
+ primaryDisplay: String?,
+ displayUnit: String?,
+ selectedCurrency: String?,
+ isQuickPayEnabled: Boolean,
+ quickPayAmount: Int,
+ quickPayDailyLimitMultiplier: Int,
+ ): PhoneSettings = PhoneSettings(
+ primaryDisplay = primaryDisplay?.let { JsonPrimitive(it).enumOrNull() },
+ displayUnit = displayUnit?.let { JsonPrimitive(it).enumOrNull() },
+ selectedCurrency = selectedCurrency?.takeIf { CURRENCY_CODE.matches(it) },
+ quickPay = quickPay(isQuickPayEnabled, quickPayAmount, quickPayDailyLimitMultiplier),
+ )
+
private fun quickPay(settings: JsonObject): QuickPayLimits? {
val isEnabled = (settings["isQuickPayEnabled"] as? JsonPrimitive)?.takeIf { !it.isString }?.booleanOrNull
val amountUsd = settings["quickPayAmount"].intOrNull()
val multiplier = settings["quickPayDailyLimitMultiplier"].intOrNull()
+ return quickPay(isEnabled, amountUsd, multiplier)
+ }
+
+ private fun quickPay(isEnabled: Boolean?, amountUsd: Int?, multiplier: Int?): QuickPayLimits? {
if (isEnabled == null || amountUsd == null || multiplier == null) return null
if (amountUsd !in 1..QuickPayLimits.MAX_AMOUNT_USD) return null
if (multiplier !in 1..QuickPayLimits.MAX_DAILY_MULTIPLIER) return null
diff --git a/wear/src/main/java/to/bitkit/wear/repositories/PhoneLinkRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/PhoneLinkRepo.kt
new file mode 100644
index 0000000000..dfb68f9093
--- /dev/null
+++ b/wear/src/main/java/to/bitkit/wear/repositories/PhoneLinkRepo.kt
@@ -0,0 +1,313 @@
+package to.bitkit.wear.repositories
+
+import android.content.Context
+import android.os.Build
+import dagger.hilt.android.qualifiers.ApplicationContext
+import kotlinx.coroutines.CoroutineDispatcher
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import to.bitkit.wear.data.PhoneStateSink
+import to.bitkit.wear.data.PhoneStateSource
+import to.bitkit.wear.di.IoDispatcher
+import to.bitkit.wear.env.Env
+import to.bitkit.wear.ext.runSuspendCatching
+import to.bitkit.wear.link.WatchLinkStore
+import to.bitkit.wear.models.PhoneSettingsParser
+import to.bitkit.wear.security.Bip39
+import to.bitkit.wear.security.Bip39Validation
+import to.bitkit.wear.security.DeviceLock
+import to.bitkit.wear.security.SeedStore
+import to.bitkit.wear.security.SeedStoreError
+import to.bitkit.wear.security.WalletSeed
+import to.bitkit.wear.utils.Logger
+import to.bitkit.wearlink.LinkKeyStore
+import to.bitkit.wearlink.LinkPacket
+import to.bitkit.wearlink.LinkRecord
+import to.bitkit.wearlink.LinkTransport
+import to.bitkit.wearlink.PairingMode
+import to.bitkit.wearlink.PairingState
+import to.bitkit.wearlink.SeedPayload
+import to.bitkit.wearlink.SeedStoreResult
+import to.bitkit.wearlink.SettingsDoc
+import to.bitkit.wearlink.StoreFailure
+import to.bitkit.wearlink.WalletLink
+import to.bitkit.wearlink.WatchAgreementKey
+import to.bitkit.wearlink.WatchInfo
+import to.bitkit.wearlink.WatchLink
+import to.bitkit.wearlink.WatchLinkListener
+import to.bitkit.wearlink.WatchPairing
+import to.bitkit.wearlink.WatchPairingEnv
+import javax.inject.Inject
+import javax.inject.Singleton
+
+/**
+ * The watch's link to the phone: the pairing ceremony's watch side, and what the paired phone sends afterwards.
+ * The protocol itself is in `:wearlink`; this class gives it the watch's wallet, Keystore and stores.
+ *
+ * A pairing runs only while the Pair screen asks for it, in this repo's own scope: once a seed has arrived it is
+ * stored and answered even if the screen went away meanwhile. The phone's settings go to the [PhoneStateSink], as
+ * the backup import's do. The phone's erase command runs the wallet's own wipe, noted on disk before the phone is
+ * told, so an erase the phone was told about is always finished.
+ */
+@Singleton
+class PhoneLinkRepo internal constructor(
+ private val ioDispatcher: CoroutineDispatcher,
+ private val transport: LinkTransport,
+ private val keys: LinkKeyStore,
+ private val agreementKey: WatchAgreementKey,
+ private val store: WatchLinkStore,
+ private val walletRepo: WalletRepo,
+ private val seedStore: SeedStore,
+ private val bip39: Bip39,
+ private val sink: PhoneStateSink,
+ private val deviceLock: DeviceLock,
+ private val appId: String,
+ private val nowMs: () -> Long,
+) {
+ companion object {
+ private const val TAG = "PhoneLinkRepo"
+ }
+
+ @Inject
+ constructor(
+ @ApplicationContext context: Context,
+ @IoDispatcher ioDispatcher: CoroutineDispatcher,
+ transport: LinkTransport,
+ keys: LinkKeyStore,
+ agreementKey: WatchAgreementKey,
+ store: WatchLinkStore,
+ walletRepo: WalletRepo,
+ seedStore: SeedStore,
+ bip39: Bip39,
+ sink: PhoneStateSink,
+ deviceLock: DeviceLock,
+ ) : this(
+ ioDispatcher = ioDispatcher,
+ transport = transport,
+ keys = keys,
+ agreementKey = agreementKey,
+ store = store,
+ walletRepo = walletRepo,
+ seedStore = seedStore,
+ bip39 = bip39,
+ sink = sink,
+ deviceLock = deviceLock,
+ appId = context.packageName,
+ nowMs = System::currentTimeMillis,
+ )
+
+ private val scope = CoroutineScope(SupervisorJob() + ioDispatcher)
+
+ private val listener = object : WatchLinkListener {
+ override suspend fun applySettings(settings: SettingsDoc) {
+ val parsed = PhoneSettingsParser.fromPush(
+ primaryDisplay = settings.primaryDisplay,
+ displayUnit = settings.displayUnit,
+ selectedCurrency = settings.selectedCurrency,
+ isQuickPayEnabled = settings.isQuickPayEnabled,
+ quickPayAmount = settings.quickPayAmount,
+ quickPayDailyLimitMultiplier = settings.quickPayDailyLimitMultiplier,
+ )
+ sink.applySettings(parsed, PhoneStateSource.Push(settings.changedAtMs), nowMs())
+ Logger.info("Applied the settings the phone pushed", context = TAG)
+ }
+
+ override suspend fun prepareErase() {
+ Logger.warn("Noting the wallet erase the paired phone asked for", context = TAG)
+ walletRepo.noteEraseByPhone().getOrThrow()
+ }
+
+ override suspend fun erase() {
+ Logger.warn("Erasing the wallet as the paired phone asked", context = TAG)
+ walletRepo.eraseByPhone().getOrThrow()
+ }
+
+ override suspend fun onUnpaired() {
+ sink.onPushSourceGone()
+ Logger.info("Ended the pairing with the phone", context = TAG)
+ }
+ }
+
+ private val link = WatchLink(
+ transport = transport,
+ keys = keys,
+ store = store,
+ listener = listener,
+ info = { WatchInfo(Env.version, deviceLock.isSecure) },
+ nowMs = nowMs,
+ )
+
+ /** The paired phone, or null. */
+ val record: Flow = store.record
+
+ private val _pairing = MutableStateFlow(WatchPairingStatus.Idle)
+ val pairing: StateFlow = _pairing.asStateFlow()
+
+ private val lock = Any()
+
+ @Volatile
+ private var session: WatchPairing? = null
+ private var isEnding = false
+ private var isRestartPending = false
+
+ init {
+ transport.attach(::onPacket)
+ scope.launch {
+ // An erase the phone was told about is finished when the process starts, whatever started it.
+ if (walletRepo.isWipePending()) walletRepo.recover()
+ // Keys that no record owns belong to a pairing that a wallet wipe took with the settings.
+ runSuspendCatching { if (store.load() == null) keys.clear() }
+ .onFailure { Logger.warn("Failed to delete link keys without a pairing", it, context = TAG) }
+ }
+ }
+
+ /**
+ * Starts waiting for the phone's hello, as the Pair screen comes up. One pairing runs at a time; its progress and
+ * its end show in [pairing]. While a cancelled one is still ending, the new one starts as soon as it has.
+ */
+ fun startPairing(): Unit = synchronized(lock) {
+ if (session != null) {
+ if (!isEnding) return
+ // The screen that asks is a new one: it must not show, or confirm, the code of the session that ends.
+ isRestartPending = true
+ _pairing.update { WatchPairingStatus.Running(PairingState.Connecting) }
+ return
+ }
+ val pairing = WatchPairing(transport, link.pairingPackets, PairingEnv())
+ session = pairing
+ _pairing.update { WatchPairingStatus.Running(PairingState.Connecting) }
+ val progress = scope.launch {
+ pairing.state.collect { state -> showProgress(pairing, state) }
+ }
+ scope.launch {
+ val result = runSuspendCatching { pairing.run().also { link.onPaired(it) } }
+ progress.cancel()
+ result.onFailure { Logger.warn("Failed to pair with the phone", it, context = TAG) }
+ val status = result.fold(
+ onSuccess = { WatchPairingStatus.Paired(isWalletReceived = it.mode == PairingMode.Transfer) },
+ onFailure = { WatchPairingStatus.Failed(it) },
+ )
+ onPairingEnd(status)
+ }
+ }
+
+ private fun showProgress(pairing: WatchPairing, state: PairingState) = synchronized(lock) {
+ if (session === pairing && !isEnding) _pairing.update { WatchPairingStatus.Running(state) }
+ }
+
+ /**
+ * The wearer says [code], the one the screen showed, matches the phone's. Only the session that shows that code
+ * now is confirmed, and never one that was cancelled.
+ */
+ fun confirmPairing(code: String): Unit = synchronized(lock) {
+ if (!isEnding) session?.confirm(code)
+ }
+
+ /** Ends the pairing that runs, as when the Pair screen goes away, and forgets the last one's end. */
+ fun cancelPairing(): Unit = synchronized(lock) {
+ isRestartPending = false
+ val running = session
+ if (running == null) {
+ _pairing.update { WatchPairingStatus.Idle }
+ return
+ }
+ isEnding = true
+ running.cancel()
+ }
+
+ private fun onPairingEnd(status: WatchPairingStatus) = synchronized(lock) {
+ session = null
+ isEnding = false
+ if (!isRestartPending) {
+ _pairing.update { status }
+ return@synchronized
+ }
+ isRestartPending = false
+ startPairing()
+ }
+
+ /** Tells the phone and forgets it. The wallet stays; also run before the wallet is removed from the watch. */
+ suspend fun unpair(): Result = withContext(ioDispatcher) {
+ runSuspendCatching { link.unpair() }
+ .onFailure { Logger.warn("Failed to unpair from the phone", it, context = TAG) }
+ }
+
+ private suspend fun onPacket(packet: LinkPacket) {
+ runSuspendCatching { link.onPacket(packet) }
+ .onFailure { Logger.debug("Dropped a packet at '${packet.path}': '${it.message}'", context = TAG) }
+ }
+
+ private suspend fun walletSecret(): ByteArray? = withContext(ioDispatcher) {
+ if (!seedStore.exists()) return@withContext null
+ linkSecret(seedStore.load().getOrThrow())
+ }
+
+ private fun linkSecret(seed: WalletSeed): ByteArray {
+ val bytes = bip39.toSeed(seed.mnemonic, seed.passphrase)
+ return WalletLink.secret(bytes, Env.network.name).also { bytes.fill(0) }
+ }
+
+ /**
+ * Stores a wallet the phone sent, through the same door as a typed recovery phrase: the phrase must pass the
+ * BIP39 checksum, be for this build's network, and find no wallet on the watch; the seed store then refuses a
+ * key outside secure hardware in a release build.
+ */
+ private suspend fun storeSeed(payload: SeedPayload): SeedStoreResult = withContext(ioDispatcher) {
+ if (!payload.network.equals(Env.network.name, ignoreCase = true)) {
+ return@withContext SeedStoreResult.Refused(StoreFailure.WrongNetwork)
+ }
+ if (bip39.validate(payload.mnemonic.split(" ")) != Bip39Validation.Valid) {
+ return@withContext SeedStoreResult.Refused(StoreFailure.InvalidPhrase)
+ }
+ if (seedStore.exists()) return@withContext SeedStoreResult.Refused(StoreFailure.HasWallet)
+ val seed = WalletSeed(payload.mnemonic, payload.passphrase)
+ walletRepo.restore(seed).fold(
+ onSuccess = {
+ Logger.info("Stored the wallet the phone sent", context = TAG)
+ SeedStoreResult.Stored(linkSecret(seed))
+ },
+ onFailure = {
+ val failure = when (it) {
+ is SeedStoreError.InsecureKey -> StoreFailure.InsecureKey
+ is SeedStoreError.AlreadyExists -> StoreFailure.HasWallet
+ else -> StoreFailure.Failed
+ }
+ SeedStoreResult.Refused(failure)
+ },
+ )
+ }
+
+ private inner class PairingEnv : WatchPairingEnv {
+ override val appId: String = this@PhoneLinkRepo.appId
+ override val name: String = Build.MODEL.orEmpty()
+ override val agreementKey: WatchAgreementKey = this@PhoneLinkRepo.agreementKey
+ override val keys: LinkKeyStore = this@PhoneLinkRepo.keys
+
+ override suspend fun watchId(): ByteArray = store.installId()
+
+ override suspend fun isLockSet(): Boolean = deviceLock.isSecure
+
+ override suspend fun walletSecret(): ByteArray? = this@PhoneLinkRepo.walletSecret()
+
+ override suspend fun storeSeed(seed: SeedPayload): SeedStoreResult = this@PhoneLinkRepo.storeSeed(seed)
+ }
+}
+
+/** Where the watch's side of a pairing stands. */
+sealed interface WatchPairingStatus {
+ data object Idle : WatchPairingStatus
+
+ data class Running(val state: PairingState) : WatchPairingStatus
+
+ /** Paired; [isWalletReceived] when the phone sent this watch its wallet. */
+ data class Paired(val isWalletReceived: Boolean) : WatchPairingStatus
+
+ data class Failed(val error: Throwable) : WatchPairingStatus
+}
diff --git a/wear/src/main/java/to/bitkit/wear/repositories/SettingsSyncRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/SettingsSyncRepo.kt
index 2b1f506528..3030270fac 100644
--- a/wear/src/main/java/to/bitkit/wear/repositories/SettingsSyncRepo.kt
+++ b/wear/src/main/java/to/bitkit/wear/repositories/SettingsSyncRepo.kt
@@ -11,6 +11,8 @@ import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withTimeoutOrNull
import to.bitkit.wear.data.ElapsedClock
+import to.bitkit.wear.data.PhoneStateSink
+import to.bitkit.wear.data.PhoneStateSource
import to.bitkit.wear.data.SettingsStore
import to.bitkit.wear.di.IoDispatcher
import to.bitkit.wear.ext.runSuspendCatching
@@ -31,7 +33,8 @@ import kotlin.time.Duration.Companion.seconds
/**
* Imports the phone's settings from its backup on VSS, which the watch can read because it holds the same seed. It
* only reads: see [PhoneBackupReader]. The watch adopts the units, the currency and QuickPay, and sets none of them
- * itself.
+ * itself. What it read goes to the [PhoneStateSink], which the paired phone's live push feeds too and which decides
+ * which of the two holds.
*/
@Singleton
class SettingsSyncRepo internal constructor(
@@ -39,6 +42,7 @@ class SettingsSyncRepo internal constructor(
private val seedStore: SeedStore,
private val backupReader: PhoneBackupReader,
private val settingsStore: SettingsStore,
+ private val sink: PhoneStateSink,
private val sparkService: WatchSparkService,
private val walletRepo: WalletRepo,
private val clock: ElapsedClock,
@@ -66,6 +70,7 @@ class SettingsSyncRepo internal constructor(
seedStore: SeedStore,
backupReader: PhoneBackupReader,
settingsStore: SettingsStore,
+ sink: PhoneStateSink,
sparkService: WatchSparkService,
walletRepo: WalletRepo,
clock: ElapsedClock,
@@ -74,6 +79,7 @@ class SettingsSyncRepo internal constructor(
seedStore,
backupReader,
settingsStore,
+ sink,
sparkService,
walletRepo,
clock,
@@ -122,22 +128,23 @@ class SettingsSyncRepo internal constructor(
val seed = seedStore.load().getOrThrow()
val backup = withTimeoutOrNull(READ_TIMEOUT) { readWhileReady(seed) } ?: throw SettingsSyncError.Timeout()
val parsed = backup.fold(
- onSuccess = { bytes -> runSuspendCatching { bytes?.let { PhoneSettingsParser.parse(it) } } },
+ onSuccess = { bytes -> runSuspendCatching { bytes?.let { PhoneSettingsParser.parseBackup(it) } } },
onFailure = { if (it is PhoneBackupUnreadable) Result.failure(it) else throw it },
)
- val settings = parsed.getOrNull()
+ val phoneBackup = parsed.getOrNull()
when {
parsed.isFailure -> {
Logger.warn("Failed to read the phone's settings backup", parsed.exceptionOrNull(), context = TAG)
- settingsStore.clearQuickPay()
+ sink.onSettingsMissing(PhoneStateSource.Backup(createdAtMs = null))
}
- settings == null -> {
+ phoneBackup == null -> {
Logger.info("Found no settings backup of the phone", context = TAG)
- settingsStore.clearQuickPay()
+ sink.onSettingsMissing(PhoneStateSource.Backup(createdAtMs = null))
}
else -> {
- settingsStore.applyPhoneSettings(settings, nowMs())
- Logger.info("Imported the phone's settings", context = TAG)
+ val source = PhoneStateSource.Backup(phoneBackup.createdAtMs)
+ val isApplied = sink.applySettings(phoneBackup.settings, source, nowMs())
+ Logger.info("Imported the phone's settings, applied '$isApplied'", context = TAG)
}
}
lastRead = wipeToken to clock.nowMs()
diff --git a/wear/src/main/java/to/bitkit/wear/repositories/WalletRepo.kt b/wear/src/main/java/to/bitkit/wear/repositories/WalletRepo.kt
index 36b3857e43..1aab31b7f7 100644
--- a/wear/src/main/java/to/bitkit/wear/repositories/WalletRepo.kt
+++ b/wear/src/main/java/to/bitkit/wear/repositories/WalletRepo.kt
@@ -118,6 +118,11 @@ class WalletRepo @Inject constructor(
.onFailure { Logger.warn("Failed to acknowledge wallet removal", it, context = TAG) }
}
+ /** Whether a wipe was noted that has not finished; [recover] finishes it. */
+ suspend fun isWipePending(): Boolean = withContext(ioDispatcher) {
+ runSuspendCatching { settingsStore.isWipePending() }.getOrDefault(false)
+ }
+
/**
* Run at every launch before the wallet is used: finishes a wipe that the last process did not complete, and
* deletes Spark storage, a seed key and a half-written seed file that no stored seed owns.
@@ -436,6 +441,21 @@ class WalletRepo @Inject constructor(
*/
suspend fun wipe(): Result = wipe(isKeyLost = false, isNoteRequired = true)
+ /**
+ * Removes the wallet because the paired phone asked for it, as [wipe] does, and ends in [WalletStatus.Removed]
+ * with the removed notice left for the wearer, as after a lost seed key: the wearer did not ask for this.
+ */
+ suspend fun eraseByPhone(): Result = wipe(isKeyLost = true, isNoteRequired = true)
+
+ /**
+ * Notes that the paired phone asked for the wallet to be removed, before the watch tells the phone so: once
+ * this has returned, [eraseByPhone] or, when the process dies first, [recover] at the next launch removes the
+ * wallet. Fails when the note cannot be written, even on a second try; nothing is promised to the phone then.
+ */
+ suspend fun noteEraseByPhone(): Result = withContext(ioDispatcher + NonCancellable) {
+ walletMutex.withLock { noteWipe(isKeyLost = true) }
+ }
+
private suspend fun wipe(isKeyLost: Boolean, isNoteRequired: Boolean): Result =
withContext(ioDispatcher + NonCancellable) {
walletMutex.withLock { wipeLocked(isKeyLost, isNoteRequired) }
diff --git a/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt b/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt
index d7b73a2b26..9e2ded0ae5 100644
--- a/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt
+++ b/wear/src/main/java/to/bitkit/wear/ui/LaunchRequest.kt
@@ -6,6 +6,7 @@ import android.nfc.NfcAdapter
import androidx.core.content.IntentCompat
import to.bitkit.wear.nfc.NdefCodec
import to.bitkit.wear.nfc.nfcPaymentRequest
+import to.bitkit.wearlink.LinkPaths
/** What an intent that opened the app asks for, beyond showing it. */
sealed interface LaunchRequest {
@@ -18,6 +19,9 @@ sealed interface LaunchRequest {
/** Show the receive QR, as from the tile. */
data object Receive : LaunchRequest
+ /** Show the Pair screen, as when the phone starts a pairing; it only shows a screen, so any app may ask. */
+ data object Pair : LaunchRequest
+
/** Say that the tapped NFC tag holds no payment request the watch takes; never made from a link. */
data object TagRefused : LaunchRequest
@@ -36,6 +40,7 @@ sealed interface LaunchRequest {
*/
fun from(action: String?, data: String?, open: String?, tagTexts: List? = null): LaunchRequest? {
if (open == OPEN_RECEIVE) return Receive
+ if (action == Intent.ACTION_VIEW && data?.lowercase()?.startsWith(LinkPaths.PAIR_URI) == true) return Pair
val input = when (action) {
Intent.ACTION_VIEW -> data
NfcAdapter.ACTION_NDEF_DISCOVERED -> tagInput(data, tagTexts)
diff --git a/wear/src/main/java/to/bitkit/wear/ui/Routes.kt b/wear/src/main/java/to/bitkit/wear/ui/Routes.kt
index b94f317772..86e02d9697 100644
--- a/wear/src/main/java/to/bitkit/wear/ui/Routes.kt
+++ b/wear/src/main/java/to/bitkit/wear/ui/Routes.kt
@@ -33,6 +33,9 @@ object Routes {
const val ACTIVITY_DETAIL = "activity/{$ACTIVITY_PAYMENT_ID}"
const val UNSUPPORTED = "unsupported"
+ /** The pairing with the phone: the confirmation code, and for a watch without a wallet the wallet's arrival. */
+ const val PAIR = "pair"
+
fun restoreWord(index: Int): String = "restore/word/$index"
fun send(input: String): String = "send?$SEND_INPUT=${Uri.encode(input)}"
diff --git a/wear/src/main/java/to/bitkit/wear/ui/WearNavHost.kt b/wear/src/main/java/to/bitkit/wear/ui/WearNavHost.kt
index 97a5983857..768f42f6e3 100644
--- a/wear/src/main/java/to/bitkit/wear/ui/WearNavHost.kt
+++ b/wear/src/main/java/to/bitkit/wear/ui/WearNavHost.kt
@@ -3,6 +3,7 @@ package to.bitkit.wear.ui
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
@@ -23,6 +24,7 @@ import to.bitkit.wear.ui.screens.activity.ActivityDetailScreen
import to.bitkit.wear.ui.screens.activity.ActivityViewModel
import to.bitkit.wear.ui.screens.home.HomeScreen
import to.bitkit.wear.ui.screens.onboarding.OnboardingScreen
+import to.bitkit.wear.ui.screens.pair.PairScreen
import to.bitkit.wear.ui.screens.receive.ReceiveQrScreen
import to.bitkit.wear.ui.screens.removed.WalletRemovedScreen
import to.bitkit.wear.ui.screens.restore.RestoreChecksumScreen
@@ -48,6 +50,7 @@ fun WearNavHost(
val navController = rememberSwipeDismissableNavController()
var isRestoreSaving by remember { mutableStateOf(false) }
var isSending by remember { mutableStateOf(false) }
+ var pairRequests by remember { mutableIntStateOf(0) }
val currentOnLaunchRequestHandle by rememberUpdatedState(onLaunchRequestHandle)
val currentIsSendUnderWay by rememberUpdatedState(isSendUnderWay)
LaunchedEffect(launchRequest) {
@@ -59,6 +62,11 @@ fun WearNavHost(
Logger.info("Dropped launch request '${request::class.simpleName}' during a send", context = TAG)
return@LaunchedEffect
}
+ // The Pair screen already shows, perhaps on the end of the last pairing: it takes the request itself.
+ if (request is LaunchRequest.Pair && navController.currentBackStackEntry?.destination?.route == Routes.PAIR) {
+ pairRequests++
+ return@LaunchedEffect
+ }
navController.showLaunchRequest(request)
}
SwipeDismissableNavHost(
@@ -70,6 +78,7 @@ fun WearNavHost(
composable(Routes.ONBOARDING) {
OnboardingScreen(
onRestoreClick = { navController.navigateTo(Routes.RESTORE) },
+ onPairClick = { navController.navigateTo(Routes.PAIR) },
onWalletFind = { navController.navigateClearingBackStack(Routes.HOME) },
)
}
@@ -82,6 +91,7 @@ fun WearNavHost(
onReceiveClick = { navController.navigateTo(Routes.RECEIVE_QR) },
onPaymentClick = { navController.navigateTo(Routes.activityDetail(it)) },
onAboutClick = { navController.navigateTo(Routes.ABOUT) },
+ onPairClick = { navController.navigateTo(Routes.PAIR) },
onWalletRemove = { navController.navigateClearingBackStack(Routes.ONBOARDING) },
onSeedKeyLoss = { navController.navigateClearingBackStack(Routes.WALLET_REMOVED) },
)
@@ -117,6 +127,13 @@ fun WearNavHost(
composable(Routes.UNSUPPORTED) {
UnsupportedScreen()
}
+ composable(Routes.PAIR) {
+ PairScreen(
+ pairRequests = pairRequests,
+ onClose = { navController.popBackStack(Routes.PAIR, inclusive = true) },
+ onWalletReceive = { navController.navigateClearingBackStack(Routes.HOME) },
+ )
+ }
}
}
@@ -181,12 +198,16 @@ private fun NavController.showRestoreWord(index: Int) {
}
/**
- * Opens what [request] asks for above Home: the send flow of a deeplink or a tapped tag, the tile's receive QR, or
- * the refusal of a tag the watch does not take. Without a wallet,
+ * Opens what [request] asks for above Home: the send flow of a deeplink or a tapped tag, the tile's receive QR, the
+ * refusal of a tag the watch does not take, or the pairing with the phone. Without a wallet,
* or outside Home's back stack, such as during the restore, the request is dropped; the caller drops it while a send
* is under way.
*/
private fun NavController.showLaunchRequest(request: LaunchRequest) {
+ if (request is LaunchRequest.Pair) {
+ showPair()
+ return
+ }
val hasHome = runCatching { getBackStackEntry(Routes.HOME) }.isSuccess
if (!hasHome) {
Logger.info("Dropped launch request '${request::class.simpleName}' outside home", context = TAG)
@@ -197,7 +218,23 @@ private fun NavController.showLaunchRequest(request: LaunchRequest) {
is LaunchRequest.Send -> navigateTo(Routes.send(request.input))
LaunchRequest.Receive -> navigateTo(Routes.RECEIVE_QR)
LaunchRequest.TagRefused -> navigateTo(Routes.TAG_REFUSED)
+ LaunchRequest.Pair -> Unit
+ }
+}
+
+/**
+ * Opens the Pair screen above Home, or above onboarding for a watch without a wallet, which is how it receives one.
+ * Anywhere else, such as during the restore, the request is dropped.
+ */
+private fun NavController.showPair() {
+ val route = currentBackStackEntry?.destination?.route
+ val hasHome = runCatching { getBackStackEntry(Routes.HOME) }.isSuccess
+ if (!hasHome && route != Routes.ONBOARDING) {
+ Logger.info("Dropped the pair request outside home and onboarding", context = TAG)
+ return
}
+ if (hasHome) popBackStack(Routes.HOME, inclusive = false)
+ navigateTo(Routes.PAIR)
}
private const val TAG = "WearNavHost"
diff --git a/wear/src/main/java/to/bitkit/wear/ui/components/BlockScreenshots.kt b/wear/src/main/java/to/bitkit/wear/ui/components/BlockScreenshots.kt
index 31a98f661c..108fb68820 100644
--- a/wear/src/main/java/to/bitkit/wear/ui/components/BlockScreenshots.kt
+++ b/wear/src/main/java/to/bitkit/wear/ui/components/BlockScreenshots.kt
@@ -4,15 +4,18 @@ import android.view.WindowManager
import androidx.activity.compose.LocalActivity
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
+import to.bitkit.wear.env.Env
import java.util.WeakHashMap
/**
* Blocks screenshots, screen recording and the recents preview while the calling screen is shown, as the phone's
- * `BlockScreenshots` does. Unlike the phone it also applies to debug builds, because these screens show the recovery
- * phrase as it is typed.
+ * `BlockScreenshots` does. Only applies in release builds, as on the phone, so debug builds can be captured for
+ * testing.
*/
@Composable
fun BlockScreenshots() {
+ if (Env.isDebug) return
+
val activity = LocalActivity.current ?: return
val window = activity.window ?: return
DisposableEffect(window) {
diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/home/HomeScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/home/HomeScreen.kt
index cf7c37dddd..ce483df5ec 100644
--- a/wear/src/main/java/to/bitkit/wear/ui/screens/home/HomeScreen.kt
+++ b/wear/src/main/java/to/bitkit/wear/ui/screens/home/HomeScreen.kt
@@ -31,6 +31,7 @@ fun HomeScreen(
onReceiveClick: () -> Unit,
onPaymentClick: (String) -> Unit,
onAboutClick: () -> Unit,
+ onPairClick: () -> Unit,
onWalletRemove: () -> Unit,
onSeedKeyLoss: () -> Unit,
modifier: Modifier = Modifier,
@@ -53,7 +54,7 @@ fun HomeScreen(
HomePage.Balance -> BalancePage(viewModel = viewModel)
HomePage.Receive -> ReceiveScreen(onQrClick = onReceiveClick)
HomePage.Activity -> ActivityScreen(onPaymentClick = onPaymentClick)
- HomePage.Settings -> SettingsScreen(onAboutClick = onAboutClick)
+ HomePage.Settings -> SettingsScreen(onAboutClick = onAboutClick, onPairClick = onPairClick)
}
}
}
diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/onboarding/OnboardingScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/onboarding/OnboardingScreen.kt
index 730d0ea4ab..c94bf63b55 100644
--- a/wear/src/main/java/to/bitkit/wear/ui/screens/onboarding/OnboardingScreen.kt
+++ b/wear/src/main/java/to/bitkit/wear/ui/screens/onboarding/OnboardingScreen.kt
@@ -16,6 +16,8 @@ import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.compose.LifecycleResumeEffect
import androidx.lifecycle.viewModelScope
+import androidx.wear.compose.material3.ButtonDefaults
+import androidx.wear.compose.material3.CompactButton
import androidx.wear.compose.material3.EdgeButton
import androidx.wear.compose.material3.EdgeButtonSize
import androidx.wear.compose.material3.Icon
@@ -33,13 +35,14 @@ import to.bitkit.wear.ui.components.WearPreviewDevices
import javax.inject.Inject
/**
- * The Bitkit mark and the one way in for now: restoring a recovery phrase. Each time it comes on screen it checks
- * for a stored wallet and leaves through [onWalletFind] when there is one, as after a restore whose save finished
- * while the wearer was away.
+ * The Bitkit mark and the two ways in: restoring a recovery phrase, or receiving the wallet from the phone. Each
+ * time it comes on screen it checks for a stored wallet and leaves through [onWalletFind] when there is one, as after
+ * a restore whose save finished while the wearer was away.
*/
@Composable
fun OnboardingScreen(
onRestoreClick: () -> Unit,
+ onPairClick: () -> Unit,
onWalletFind: () -> Unit,
modifier: Modifier = Modifier,
viewModel: OnboardingViewModel = hiltViewModel(),
@@ -54,6 +57,7 @@ fun OnboardingScreen(
}
Content(
onRestoreClick = onRestoreClick,
+ onPairClick = onPairClick,
modifier = modifier
)
}
@@ -61,6 +65,7 @@ fun OnboardingScreen(
@Composable
private fun Content(
onRestoreClick: () -> Unit,
+ onPairClick: () -> Unit,
modifier: Modifier = Modifier,
) {
CenteredScreen(
@@ -87,6 +92,13 @@ private fun Content(
.fillMaxWidth(0.7f)
.testTag("WatchOnboardingLogo")
)
+ CompactButton(
+ onClick = onPairClick,
+ icon = { Icon(painter = painterResource(R.drawable.ic_phone), contentDescription = null) },
+ label = { Text(stringResource(R.string.onboarding__from_phone)) },
+ colors = ButtonDefaults.filledTonalButtonColors(),
+ modifier = Modifier.testTag("WatchOnboardingFromPhone")
+ )
}
}
@@ -112,6 +124,6 @@ sealed interface OnboardingEffect {
@Composable
private fun Preview() {
WearPreview {
- Content(onRestoreClick = {})
+ Content(onRestoreClick = {}, onPairClick = {})
}
}
diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/pair/PairScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/pair/PairScreen.kt
new file mode 100644
index 0000000000..43acd8c159
--- /dev/null
+++ b/wear/src/main/java/to/bitkit/wear/ui/screens/pair/PairScreen.kt
@@ -0,0 +1,193 @@
+package to.bitkit.wear.ui.screens.pair
+
+import androidx.compose.foundation.layout.size
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.rememberUpdatedState
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.testTag
+import androidx.compose.ui.res.painterResource
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import androidx.wear.compose.material3.EdgeButton
+import androidx.wear.compose.material3.EdgeButtonSize
+import androidx.wear.compose.material3.Icon
+import androidx.wear.compose.material3.MaterialTheme
+import androidx.wear.compose.material3.Text
+import kotlinx.coroutines.delay
+import to.bitkit.wear.R
+import to.bitkit.wear.ui.components.BezelLoading
+import to.bitkit.wear.ui.components.BlockScreenshots
+import to.bitkit.wear.ui.components.CenteredScreen
+import to.bitkit.wear.ui.components.ScreenAwake
+import to.bitkit.wear.ui.components.WearPreview
+import to.bitkit.wear.ui.components.WearPreviewDevices
+import to.bitkit.wear.ui.components.isAmbient
+import kotlin.time.Duration.Companion.seconds
+
+/** How long the end of a pairing shows before the screen closes by itself. */
+private val RESULT_TIME = 3.seconds
+
+/**
+ * The watch's side of a pairing with the phone. It waits for the phone, shows the confirmation code to compare with
+ * the phone's above the one button that says they match, and ends on a check or one line. Swiping the screen away
+ * cancels, at every step. A watch without a wallet receives the phone's here and leaves through
+ * [onWalletReceive]; every other end leaves through [onClose]. The code is hidden in ambient mode and from
+ * screenshots, like the restore screens. [pairRequests] counts the phone's requests to open this screen that came
+ * while it showed: each one starts waiting anew when the last pairing has ended.
+ */
+@Composable
+fun PairScreen(
+ pairRequests: Int,
+ onClose: () -> Unit,
+ onWalletReceive: () -> Unit,
+ modifier: Modifier = Modifier,
+ viewModel: PairViewModel = hiltViewModel(),
+) {
+ val uiState by viewModel.uiState.collectAsStateWithLifecycle()
+ val currentOnClose by rememberUpdatedState(onClose)
+ val currentOnWalletReceive by rememberUpdatedState(onWalletReceive)
+ val step = uiState.step
+ LaunchedEffect(pairRequests) {
+ if (pairRequests > 0) viewModel.onPairRequest()
+ }
+ LaunchedEffect(step) {
+ when (step) {
+ is PairStep.Done -> {
+ delay(RESULT_TIME)
+ if (step.isWalletReceived) currentOnWalletReceive() else currentOnClose()
+ }
+ is PairStep.Failed -> {
+ if (step.failure != PairFailure.Dismissed) delay(RESULT_TIME)
+ currentOnClose()
+ }
+ else -> Unit
+ }
+ }
+ BlockScreenshots()
+ ScreenAwake()
+ Content(
+ step = step,
+ isAmbient = isAmbient(),
+ onConfirmClick = viewModel::onConfirmClick,
+ modifier = modifier
+ )
+}
+
+@Composable
+private fun Content(
+ step: PairStep,
+ isAmbient: Boolean,
+ onConfirmClick: () -> Unit,
+ modifier: Modifier = Modifier,
+) {
+ val code = (step as? PairStep.Code)?.takeUnless { isAmbient }
+ CenteredScreen(
+ edgeButton = code?.let { { ConfirmButton(onConfirmClick) } },
+ overlay = { if (step is PairStep.Waiting || step is PairStep.Working) BezelLoading() },
+ modifier = modifier.testTag("WatchPairScreen")
+ ) {
+ when (step) {
+ PairStep.Waiting -> Message(R.drawable.ic_phone, R.string.pair__waiting, "WatchPairWaiting")
+ PairStep.Working -> Message(R.drawable.ic_phone, null, "WatchPairWorking")
+ is PairStep.Done -> Message(R.drawable.ic_check, R.string.pair__done, "WatchPairDone")
+ is PairStep.Failed -> if (step.failure != PairFailure.Dismissed) {
+ Message(R.drawable.ic_close, failureText(step.failure), "WatchPairError", isError = true)
+ }
+ is PairStep.Code -> code?.let { Code(it) }
+ }
+ }
+}
+
+@Composable
+private fun Code(step: PairStep.Code) {
+ Text(
+ text = step.phoneName,
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ maxLines = 1,
+ modifier = Modifier.testTag("WatchPairPhone")
+ )
+ Text(
+ text = step.code,
+ style = MaterialTheme.typography.displaySmall,
+ textAlign = TextAlign.Center,
+ maxLines = 1,
+ modifier = Modifier.testTag("WatchPairCode")
+ )
+}
+
+@Composable
+private fun ConfirmButton(onClick: () -> Unit) {
+ EdgeButton(
+ onClick = onClick,
+ buttonSize = EdgeButtonSize.Small,
+ modifier = Modifier.testTag("WatchPairConfirm")
+ ) {
+ Text(text = stringResource(R.string.pair__confirm), maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
+}
+
+@Composable
+private fun Message(
+ icon: Int,
+ text: Int?,
+ testTag: String,
+ isError: Boolean = false,
+) {
+ Icon(
+ painter = painterResource(icon),
+ contentDescription = null,
+ tint = if (isError) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
+ modifier = Modifier.size(32.dp)
+ )
+ text?.let {
+ Text(
+ text = stringResource(it),
+ style = MaterialTheme.typography.titleMedium,
+ textAlign = TextAlign.Center,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.testTag(testTag)
+ )
+ }
+}
+
+private fun failureText(failure: PairFailure): Int = when (failure) {
+ PairFailure.Dismissed, PairFailure.Cancelled -> R.string.pair__error_cancelled
+ PairFailure.TimedOut -> R.string.pair__error_timeout
+ PairFailure.DifferentWallet -> R.string.pair__error_different_wallet
+ PairFailure.UpdateRequired -> R.string.pair__error_update
+ PairFailure.Unverified -> R.string.pair__error_unverified
+ PairFailure.InsecureKey -> R.string.restore__error_insecure
+ PairFailure.Failed -> R.string.pair__error_failed
+}
+
+@WearPreviewDevices
+@Composable
+private fun PreviewCode() {
+ WearPreview {
+ Content(
+ step = PairStep.Code("048213", "Pixel 9"),
+ isAmbient = false,
+ onConfirmClick = {},
+ )
+ }
+}
+
+@WearPreviewDevices
+@Composable
+private fun PreviewFailed() {
+ WearPreview {
+ Content(
+ step = PairStep.Failed(PairFailure.DifferentWallet),
+ isAmbient = false,
+ onConfirmClick = {},
+ )
+ }
+}
diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/pair/PairViewModel.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/pair/PairViewModel.kt
new file mode 100644
index 0000000000..8cb9d69eb7
--- /dev/null
+++ b/wear/src/main/java/to/bitkit/wear/ui/screens/pair/PairViewModel.kt
@@ -0,0 +1,141 @@
+package to.bitkit.wear.ui.screens.pair
+
+import androidx.compose.runtime.Immutable
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.viewModelScope
+import dagger.hilt.android.lifecycle.HiltViewModel
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+import to.bitkit.wear.data.ForegroundMonitor
+import to.bitkit.wear.repositories.PhoneLinkRepo
+import to.bitkit.wear.repositories.WatchPairingStatus
+import to.bitkit.wearlink.AbortReason
+import to.bitkit.wearlink.LinkError
+import to.bitkit.wearlink.PairingState
+import to.bitkit.wearlink.StoreFailure
+import javax.inject.Inject
+
+/**
+ * Runs the watch's side of a pairing for as long as the Pair screen shows: it starts waiting for the phone when the
+ * screen opens and cancels when the screen closes or the app leaves the screen.
+ */
+@HiltViewModel
+class PairViewModel @Inject constructor(
+ private val phoneLinkRepo: PhoneLinkRepo,
+ foregroundMonitor: ForegroundMonitor,
+) : ViewModel() {
+ private val _uiState = MutableStateFlow(PairUiState())
+ val uiState: StateFlow = _uiState.asStateFlow()
+
+ private var isRequestPending = false
+
+ init {
+ phoneLinkRepo.startPairing()
+ viewModelScope.launch {
+ phoneLinkRepo.pairing.collect { status -> onStatus(status) }
+ }
+ viewModelScope.launch {
+ foregroundMonitor.isForeground.collect { isForeground -> if (!isForeground) phoneLinkRepo.cancelPairing() }
+ }
+ }
+
+ /**
+ * The phone asked for this screen while it already showed: a pairing that failed starts waiting anew, so the
+ * phone's retry is answered. One that runs past its hello goes on, and the request is kept: when that pairing
+ * fails or the phone aborts it, as when the request overtook the abort of the pairing it replaces, the screen
+ * waits anew. A pairing the wearer dismissed, or one that paired, drops the request.
+ */
+ fun onPairRequest() {
+ if (phoneLinkRepo.pairing.value is WatchPairingStatus.Paired) return
+ phoneLinkRepo.startPairing()
+ val status = phoneLinkRepo.pairing.value
+ isRequestPending = status is WatchPairingStatus.Running && status.state != PairingState.Connecting
+ }
+
+ fun onConfirmClick() {
+ val step = _uiState.value.step as? PairStep.Code ?: return
+ phoneLinkRepo.confirmPairing(step.code)
+ }
+
+ override fun onCleared() {
+ phoneLinkRepo.cancelPairing()
+ }
+
+ private fun onStatus(status: WatchPairingStatus) {
+ if (status !is WatchPairingStatus.Running) {
+ val isRestart = isRequestPending && status is WatchPairingStatus.Failed &&
+ failure(status.error) != PairFailure.Dismissed
+ isRequestPending = false
+ if (isRestart) {
+ phoneLinkRepo.startPairing()
+ return
+ }
+ }
+ _uiState.update { it.copy(step = step(status)) }
+ }
+
+ private fun step(status: WatchPairingStatus): PairStep = when (status) {
+ WatchPairingStatus.Idle -> PairStep.Waiting
+ is WatchPairingStatus.Paired -> PairStep.Done(status.isWalletReceived)
+ is WatchPairingStatus.Failed -> PairStep.Failed(failure(status.error))
+ is WatchPairingStatus.Running -> when (val state = status.state) {
+ PairingState.Connecting -> PairStep.Waiting
+ PairingState.Transferring -> PairStep.Working
+ is PairingState.Code if state.isConfirmed -> PairStep.Working
+ is PairingState.Code -> PairStep.Code(state.code, state.peerName)
+ }
+ }
+
+ private fun failure(error: Throwable): PairFailure = when (error) {
+ is LinkError.Cancelled -> PairFailure.Dismissed
+ is LinkError.Timeout -> PairFailure.TimedOut
+ is LinkError.DifferentWallet -> PairFailure.DifferentWallet
+ is LinkError.UpdateRequired -> PairFailure.UpdateRequired
+ is LinkError.TransferFailed if error.reason == StoreFailure.InsecureKey -> PairFailure.InsecureKey
+ is LinkError.PeerAborted -> when (error.reason) {
+ AbortReason.Cancelled -> PairFailure.Cancelled
+ AbortReason.DifferentWallet -> PairFailure.DifferentWallet
+ AbortReason.UpdateRequired -> PairFailure.UpdateRequired
+ AbortReason.Unverified -> PairFailure.Unverified
+ AbortReason.Failed -> PairFailure.Failed
+ }
+ else -> PairFailure.Failed
+ }
+}
+
+@Immutable
+data class PairUiState(val step: PairStep = PairStep.Waiting)
+
+sealed interface PairStep {
+ /** Waiting for the phone to start. */
+ data object Waiting : PairStep
+
+ /** The code to compare with the phone's, and the phone's name. */
+ data class Code(val code: String, val phoneName: String) : PairStep
+
+ /** Confirmed here; waiting for the phone, or for the wallet to arrive. */
+ data object Working : PairStep
+
+ data class Done(val isWalletReceived: Boolean) : PairStep
+
+ data class Failed(val failure: PairFailure) : PairStep
+}
+
+enum class PairFailure {
+ /** The wearer cancelled or left; the screen closes without a word. */
+ Dismissed,
+
+ /** The phone's user cancelled. */
+ Cancelled,
+ TimedOut,
+ DifferentWallet,
+ UpdateRequired,
+
+ /** The phone could not verify this watch's secure hardware, so it sent no wallet. */
+ Unverified,
+ InsecureKey,
+ Failed,
+}
diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveQrScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveQrScreen.kt
index 91bff85e26..c241240bd2 100644
--- a/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveQrScreen.kt
+++ b/wear/src/main/java/to/bitkit/wear/ui/screens/receive/ReceiveQrScreen.kt
@@ -29,11 +29,14 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.LifecycleResumeEffect
import androidx.lifecycle.compose.LifecycleStartEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import androidx.wear.compose.material3.EdgeButton
+import androidx.wear.compose.material3.EdgeButtonSize
import androidx.wear.compose.material3.FilledTonalIconButton
import androidx.wear.compose.material3.Icon
import androidx.wear.compose.material3.IconButtonDefaults
@@ -120,8 +123,8 @@ internal fun receiveNfcHintState(
* shows. After [QR_AWAKE_LIMIT] without a touch it rests: the QR hides behind a dimmed icon and the screen may turn
* off again, so a forgotten QR does not drain the battery; a tap, or waking the watch from ambient mode, shows it
* again, as does a tap anywhere on the resting screen. Ambient mode hides it. A paid invoice turns into a check with
- * the amount and its own haptic; a tap on the check makes a new invoice. In ambient mode the check shows without
- * the amount, as the always-on screen shows no amount.
+ * the amount and its own haptic, above the button that makes a new invoice; the check itself is no button. In
+ * ambient mode the check shows without the amount and without the button, as the always-on screen shows no amount.
*
* While the QR shows, the watch also offers the invoice as an NFC tag, as the phone's Receive does, with the NFC
* hint below the QR: see [receiveTagUri].
@@ -317,12 +320,15 @@ private fun Paid(
modifier: Modifier = Modifier,
) {
val isDimmed = amount == null
- CenteredScreen(modifier = modifier) {
+ CenteredScreen(
+ edgeButton = amount?.let { { NewInvoiceButton(onClick) } },
+ modifier = modifier
+ ) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
- verticalArrangement = Arrangement.spacedBy(8.dp),
+ verticalArrangement = Arrangement.spacedBy(4.dp),
modifier = Modifier
- .clickableAlpha(onClickLabel = stringResource(R.string.receive__new), onClick = onClick)
+ .semantics(mergeDescendants = true) {}
.testTag("WatchReceivePaid")
) {
Icon(
@@ -336,6 +342,17 @@ private fun Paid(
}
}
+@Composable
+private fun NewInvoiceButton(onClick: () -> Unit) {
+ EdgeButton(
+ onClick = onClick,
+ buttonSize = EdgeButtonSize.Small,
+ modifier = Modifier.testTag("WatchReceiveNew")
+ ) {
+ Text(text = stringResource(R.string.receive__new), maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
+}
+
@Composable
private fun Error(
onRetryClick: () -> Unit,
diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/settings/SettingsScreen.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/settings/SettingsScreen.kt
index ba1e9ae17e..6d4244fa47 100644
--- a/wear/src/main/java/to/bitkit/wear/ui/screens/settings/SettingsScreen.kt
+++ b/wear/src/main/java/to/bitkit/wear/ui/screens/settings/SettingsScreen.kt
@@ -2,6 +2,7 @@ package to.bitkit.wear.ui.screens.settings
import android.text.format.DateUtils
import androidx.annotation.DrawableRes
+import androidx.annotation.StringRes
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
@@ -14,6 +15,7 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTagsAsResourceId
import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.text.style.TextOverflow
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.wear.compose.material3.AlertDialog
@@ -36,6 +38,7 @@ import to.bitkit.wear.ui.screens.activity.rememberNowSecs
@Composable
fun SettingsScreen(
onAboutClick: () -> Unit,
+ onPairClick: () -> Unit,
modifier: Modifier = Modifier,
viewModel: SettingsViewModel = hiltViewModel(),
) {
@@ -46,6 +49,10 @@ fun SettingsScreen(
uiState = uiState,
nowMs = rememberNowSecs(loadedSecs = syncedSecs) * DateUtils.SECOND_IN_MILLIS,
onAboutClick = onAboutClick,
+ onPairClick = onPairClick,
+ onUnpairClick = viewModel::onUnpairClick,
+ onUnpairConfirm = viewModel::onUnpairConfirm,
+ onUnpairDismiss = viewModel::onUnpairDismiss,
onSyncClick = viewModel::onSyncClick,
onRemoveClick = viewModel::onRemoveClick,
onRemoveConfirm = viewModel::onRemoveConfirm,
@@ -59,6 +66,10 @@ private fun Content(
uiState: SettingsUiState,
nowMs: Long,
onAboutClick: () -> Unit,
+ onPairClick: () -> Unit,
+ onUnpairClick: () -> Unit,
+ onUnpairConfirm: () -> Unit,
+ onUnpairDismiss: () -> Unit,
onSyncClick: () -> Unit,
onRemoveClick: () -> Unit,
onRemoveConfirm: () -> Unit,
@@ -109,6 +120,42 @@ private fun Content(
.testTag("WatchSettingsSync")
)
}
+ item {
+ val pairedPhone = uiState.pairedPhone
+ FilledTonalButton(
+ onClick = if (pairedPhone == null) onPairClick else onUnpairClick,
+ enabled = !uiState.isRemoving && !uiState.isUnpairing,
+ icon = { RowIcon(R.drawable.ic_phone) },
+ label = {
+ val label = if (pairedPhone == null) R.string.settings__pair else R.string.settings__phone
+ Text(stringResource(label))
+ },
+ secondaryLabel = pairedPhone?.let { name ->
+ {
+ Text(text = name, maxLines = 1, modifier = Modifier.testTag("WatchSettingsPairedName"))
+ }
+ },
+ transformation = SurfaceTransformation(spec),
+ modifier = Modifier
+ .fillMaxWidth()
+ .transformedHeight(this, spec)
+ .testTag(if (pairedPhone == null) "WatchSettingsPair" else "WatchSettingsPaired")
+ )
+ }
+ if (uiState.isUnpairFailed && uiState.pairedPhone != null) {
+ item {
+ Text(
+ text = stringResource(R.string.settings__unpair_failed),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.error,
+ textAlign = TextAlign.Center,
+ modifier = Modifier
+ .fillMaxWidth()
+ .transformedHeight(this, spec)
+ .testTag("WatchPhoneUnpairFailed")
+ )
+ }
+ }
if (uiState.isSyncFailed) {
item {
Text(
@@ -157,22 +204,60 @@ private fun Content(
}
if (uiState.isRemoving || uiState.isSyncing) BezelLoading()
}
+ ConfirmDialog(
+ isVisible = uiState.isRemoveDialogVisible,
+ title = R.string.settings__remove_wallet_confirm_title,
+ label = R.string.settings__remove_wallet_confirm,
+ testTag = "WatchSettingsRemoveConfirm",
+ onConfirm = onRemoveConfirm,
+ onDismiss = onRemoveDismiss,
+ isDestructive = true,
+ )
+ ConfirmDialog(
+ isVisible = uiState.isUnpairDialogVisible,
+ title = R.string.settings__unpair_confirm_title,
+ label = R.string.settings__unpair_confirm,
+ testTag = "WatchPhoneUnpairConfirm",
+ onConfirm = onUnpairConfirm,
+ onDismiss = onUnpairDismiss,
+ )
+}
+
+/**
+ * A question with the one button that confirms it, named by what it does; swiping the dialog away cancels. A check
+ * icon is never a button on the watch: it only ever says that something succeeded.
+ */
+@Composable
+private fun ConfirmDialog(
+ isVisible: Boolean,
+ @StringRes title: Int,
+ @StringRes label: Int,
+ testTag: String,
+ onConfirm: () -> Unit,
+ onDismiss: () -> Unit,
+ isDestructive: Boolean = false,
+) {
AlertDialog(
- visible = uiState.isRemoveDialogVisible,
- onDismissRequest = onRemoveDismiss,
- title = { Text(stringResource(R.string.settings__remove_wallet_confirm_title)) },
- confirmButton = {
- AlertDialogDefaults.ConfirmButton(
- onClick = onRemoveConfirm,
- modifier = Modifier.testTag("WatchSettingsRemoveConfirm")
- )
- },
- dismissButton = {
- AlertDialogDefaults.DismissButton(
- onClick = onRemoveDismiss,
- modifier = Modifier.testTag("WatchSettingsRemoveCancel")
- )
+ visible = isVisible,
+ onDismissRequest = onDismiss,
+ edgeButton = {
+ val colors = if (isDestructive) {
+ ButtonDefaults.buttonColors(
+ containerColor = MaterialTheme.colorScheme.error,
+ contentColor = MaterialTheme.colorScheme.onError,
+ )
+ } else {
+ ButtonDefaults.buttonColors()
+ }
+ AlertDialogDefaults.EdgeButton(
+ onClick = onConfirm,
+ colors = colors,
+ modifier = Modifier.testTag(testTag)
+ ) {
+ Text(text = stringResource(label), maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
},
+ title = { Text(stringResource(title)) },
modifier = Modifier.semantics { testTagsAsResourceId = true }
)
}
@@ -201,6 +286,30 @@ private fun Preview() {
uiState = SettingsUiState(phoneSyncedAtMs = 0, isSyncFailed = true),
nowMs = 120_000,
onAboutClick = {},
+ onPairClick = {},
+ onUnpairClick = {},
+ onUnpairConfirm = {},
+ onUnpairDismiss = {},
+ onSyncClick = {},
+ onRemoveClick = {},
+ onRemoveConfirm = {},
+ onRemoveDismiss = {},
+ )
+ }
+}
+
+@WearPreviewDevices
+@Composable
+private fun PreviewUnpairConfirm() {
+ WearPreview {
+ Content(
+ uiState = SettingsUiState(pairedPhone = "Pixel 9", isUnpairDialogVisible = true),
+ nowMs = 0,
+ onAboutClick = {},
+ onPairClick = {},
+ onUnpairClick = {},
+ onUnpairConfirm = {},
+ onUnpairDismiss = {},
onSyncClick = {},
onRemoveClick = {},
onRemoveConfirm = {},
@@ -217,6 +326,10 @@ private fun PreviewRemoveConfirm() {
uiState = SettingsUiState(isRemoveDialogVisible = true),
nowMs = 0,
onAboutClick = {},
+ onPairClick = {},
+ onUnpairClick = {},
+ onUnpairConfirm = {},
+ onUnpairDismiss = {},
onSyncClick = {},
onRemoveClick = {},
onRemoveConfirm = {},
diff --git a/wear/src/main/java/to/bitkit/wear/ui/screens/settings/SettingsViewModel.kt b/wear/src/main/java/to/bitkit/wear/ui/screens/settings/SettingsViewModel.kt
index 0ca553a1d4..8cdb0224e9 100644
--- a/wear/src/main/java/to/bitkit/wear/ui/screens/settings/SettingsViewModel.kt
+++ b/wear/src/main/java/to/bitkit/wear/ui/screens/settings/SettingsViewModel.kt
@@ -12,6 +12,7 @@ import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import to.bitkit.wear.data.SettingsStore
+import to.bitkit.wear.repositories.PhoneLinkRepo
import to.bitkit.wear.repositories.SettingsSyncRepo
import to.bitkit.wear.repositories.WalletRepo
import javax.inject.Inject
@@ -20,6 +21,7 @@ import javax.inject.Inject
class SettingsViewModel @Inject constructor(
private val walletRepo: WalletRepo,
private val settingsSyncRepo: SettingsSyncRepo,
+ private val phoneLinkRepo: PhoneLinkRepo,
settingsStore: SettingsStore,
) : ViewModel() {
private val _uiState = MutableStateFlow(SettingsUiState())
@@ -31,6 +33,29 @@ class SettingsViewModel @Inject constructor(
_uiState.update { it.copy(phoneSyncedAtMs = syncedAtMs) }
}
}
+ viewModelScope.launch {
+ phoneLinkRepo.record.map { it?.peerName }.distinctUntilChanged().collect { name ->
+ _uiState.update { it.copy(pairedPhone = name, isUnpairDialogVisible = false, isUnpairFailed = false) }
+ }
+ }
+ }
+
+ fun onUnpairClick() {
+ _uiState.update { it.copy(isUnpairDialogVisible = true, isUnpairFailed = false) }
+ }
+
+ fun onUnpairDismiss() {
+ _uiState.update { it.copy(isUnpairDialogVisible = false) }
+ }
+
+ /** Forgets the paired phone, after telling it. The wallet stays on the watch. */
+ fun onUnpairConfirm() {
+ if (_uiState.value.isUnpairing) return
+ _uiState.update { it.copy(isUnpairDialogVisible = false, isUnpairing = true, isUnpairFailed = false) }
+ viewModelScope.launch {
+ phoneLinkRepo.unpair().onFailure { _uiState.update { it.copy(isUnpairFailed = true) } }
+ _uiState.update { it.copy(isUnpairing = false) }
+ }
}
/**
@@ -62,6 +87,8 @@ class SettingsViewModel @Inject constructor(
if (_uiState.value.isRemoving) return
_uiState.update { it.copy(isRemoveDialogVisible = false, isRemoving = true, isRemoveFailed = false) }
viewModelScope.launch {
+ // The phone is told while the link keys still exist; the wipe then takes the pairing with the settings.
+ phoneLinkRepo.unpair()
walletRepo.wipe().onFailure { _uiState.update { it.copy(isRemoveFailed = true) } }
_uiState.update { it.copy(isRemoving = false) }
}
@@ -77,4 +104,9 @@ data class SettingsUiState(
val isSyncFailed: Boolean = false,
/** When the phone's settings were last imported, in epoch milliseconds, or null when there is no import. */
val phoneSyncedAtMs: Long? = null,
+ /** The name of the paired phone, or null when none is paired. */
+ val pairedPhone: String? = null,
+ val isUnpairDialogVisible: Boolean = false,
+ val isUnpairing: Boolean = false,
+ val isUnpairFailed: Boolean = false,
)
diff --git a/wear/src/main/res/drawable/ic_phone.xml b/wear/src/main/res/drawable/ic_phone.xml
new file mode 100644
index 0000000000..483583de6f
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_phone.xml
@@ -0,0 +1,11 @@
+
+
+
+
+
diff --git a/wear/src/main/res/raw/keep.xml b/wear/src/main/res/raw/keep.xml
new file mode 100644
index 0000000000..89c9e52cde
--- /dev/null
+++ b/wear/src/main/res/raw/keep.xml
@@ -0,0 +1,5 @@
+
+
+
diff --git a/wear/src/main/res/values-ar/strings.xml b/wear/src/main/res/values-ar/strings.xml
index 18fcf93f9f..7845d30348 100644
--- a/wear/src/main/res/values-ar/strings.xml
+++ b/wear/src/main/res/values-ar/strings.xml
@@ -19,7 +19,17 @@
تبديل الوحدة
فتح إعدادات NFC
طلب دفع Bitkit
+ من الهاتف
استعادة
+ متطابقة
+ تم الإقران
+ تم الإلغاء
+ محفظة مختلفة
+ تعذّر الإقران
+ انتهت المهلة
+ الساعة غير موثّقة
+ تحديث Bitkit
+ ابدأ من الهاتف
تعذّر إنشاء الفاتورة
رمز QR مخفي
فاتورة جديدة
@@ -72,12 +82,18 @@
تم الإرسال
تحقق من النشاط
في انتظار الشبكة
+ إقران الهاتف
+ الهاتف
إعدادات الهاتف
تعذّر الاستيراد
إزالة المحفظة
+ إزالة
إزالة المحفظة؟
تعذّرت إزالة المحفظة
الإعدادات
+ إلغاء الإقران
+ إلغاء إقران الهاتف؟
+ تعذّر إلغاء الإقران
لا يتوفر Spark على هذه الشبكة
غير متاح على الشبكة الرئيسية بعد
غير مدعوم
diff --git a/wear/src/main/res/values-b+es+419/strings.xml b/wear/src/main/res/values-b+es+419/strings.xml
index c53dab797a..1ab4c8f1b1 100644
--- a/wear/src/main/res/values-b+es+419/strings.xml
+++ b/wear/src/main/res/values-b+es+419/strings.xml
@@ -19,7 +19,17 @@
Cambiar unidad
Abrir ajustes de NFC
Solicitud de pago de Bitkit
+ Desde el teléfono
Restaurar
+ Coinciden
+ Vinculado
+ Cancelado
+ Otra billetera
+ No se pudo vincular
+ Tiempo agotado
+ Reloj no verificado
+ Actualizar Bitkit
+ Ve al teléfono
No se creó la factura
QR oculto
Nueva factura
@@ -69,12 +79,18 @@
Enviado
Revisa la actividad
Esperando la red
+ Vincular teléfono
+ Teléfono
Ajustes del teléfono
No se pudo importar
Eliminar billetera
+ Eliminar
¿Eliminar billetera?
No se pudo eliminar la billetera
Ajustes
+ Desvincular
+ ¿Desvincular teléfono?
+ Error al desvincular
No hay Spark en esta red
Aún no en mainnet
No compatible
diff --git a/wear/src/main/res/values-ca/strings.xml b/wear/src/main/res/values-ca/strings.xml
index 80aa892a73..151f8aeaba 100644
--- a/wear/src/main/res/values-ca/strings.xml
+++ b/wear/src/main/res/values-ca/strings.xml
@@ -19,7 +19,17 @@
Canvia la unitat
Obre la configuració de l\'NFC
Sol·licitud de pagament de Bitkit
+ Des del telèfon
Restaurar
+ Coincideixen
+ Vinculat
+ Cancel·lat
+ Cartera diferent
+ Vinculació fallida
+ Temps esgotat
+ No verificat
+ Actualitza Bitkit
+ Comença al telèfon
No s\'ha creat la factura
QR amagat
Nova factura
@@ -31,7 +41,7 @@
Revisa
Frase no vàlida
No s\'ha pogut desar la cartera
- Sense maquinari segur
+ Maquinari no segur
- %1$d paraula
- %1$d paraules
@@ -69,12 +79,18 @@
Enviat
Revisa l\'activitat
Esperant la xarxa
+ Vincula el telèfon
+ Telèfon
Configuració del telèfon
No s\'ha pogut importar
Elimina la cartera
+ Elimina
Eliminar la cartera?
No s\'ha pogut eliminar la cartera
Configuracions
+ Desvincula
+ Desvincular el telèfon?
+ Error en desvincular
No hi ha Spark en aquesta xarxa
Encara no a mainnet
No compatible
diff --git a/wear/src/main/res/values-cs/strings.xml b/wear/src/main/res/values-cs/strings.xml
index f1e0cb3fb1..e5ab31a9ae 100644
--- a/wear/src/main/res/values-cs/strings.xml
+++ b/wear/src/main/res/values-cs/strings.xml
@@ -19,7 +19,17 @@
Přepnout jednotku
Otevřít nastavení NFC
Žádost o platbu Bitkit
+ Z telefonu
Obnovit
+ Shodují se
+ Spárováno
+ Zrušeno
+ Jiná peněženka
+ Párování selhalo
+ Čas vypršel
+ Hodinky neověřeny
+ Aktualizujte Bitkit
+ Začněte v telefonu
Fakturu nelze vytvořit
QR skryt
Nová faktura
@@ -31,7 +41,7 @@
Zkontrolovat
Neplatná fráze
Peněženku nelze uložit
- Chybí bezpečný hardware
+ Chybí bezpečný čip
- %1$d slovo
- %1$d slova
@@ -70,12 +80,18 @@
Odesláno
Zkontrolujte aktivitu
Čekání na síť
+ Spárovat telefon
+ Telefon
Nastavení telefonu
Import se nezdařil
Odebrat peněženku
+ Odebrat
Odebrat peněženku?
Peněženku nelze odebrat
Nastavení
+ Odpárovat
+ Zrušit spárování?
+ Odpárování selhalo
Spark v této síti není
Na mainnetu zatím ne
Nepodporováno
diff --git a/wear/src/main/res/values-de/strings.xml b/wear/src/main/res/values-de/strings.xml
index cad9a3be67..b603b3193f 100644
--- a/wear/src/main/res/values-de/strings.xml
+++ b/wear/src/main/res/values-de/strings.xml
@@ -19,7 +19,17 @@
Einheit wechseln
NFC-Einstellungen öffnen
Bitkit-Zahlungsanforderung
+ Vom Telefon
Wiederherstellen
+ Stimmt
+ Gekoppelt
+ Abgebrochen
+ Anderes Wallet
+ Nicht gekoppelt
+ Zeit abgelaufen
+ Nicht verifiziert
+ Bitkit aktualisieren
+ Am Telefon starten
Rechnung nicht erstellt
QR versteckt
Neue Rechnung
@@ -31,7 +41,7 @@
Prüfen
Ungültige Phrase
Wallet konnte nicht gespeichert werden
- Keine sichere Hardware
+ Unsichere Hardware
- %1$d Wort
- %1$d Wörter
@@ -68,12 +78,18 @@
Gesendet
Aktivität prüfen
Warte auf Netzwerk
+ Telefon koppeln
+ Telefon
Telefon-Einstellungen
Import fehlgeschlagen
Wallet entfernen
+ Entfernen
Wallet entfernen?
Wallet konnte nicht entfernt werden
Einstellungen
+ Entkoppeln
+ Telefon entkoppeln?
+ Nicht entkoppelt
Kein Spark in diesem Netzwerk
Noch nicht im Mainnet
Nicht unterstützt
diff --git a/wear/src/main/res/values-el/strings.xml b/wear/src/main/res/values-el/strings.xml
index f80d5407a7..b785b869a4 100644
--- a/wear/src/main/res/values-el/strings.xml
+++ b/wear/src/main/res/values-el/strings.xml
@@ -19,7 +19,17 @@
Αλλαγή μονάδας
Άνοιγμα ρυθμίσεων NFC
Αίτημα πληρωμής Bitkit
+ Από το τηλέφωνο
Επαναφορά
+ Ταιριάζουν
+ Συζεύχθηκε
+ Ακυρώθηκε
+ Άλλο πορτοφόλι
+ Αποτυχία σύζευξης
+ Έληξε ο χρόνος
+ Μη επαληθευμένο
+ Ενημέρωση Bitkit
+ Ξεκίνα στο τηλέφωνο
Αποτυχία τιμολογίου
QR κρυφό
Νέο τιμολόγιο
@@ -68,12 +78,18 @@
Στάλθηκε
Δες τη δραστηριότητα
Αναμονή για δίκτυο
+ Σύζευξη τηλεφώνου
+ Τηλέφωνο
Ρυθμίσεις τηλεφώνου
Αδυναμία εισαγωγής
Αφαίρεση πορτοφολιού
+ Αφαίρεση
Αφαίρεση πορτοφολιού;
Αδυναμία αφαίρεσης πορτοφολιού
Ρυθμίσεις
+ Αποσύζευξη
+ Αποσύζευξη τηλεφώνου;
+ Αποτυχία αποσύζευξης
Δεν υπάρχει Spark σε αυτό το δίκτυο
Όχι ακόμη στο mainnet
Δεν υποστηρίζεται
diff --git a/wear/src/main/res/values-es-rES/strings.xml b/wear/src/main/res/values-es-rES/strings.xml
index d94ea02061..cecb4b4b63 100644
--- a/wear/src/main/res/values-es-rES/strings.xml
+++ b/wear/src/main/res/values-es-rES/strings.xml
@@ -19,7 +19,17 @@
Cambiar unidad
Abrir ajustes de NFC
Solicitud de pago de Bitkit
+ Desde el teléfono
Restaurar
+ Coinciden
+ Vinculado
+ Cancelado
+ Otra cartera
+ No se pudo vincular
+ Tiempo agotado
+ Reloj no verificado
+ Actualizar Bitkit
+ Ve al teléfono
No se creó la factura
QR oculto
Nueva factura
@@ -69,12 +79,18 @@
Enviado
Revisa la actividad
Esperando a la red
+ Vincular teléfono
+ Teléfono
Ajustes del teléfono
No se pudo importar
Eliminar cartera
+ Eliminar
¿Eliminar cartera?
No se pudo eliminar la cartera
Ajustes
+ Desvincular
+ ¿Desvincular teléfono?
+ Error al desvincular
No hay Spark en esta red
Aún no en mainnet
No compatible
diff --git a/wear/src/main/res/values-es/strings.xml b/wear/src/main/res/values-es/strings.xml
index d94ea02061..cecb4b4b63 100644
--- a/wear/src/main/res/values-es/strings.xml
+++ b/wear/src/main/res/values-es/strings.xml
@@ -19,7 +19,17 @@
Cambiar unidad
Abrir ajustes de NFC
Solicitud de pago de Bitkit
+ Desde el teléfono
Restaurar
+ Coinciden
+ Vinculado
+ Cancelado
+ Otra cartera
+ No se pudo vincular
+ Tiempo agotado
+ Reloj no verificado
+ Actualizar Bitkit
+ Ve al teléfono
No se creó la factura
QR oculto
Nueva factura
@@ -69,12 +79,18 @@
Enviado
Revisa la actividad
Esperando a la red
+ Vincular teléfono
+ Teléfono
Ajustes del teléfono
No se pudo importar
Eliminar cartera
+ Eliminar
¿Eliminar cartera?
No se pudo eliminar la cartera
Ajustes
+ Desvincular
+ ¿Desvincular teléfono?
+ Error al desvincular
No hay Spark en esta red
Aún no en mainnet
No compatible
diff --git a/wear/src/main/res/values-fr/strings.xml b/wear/src/main/res/values-fr/strings.xml
index db0d89cd75..d98eed8148 100644
--- a/wear/src/main/res/values-fr/strings.xml
+++ b/wear/src/main/res/values-fr/strings.xml
@@ -19,7 +19,17 @@
Changer d\'unité
Ouvrir les réglages NFC
Demande de paiement Bitkit
+ Depuis le téléphone
Restaurer
+ Identiques
+ Associée
+ Annulé
+ Autre wallet
+ Association échouée
+ Délai dépassé
+ Montre non vérifiée
+ Mettre à jour Bitkit
+ Depuis le téléphone
Facture non créée
QR masqué
Nouvelle facture
@@ -31,7 +41,7 @@
Vérifier
Phrase invalide
Impossible d\'enregistrer le wallet
- Aucun matériel sécurisé
+ Matériel non sûr
- %1$d mot
- %1$d mots
@@ -69,12 +79,18 @@
Envoyé
Voir l\'activité
En attente du réseau
+ Associer le téléphone
+ Téléphone
Paramètres du téléphone
Échec de l\'importation
Supprimer le wallet
+ Supprimer
Supprimer le wallet ?
Impossible de supprimer le wallet
Paramètres
+ Dissocier
+ Dissocier le téléphone ?
+ Dissociation échouée
Pas de Spark sur ce réseau
Pas encore sur le mainnet
Non pris en charge
diff --git a/wear/src/main/res/values-it/strings.xml b/wear/src/main/res/values-it/strings.xml
index 454a7ede8c..4e6a4001c4 100644
--- a/wear/src/main/res/values-it/strings.xml
+++ b/wear/src/main/res/values-it/strings.xml
@@ -19,7 +19,17 @@
Cambia unità
Apri impostazioni NFC
Richiesta di pagamento Bitkit
+ Dal telefono
Ripristina
+ Uguali
+ Associato
+ Annullato
+ Portafoglio diverso
+ Associazione fallita
+ Tempo scaduto
+ Non verificato
+ Aggiorna Bitkit
+ Avvia dal telefono
Fattura non creata
QR nascosto
Nuova fattura
@@ -31,7 +41,7 @@
Rivedi
Frase non valida
Impossibile salvare il portafoglio
- Nessun hardware sicuro
+ Hardware non sicuro
- %1$d parola
- %1$d parole
@@ -69,12 +79,18 @@
Inviato
Controlla l\'attività
In attesa della rete
+ Associa telefono
+ Telefono
Impostazioni telefono
Importazione non riuscita
Rimuovi portafoglio
+ Rimuovi
Rimuovere il portafoglio?
Impossibile rimuovere il portafoglio
Impostazioni
+ Dissocia
+ Dissociare il telefono?
+ Non dissociato
Spark non disponibile su questa rete
Non ancora su mainnet
Non supportato
diff --git a/wear/src/main/res/values-nl/strings.xml b/wear/src/main/res/values-nl/strings.xml
index cc1b0c5a2e..26e3ce0143 100644
--- a/wear/src/main/res/values-nl/strings.xml
+++ b/wear/src/main/res/values-nl/strings.xml
@@ -19,7 +19,17 @@
Eenheid wisselen
NFC-instellingen openen
Bitkit-betaalverzoek
+ Vanaf telefoon
Herstellen
+ Gelijk
+ Gekoppeld
+ Geannuleerd
+ Andere wallet
+ Koppelen mislukt
+ Time-out
+ Niet geverifieerd
+ Bitkit bijwerken
+ Start op telefoon
Factuur niet gemaakt
QR verborgen
Nieuwe factuur
@@ -31,7 +41,7 @@
Controleren
Ongeldige zin
Wallet opslaan mislukt
- Geen veilige hardware
+ Onveilige hardware
- %1$d woord
- %1$d woorden
@@ -68,12 +78,18 @@
Verzonden
Bekijk activiteit
Wachten op netwerk
+ Telefoon koppelen
+ Telefoon
Telefooninstellingen
Importeren mislukt
Wallet verwijderen
+ Verwijderen
Wallet verwijderen?
Wallet verwijderen mislukt
Instellingen
+ Ontkoppelen
+ Telefoon ontkoppelen?
+ Ontkoppelen mislukt
Geen Spark op dit netwerk
Nog niet op mainnet
Niet ondersteund
diff --git a/wear/src/main/res/values-pl/strings.xml b/wear/src/main/res/values-pl/strings.xml
index e855bb5d05..05b66a8e72 100644
--- a/wear/src/main/res/values-pl/strings.xml
+++ b/wear/src/main/res/values-pl/strings.xml
@@ -19,7 +19,17 @@
Zmień jednostkę
Otwórz ustawienia NFC
Żądanie płatności Bitkit
+ Z telefonu
Odzyskaj
+ Zgodne
+ Sparowano
+ Anulowano
+ Inny portfel
+ Błąd parowania
+ Upłynął czas
+ Niezweryfikowany
+ Zaktualizuj Bitkit
+ Zacznij na telefonie
Nie utworzono faktury
QR ukryty
Nowa faktura
@@ -31,7 +41,7 @@
Sprawdź
Nieprawidłowa fraza
Nie udało się zapisać portfela
- Brak bezpiecznego sprzętu
+ Sprzęt niechroniony
- %1$d słowo
- %1$d słowa
@@ -70,12 +80,18 @@
Wysłano
Sprawdź aktywność
Czekam na sieć
+ Sparuj telefon
+ Telefon
Ustawienia telefonu
Import nie powiódł się
Usuń portfel
+ Usuń
Usunąć portfel?
Nie udało się usunąć portfela
Ustawienia
+ Rozłącz
+ Anulować sparowanie?
+ Błąd rozłączania
Brak Spark w tej sieci
Jeszcze nie w mainnecie
Nieobsługiwane
diff --git a/wear/src/main/res/values-pt-rBR/strings.xml b/wear/src/main/res/values-pt-rBR/strings.xml
index 40ff1f4193..abc298b387 100644
--- a/wear/src/main/res/values-pt-rBR/strings.xml
+++ b/wear/src/main/res/values-pt-rBR/strings.xml
@@ -19,7 +19,17 @@
Alternar unidade
Abrir configurações de NFC
Solicitação de pagamento Bitkit
+ Do celular
Restaurar
+ Coincidem
+ Pareado
+ Cancelado
+ Carteira diferente
+ Falha ao parear
+ Tempo esgotado
+ Não verificado
+ Atualizar Bitkit
+ Inicie no celular
Invoice não criado
QR oculto
Novo invoice
@@ -69,12 +79,18 @@
Enviado
Veja a atividade
Aguardando a rede
+ Parear celular
+ Celular
Ajustes do celular
Não foi possível importar
Remover carteira
+ Remover
Remover carteira?
Não foi possível remover a carteira
Ajustes
+ Desparear
+ Desparear celular?
+ Falha ao desparear
Sem Spark nesta rede
Ainda não na mainnet
Não suportado
diff --git a/wear/src/main/res/values-pt/strings.xml b/wear/src/main/res/values-pt/strings.xml
index 0d1c2f04ff..dc0c261984 100644
--- a/wear/src/main/res/values-pt/strings.xml
+++ b/wear/src/main/res/values-pt/strings.xml
@@ -19,7 +19,17 @@
Alternar unidade
Abrir definições de NFC
Pedido de pagamento Bitkit
+ Do telemóvel
Restaurar
+ Coincidem
+ Emparelhado
+ Cancelado
+ Carteira diferente
+ Falha ao emparelhar
+ Tempo esgotado
+ Não verificado
+ Atualizar Bitkit
+ Inicie no telemóvel
Fatura não criada
QR oculto
Nova fatura
@@ -69,12 +79,18 @@
Enviado
Veja a atividade
À espera da rede
+ Emparelhar telemóvel
+ Telemóvel
Ajustes do telemóvel
Não foi possível importar
Remover carteira
+ Remover
Remover carteira?
Não foi possível remover a carteira
Ajustes
+ Desemparelhar
+ Desemparelhar telemóvel?
+ Não desemparelhado
Sem Spark nesta rede
Ainda não na mainnet
Não suportado
diff --git a/wear/src/main/res/values-ru/strings.xml b/wear/src/main/res/values-ru/strings.xml
index e09029d8e3..5eabc4143f 100644
--- a/wear/src/main/res/values-ru/strings.xml
+++ b/wear/src/main/res/values-ru/strings.xml
@@ -19,7 +19,17 @@
Сменить единицу
Открыть настройки NFC
Запрос на оплату Bitkit
+ С телефона
Восстановить
+ Совпадают
+ Сопряжено
+ Отменено
+ Другой кошелёк
+ Не удалось сопрячь
+ Время истекло
+ Часы не проверены
+ Обновите Bitkit
+ Начните на телефоне
Счёт не создан
QR скрыт
Новый счёт
@@ -31,7 +41,7 @@
Проверить
Неверная фраза
Не удалось сохранить кошелёк
- Нет защищённого модуля
+ Нет защищённого чипа
- %1$d слово
- %1$d слова
@@ -70,12 +80,18 @@
Отправлено
Проверьте активность
Ожидание сети
+ Сопрячь телефон
+ Телефон
Настройки телефона
Не удалось импортировать
Удалить кошелёк
+ Удалить
Удалить кошелёк?
Не удалось удалить кошелёк
Настройки
+ Отключить
+ Отменить сопряжение?
+ Не удалось отключить
Нет Spark в этой сети
Пока нет в основной сети
Не поддерживается
diff --git a/wear/src/main/res/values/strings.xml b/wear/src/main/res/values/strings.xml
index 62ada3d2c4..ee46a726d5 100644
--- a/wear/src/main/res/values/strings.xml
+++ b/wear/src/main/res/values/strings.xml
@@ -19,7 +19,17 @@
Switch unit
Open NFC settings
Bitkit payment request
+ From phone
Restore
+ Match
+ Paired
+ Cancelled
+ Different wallet
+ Couldn\'t pair
+ Timed out
+ Watch not verified
+ Update Bitkit
+ Start on phone
Couldn\'t create invoice
QR hidden
New invoice
@@ -68,12 +78,18 @@
Sent
Check activity
Waiting for network
+ Pair phone
+ Phone
Phone settings
Couldn\'t import
Remove wallet
+ Remove
Remove wallet?
Couldn\'t remove wallet
Settings
+ Unpair
+ Unpair phone?
+ Couldn\'t unpair
No Spark on this network
Not on mainnet yet
Not supported
diff --git a/wear/src/main/res/values/wear.xml b/wear/src/main/res/values/wear.xml
new file mode 100644
index 0000000000..b3676f9c0d
--- /dev/null
+++ b/wear/src/main/res/values/wear.xml
@@ -0,0 +1,8 @@
+
+
+
+
+ - bitkit_watch_v1
+
+
diff --git a/wear/src/release/java/to/bitkit/wear/di/LinkTransportModule.kt b/wear/src/release/java/to/bitkit/wear/di/LinkTransportModule.kt
new file mode 100644
index 0000000000..4336f571d7
--- /dev/null
+++ b/wear/src/release/java/to/bitkit/wear/di/LinkTransportModule.kt
@@ -0,0 +1,18 @@
+package to.bitkit.wear.di
+
+import dagger.Binds
+import dagger.Module
+import dagger.hilt.InstallIn
+import dagger.hilt.components.SingletonComponent
+import to.bitkit.wear.link.DataLayerTransport
+import to.bitkit.wearlink.LinkTransport
+import javax.inject.Singleton
+
+/** A release build reaches the phone over the Wear Data Layer and has no other carrier. */
+@Module
+@InstallIn(SingletonComponent::class)
+abstract class LinkTransportModule {
+ @Binds
+ @Singleton
+ abstract fun bindLinkTransport(transport: DataLayerTransport): LinkTransport
+}
diff --git a/wear/src/test/java/to/bitkit/wear/data/SettingsPhoneStateSinkTest.kt b/wear/src/test/java/to/bitkit/wear/data/SettingsPhoneStateSinkTest.kt
new file mode 100644
index 0000000000..2200ba0b7f
--- /dev/null
+++ b/wear/src/test/java/to/bitkit/wear/data/SettingsPhoneStateSinkTest.kt
@@ -0,0 +1,135 @@
+package to.bitkit.wear.data
+
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.flow.first
+import org.junit.Rule
+import org.junit.Test
+import org.junit.rules.TemporaryFolder
+import to.bitkit.wear.models.BitcoinDisplayUnit
+import to.bitkit.wear.models.PhoneSettings
+import to.bitkit.wear.models.PrimaryDisplay
+import to.bitkit.wear.models.QuickPayLimits
+import to.bitkit.wear.test.BaseUnitTest
+import java.io.File
+import kotlin.test.assertEquals
+import kotlin.test.assertFalse
+import kotlin.test.assertNull
+import kotlin.test.assertTrue
+
+/** Which of the phone's settings holds on the watch when a backup import and a live push disagree. */
+class SettingsPhoneStateSinkTest : BaseUnitTest() {
+ private companion object {
+ val ON = PhoneSettings(PrimaryDisplay.FIAT, BitcoinDisplayUnit.CLASSIC, "EUR", QuickPayLimits(true, 10, 3))
+ val OFF = ON.copy(quickPay = QuickPayLimits(false, 10, 3))
+ }
+
+ @get:Rule
+ val folder = TemporaryFolder()
+
+ private val store by lazy {
+ val dataStore = settingsDataStore(CoroutineScope(Job())) { File(folder.root, "settings.preferences_pb") }
+ SettingsStore(dataStore, WipeMarker(lazy { File(folder.root, "seed") }))
+ }
+ private val sut by lazy { SettingsPhoneStateSink(store) }
+
+ private suspend fun quickPay() = store.data.first().quickPay
+
+ @Test
+ fun `a watch that was never pushed anything imports the backup, whatever its age`() = test {
+ assertTrue(sut.applySettings(ON, PhoneStateSource.Backup(createdAtMs = null), syncedAtMs = 1))
+
+ assertEquals(ON.quickPay, quickPay())
+ assertEquals(1, store.data.first().phoneSyncedAtMs)
+ }
+
+ @Test
+ fun `a backup older than the last push does not undo it`() = test {
+ sut.applySettings(OFF, PhoneStateSource.Push(changedAtMs = 2_000), syncedAtMs = 10)
+
+ val isApplied = sut.applySettings(ON, PhoneStateSource.Backup(createdAtMs = 1_000), syncedAtMs = 20)
+
+ assertFalse(isApplied)
+ assertEquals(OFF.quickPay, quickPay())
+ assertEquals(10, store.data.first().phoneSyncedAtMs)
+ }
+
+ @Test
+ fun `a backup that does not say when it was written does not undo a push`() = test {
+ sut.applySettings(OFF, PhoneStateSource.Push(changedAtMs = 2_000), syncedAtMs = 10)
+
+ assertFalse(sut.applySettings(ON, PhoneStateSource.Backup(createdAtMs = null), syncedAtMs = 20))
+ assertEquals(OFF.quickPay, quickPay())
+ }
+
+ @Test
+ fun `a push from a phone whose clock runs ahead is adopted, and does not shadow the backups after it`() = test {
+ val watchNow = 1_000_000L
+ val ahead = watchNow + 86_400_000L
+ sut.applySettings(ON, PhoneStateSource.Push(changedAtMs = ahead), syncedAtMs = watchNow)
+ assertEquals(ON.quickPay, quickPay())
+ assertEquals(watchNow + SettingsPhoneStateSink.MAX_PUSH_AHEAD.inWholeMilliseconds, store.pushedSettingsAtMs())
+
+ // The phone lost the pairing; its backup, written an hour later by its real clock, turns QuickPay off.
+ val isApplied = sut.applySettings(OFF, PhoneStateSource.Backup(watchNow + 3_600_000L), watchNow + 3_600_000L)
+
+ assertTrue(isApplied)
+ assertEquals(OFF.quickPay, quickPay())
+ }
+
+ @Test
+ fun `a push time within the allowed skew is kept as the phone gave it`() = test {
+ sut.applySettings(ON, PhoneStateSource.Push(changedAtMs = 1_060_000), syncedAtMs = 1_000_000)
+
+ assertEquals(1_060_000, store.pushedSettingsAtMs())
+ }
+
+ @Test
+ fun `a backup written after the last push holds`() = test {
+ sut.applySettings(OFF, PhoneStateSource.Push(changedAtMs = 2_000), syncedAtMs = 10)
+
+ assertTrue(sut.applySettings(ON, PhoneStateSource.Backup(createdAtMs = 3_000), syncedAtMs = 20))
+ assertEquals(ON.quickPay, quickPay())
+ }
+
+ @Test
+ fun `a push holds over any backup, also one with a later time`() = test {
+ sut.applySettings(ON, PhoneStateSource.Backup(createdAtMs = 9_000), syncedAtMs = 10)
+
+ assertTrue(sut.applySettings(OFF, PhoneStateSource.Push(changedAtMs = 2_000), syncedAtMs = 20))
+ assertEquals(OFF.quickPay, quickPay())
+ assertEquals(2_000, store.pushedSettingsAtMs())
+ }
+
+ @Test
+ fun `a missing backup turns QuickPay off only while no push holds`() = test {
+ sut.applySettings(ON, PhoneStateSource.Push(changedAtMs = 2_000), syncedAtMs = 10)
+
+ sut.onSettingsMissing(PhoneStateSource.Backup(createdAtMs = null))
+ assertEquals(ON.quickPay, quickPay())
+
+ sut.onPushSourceGone()
+ sut.onSettingsMissing(PhoneStateSource.Backup(createdAtMs = null))
+ assertNull(quickPay())
+ }
+
+ @Test
+ fun `once the pairing ends an older backup holds again and the pushed settings stay until then`() = test {
+ sut.applySettings(OFF, PhoneStateSource.Push(changedAtMs = 2_000), syncedAtMs = 10)
+
+ sut.onPushSourceGone()
+
+ assertEquals(OFF.quickPay, quickPay())
+ assertTrue(sut.applySettings(ON, PhoneStateSource.Backup(createdAtMs = 1_000), syncedAtMs = 20))
+ assertEquals(ON.quickPay, quickPay())
+ }
+
+ @Test
+ fun `a wipe that takes the imported settings takes the push's time with them`() = test {
+ sut.applySettings(OFF, PhoneStateSource.Push(changedAtMs = 2_000), syncedAtMs = 10)
+
+ store.clearPhoneSettings()
+
+ assertNull(store.pushedSettingsAtMs())
+ }
+}
diff --git a/wear/src/test/java/to/bitkit/wear/link/LinkSourcesTest.kt b/wear/src/test/java/to/bitkit/wear/link/LinkSourcesTest.kt
new file mode 100644
index 0000000000..f2434ddef2
--- /dev/null
+++ b/wear/src/test/java/to/bitkit/wear/link/LinkSourcesTest.kt
@@ -0,0 +1,73 @@
+package to.bitkit.wear.link
+
+import org.junit.Test
+import java.io.File
+import kotlin.test.assertEquals
+import kotlin.test.assertTrue
+
+/**
+ * What the pairing's safety rests on in the watch app's structure, pinned so a later change cannot loosen it
+ * unnoticed: where the Wear Data Layer is named, and the resources Play services reads by name.
+ */
+class LinkSourcesTest {
+ private companion object {
+ const val DATA_LAYER_PACKAGE = "com.google.android.gms.wearable"
+ const val CAPABILITY = "bitkit_watch_v1"
+ }
+
+ private val module: File by lazy {
+ generateSequence(File("").absoluteFile) { it.parentFile }
+ .map { if (it.name == "wear") it else File(it, "wear") }
+ .first { File(it, "src/main/java").isDirectory }
+ }
+
+ private fun sources(sourceSet: String): List =
+ File(module, "src/$sourceSet").walkTopDown().filter { it.isFile && it.extension == "kt" }.toList()
+
+ @Test
+ fun `only the transport and its listener service name the wear data layer`() {
+ val naming = (sources("main") + sources("release"))
+ .filter { DATA_LAYER_PACKAGE in it.readText() }
+ .map { it.name }
+
+ assertEquals(setOf("DataLayerTransport.kt", "LinkListenerService.kt"), naming.toSet())
+ }
+
+ @Test
+ fun `the transport never stores a handshake or seed message as a data item`() {
+ val transport = sources("main").single { it.name == "DataLayerTransport.kt" }.readText()
+ val send = transport.substringAfter("override suspend fun send(")
+ .substringBefore("override suspend fun putState(")
+
+ assertTrue("messageClient.sendMessage" in send)
+ assertTrue("dataClient" !in send)
+ }
+
+ @Test
+ fun `no main or release source names the debug socket carrier or the test fixtures`() {
+ val naming = (sources("main") + sources("release"))
+ .filter { "wearlink.testing" in it.readText() }
+ .map { it.name }
+
+ assertEquals(emptyList(), naming)
+ }
+
+ @Test
+ fun `the capability is declared and kept through the release build's resource shrinking`() {
+ val wear = File(module, "src/main/res/values/wear.xml").readText()
+ val keep = File(module, "src/main/res/raw/keep.xml").readText()
+
+ assertTrue("android_wear_capabilities" in wear && CAPABILITY in wear)
+ assertTrue("tools:keep=\"@array/android_wear_capabilities\"" in keep)
+ }
+
+ @Test
+ fun `the phone finds the watch app by the capability the watch declares`() {
+ val phone = File(module.parentFile, "app/src/main/java/to/bitkit/watch/WatchDataLayerTransport.kt").readText()
+ val phoneWear = File(module.parentFile, "app/src/main/res/values/wear.xml").readText()
+ val watch = sources("main").single { it.name == "DataLayerTransport.kt" }.readText()
+
+ assertTrue("\"$CAPABILITY\"" in phone)
+ assertTrue("bitkit_phone_v1" in phoneWear && "\"bitkit_phone_v1\"" in watch)
+ }
+}
diff --git a/wear/src/test/java/to/bitkit/wear/link/PhoneLinkRepoTest.kt b/wear/src/test/java/to/bitkit/wear/link/PhoneLinkRepoTest.kt
new file mode 100644
index 0000000000..4d6c4745b0
--- /dev/null
+++ b/wear/src/test/java/to/bitkit/wear/link/PhoneLinkRepoTest.kt
@@ -0,0 +1,423 @@
+package to.bitkit.wear.link
+
+import androidx.datastore.preferences.core.emptyPreferences
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.async
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.test.StandardTestDispatcher
+import kotlinx.coroutines.test.TestScope
+import kotlinx.coroutines.test.runCurrent
+import org.junit.Test
+import org.mockito.kotlin.any
+import org.mockito.kotlin.doAnswer
+import org.mockito.kotlin.inOrder
+import org.mockito.kotlin.mock
+import org.mockito.kotlin.never
+import org.mockito.kotlin.verify
+import org.mockito.kotlin.whenever
+import to.bitkit.wear.data.PhoneStateSink
+import to.bitkit.wear.data.PhoneStateSource
+import to.bitkit.wear.models.BitcoinDisplayUnit
+import to.bitkit.wear.models.PhoneSettings
+import to.bitkit.wear.models.PrimaryDisplay
+import to.bitkit.wear.models.QuickPayLimits
+import to.bitkit.wear.repositories.PhoneLinkRepo
+import to.bitkit.wear.repositories.WalletRepo
+import to.bitkit.wear.repositories.WatchPairingStatus
+import to.bitkit.wear.security.FakeBip39
+import to.bitkit.wear.security.FakeDeviceLock
+import to.bitkit.wear.security.FakeSeedStore
+import to.bitkit.wear.security.KeyBacking
+import to.bitkit.wear.security.SeedStoreError
+import to.bitkit.wear.security.WalletSeed
+import to.bitkit.wear.test.BaseUnitTest
+import to.bitkit.wear.test.InMemoryDataStore
+import to.bitkit.wearlink.AttestationPolicy
+import to.bitkit.wearlink.AttestationVerifier
+import to.bitkit.wearlink.Handshake
+import to.bitkit.wearlink.LinkError
+import to.bitkit.wearlink.PairedLink
+import to.bitkit.wearlink.PairingState
+import to.bitkit.wearlink.PairingThrottle
+import to.bitkit.wearlink.PhoneLink
+import to.bitkit.wearlink.PhonePairing
+import to.bitkit.wearlink.PhonePairingEnv
+import to.bitkit.wearlink.Removal
+import to.bitkit.wearlink.SeedPayload
+import to.bitkit.wearlink.SettingsDoc
+import to.bitkit.wearlink.StoreFailure
+import to.bitkit.wearlink.WalletLink
+import to.bitkit.wearlink.testing.FakeLinkNetwork
+import to.bitkit.wearlink.testing.InMemoryLinkKeyStore
+import to.bitkit.wearlink.testing.InMemoryRecordStore
+import to.bitkit.wearlink.testing.InMemoryThrottleStore
+import to.bitkit.wearlink.testing.SoftwareAgreementKey
+import kotlin.test.assertEquals
+import kotlin.test.assertIs
+import kotlin.test.assertNotNull
+import kotlin.test.assertNull
+import kotlin.test.assertTrue
+
+/**
+ * The watch's link repository against the real protocol, with the phone's side played by `:wearlink`'s own phone
+ * classes over the in-process carrier.
+ */
+@OptIn(ExperimentalCoroutinesApi::class)
+class PhoneLinkRepoTest : BaseUnitTest(StandardTestDispatcher()) {
+ private companion object {
+ const val APP_ID = "to.bitkit.dev"
+ const val NOW = 1_800_000_000_000L
+ const val MNEMONIC = "abandon ability able about"
+ const val PASSPHRASE = "pass"
+ val bip39 = FakeBip39()
+
+ /** The network name of this build, as `Env.network` gives it. */
+ const val NETWORK = "REGTEST"
+
+ fun secret(mnemonic: String, passphrase: String?) =
+ WalletLink.secret(bip39.toSeed(mnemonic, passphrase), NETWORK)
+ }
+
+ private val watchKeys = InMemoryLinkKeyStore()
+ private val phoneKeys = InMemoryLinkKeyStore()
+ private val phoneStore = InMemoryRecordStore()
+ private val seedStore = FakeSeedStore()
+ private val walletRepo = mock()
+ private val sink = mock()
+ private val agreementKey = SoftwareAgreementKey()
+
+ private lateinit var network: FakeLinkNetwork
+ private lateinit var store: WatchLinkStore
+ private lateinit var phoneLink: PhoneLink
+ private lateinit var sut: PhoneLinkRepo
+ private var phoneSeed = SeedPayload(NETWORK, MNEMONIC, PASSPHRASE)
+ private var isWipePending = false
+
+ private fun TestScope.setUp() {
+ network = FakeLinkNetwork(backgroundScope)
+ store = WatchLinkStore(InMemoryDataStore(emptyPreferences()))
+ phoneLink = PhoneLink(network.phone, phoneKeys, phoneStore, nowMs = { NOW })
+ network.phone.attach { packet -> runCatching { phoneLink.onPacket(packet) } }
+ whenever { walletRepo.restore(any()) }.doAnswer {
+ seedStore.seed = it.getArgument(0)
+ Result.success(Unit)
+ }
+ whenever { walletRepo.eraseByPhone() }.thenReturn(Result.success(Unit))
+ whenever { walletRepo.noteEraseByPhone() }.thenReturn(Result.success(Unit))
+ whenever { walletRepo.isWipePending() }.thenReturn(isWipePending)
+ whenever { walletRepo.recover() }.thenReturn(Result.success(Unit))
+ sut = PhoneLinkRepo(
+ ioDispatcher = testDispatcher,
+ transport = network.watch,
+ keys = watchKeys,
+ agreementKey = agreementKey,
+ store = store,
+ walletRepo = walletRepo,
+ seedStore = seedStore,
+ bip39 = bip39,
+ sink = sink,
+ deviceLock = FakeDeviceLock(),
+ appId = APP_ID,
+ nowMs = { NOW },
+ )
+ }
+
+ private val phoneEnv = object : PhonePairingEnv {
+ override val appId = APP_ID
+ override val name = "Pixel 9"
+ override val verifier = AttestationVerifier(AttestationPolicy(APP_ID, emptySet(), nowMs = { NOW }))
+ override val isUnverifiedTransferAllowed = true
+ override val throttle = PairingThrottle(InMemoryThrottleStore()) { NOW }
+ override val keys = phoneKeys
+
+ override suspend fun phoneId() = ByteArray(Handshake.ID_BYTES) { 1 }
+
+ override suspend fun isPinSet() = true
+
+ override suspend fun attestationStatus() = null
+
+ override suspend fun walletSecret() = secret(MNEMONIC, PASSPHRASE)
+
+ override suspend fun seed() = phoneSeed
+ }
+
+ /** Runs a pairing from the phone against the repository, confirming on both sides. */
+ private suspend fun TestScope.pair(): Result {
+ sut.startPairing()
+ val session = PhonePairing(network.phone, phoneLink.pairingPackets, network.phone.nodes().single(), phoneEnv)
+ val phone = async { runCatching { session.run() } }
+ val confirming = async {
+ val code = (session.state.first { it is PairingState.Code } as PairingState.Code).code
+ sut.pairing.first { (it as? WatchPairingStatus.Running)?.state is PairingState.Code }
+ sut.confirmPairing(code)
+ session.confirm(code, isAuthenticated = true)
+ }
+ val result = phone.await()
+ confirming.cancel()
+ runCurrent()
+ result.onSuccess { phoneLink.onPaired(it) }
+ runCurrent()
+ return result
+ }
+
+ @Test
+ fun `a watch without a wallet stores the wallet the phone sends, through the wallet's own restore`() = test {
+ setUp()
+
+ val link = pair().getOrThrow()
+
+ verify(walletRepo).restore(WalletSeed(MNEMONIC, PASSPHRASE))
+ assertEquals(WatchPairingStatus.Paired(isWalletReceived = true), sut.pairing.value)
+ assertEquals(link.pairingId, assertNotNull(store.load()).pairingId)
+ assertEquals("Pixel 9", assertNotNull(store.load()).peerName)
+ }
+
+ @Test
+ fun `a watch that holds the phone's wallet pairs without storing anything`() = test {
+ setUp()
+ seedStore.seed = WalletSeed(MNEMONIC, PASSPHRASE)
+
+ pair().getOrThrow()
+
+ verify(walletRepo, never()).restore(any())
+ assertEquals(WatchPairingStatus.Paired(isWalletReceived = false), sut.pairing.value)
+ }
+
+ @Test
+ fun `a watch with another wallet does not pair`() = test {
+ setUp()
+ seedStore.seed = WalletSeed(MNEMONIC, "another passphrase")
+
+ val result = pair()
+
+ assertIs(result.exceptionOrNull())
+ assertIs((sut.pairing.value as WatchPairingStatus.Failed).error)
+ assertNull(store.load())
+ }
+
+ @Test
+ fun `a phrase that fails the checksum is not stored`() = test {
+ setUp()
+ phoneSeed = SeedPayload(NETWORK, "abandon ability able above", null)
+
+ val error = assertIs(pair().exceptionOrNull())
+
+ assertEquals(StoreFailure.InvalidPhrase, error.reason)
+ verify(walletRepo, never()).restore(any())
+ assertNull(store.load())
+ }
+
+ @Test
+ fun `a wallet of another network is not stored`() = test {
+ setUp()
+ phoneSeed = SeedPayload("bitcoin", MNEMONIC, null)
+
+ val error = assertIs(pair().exceptionOrNull())
+
+ assertEquals(StoreFailure.WrongNetwork, error.reason)
+ verify(walletRepo, never()).restore(any())
+ }
+
+ @Test
+ fun `a watch without secure hardware refuses the wallet and says why`() = test {
+ setUp()
+ whenever { walletRepo.restore(any()) }
+ .thenReturn(Result.failure(SeedStoreError.InsecureKey(KeyBacking.Software)))
+
+ val error = assertIs(pair().exceptionOrNull())
+
+ assertEquals(StoreFailure.InsecureKey, error.reason)
+ assertNull(store.load())
+ assertTrue(watchKeys.keys.isEmpty())
+ }
+
+ @Test
+ fun `the phone's pushed settings go to the sink as a push, held to the backup's rules`() = test {
+ setUp()
+ seedStore.seed = WalletSeed(MNEMONIC, PASSPHRASE)
+ pair().getOrThrow()
+
+ phoneLink.publishSettings(SettingsDoc("fiat", "CLASSIC", "EUR", true, 10, 3, changedAtMs = 500))
+ runCurrent()
+
+ val expected = PhoneSettings(
+ primaryDisplay = PrimaryDisplay.FIAT,
+ displayUnit = BitcoinDisplayUnit.CLASSIC,
+ selectedCurrency = "EUR",
+ quickPay = QuickPayLimits(isEnabled = true, amountUsd = 10, dailyMultiplier = 3),
+ )
+ verify(sink).applySettings(expected, PhoneStateSource.Push(500), NOW)
+ assertTrue(assertNotNull(phoneStore.load()).isSettingsUpToDate)
+ }
+
+ @Test
+ fun `pushed QuickPay values outside the phone's sliders turn QuickPay off`() = test {
+ setUp()
+ seedStore.seed = WalletSeed(MNEMONIC, PASSPHRASE)
+ pair().getOrThrow()
+
+ phoneLink.publishSettings(SettingsDoc("BITCOIN", "MODERN", "usd", true, 5_000, 3, changedAtMs = 500))
+ runCurrent()
+
+ val expected = PhoneSettings(
+ primaryDisplay = PrimaryDisplay.BITCOIN,
+ displayUnit = BitcoinDisplayUnit.MODERN,
+ selectedCurrency = null,
+ quickPay = null,
+ )
+ verify(sink).applySettings(expected, PhoneStateSource.Push(500), NOW)
+ }
+
+ @Test
+ fun `the phone's erase runs the wallet's own wipe and ends the pairing`() = test {
+ setUp()
+ seedStore.seed = WalletSeed(MNEMONIC, PASSPHRASE)
+ pair().getOrThrow()
+
+ phoneLink.remove(isErase = true)
+ runCurrent()
+
+ inOrder(walletRepo) {
+ verify(walletRepo).noteEraseByPhone()
+ verify(walletRepo).eraseByPhone()
+ }
+ assertNull(store.load())
+ assertTrue(watchKeys.keys.isEmpty())
+ assertNull(phoneStore.load())
+ }
+
+ @Test
+ fun `an erase that cannot be noted is not run and not acknowledged, and runs when it is delivered again`() = test {
+ setUp()
+ seedStore.seed = WalletSeed(MNEMONIC, PASSPHRASE)
+ pair().getOrThrow()
+ whenever { walletRepo.noteEraseByPhone() }.thenReturn(Result.failure(SeedStoreError.Failed()))
+
+ phoneLink.remove(isErase = true)
+ runCurrent()
+
+ verify(walletRepo, never()).eraseByPhone()
+ assertNotNull(store.load())
+ assertEquals(Removal.Erase, assertNotNull(phoneStore.load()).removal)
+
+ whenever { walletRepo.noteEraseByPhone() }.thenReturn(Result.success(Unit))
+ network.reconnect()
+ runCurrent()
+
+ verify(walletRepo).eraseByPhone()
+ assertNull(store.load())
+ assertNull(phoneStore.load())
+ }
+
+ @Test
+ fun `the phone's unpair keeps the wallet and lets the backup import hold again`() = test {
+ setUp()
+ seedStore.seed = WalletSeed(MNEMONIC, PASSPHRASE)
+ pair().getOrThrow()
+
+ phoneLink.remove(isErase = false)
+ runCurrent()
+
+ verify(walletRepo, never()).eraseByPhone()
+ verify(sink).onPushSourceGone()
+ assertNull(store.load())
+ }
+
+ @Test
+ fun `the wearer's unpair tells the phone and forgets it`() = test {
+ setUp()
+ seedStore.seed = WalletSeed(MNEMONIC, PASSPHRASE)
+ pair().getOrThrow()
+
+ sut.unpair().getOrThrow()
+ runCurrent()
+
+ assertNull(store.load())
+ assertNull(phoneStore.load())
+ assertTrue(watchKeys.keys.isEmpty())
+ }
+
+ @Test
+ fun `an erase that was noted and not finished is finished when the process starts`() = test {
+ isWipePending = true
+
+ setUp()
+ runCurrent()
+
+ verify(walletRepo).recover()
+ }
+
+ @Test
+ fun `a start with no erase noted leaves the wallet's storage alone`() = test {
+ setUp()
+ runCurrent()
+
+ verify(walletRepo, never()).recover()
+ }
+
+ @Test
+ fun `a pairing asked for after the last one failed waits anew and pairs`() = test {
+ setUp()
+ seedStore.seed = WalletSeed(MNEMONIC, PASSPHRASE)
+ sut.startPairing()
+ val first = PhonePairing(network.phone, phoneLink.pairingPackets, network.phone.nodes().single(), phoneEnv)
+ val firstPhone = async { runCatching { first.run() } }
+ sut.pairing.first { (it as? WatchPairingStatus.Running)?.state is PairingState.Code }
+ first.cancel()
+ firstPhone.await()
+ sut.pairing.first { it is WatchPairingStatus.Failed }
+
+ // The Pair screen still shows that end when the phone asks again.
+ assertTrue(pair().isSuccess)
+ assertNotNull(store.load())
+ }
+
+ @Test
+ fun `link keys that no pairing owns are deleted at start`() = test {
+ watchKeys.import("wearlink.0102030405060708.phone", ByteArray(32))
+
+ setUp()
+ runCurrent()
+
+ assertTrue(watchKeys.keys.isEmpty())
+ }
+
+ @Test
+ fun `leaving the pair screen ends the pairing and tells the phone`() = test {
+ setUp()
+ sut.startPairing()
+ val session = PhonePairing(network.phone, phoneLink.pairingPackets, network.phone.nodes().single(), phoneEnv)
+ val phone = async { runCatching { session.run() } }
+ session.state.first { it is PairingState.Code }
+
+ sut.cancelPairing()
+
+ assertIs(phone.await().exceptionOrNull())
+ val failed = sut.pairing.first { it is WatchPairingStatus.Failed } as WatchPairingStatus.Failed
+ assertIs(failed.error)
+ }
+
+ @Test
+ fun `a pair screen opened while the last pairing ends waits anew, without the old code`() = test {
+ setUp()
+ seedStore.seed = WalletSeed(MNEMONIC, PASSPHRASE)
+ sut.startPairing()
+ val first = PhonePairing(network.phone, phoneLink.pairingPackets, network.phone.nodes().single(), phoneEnv)
+ val firstPhone = async { runCatching { first.run() } }
+ val shown = sut.pairing.first { (it as? WatchPairingStatus.Running)?.state is PairingState.Code }
+ val code = ((shown as WatchPairingStatus.Running).state as PairingState.Code).code
+
+ // The screen closes and a new one opens before the session has ended.
+ sut.cancelPairing()
+ sut.startPairing()
+
+ assertEquals(WatchPairingStatus.Running(PairingState.Connecting), sut.pairing.value)
+ sut.confirmPairing(code)
+ assertIs(firstPhone.await().exceptionOrNull())
+ runCurrent()
+ assertEquals(WatchPairingStatus.Running(PairingState.Connecting), sut.pairing.value)
+
+ assertTrue(pair().isSuccess)
+ assertNotNull(store.load())
+ }
+}
diff --git a/wear/src/test/java/to/bitkit/wear/models/PhoneSettingsParserTest.kt b/wear/src/test/java/to/bitkit/wear/models/PhoneSettingsParserTest.kt
index aa2d4bf5c7..e64841d057 100644
--- a/wear/src/test/java/to/bitkit/wear/models/PhoneSettingsParserTest.kt
+++ b/wear/src/test/java/to/bitkit/wear/models/PhoneSettingsParserTest.kt
@@ -143,4 +143,34 @@ class PhoneSettingsParserTest {
""""quickPayDailyLimitMultiplier":$multiplier}}"""
private fun parse(raw: String) = PhoneSettingsParser.parse(raw.toByteArray())
+
+ @Test
+ fun `the backup's own time is read when it is a number`() {
+ fun createdAt(raw: String) = PhoneSettingsParser.parseBackup(raw.toByteArray()).createdAtMs
+
+ assertEquals(1_800_000_000_000L, createdAt(ANDROID_BACKUP))
+ assertEquals(null, createdAt("""{"version":1,"createdAt":"soon","settings":{}}"""))
+ assertEquals(null, createdAt("""{"version":1,"settings":{}}"""))
+ }
+
+ @Test
+ fun `pushed settings are held to the same rules as a backup`() {
+ val settings = PhoneSettingsParser.fromPush("fiat", "CLASSIC", "EUR", true, 10, 3)
+
+ assertEquals(PrimaryDisplay.FIAT, settings.primaryDisplay)
+ assertEquals(BitcoinDisplayUnit.CLASSIC, settings.displayUnit)
+ assertEquals("EUR", settings.selectedCurrency)
+ assertEquals(QuickPayLimits(isEnabled = true, amountUsd = 10, dailyMultiplier = 3), settings.quickPay)
+ }
+
+ @Test
+ fun `pushed values the phone cannot have are dropped, and QuickPay outside its sliders is off`() {
+ val settings = PhoneSettingsParser.fromPush("sideways", null, "euro", true, 51, 3)
+
+ assertEquals(null, settings.primaryDisplay)
+ assertEquals(null, settings.displayUnit)
+ assertEquals(null, settings.selectedCurrency)
+ assertEquals(null, settings.quickPay)
+ assertEquals(null, PhoneSettingsParser.fromPush(null, null, null, true, 10, 0).quickPay)
+ }
}
diff --git a/wear/src/test/java/to/bitkit/wear/repositories/SettingsSyncRepoTest.kt b/wear/src/test/java/to/bitkit/wear/repositories/SettingsSyncRepoTest.kt
index 191dc2314a..e0a79d08f3 100644
--- a/wear/src/test/java/to/bitkit/wear/repositories/SettingsSyncRepoTest.kt
+++ b/wear/src/test/java/to/bitkit/wear/repositories/SettingsSyncRepoTest.kt
@@ -13,6 +13,7 @@ import kotlinx.coroutines.withTimeoutOrNull
import org.junit.Before
import org.junit.Test
import org.mockito.kotlin.any
+import org.mockito.kotlin.atLeast
import org.mockito.kotlin.doSuspendableAnswer
import org.mockito.kotlin.inOrder
import org.mockito.kotlin.mock
@@ -21,6 +22,7 @@ import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.verifyNoMoreInteractions
import org.mockito.kotlin.whenever
+import to.bitkit.wear.data.SettingsPhoneStateSink
import to.bitkit.wear.data.SettingsStore
import to.bitkit.wear.models.BitcoinDisplayUnit
import to.bitkit.wear.models.PhoneSettings
@@ -88,6 +90,7 @@ class SettingsSyncRepoTest : BaseUnitTest() {
seedStore,
reader,
settingsStore,
+ SettingsPhoneStateSink(settingsStore),
sparkService,
walletRepo,
{ elapsedMs },
@@ -101,6 +104,7 @@ class SettingsSyncRepoTest : BaseUnitTest() {
assertEquals(listOf(SEED to "SETTINGS"), reads)
verify(settingsStore).applyPhoneSettings(SETTINGS, NOW)
+ verify(settingsStore, atLeast(0)).pushedSettingsAtMs()
verifyNoMoreInteractions(settingsStore)
}
@@ -111,6 +115,7 @@ class SettingsSyncRepoTest : BaseUnitTest() {
sut.sync().getOrThrow()
verify(settingsStore).clearQuickPay()
+ verify(settingsStore, atLeast(0)).pushedSettingsAtMs()
verifyNoMoreInteractions(settingsStore)
}
@@ -123,6 +128,7 @@ class SettingsSyncRepoTest : BaseUnitTest() {
}
verify(settingsStore, times(2)).clearQuickPay()
+ verify(settingsStore, atLeast(0)).pushedSettingsAtMs()
verifyNoMoreInteractions(settingsStore)
}
@@ -133,6 +139,7 @@ class SettingsSyncRepoTest : BaseUnitTest() {
assertTrue(sut.sync().isSuccess)
verify(settingsStore).clearQuickPay()
+ verify(settingsStore, atLeast(0)).pushedSettingsAtMs()
verifyNoMoreInteractions(settingsStore)
}
@@ -206,6 +213,7 @@ class SettingsSyncRepoTest : BaseUnitTest() {
assertIs(result.await().exceptionOrNull(), "$status")
assertTrue(isReadEnded, "$status")
}
+ verify(settingsStore, atLeast(0)).pushedSettingsAtMs()
verifyNoMoreInteractions(settingsStore)
}
@@ -215,6 +223,7 @@ class SettingsSyncRepoTest : BaseUnitTest() {
assertIs(sut.sync().exceptionOrNull())
+ verify(settingsStore, atLeast(0)).pushedSettingsAtMs()
verifyNoMoreInteractions(settingsStore)
}
@@ -234,6 +243,7 @@ class SettingsSyncRepoTest : BaseUnitTest() {
assertIs(result.await().exceptionOrNull())
assertTrue(isReadEnded)
+ verify(settingsStore, atLeast(0)).pushedSettingsAtMs()
verifyNoMoreInteractions(settingsStore)
}
@@ -252,6 +262,7 @@ class SettingsSyncRepoTest : BaseUnitTest() {
BACKUP
},
settingsStore,
+ SettingsPhoneStateSink(settingsStore),
sparkService,
walletRepo,
{ elapsedMs },
@@ -289,6 +300,7 @@ class SettingsSyncRepoTest : BaseUnitTest() {
}
assertTrue(reads.isEmpty())
+ verify(settingsStore, atLeast(0)).pushedSettingsAtMs()
verifyNoMoreInteractions(settingsStore)
}
@@ -302,6 +314,7 @@ class SettingsSyncRepoTest : BaseUnitTest() {
assertIs(sut.sync().exceptionOrNull())
assertTrue(reads.isEmpty())
+ verify(settingsStore, atLeast(0)).pushedSettingsAtMs()
verifyNoMoreInteractions(settingsStore)
}
@@ -333,6 +346,7 @@ class SettingsSyncRepoTest : BaseUnitTest() {
val result = async { sut.sync() }
result.cancel()
+ verify(settingsStore, atLeast(0)).pushedSettingsAtMs()
verifyNoMoreInteractions(settingsStore)
val next = async { sut.sync() }
gate.complete(Unit)
@@ -340,6 +354,7 @@ class SettingsSyncRepoTest : BaseUnitTest() {
assertTrue(next.await().isSuccess)
assertEquals(1, reads.size)
verify(settingsStore).applyPhoneSettings(SETTINGS, NOW)
+ verify(settingsStore, atLeast(0)).pushedSettingsAtMs()
verifyNoMoreInteractions(settingsStore)
}
diff --git a/wear/src/test/java/to/bitkit/wear/repositories/WalletRepoTest.kt b/wear/src/test/java/to/bitkit/wear/repositories/WalletRepoTest.kt
index df8089b035..ed8fe19378 100644
--- a/wear/src/test/java/to/bitkit/wear/repositories/WalletRepoTest.kt
+++ b/wear/src/test/java/to/bitkit/wear/repositories/WalletRepoTest.kt
@@ -187,6 +187,26 @@ class WalletRepoTest : BaseUnitTest() {
verify(settingsStore).finishWipe()
}
+ @Test
+ fun `an erase the phone asked for is noted with the removed notice, and deletes nothing yet`() = test {
+ assertTrue(sut.noteEraseByPhone().isSuccess)
+
+ verify(settingsStore).beginWipe(true)
+ verify(seedStore, never()).wipe()
+ verify(sparkService, never()).wipeStorage()
+ verify(settingsStore, never()).finishWipe()
+ }
+
+ @Test
+ fun `an erase note that cannot be written, even on a second try, fails`() = test {
+ whenever(settingsStore.beginWipe(any())).thenAnswer { throw SeedStoreError.Failed() }
+
+ assertIs(sut.noteEraseByPhone().exceptionOrNull())
+
+ verify(settingsStore, times(2)).beginWipe(true)
+ verify(seedStore, never()).wipe()
+ }
+
@Test
fun `a removal whose note cannot be written deletes nothing and fails`() = test {
whenever(seedStore.load()).thenReturn(Result.success(seed))
diff --git a/wear/src/test/java/to/bitkit/wear/test/InMemoryDataStore.kt b/wear/src/test/java/to/bitkit/wear/test/InMemoryDataStore.kt
new file mode 100644
index 0000000000..7312b29f31
--- /dev/null
+++ b/wear/src/test/java/to/bitkit/wear/test/InMemoryDataStore.kt
@@ -0,0 +1,19 @@
+package to.bitkit.wear.test
+
+import androidx.datastore.core.DataStore
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+
+/** A [DataStore] in memory, for tests that must not leave the test dispatcher for a file. */
+class InMemoryDataStore(initial: T) : DataStore {
+ private val state = MutableStateFlow(initial)
+ private val mutex = Mutex()
+
+ override val data: Flow = state
+
+ override suspend fun updateData(transform: suspend (t: T) -> T): T = mutex.withLock {
+ transform(state.value).also { state.value = it }
+ }
+}
diff --git a/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt b/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt
index 5a7756cfe8..cf79d0a270 100644
--- a/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt
+++ b/wear/src/test/java/to/bitkit/wear/ui/LaunchRequestTest.kt
@@ -137,4 +137,12 @@ class LaunchRequestTest {
private fun fromTag(data: String?, texts: List? = null) =
LaunchRequest.from(NfcAdapter.ACTION_NDEF_DISCOVERED, data, open = null, tagTexts = texts)
+
+ @Test
+ fun `the phone's pair link asks for the pair screen, in any case`() {
+ assertEquals(LaunchRequest.Pair, LaunchRequest.from(Intent.ACTION_VIEW, "bitkitwear://pair", open = null))
+ assertEquals(LaunchRequest.Pair, LaunchRequest.from(Intent.ACTION_VIEW, "BITKITWEAR://PAIR", open = null))
+ assertNull(LaunchRequest.from(Intent.ACTION_VIEW, "bitkitwear://other", open = null))
+ assertNull(LaunchRequest.from(Intent.ACTION_MAIN, "bitkitwear://pair", open = null))
+ }
}
diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/pair/PairViewModelTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/pair/PairViewModelTest.kt
new file mode 100644
index 0000000000..ed91cf36ac
--- /dev/null
+++ b/wear/src/test/java/to/bitkit/wear/ui/screens/pair/PairViewModelTest.kt
@@ -0,0 +1,168 @@
+package to.bitkit.wear.ui.screens.pair
+
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.update
+import org.junit.Before
+import org.junit.Test
+import org.mockito.kotlin.any
+import org.mockito.kotlin.mock
+import org.mockito.kotlin.never
+import org.mockito.kotlin.times
+import org.mockito.kotlin.verify
+import org.mockito.kotlin.whenever
+import to.bitkit.wear.repositories.PhoneLinkRepo
+import to.bitkit.wear.repositories.WatchPairingStatus
+import to.bitkit.wear.security.FakeForegroundMonitor
+import to.bitkit.wear.test.BaseUnitTest
+import to.bitkit.wearlink.AbortReason
+import to.bitkit.wearlink.LinkError
+import to.bitkit.wearlink.PairingMode
+import to.bitkit.wearlink.PairingState
+import to.bitkit.wearlink.StoreFailure
+import kotlin.test.assertEquals
+
+class PairViewModelTest : BaseUnitTest() {
+ private val repo = mock()
+ private val pairing = MutableStateFlow(WatchPairingStatus.Idle)
+ private val foreground = FakeForegroundMonitor()
+
+ private lateinit var sut: PairViewModel
+
+ @Before
+ fun setUp() {
+ whenever(repo.pairing).thenReturn(pairing)
+ sut = PairViewModel(repo, foreground)
+ }
+
+ private fun step(status: WatchPairingStatus): PairStep {
+ pairing.update { status }
+ return sut.uiState.value.step
+ }
+
+ private fun failure(error: Throwable) = (step(WatchPairingStatus.Failed(error)) as PairStep.Failed).failure
+
+ @Test
+ fun `the screen starts waiting for the phone as it opens`() = test {
+ verify(repo).startPairing()
+ assertEquals(PairStep.Waiting, sut.uiState.value.step)
+ }
+
+ @Test
+ fun `the code shows with the phone's name until the wearer confirms`() = test {
+ val code = PairingState.Code("048213", PairingMode.Proof, "Pixel 9", attestation = null)
+
+ assertEquals(PairStep.Code("048213", "Pixel 9"), step(WatchPairingStatus.Running(code)))
+ assertEquals(PairStep.Working, step(WatchPairingStatus.Running(code.copy(isConfirmed = true))))
+ assertEquals(PairStep.Working, step(WatchPairingStatus.Running(PairingState.Transferring)))
+ }
+
+ @Test
+ fun `the end says whether a wallet arrived`() = test {
+ assertEquals(PairStep.Done(isWalletReceived = true), step(WatchPairingStatus.Paired(isWalletReceived = true)))
+ }
+
+ @Test
+ fun `each failure gets its one line`() = test {
+ assertEquals(PairFailure.Dismissed, failure(LinkError.Cancelled()))
+ assertEquals(PairFailure.Cancelled, failure(LinkError.PeerAborted(AbortReason.Cancelled)))
+ assertEquals(PairFailure.TimedOut, failure(LinkError.Timeout()))
+ assertEquals(PairFailure.DifferentWallet, failure(LinkError.DifferentWallet()))
+ assertEquals(PairFailure.DifferentWallet, failure(LinkError.PeerAborted(AbortReason.DifferentWallet)))
+ assertEquals(PairFailure.UpdateRequired, failure(LinkError.UpdateRequired()))
+ assertEquals(PairFailure.Unverified, failure(LinkError.PeerAborted(AbortReason.Unverified)))
+ assertEquals(PairFailure.InsecureKey, failure(LinkError.TransferFailed(StoreFailure.InsecureKey)))
+ assertEquals(PairFailure.Failed, failure(LinkError.TransferFailed(StoreFailure.Failed)))
+ assertEquals(PairFailure.Failed, failure(IllegalStateException()))
+ }
+
+ @Test
+ fun `the button confirms the code that shows`() = test {
+ step(WatchPairingStatus.Running(PairingState.Code("048213", PairingMode.Proof, "Pixel 9", null)))
+
+ sut.onConfirmClick()
+
+ verify(repo).confirmPairing("048213")
+ verify(repo, never()).cancelPairing()
+ }
+
+ @Test
+ fun `the button confirms nothing without a code on screen`() = test {
+ sut.onConfirmClick()
+
+ verify(repo, never()).confirmPairing(any())
+ }
+
+ @Test
+ fun `the phone's request while a failed pairing still shows starts waiting anew`() = test {
+ step(WatchPairingStatus.Failed(LinkError.PeerAborted(AbortReason.Cancelled)))
+
+ sut.onPairRequest()
+
+ verify(repo, times(2)).startPairing()
+ }
+
+ @Test
+ fun `the phone's request after the watch paired starts nothing`() = test {
+ step(WatchPairingStatus.Paired(isWalletReceived = false))
+
+ sut.onPairRequest()
+
+ verify(repo, times(1)).startPairing()
+ }
+
+ @Test
+ fun `the phone's request during the code waits anew once the phone aborts that pairing`() = test {
+ step(WatchPairingStatus.Running(PairingState.Code("048213", PairingMode.Proof, "Pixel 9", null)))
+
+ sut.onPairRequest()
+ step(WatchPairingStatus.Failed(LinkError.PeerAborted(AbortReason.Cancelled)))
+
+ verify(repo, times(3)).startPairing()
+ verify(repo, never()).cancelPairing()
+ }
+
+ @Test
+ fun `a kept request restarts only once`() = test {
+ step(WatchPairingStatus.Running(PairingState.Code("048213", PairingMode.Proof, "Pixel 9", null)))
+ sut.onPairRequest()
+ step(WatchPairingStatus.Failed(LinkError.PeerAborted(AbortReason.Cancelled)))
+
+ assertEquals(PairStep.Failed(PairFailure.TimedOut), step(WatchPairingStatus.Failed(LinkError.Timeout())))
+ verify(repo, times(3)).startPairing()
+ }
+
+ @Test
+ fun `a kept request is dropped when the wearer dismisses the pairing`() = test {
+ step(WatchPairingStatus.Running(PairingState.Transferring))
+ sut.onPairRequest()
+
+ assertEquals(PairStep.Failed(PairFailure.Dismissed), step(WatchPairingStatus.Failed(LinkError.Cancelled())))
+ verify(repo, times(2)).startPairing()
+ }
+
+ @Test
+ fun `a kept request is dropped once the watch paired`() = test {
+ step(WatchPairingStatus.Running(PairingState.Transferring))
+ sut.onPairRequest()
+ step(WatchPairingStatus.Paired(isWalletReceived = true))
+
+ step(WatchPairingStatus.Failed(LinkError.Timeout()))
+ verify(repo, times(2)).startPairing()
+ }
+
+ @Test
+ fun `a request while waiting for the hello is not kept`() = test {
+ step(WatchPairingStatus.Running(PairingState.Connecting))
+ sut.onPairRequest()
+
+ assertEquals(PairStep.Failed(PairFailure.TimedOut), step(WatchPairingStatus.Failed(LinkError.Timeout())))
+ verify(repo, times(2)).startPairing()
+ }
+
+ @Test
+ fun `the pairing is cancelled when the app leaves the screen`() = test {
+ foreground.isForeground.update { false }
+
+ verify(repo).cancelPairing()
+ }
+}
diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveQrContentTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveQrContentTest.kt
index 8117d95898..d7bbe720c1 100644
--- a/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveQrContentTest.kt
+++ b/wear/src/test/java/to/bitkit/wear/ui/screens/receive/ReceiveQrContentTest.kt
@@ -13,6 +13,7 @@ import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.onRoot
+import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performTouchInput
import org.junit.Rule
import org.junit.Test
@@ -38,6 +39,7 @@ class ReceiveQrContentTest {
private val paid = ReceiveUiState(paidAmount = DisplayAmount(symbol = "₿", text = "50 000"))
private val shown = ReceiveUiState(qrContent = "LNBCRT1TEST")
private var shows = 0
+ private var refreshes = 0
private var nfcSettingsOpens = 0
@Test
@@ -50,10 +52,34 @@ class ReceiveQrContentTest {
composeRule.onNodeWithText("50 000", useUnmergedTree = true).assertExists()
}
+ @Test
+ fun `the paid check is no button, and the button below it makes a new invoice`() {
+ setContent(paid, isAmbient = false)
+
+ composeRule.onNodeWithTag("WatchReceivePaid").assertHasNoClickAction()
+ composeRule.onNodeWithText("New invoice", useUnmergedTree = true).assertExists()
+ composeRule.onNodeWithTag("WatchReceiveNew").performClick()
+ composeRule.waitForIdle()
+
+ assertEquals(1, refreshes)
+ }
+
+ @Test
+ @Config(sdk = [34], qualifiers = "w192dp-h192dp-round")
+ fun `the new invoice button stays clear of the paid amount on the smallest round screen`() {
+ setContent(paid, isAmbient = false)
+
+ val paidBounds = composeRule.onNodeWithTag("WatchReceivePaid").fetchSemanticsNode().boundsInRoot
+ val button = composeRule.onNodeWithTag("WatchReceiveNew").fetchSemanticsNode().boundsInRoot
+ assertTrue(paidBounds.bottom <= button.top, "$paidBounds overlaps $button")
+ }
+
@Test
fun `a paid invoice in ambient mode shows the check without its amount`() {
setContent(paid, isAmbient = true)
+ composeRule.onNodeWithTag("WatchReceiveNew").assertDoesNotExist()
+
composeRule.onNodeWithTag("WatchReceivePaid").assertExists()
composeRule.onNodeWithContentDescription("Paid").assertExists()
composeRule.onNodeWithTag("WatchReceivePaidAmount", useUnmergedTree = true).assertDoesNotExist()
@@ -184,7 +210,7 @@ class ReceiveQrContentTest {
ReceiveQrContent(
uiState = uiState,
isAmbient = isAmbient,
- onRefreshClick = {},
+ onRefreshClick = { refreshes++ },
isResting = isResting,
nfcHint = nfcHint,
onShowClick = { shows++ },
diff --git a/wear/src/test/java/to/bitkit/wear/ui/screens/settings/SettingsViewModelTest.kt b/wear/src/test/java/to/bitkit/wear/ui/screens/settings/SettingsViewModelTest.kt
index 24645030b9..5fe74371d4 100644
--- a/wear/src/test/java/to/bitkit/wear/ui/screens/settings/SettingsViewModelTest.kt
+++ b/wear/src/test/java/to/bitkit/wear/ui/screens/settings/SettingsViewModelTest.kt
@@ -6,6 +6,7 @@ import kotlinx.coroutines.flow.update
import org.junit.Before
import org.junit.Test
import org.mockito.kotlin.doSuspendableAnswer
+import org.mockito.kotlin.inOrder
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
import org.mockito.kotlin.times
@@ -13,10 +14,12 @@ import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import to.bitkit.wear.data.SettingsStore
import to.bitkit.wear.data.WatchSettings
+import to.bitkit.wear.repositories.PhoneLinkRepo
import to.bitkit.wear.repositories.SettingsSyncRepo
import to.bitkit.wear.repositories.WalletRepo
import to.bitkit.wear.services.SparkError
import to.bitkit.wear.test.BaseUnitTest
+import to.bitkit.wearlink.LinkRecord
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
@@ -26,6 +29,8 @@ class SettingsViewModelTest : BaseUnitTest() {
private val walletRepo = mock()
private val settingsSyncRepo = mock()
private val settingsStore = mock()
+ private val phoneLinkRepo = mock()
+ private val linkRecord = MutableStateFlow(null)
private val settings = MutableStateFlow(WatchSettings())
private lateinit var sut: SettingsViewModel
@@ -33,7 +38,9 @@ class SettingsViewModelTest : BaseUnitTest() {
@Before
fun setUp() {
whenever(settingsStore.data).thenReturn(settings)
- sut = SettingsViewModel(walletRepo, settingsSyncRepo, settingsStore)
+ whenever(phoneLinkRepo.record).thenReturn(linkRecord)
+ whenever { phoneLinkRepo.unpair() }.thenReturn(Result.success(Unit))
+ sut = SettingsViewModel(walletRepo, settingsSyncRepo, phoneLinkRepo, settingsStore)
}
@Test
@@ -103,4 +110,60 @@ class SettingsViewModelTest : BaseUnitTest() {
assertTrue(sut.uiState.value.isRemoveFailed)
assertFalse(sut.uiState.value.isRemoving)
}
+
+ @Test
+ fun `removing the wallet tells the paired phone before the wipe takes the link`() = test {
+ whenever(walletRepo.wipe()).thenReturn(Result.success(Unit))
+
+ sut.onRemoveConfirm()
+
+ inOrder(phoneLinkRepo, walletRepo) {
+ verify(phoneLinkRepo).unpair()
+ verify(walletRepo).wipe()
+ }
+ }
+
+ @Test
+ fun `the row shows the paired phone and unpairs only on confirm`() = test {
+ linkRecord.update { LinkRecord("0102030405060708", "aa", "node", "Pixel 9", pairedAtMs = 1) }
+ assertEquals("Pixel 9", sut.uiState.value.pairedPhone)
+
+ sut.onUnpairClick()
+ assertTrue(sut.uiState.value.isUnpairDialogVisible)
+ verify(phoneLinkRepo, never()).unpair()
+
+ sut.onUnpairConfirm()
+
+ verify(phoneLinkRepo).unpair()
+ assertFalse(sut.uiState.value.isUnpairDialogVisible)
+ assertFalse(sut.uiState.value.isUnpairFailed)
+ }
+
+ @Test
+ fun `an unpair that fails shows the failure until the next try`() = test {
+ linkRecord.update { LinkRecord("0102030405060708", "aa", "node", "Pixel 9", pairedAtMs = 1) }
+ whenever { phoneLinkRepo.unpair() }.thenReturn(Result.failure(IllegalStateException("no store")))
+ sut.onUnpairClick()
+
+ sut.onUnpairConfirm()
+
+ assertTrue(sut.uiState.value.isUnpairFailed)
+ assertFalse(sut.uiState.value.isUnpairing)
+
+ sut.onUnpairClick()
+ assertFalse(sut.uiState.value.isUnpairFailed)
+ }
+
+ @Test
+ fun `an unpair failure goes once the pairing ends some other way`() = test {
+ linkRecord.update { LinkRecord("0102030405060708", "aa", "node", "Pixel 9", pairedAtMs = 1) }
+ whenever { phoneLinkRepo.unpair() }.thenReturn(Result.failure(IllegalStateException("no store")))
+ sut.onUnpairConfirm()
+ assertTrue(sut.uiState.value.isUnpairFailed)
+
+ linkRecord.update { null }
+
+ assertNull(sut.uiState.value.pairedPhone)
+ assertFalse(sut.uiState.value.isUnpairFailed)
+ }
}
diff --git a/wearlink/.gitignore b/wearlink/.gitignore
new file mode 100644
index 0000000000..796b96d1c4
--- /dev/null
+++ b/wearlink/.gitignore
@@ -0,0 +1 @@
+/build
diff --git a/wearlink/build.gradle.kts b/wearlink/build.gradle.kts
new file mode 100644
index 0000000000..da55f9cde5
--- /dev/null
+++ b/wearlink/build.gradle.kts
@@ -0,0 +1,56 @@
+import org.gradle.api.tasks.testing.logging.TestExceptionFormat
+import org.gradle.api.tasks.testing.logging.TestLogEvent
+import org.jetbrains.kotlin.gradle.dsl.JvmTarget
+
+// The phone-to-watch link protocol, shared by :app and :wear so both roles run the same code and are tested against
+// each other in one process. Plain JVM: no Android, no UI, no Play services. See docs/wear.md, Pairing.
+plugins {
+ alias(libs.plugins.kotlin.jvm)
+ alias(libs.plugins.kotlin.serialization)
+ alias(libs.plugins.detekt)
+ `java-test-fixtures`
+}
+
+java {
+ sourceCompatibility = JavaVersion.VERSION_11
+ targetCompatibility = JavaVersion.VERSION_11
+}
+
+kotlin {
+ compilerOptions {
+ jvmTarget = JvmTarget.JVM_11
+ allWarningsAsErrors = true
+ }
+}
+
+dependencies {
+ implementation(platform(libs.kotlin.bom))
+ implementation(platform(libs.kotlinx.coroutines.bom))
+ implementation(libs.kotlinx.coroutines.core)
+ implementation(libs.kotlinx.serialization.json)
+ // HKDF and the ASN.1 reader of the key attestation record.
+ implementation(libs.bouncycastle.provider.jdk)
+ testFixturesImplementation(platform(libs.kotlin.bom))
+ testFixturesImplementation(platform(libs.kotlinx.coroutines.bom))
+ testFixturesImplementation(libs.kotlinx.coroutines.core)
+ testImplementation(libs.test.kotlin)
+ testImplementation(libs.test.junit)
+ testImplementation(platform(libs.kotlinx.coroutines.bom))
+ testImplementation(libs.test.coroutines)
+ testImplementation(libs.bouncycastle.pkix.jdk) // test certificates
+ detektPlugins(libs.detekt.formatting)
+ // The shared detekt config names the Compose rule set, so the plugin must be present for it to load.
+ detektPlugins(libs.detekt.compose.rules)
+}
+
+tasks.withType().configureEach {
+ testLogging {
+ events(TestLogEvent.FAILED, TestLogEvent.PASSED, TestLogEvent.SKIPPED)
+ exceptionFormat = TestExceptionFormat.FULL
+ }
+}
+
+// The repo's checks name the apps' variant tasks (`just test`, `just compile`, CI and scripts/update-verification-
+// metadata.sh), which a JVM module does not have, so these run this module's own under the same names.
+tasks.register("testDevDebugUnitTest") { dependsOn(tasks.named("test")) }
+tasks.register("compileDevDebugKotlin") { dependsOn(tasks.named("compileKotlin")) }
diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/Attestation.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/Attestation.kt
new file mode 100644
index 0000000000..c8289eb698
--- /dev/null
+++ b/wearlink/src/main/kotlin/to/bitkit/wearlink/Attestation.kt
@@ -0,0 +1,229 @@
+package to.bitkit.wearlink
+
+import org.bouncycastle.asn1.ASN1Boolean
+import org.bouncycastle.asn1.ASN1Encodable
+import org.bouncycastle.asn1.ASN1Enumerated
+import org.bouncycastle.asn1.ASN1Integer
+import org.bouncycastle.asn1.ASN1OctetString
+import org.bouncycastle.asn1.ASN1Primitive
+import org.bouncycastle.asn1.ASN1Sequence
+import org.bouncycastle.asn1.ASN1Set
+import org.bouncycastle.asn1.ASN1TaggedObject
+import java.security.cert.CertificateFactory
+import java.security.cert.X509Certificate
+import java.security.interfaces.ECPublicKey
+import java.util.Date
+
+/** Where an attested key lives. */
+enum class KeyLevel { StrongBox, TrustedEnvironment }
+
+/** Why a key attestation was not accepted. */
+enum class AttestationFailure {
+ /** The watch sent no certificate chain. */
+ NoChain,
+ Malformed,
+
+ /** A certificate is expired, not signed by the next one, or not allowed to sign one. */
+ BrokenChain,
+
+ /** The chain does not end in one of Google's hardware attestation roots, as on an emulator. */
+ UntrustedRoot,
+
+ /** The attested key is not the key the watch offered for the key agreement. */
+ KeyMismatch,
+ NoAttestation,
+
+ /** The attestation was made for another handshake. */
+ WrongChallenge,
+
+ /** The key, or the attestation itself, was made in software. */
+ SoftwareKey,
+
+ /** The key may do more than a key agreement on P-256, or was not generated inside the hardware. */
+ WrongKeyUse,
+
+ /** The watch's bootloader is unlocked or its system image is not verified. */
+ UnverifiedBoot,
+
+ /** The key belongs to another app, or to one signed by another key. */
+ WrongApp,
+
+ /** A certificate of the chain is on Google's status list: its key leaked or was withdrawn. */
+ Revoked,
+
+ /** Google's status list could not be read, so whether the chain is revoked is not known. */
+ StatusUnknown,
+}
+
+sealed interface AttestationVerdict {
+ data class Verified(val level: KeyLevel) : AttestationVerdict
+
+ data class Unverified(val failure: AttestationFailure) : AttestationVerdict
+}
+
+/**
+ * What an attested key must show. [packageName] and [signingDigests] (SHA-256, lowercase hex) name the watch app:
+ * it has the phone app's application id and signing certificate. [trustedRoots] are the SHA-256 of the public keys
+ * (SubjectPublicKeyInfo, lowercase hex) of the roots a chain may end in.
+ */
+class AttestationPolicy(
+ val packageName: String,
+ val signingDigests: Set,
+ val trustedRoots: Set = GOOGLE_HARDWARE_ROOTS,
+ val nowMs: () -> Long,
+) {
+ companion object {
+ /**
+ * Google's hardware attestation roots, from https://android.googleapis.com/attestation/root (read
+ * 2026-11-28): the RSA root in use since 2016 and the P-384 "Key Attestation CA1" that replaces it. Pinned
+ * by public key, since Google reissues the certificates of the same keys.
+ */
+ val GOOGLE_HARDWARE_ROOTS = setOf(
+ "feb2ea7551ee316ed4bb443c8293b884dbfdea40b603ee3e4f4a897e4580fbae",
+ "3ee44512a1af2beb39c889490c60ea3f82e43f5d5a5532f5ab9419f676cd07ec",
+ )
+ }
+}
+
+/**
+ * Checks an Android Keystore key attestation: that the key the watch offers for the key agreement was generated
+ * inside its secure hardware, by Bitkit, for this handshake, and can do nothing but a key agreement.
+ *
+ * The chain is walked by hand, as Google's own verifier does, since attestation chains do not pass the general PKIX
+ * rules: each certificate must be valid now and signed by the next, every certificate but the first must be a CA that
+ * may sign certificates and must not carry an attestation record (so a key attested for signing cannot issue a forged
+ * record below itself), and the last one's public key must be a pinned Google root. Revocation is not checked here:
+ * [PhonePairing] reads Google's [AttestationStatusList] for a chain this accepts.
+ */
+class AttestationVerifier(private val policy: AttestationPolicy) {
+ companion object {
+ /** The OID of the key description extension. */
+ const val KEY_DESCRIPTION_OID = "1.3.6.1.4.1.11129.2.1.17"
+ private const val MAX_CHAIN = 10
+
+ private const val LEVEL_TEE = 1
+ private const val LEVEL_STRONGBOX = 2
+ private const val INDEX_ATTESTATION_LEVEL = 1
+ private const val INDEX_KEYMINT_LEVEL = 3
+ private const val INDEX_CHALLENGE = 4
+ private const val INDEX_SOFTWARE = 6
+ private const val INDEX_HARDWARE = 7
+ private const val DESCRIPTION_SIZE = 8
+
+ private const val TAG_PURPOSE = 1
+ private const val TAG_ALGORITHM = 2
+ private const val TAG_EC_CURVE = 10
+ private const val TAG_ORIGIN = 702
+ private const val TAG_ROOT_OF_TRUST = 704
+ private const val TAG_APPLICATION_ID = 709
+
+ private const val PURPOSE_AGREE_KEY = 6
+ private const val ALGORITHM_EC = 3
+ private const val CURVE_P256 = 1
+ private const val ORIGIN_GENERATED = 0
+ private const val BOOT_VERIFIED = 0
+ private const val ROOT_OF_TRUST_MIN_SIZE = 3
+
+ /** The index of keyCertSign in a certificate's key usage. */
+ private const val USAGE_CERT_SIGN = 5
+ }
+
+ /**
+ * The verdict on [chain] (DER certificates, the key's own first) for a key that must be [publicKey] (X.509
+ * encoded) and attested with [challenge]. It never throws: whatever cannot be read is unverified.
+ */
+ fun verify(chain: List, challenge: ByteArray, publicKey: ByteArray): AttestationVerdict =
+ runCatching { AttestationVerdict.Verified(check(chain, challenge, publicKey)) }.getOrElse {
+ AttestationVerdict.Unverified((it as? Refusal)?.failure ?: AttestationFailure.Malformed)
+ }
+
+ private fun check(chain: List, challenge: ByteArray, publicKey: ByteArray): KeyLevel {
+ if (chain.isEmpty()) refuse(AttestationFailure.NoChain)
+ if (chain.size > MAX_CHAIN) refuse(AttestationFailure.Malformed)
+ val factory = CertificateFactory.getInstance("X.509")
+ val certificates = chain.map { factory.generateCertificate(it.inputStream()) as X509Certificate }
+ checkChain(certificates)
+ val leaf = certificates.first()
+ val attested = leaf.publicKey as? ECPublicKey ?: refuse(AttestationFailure.WrongKeyUse)
+ val offered = LinkCrypto.decodePublicKey(publicKey)
+ if (attested.w != offered.w || !LinkCrypto.isOnP256(attested)) refuse(AttestationFailure.KeyMismatch)
+ val extension = leaf.getExtensionValue(KEY_DESCRIPTION_OID) ?: refuse(AttestationFailure.NoAttestation)
+ val description = ASN1Sequence.getInstance(ASN1OctetString.getInstance(extension).octets)
+ if (description.size() < DESCRIPTION_SIZE) refuse(AttestationFailure.Malformed)
+ val attestedChallenge = ASN1OctetString.getInstance(description.getObjectAt(INDEX_CHALLENGE)).octets
+ if (!LinkCrypto.isEqual(attestedChallenge, challenge)) refuse(AttestationFailure.WrongChallenge)
+ val attestationLevel = level(description.getObjectAt(INDEX_ATTESTATION_LEVEL))
+ val keyLevel = level(description.getObjectAt(INDEX_KEYMINT_LEVEL))
+ if (attestationLevel == null || keyLevel == null) refuse(AttestationFailure.SoftwareKey)
+ val hardware = authorizations(description.getObjectAt(INDEX_HARDWARE))
+ checkKeyUse(hardware)
+ checkBoot(hardware[TAG_ROOT_OF_TRUST])
+ checkApp(authorizations(description.getObjectAt(INDEX_SOFTWARE))[TAG_APPLICATION_ID])
+ return keyLevel
+ }
+
+ private fun checkChain(certificates: List) {
+ val now = Date(policy.nowMs())
+ certificates.forEachIndexed { index, certificate ->
+ val issuer = certificates.getOrElse(index + 1) { certificate }
+ runCatching {
+ certificate.checkValidity(now)
+ certificate.verify(issuer.publicKey)
+ }.getOrElse { refuse(AttestationFailure.BrokenChain) }
+ if (index == 0) return@forEachIndexed
+ val isAuthority = certificate.basicConstraints >= 0
+ val maySign = certificate.keyUsage?.getOrNull(USAGE_CERT_SIGN) != false
+ val hasRecord = certificate.getExtensionValue(KEY_DESCRIPTION_OID) != null
+ if (!isAuthority || !maySign || hasRecord) refuse(AttestationFailure.BrokenChain)
+ }
+ val root = LinkCrypto.sha256(certificates.last().publicKey.encoded).toHex()
+ if (root !in policy.trustedRoots) refuse(AttestationFailure.UntrustedRoot)
+ }
+
+ private fun checkKeyUse(hardware: Map) {
+ val purposes = hardware[TAG_PURPOSE]?.let { set -> ASN1Set.getInstance(set).map { it.int() }.toSet() }
+ val isAgreementOnly = purposes == setOf(PURPOSE_AGREE_KEY)
+ val isP256 = hardware[TAG_ALGORITHM]?.int() == ALGORITHM_EC && hardware[TAG_EC_CURVE]?.int() == CURVE_P256
+ val isGenerated = hardware[TAG_ORIGIN]?.int() == ORIGIN_GENERATED
+ if (!isAgreementOnly || !isP256 || !isGenerated) refuse(AttestationFailure.WrongKeyUse)
+ }
+
+ private fun checkBoot(rootOfTrust: ASN1Primitive?) {
+ val fields = rootOfTrust?.let(ASN1Sequence::getInstance) ?: refuse(AttestationFailure.UnverifiedBoot)
+ if (fields.size() < ROOT_OF_TRUST_MIN_SIZE) refuse(AttestationFailure.UnverifiedBoot)
+ val isLocked = ASN1Boolean.getInstance(fields.getObjectAt(1)).isTrue
+ val state = ASN1Enumerated.getInstance(fields.getObjectAt(2)).intValueExact()
+ if (!isLocked || state != BOOT_VERIFIED) refuse(AttestationFailure.UnverifiedBoot)
+ }
+
+ private fun checkApp(applicationId: ASN1Primitive?) {
+ val encoded = applicationId?.let { ASN1OctetString.getInstance(it).octets }
+ ?: refuse(AttestationFailure.WrongApp)
+ val fields = ASN1Sequence.getInstance(encoded)
+ val packages = ASN1Set.getInstance(fields.getObjectAt(0)).map {
+ ASN1OctetString.getInstance(ASN1Sequence.getInstance(it).getObjectAt(0)).octets.decodeToString()
+ }
+ val digests = ASN1Set.getInstance(fields.getObjectAt(1)).map { ASN1OctetString.getInstance(it).octets.toHex() }
+ val isApp = packages == listOf(policy.packageName)
+ val isSigner = digests.isNotEmpty() && digests.all { it in policy.signingDigests }
+ if (!isApp || !isSigner) refuse(AttestationFailure.WrongApp)
+ }
+
+ private fun level(value: ASN1Encodable): KeyLevel? = when (ASN1Enumerated.getInstance(value).intValueExact()) {
+ LEVEL_TEE -> KeyLevel.TrustedEnvironment
+ LEVEL_STRONGBOX -> KeyLevel.StrongBox
+ else -> null
+ }
+
+ private fun authorizations(list: ASN1Encodable): Map =
+ ASN1Sequence.getInstance(list).associate {
+ val tagged = ASN1TaggedObject.getInstance(it)
+ tagged.tagNo to tagged.explicitBaseObject.toASN1Primitive()
+ }
+
+ private fun ASN1Encodable.int(): Int = ASN1Integer.getInstance(this).intValueExact()
+
+ private fun refuse(failure: AttestationFailure): Nothing = throw Refusal(failure)
+
+ private class Refusal(val failure: AttestationFailure) : Exception()
+}
diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/AttestationStatusList.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/AttestationStatusList.kt
new file mode 100644
index 0000000000..7ad4c34bd7
--- /dev/null
+++ b/wearlink/src/main/kotlin/to/bitkit/wearlink/AttestationStatusList.kt
@@ -0,0 +1,70 @@
+package to.bitkit.wearlink
+
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.jsonObject
+import java.math.BigInteger
+import java.security.cert.CertificateFactory
+import java.security.cert.X509Certificate
+
+/**
+ * Google's attestation status list: the serial numbers of the attestation certificates Google has revoked or
+ * suspended, most of them keys that leaked from a device and can attest anything. A chain that passes
+ * [AttestationVerifier] with one of these in it proves nothing, so the phone reads the list before it sends a wallet.
+ *
+ * The list is public and the same for everyone: reading it sends nothing about the user, the wallet or the watch.
+ */
+class AttestationStatusList private constructor(private val entries: Map) {
+ enum class Status {
+ Revoked,
+ Suspended,
+
+ /** Listed with a status this version does not know; refused like the others. */
+ Unknown,
+ }
+
+ companion object {
+ /** Where Google publishes the list, as JSON. */
+ const val URL = "https://android.googleapis.com/attestation/status"
+
+ /** No list is read beyond this size; today's is a quarter of a megabyte. */
+ const val MAX_BYTES = 8 * 1024 * 1024
+
+ private const val HEX_RADIX = 16
+
+ /**
+ * Reads the list as Google publishes it, from the [body] of the response: `entries`, keyed by a
+ * certificate's serial number in hexadecimal, each with a `status`. Fails with [LinkError.Malformed] for
+ * anything else, or beyond [MAX_BYTES], so a response that is not the list is never taken for an empty one.
+ */
+ fun parse(body: ByteArray): AttestationStatusList {
+ if (body.size > MAX_BYTES) throw LinkError.Malformed()
+ val entries = runCatching {
+ val json = body.decodeToString(throwOnInvalidSequence = true)
+ val listed = linkJson.parseToJsonElement(json).jsonObject.getValue("entries").jsonObject
+ listed.entries.associate { (serial, entry) -> key(serial) to status(entry as? JsonObject) }
+ }.getOrElse { throw LinkError.Malformed(it) }
+ return AttestationStatusList(entries)
+ }
+
+ private fun key(serial: String): String = serial.lowercase().trimStart('0')
+
+ private fun status(entry: JsonObject?): Status = when ((entry?.get("status") as? JsonPrimitive)?.content) {
+ "REVOKED" -> Status.Revoked
+ "SUSPENDED" -> Status.Suspended
+ else -> Status.Unknown
+ }
+ }
+
+ /** The status of the certificate with [serial], or null when it is not listed. */
+ fun status(serial: BigInteger): Status? = entries[serial.toString(HEX_RADIX)]
+
+ /**
+ * Whether any certificate of [chain] (DER certificates) is listed, whatever its status. A chain that cannot be
+ * read counts as listed.
+ */
+ fun lists(chain: List): Boolean = runCatching {
+ val factory = CertificateFactory.getInstance("X.509")
+ chain.any { status((factory.generateCertificate(it.inputStream()) as X509Certificate).serialNumber) != null }
+ }.getOrDefault(true)
+}
diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/Handshake.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/Handshake.kt
new file mode 100644
index 0000000000..36f7b1cf89
--- /dev/null
+++ b/wearlink/src/main/kotlin/to/bitkit/wearlink/Handshake.kt
@@ -0,0 +1,261 @@
+package to.bitkit.wearlink
+
+import java.security.SecureRandom
+import kotlin.time.Duration.Companion.seconds
+
+/** The constants and messages of the pairing handshake. `docs/wear.md`, Pairing, describes the ceremony. */
+object Handshake {
+ /** The protocol version this build speaks; a hello carries the range, and the reply picks from it. */
+ const val VERSION = 1
+ const val ID_BYTES = 16
+ const val NONCE_BYTES = 32
+ const val PAIRING_ID_BYTES = 8
+ const val CODE_DIGITS = 6
+
+ /** How long a whole ceremony may take, from the hello to the last message. */
+ val TIMEOUT = 90.seconds
+
+ /** How often the phone repeats its hello until the watch's Pair screen is up and answers. */
+ val HELLO_INTERVAL = 2.seconds
+
+ internal const val MAX_KEY_BYTES = 256
+ internal const val MAX_CERTIFICATE_BYTES = 8 * 1024
+ internal const val MAX_CERTIFICATES = 10
+ internal const val MAX_SEED_BYTES = 2 * 1024
+
+ private val COMMIT_LABEL = "bitkit wear link v1 commit".encodeToByteArray()
+ private val ATTEST_LABEL = "bitkit wear link v1 attest".encodeToByteArray()
+ private val TRANSCRIPT_LABEL = "bitkit wear link v1 transcript".encodeToByteArray()
+
+ /** The phone's commitment to its key agreement key, sent before it sees the watch's. */
+ fun commitment(publicKey: ByteArray, nonce: ByteArray): ByteArray =
+ LinkCrypto.sha256(COMMIT_LABEL, WireWriter().bytes(publicKey).bytes(nonce).toByteArray())
+
+ /** The challenge the watch's key is attested with: it binds the attestation to this one hello. */
+ fun attestationChallenge(hello: ByteArray): ByteArray = LinkCrypto.sha256(ATTEST_LABEL, hello)
+
+ /** The hash of the three clear handshake messages, exactly as they were sent. */
+ fun transcript(hello: ByteArray, reply: ByteArray, reveal: ByteArray): ByteArray =
+ LinkCrypto.sha256(TRANSCRIPT_LABEL, WireWriter().bytes(hello).bytes(reply).bytes(reveal).toByteArray())
+}
+
+/** How a pairing links the two devices. */
+enum class PairingMode {
+ /** The watch already holds the phone's wallet and proves it; no seed is sent. */
+ Proof,
+
+ /** The watch holds no wallet, and the phone sends it the seed. */
+ Transfer,
+}
+
+/** Phone to watch, in clear: the phone's identity for this pairing and its commitment to its key. */
+internal class Hello(
+ val minVersion: Int,
+ val maxVersion: Int,
+ val appId: String,
+ val phoneId: ByteArray,
+ val nonce: ByteArray,
+ val commitment: ByteArray,
+ val name: String,
+) {
+ fun encode(): ByteArray = WireWriter()
+ .int(minVersion).int(maxVersion).string(appId).fixed(phoneId).fixed(nonce).fixed(commitment).string(name)
+ .toByteArray()
+
+ companion object {
+ fun decode(bytes: ByteArray): Hello = WireReader(bytes).run {
+ Hello(
+ minVersion = int(),
+ maxVersion = int(),
+ appId = string(),
+ phoneId = fixed(Handshake.ID_BYTES),
+ nonce = fixed(Handshake.NONCE_BYTES),
+ commitment = fixed(LinkCrypto.HASH_BYTES),
+ name = string(),
+ ).also { end() }
+ }
+ }
+}
+
+/**
+ * Watch to phone, in clear: the watch's key agreement key, which lives in its Keystore, with the certificate chain
+ * that attests it, and whether the watch holds a wallet.
+ */
+internal class Reply(
+ val version: Int,
+ val watchId: ByteArray,
+ val nonce: ByteArray,
+ val hasWallet: Boolean,
+ val publicKey: ByteArray,
+ val chain: List,
+ val name: String,
+ val isLockSet: Boolean,
+) {
+ fun encode(): ByteArray = WireWriter()
+ .int(version).fixed(watchId).fixed(nonce).bool(hasWallet).bytes(publicKey).list(chain).string(name)
+ .bool(isLockSet)
+ .toByteArray()
+
+ companion object {
+ fun decode(bytes: ByteArray): Reply = WireReader(bytes).run {
+ Reply(
+ version = int(),
+ watchId = fixed(Handshake.ID_BYTES),
+ nonce = fixed(Handshake.NONCE_BYTES),
+ hasWallet = bool(),
+ publicKey = bytes(Handshake.MAX_KEY_BYTES),
+ chain = list(Handshake.MAX_CERTIFICATES, Handshake.MAX_CERTIFICATE_BYTES),
+ name = string(),
+ isLockSet = bool(),
+ ).also { end() }
+ }
+ }
+}
+
+/** Phone to watch, in clear: the key the hello committed to. */
+internal class Reveal(val publicKey: ByteArray, val nonce: ByteArray) {
+ fun encode(): ByteArray = WireWriter().bytes(publicKey).fixed(nonce).toByteArray()
+
+ companion object {
+ fun decode(bytes: ByteArray): Reveal = WireReader(bytes).run {
+ Reveal(bytes(Handshake.MAX_KEY_BYTES), fixed(Handshake.NONCE_BYTES)).also { end() }
+ }
+ }
+}
+
+/** Both ways: proof of having derived the session keys and, between two holders of one wallet, of the wallet. */
+internal class Confirm(val keyMac: ByteArray, val walletProof: ByteArray?) {
+ fun encode(): ByteArray = WireWriter().fixed(keyMac).bytes(walletProof ?: ByteArray(0)).toByteArray()
+
+ companion object {
+ fun decode(bytes: ByteArray): Confirm = WireReader(bytes).run {
+ val keyMac = fixed(LinkCrypto.HASH_BYTES)
+ val proof = bytes(LinkCrypto.HASH_BYTES)
+ if (proof.isNotEmpty() && proof.size != LinkCrypto.HASH_BYTES) throw LinkError.Malformed()
+ Confirm(keyMac, proof.takeIf { it.isNotEmpty() }).also { end() }
+ }
+ }
+}
+
+/** The wallet as the phone sends it, inside the session's encryption only. [toString] prints nothing of it. */
+class SeedPayload(val network: String, val mnemonic: String, val passphrase: String?) {
+ override fun toString(): String = "SeedPayload(***)"
+
+ internal fun encode(): ByteArray = WireWriter()
+ .string(network).string(mnemonic).bool(passphrase != null).string(passphrase.orEmpty())
+ .toByteArray()
+
+ internal companion object {
+ fun decode(bytes: ByteArray): SeedPayload = WireReader(bytes).run {
+ val network = string()
+ val mnemonic = string(Handshake.MAX_SEED_BYTES)
+ val hasPassphrase = bool()
+ val passphrase = string(Handshake.MAX_SEED_BYTES)
+ SeedPayload(network, mnemonic, passphrase.takeIf { hasPassphrase }).also { end() }
+ }
+ }
+}
+
+/** Watch to phone, encrypted: whether the seed was stored, and the proof that it is the phone's wallet. */
+internal class Stored(val failure: StoreFailure?, val walletProof: ByteArray) {
+ fun encode(): ByteArray = WireWriter().byte(failure?.let { it.ordinal + 1 } ?: 0).bytes(walletProof).toByteArray()
+
+ companion object {
+ fun decode(bytes: ByteArray): Stored = WireReader(bytes).run {
+ val code = byte()
+ val failure = if (code == 0) null else StoreFailure.entries.getOrNull(code - 1) ?: StoreFailure.Failed
+ Stored(failure, bytes(LinkCrypto.HASH_BYTES)).also { end() }
+ }
+ }
+}
+
+/**
+ * The keys of one handshake, derived with HKDF-SHA256 from the ECDH shared secret, salted with the transcript hash.
+ * The handshake keys encrypt the accepts and the seed and are dropped with the session; the link keys go into each
+ * device's key store as the pairing's long-term keys. One key per direction.
+ */
+internal class SessionKeys private constructor(
+ val transcript: ByteArray,
+ private val handshakePhone: ByteArray,
+ private val handshakeWatch: ByteArray,
+ private val confirm: ByteArray,
+ val linkPhone: ByteArray,
+ val linkWatch: ByteArray,
+ val pairingId: ByteArray,
+ val code: String,
+) {
+ companion object {
+ private val INFO = "bitkit wear link v1 keys".encodeToByteArray()
+ private const val CODE_BYTES = 4
+ private const val CODE_RANGE = 1_000_000L
+ private const val UINT_MASK = 0xffffffffL
+
+ fun derive(shared: ByteArray, transcript: ByteArray): SessionKeys {
+ val size = LinkCrypto.KEY_BYTES
+ val okm = LinkCrypto.hkdf(shared, transcript, INFO, size * 5 + Handshake.PAIRING_ID_BYTES + CODE_BYTES)
+ val reader = WireReader(okm)
+ val keys = SessionKeys(
+ transcript = transcript,
+ handshakePhone = reader.fixed(size),
+ handshakeWatch = reader.fixed(size),
+ confirm = reader.fixed(size),
+ linkPhone = reader.fixed(size),
+ linkWatch = reader.fixed(size),
+ pairingId = reader.fixed(Handshake.PAIRING_ID_BYTES),
+ code = (reader.int().toLong() and UINT_MASK).rem(CODE_RANGE).toString()
+ .padStart(Handshake.CODE_DIGITS, '0'),
+ )
+ okm.fill(0)
+ return keys
+ }
+ }
+
+ fun keyMac(role: LinkRole): ByteArray = LinkCrypto.hmac(confirm, byteArrayOf(role.id.toByte()), transcript)
+
+ /** Encrypts a handshake message of [role] for [path]; the transcript and the path are bound to it. */
+ fun seal(role: LinkRole, path: String, plaintext: ByteArray, random: SecureRandom): ByteArray =
+ LinkCrypto.seal(handshakeKey(role), plaintext, aad(path), random)
+
+ fun open(role: LinkRole, path: String, blob: ByteArray): ByteArray =
+ LinkCrypto.open(handshakeKey(role), blob, aad(path))
+
+ fun clear() = listOf(handshakePhone, handshakeWatch, confirm, linkPhone, linkWatch).forEach { it.fill(0) }
+
+ private fun handshakeKey(role: LinkRole) = if (role == LinkRole.Phone) handshakePhone else handshakeWatch
+
+ private fun aad(path: String) = WireWriter().fixed(transcript).string(path).toByteArray()
+}
+
+/** What a finished pairing leaves, besides the two link keys now in the key store under [pairingId]. */
+class PairedLink(
+ val pairingId: String,
+ val mode: PairingMode,
+ val peerId: String,
+ val peerNodeId: String,
+ val peerName: String,
+ val version: Int,
+ /** The phone's verdict on the watch's key; null on the watch, which attests nothing of the phone. */
+ val attestation: AttestationVerdict?,
+ val isPeerLockSet: Boolean,
+)
+
+/** What a pairing shows while it runs; it ends by returning a [PairedLink] or throwing a [LinkError]. */
+sealed interface PairingState {
+ /** Waiting for the other device. */
+ data object Connecting : PairingState
+
+ /**
+ * Both screens show [code]; each user confirms that the two match. [attestation] is the phone's verdict on the
+ * watch's key, null on the watch.
+ */
+ data class Code(
+ val code: String,
+ val mode: PairingMode,
+ val peerName: String,
+ val attestation: AttestationVerdict?,
+ val isConfirmed: Boolean = false,
+ ) : PairingState
+
+ /** The seed is on its way to the watch's key store. */
+ data object Transferring : PairingState
+}
diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkChannel.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkChannel.kt
new file mode 100644
index 0000000000..cd19adf37f
--- /dev/null
+++ b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkChannel.kt
@@ -0,0 +1,105 @@
+package to.bitkit.wearlink
+
+import java.nio.ByteBuffer
+
+/**
+ * The two long-term keys of a pairing, in the platform's key store: imported once, never readable again. On Android
+ * they are AES-256-GCM keys in AndroidKeyStore, usable while the device is locked, so an erase command can be read
+ * on a locked watch. Every method fails with a [LinkError.KeyFailure], or [LinkError.Rejected] for bytes that are
+ * not authentic.
+ */
+interface LinkKeyStore {
+ /** Imports [key] as [alias], replacing any earlier one. The caller zeroes [key] afterwards. */
+ fun import(alias: String, key: ByteArray)
+
+ /** The IV followed by the ciphertext and tag. */
+ fun encrypt(alias: String, plaintext: ByteArray, aad: ByteArray): ByteArray
+
+ fun decrypt(alias: String, blob: ByteArray, aad: ByteArray): ByteArray
+
+ fun delete(alias: String)
+
+ /** Deletes every link key, as when no pairing is left that could own one. */
+ fun clear()
+
+ companion object {
+ /** The alias of the key [role] encrypts with in the pairing [pairingId]. */
+ fun alias(pairingId: String, role: LinkRole): String = "wearlink.$pairingId.${role.name.lowercase()}"
+ }
+}
+
+/** The message counters of a pairing, which survive a restart. */
+interface LinkCounters {
+ /** The next counter to send under, stored before it is returned so it is never used twice. */
+ suspend fun nextSend(): Long
+
+ /** The highest counter taken at [path], or 0. */
+ suspend fun received(path: String): Long
+
+ suspend fun setReceived(path: String, counter: Long)
+}
+
+/**
+ * Everything the two devices say after pairing travels in an envelope: a header in clear and the body encrypted with
+ * AES-256-GCM under the writer's link key, with the header and the path as associated data. The counter orders
+ * messages: at each path a reader takes only a counter higher than the last, so nothing is replayed, rolled back or
+ * applied out of order, whatever the carrier does. A new pairing has new keys and a new id, so nothing of an earlier
+ * one opens.
+ */
+class LinkChannel(
+ private val role: LinkRole,
+ private val pairingId: String,
+ private val keys: LinkKeyStore,
+ private val counters: LinkCounters,
+) {
+ companion object {
+ private const val MAGIC = 0x424b574c // "BKWL"
+ private const val HEADER_BYTES = Int.SIZE_BYTES + 2 + Handshake.PAIRING_ID_BYTES + Long.SIZE_BYTES
+ }
+
+ private val id = pairingId.hexToBytes()
+
+ /** An envelope of [body] for [path], under the next counter. */
+ suspend fun seal(path: String, body: ByteArray): Sealed {
+ val counter = counters.nextSend()
+ val header = header(role, counter)
+ val blob = keys.encrypt(LinkKeyStore.alias(pairingId, role), body, header + path.encodeToByteArray())
+ return Sealed(counter, header + blob)
+ }
+
+ /**
+ * The body of [envelope] as it arrived at [path], or a [LinkError.Rejected] when it is not the peer's, not for
+ * this pairing and path, or not newer than the last one taken there. The reader applies the body and then
+ * [commit]s its counter, so a body whose effect a crash cut short is taken again when it is delivered again.
+ */
+ suspend fun open(path: String, envelope: ByteArray): Opened {
+ if (envelope.size <= HEADER_BYTES) throw LinkError.Rejected("too short")
+ val buffer = ByteBuffer.wrap(envelope, 0, HEADER_BYTES)
+ if (buffer.getInt() != MAGIC) throw LinkError.Rejected("not an envelope")
+ if (buffer.get().toInt() != Handshake.VERSION) throw LinkError.Rejected("another version")
+ if (buffer.get().toInt() != role.peer.id) throw LinkError.Rejected("wrong writer")
+ val pairing = ByteArray(Handshake.PAIRING_ID_BYTES).also { buffer.get(it) }
+ if (!pairing.contentEquals(id)) throw LinkError.Rejected("another pairing")
+ val counter = buffer.getLong()
+ val header = envelope.copyOfRange(0, HEADER_BYTES)
+ val blob = envelope.copyOfRange(HEADER_BYTES, envelope.size)
+ val body = keys.decrypt(LinkKeyStore.alias(pairingId, role.peer), blob, header + path.encodeToByteArray())
+ if (counter <= counters.received(path)) throw LinkError.Rejected("not newer")
+ return Opened(counter, body)
+ }
+
+ /** Records that the envelope with [counter] at [path] was applied; nothing as old is taken there again. */
+ suspend fun commit(path: String, counter: Long) = counters.setReceived(path, counter)
+
+ private fun header(writer: LinkRole, counter: Long): ByteArray = ByteBuffer.allocate(HEADER_BYTES)
+ .putInt(MAGIC)
+ .put(Handshake.VERSION.toByte())
+ .put(writer.id.toByte())
+ .put(id)
+ .putLong(counter)
+ .array()
+
+ class Sealed(val counter: Long, val envelope: ByteArray)
+
+ class Opened(val counter: Long, val body: ByteArray)
+}
diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkCrypto.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkCrypto.kt
new file mode 100644
index 0000000000..52c47c37c4
--- /dev/null
+++ b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkCrypto.kt
@@ -0,0 +1,127 @@
+package to.bitkit.wearlink
+
+import org.bouncycastle.crypto.digests.SHA256Digest
+import org.bouncycastle.crypto.generators.HKDFBytesGenerator
+import org.bouncycastle.crypto.params.HKDFParameters
+import java.security.AlgorithmParameters
+import java.security.KeyFactory
+import java.security.KeyPair
+import java.security.KeyPairGenerator
+import java.security.MessageDigest
+import java.security.PrivateKey
+import java.security.PublicKey
+import java.security.SecureRandom
+import java.security.interfaces.ECPublicKey
+import java.security.spec.ECFieldFp
+import java.security.spec.ECGenParameterSpec
+import java.security.spec.ECParameterSpec
+import java.security.spec.ECPoint
+import java.security.spec.X509EncodedKeySpec
+import javax.crypto.Cipher
+import javax.crypto.KeyAgreement
+import javax.crypto.Mac
+import javax.crypto.spec.GCMParameterSpec
+import javax.crypto.spec.SecretKeySpec
+
+/**
+ * The link's primitives, each one a call into the platform's providers or BouncyCastle: SHA-256, HMAC-SHA256,
+ * HKDF-SHA256 (BouncyCastle), AES-256-GCM, and P-256 key agreement. Nothing here implements an algorithm.
+ */
+object LinkCrypto {
+ const val KEY_BYTES = 32
+ const val IV_BYTES = 12
+ const val HASH_BYTES = 32
+ private const val TAG_BITS = 128
+ private const val HMAC = "HmacSHA256"
+ private const val AES_GCM = "AES/GCM/NoPadding"
+ private const val CURVE = "secp256r1"
+ private const val FIELD_BITS = 256
+
+ private val p256: ECParameterSpec by lazy {
+ AlgorithmParameters.getInstance("EC").run {
+ init(ECGenParameterSpec(CURVE))
+ getParameterSpec(ECParameterSpec::class.java)
+ }
+ }
+
+ fun sha256(vararg parts: ByteArray): ByteArray = MessageDigest.getInstance("SHA-256").run {
+ parts.forEach(::update)
+ digest()
+ }
+
+ fun hmac(key: ByteArray, vararg parts: ByteArray): ByteArray = Mac.getInstance(HMAC).run {
+ init(SecretKeySpec(key, HMAC))
+ parts.forEach(::update)
+ doFinal()
+ }
+
+ /** HKDF-SHA256 (RFC 5869), extract and expand, by BouncyCastle. */
+ fun hkdf(ikm: ByteArray, salt: ByteArray, info: ByteArray, length: Int): ByteArray {
+ val generator = HKDFBytesGenerator(SHA256Digest())
+ generator.init(HKDFParameters(ikm, salt, info))
+ return ByteArray(length).also { generator.generateBytes(it, 0, length) }
+ }
+
+ fun isEqual(a: ByteArray, b: ByteArray): Boolean = MessageDigest.isEqual(a, b)
+
+ /** The IV followed by the ciphertext and tag of [plaintext] under [key], bound to [aad]. */
+ fun seal(key: ByteArray, plaintext: ByteArray, aad: ByteArray, random: SecureRandom): ByteArray {
+ val iv = ByteArray(IV_BYTES).also(random::nextBytes)
+ val cipher = Cipher.getInstance(AES_GCM)
+ cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(TAG_BITS, iv))
+ cipher.updateAAD(aad)
+ return iv + cipher.doFinal(plaintext)
+ }
+
+ /** Reverses [seal]; fails with [LinkError.Rejected] when the key, the bytes or [aad] differ. */
+ fun open(key: ByteArray, blob: ByteArray, aad: ByteArray): ByteArray {
+ if (blob.size <= IV_BYTES) throw LinkError.Rejected("too short")
+ return runCatching {
+ val cipher = Cipher.getInstance(AES_GCM)
+ cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(TAG_BITS, blob, 0, IV_BYTES))
+ cipher.updateAAD(aad)
+ cipher.doFinal(blob, IV_BYTES, blob.size - IV_BYTES)
+ }.getOrElse { throw LinkError.Rejected("not authentic") }
+ }
+
+ fun generateKeyPair(random: SecureRandom): KeyPair = KeyPairGenerator.getInstance("EC").run {
+ initialize(ECGenParameterSpec(CURVE), random)
+ generateKeyPair()
+ }
+
+ /**
+ * Reads an X.509 encoded public key and accepts it only as a point of P-256, so a peer cannot move the key
+ * agreement to another curve or to a point outside it.
+ */
+ fun decodePublicKey(encoded: ByteArray): ECPublicKey {
+ val key = runCatching {
+ KeyFactory.getInstance("EC").generatePublic(X509EncodedKeySpec(encoded)) as ECPublicKey
+ }.getOrElse { throw LinkError.Malformed(it) }
+ if (!isOnP256(key)) throw LinkError.Malformed()
+ return key
+ }
+
+ fun isOnP256(key: ECPublicKey): Boolean {
+ val params = key.params
+ val curve = p256.curve
+ val prime = (curve.field as ECFieldFp).p
+ val isP256 = params.curve == curve && params.generator == p256.generator && params.order == p256.order &&
+ params.cofactor == 1 && curve.field.fieldSize == FIELD_BITS
+ val point = key.w
+ if (!isP256 || point == ECPoint.POINT_INFINITY) return false
+ val x = point.affineX
+ val y = point.affineY
+ if (x.signum() < 0 || x >= prime || y.signum() < 0 || y >= prime) return false
+ val right = x.pow(CUBE).add(curve.a.multiply(x)).add(curve.b).mod(prime)
+ return y.multiply(y).mod(prime) == right
+ }
+
+ /** The raw ECDH shared secret of [privateKey] and [peer]. */
+ fun agree(privateKey: PrivateKey, peer: PublicKey): ByteArray = KeyAgreement.getInstance("ECDH").run {
+ init(privateKey)
+ doPhase(peer, true)
+ generateSecret()
+ }
+
+ private const val CUBE = 3
+}
diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkDocs.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkDocs.kt
new file mode 100644
index 0000000000..2993480e13
--- /dev/null
+++ b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkDocs.kt
@@ -0,0 +1,124 @@
+package to.bitkit.wearlink
+
+import kotlinx.coroutines.flow.Flow
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.Json
+
+/** The state documents of a pairing. Each has one writer and is a full snapshot, so applying one twice is harmless. */
+internal val linkJson = Json {
+ ignoreUnknownKeys = true
+ encodeDefaults = true
+}
+
+/** Phone to watch: whether the pairing stands. [Revoked] and [Erase] are final for the pairing. */
+@Serializable
+data class ControlDoc(val state: State) {
+ enum class State {
+ Paired,
+
+ /** The phone removed the watch; the watch forgets the phone and keeps its wallet. */
+ Revoked,
+
+ /** The phone removed the watch and asks it to delete its wallet. */
+ Erase,
+ }
+}
+
+/**
+ * Phone to watch: the phone's settings the watch adopts, as the phone's settings backup names them, and when the
+ * phone last changed them, by the phone's clock in epoch milliseconds.
+ */
+@Serializable
+data class SettingsDoc(
+ val primaryDisplay: String? = null,
+ val displayUnit: String? = null,
+ val selectedCurrency: String? = null,
+ val isQuickPayEnabled: Boolean = false,
+ val quickPayAmount: Int = 0,
+ val quickPayDailyLimitMultiplier: Int = 0,
+ val changedAtMs: Long = 0,
+)
+
+/** Watch to phone: what the watch has applied, and whether it still holds the pairing. */
+@Serializable
+data class StatusDoc(
+ val state: State,
+ /** The counter of the last settings document the watch applied. */
+ val settingsCounter: Long = 0,
+ val appVersion: String = "",
+ val isLockSet: Boolean = false,
+) {
+ enum class State {
+ Paired,
+
+ /** The watch forgot the phone, by the wearer's choice or the phone's. */
+ Unpaired,
+
+ /** The watch is deleting its wallet as the phone asked; sent before the keys are gone. */
+ Erased,
+ }
+}
+
+/** A removal the phone asked for and the watch has not acknowledged. */
+enum class Removal { Unpair, Erase }
+
+/**
+ * One device's note of its pairing. It holds nothing secret: the keys are in the key store, under [pairingId].
+ * [settingsSent] is the counter of the phone's last settings document, and [settingsApplied] the last one the watch
+ * applied, as the watch reported it (phone) or did it (watch). [settingsChangedAtMs] is the phone's time of the last
+ * settings the watch applied from a push.
+ */
+@Serializable
+data class LinkRecord(
+ val pairingId: String,
+ val peerId: String,
+ val peerNodeId: String,
+ val peerName: String,
+ val pairedAtMs: Long,
+ val isSeedTransferred: Boolean = false,
+ /** Where the watch's attested key lives, or null when its attestation was not verified. */
+ val keyLevel: KeyLevel? = null,
+ val isPeerLockSet: Boolean = false,
+ val sendCounter: Long = 0,
+ val received: Map = emptyMap(),
+ val removal: Removal? = null,
+ val settingsSent: Long = 0,
+ val settingsApplied: Long = 0,
+ val settingsChangedAtMs: Long = 0,
+ val lastSeenMs: Long = 0,
+) {
+ val isSettingsUpToDate: Boolean get() = settingsApplied >= settingsSent
+
+ fun encode(): String = linkJson.encodeToString(serializer(), this)
+
+ companion object {
+ /** The record [text] holds, or null when it is not one. */
+ fun decode(text: String): LinkRecord? =
+ runCatching { linkJson.decodeFromString(serializer(), text) }.getOrNull()
+ }
+}
+
+/** Where a device keeps its one [LinkRecord]. Updates are atomic and stored before they return. */
+interface LinkRecordStore {
+ val record: Flow
+
+ suspend fun load(): LinkRecord?
+
+ suspend fun update(transform: (LinkRecord?) -> LinkRecord?): LinkRecord?
+}
+
+internal class RecordCounters(private val store: LinkRecordStore, private val pairingId: String) : LinkCounters {
+ override suspend fun nextSend(): Long {
+ val record = store.update { if (it?.pairingId == pairingId) it.copy(sendCounter = it.sendCounter + 1) else it }
+ return record?.takeIf { it.pairingId == pairingId }?.sendCounter ?: throw LinkError.NotPaired()
+ }
+
+ override suspend fun received(path: String): Long =
+ store.load()?.takeIf { it.pairingId == pairingId }?.received?.get(path) ?: 0
+
+ override suspend fun setReceived(path: String, counter: Long) {
+ store.update {
+ if (it?.pairingId == pairingId) it.copy(received = it.received + (path to counter)) else it
+ }
+ }
+}
diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkEndpoints.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkEndpoints.kt
new file mode 100644
index 0000000000..c7009b7137
--- /dev/null
+++ b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkEndpoints.kt
@@ -0,0 +1,271 @@
+package to.bitkit.wearlink
+
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.flow.asSharedFlow
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+
+/**
+ * One device's end of the link after pairing: it seals and publishes this device's documents and takes the peer's.
+ * Everything that arrives passes through [onPacket], one packet at a time. The handshake's messages are handed on
+ * to [pairingPackets], for the pairing session that may be running.
+ */
+abstract class LinkEndpoint internal constructor(
+ private val role: LinkRole,
+ protected val transport: LinkTransport,
+ protected val keys: LinkKeyStore,
+ protected val store: LinkRecordStore,
+) {
+ private val mutex = Mutex()
+ private val _pairingPackets = MutableSharedFlow(extraBufferCapacity = PAIRING_BUFFER)
+ val pairingPackets: Flow = _pairingPackets.asSharedFlow()
+
+ val record: Flow get() = store.record
+
+ /**
+ * Takes what arrived. Fails with a [LinkError] for anything that is not an authentic, new document of the
+ * current pairing; such a packet changes nothing.
+ */
+ suspend fun onPacket(packet: LinkPacket) {
+ if (LinkPaths.isPairing(packet.path)) {
+ _pairingPackets.emit(packet)
+ return
+ }
+ mutex.withLock {
+ val record = store.load() ?: throw LinkError.NotPaired()
+ val name = LinkPaths.stateName(record.pairingId, packet.path) ?: throw LinkError.Rejected("another pairing")
+ val channel = channel(record.pairingId)
+ val opened = channel.open(packet.path, packet.payload)
+ apply(record, name, opened.body, opened.counter)
+ // A document that ended the pairing took its record with it.
+ if (store.load()?.pairingId == record.pairingId) channel.commit(packet.path, opened.counter)
+ }
+ }
+
+ internal abstract suspend fun apply(record: LinkRecord, name: String, body: ByteArray, counter: Long)
+
+ protected suspend fun locked(block: suspend () -> T): T = mutex.withLock { block() }
+
+ /**
+ * Seals [body] as the document [name] and publishes it both ways: stored, so it arrives after a reconnect, and
+ * sent at once, which fails silently when the peer is away. Returns the counter it went out under.
+ */
+ protected suspend fun publish(record: LinkRecord, name: String, body: ByteArray): Long {
+ val path = LinkPaths.state(record.pairingId, name)
+ val sealed = channel(record.pairingId).seal(path, body)
+ transport.putState(path, sealed.envelope)
+ runSuspendCatching { transport.send(record.peerNodeId, path, sealed.envelope) }
+ return sealed.counter
+ }
+
+ /** Replaces the record with the one of a pairing that just finished, dropping the keys of the one before. */
+ protected suspend fun replace(link: PairedLink, nowMs: Long): LinkRecord {
+ val old = store.load()
+ val record = LinkRecord(
+ pairingId = link.pairingId,
+ peerId = link.peerId,
+ peerNodeId = link.peerNodeId,
+ peerName = link.peerName,
+ pairedAtMs = nowMs,
+ isSeedTransferred = link.mode == PairingMode.Transfer,
+ keyLevel = (link.attestation as? AttestationVerdict.Verified)?.level,
+ isPeerLockSet = link.isPeerLockSet,
+ lastSeenMs = nowMs,
+ )
+ store.update { record }
+ if (old != null && old.pairingId != link.pairingId) deleteKeys(old.pairingId)
+ return record
+ }
+
+ /** Deletes the record, then the documents [staleStates] this device published, then the keys. */
+ protected suspend fun drop(record: LinkRecord, vararg staleStates: String) {
+ store.update { if (it?.pairingId == record.pairingId) null else it }
+ staleStates.forEach { name ->
+ runSuspendCatching { transport.deleteState(LinkPaths.state(record.pairingId, name)) }
+ }
+ deleteKeys(record.pairingId)
+ }
+
+ private fun deleteKeys(pairingId: String) = LinkRole.entries.forEach {
+ runCatching { keys.delete(LinkKeyStore.alias(pairingId, it)) }
+ }
+
+ private fun channel(pairingId: String) = LinkChannel(role, pairingId, keys, RecordCounters(store, pairingId))
+
+ private companion object {
+ const val PAIRING_BUFFER = 32
+ }
+}
+
+/**
+ * The phone's end: it publishes the control and settings documents and reads the watch's status.
+ *
+ * [onSettingsMissed] is called, without waiting for it, when the watch reports that it has applied no settings
+ * though some were published: the phone finished pairing and published before the watch had noted the pairing, so
+ * the watch dropped them. The phone app then publishes its settings again. It happens at most once per pairing.
+ */
+class PhoneLink(
+ transport: LinkTransport,
+ keys: LinkKeyStore,
+ store: LinkRecordStore,
+ private val onSettingsMissed: () -> Unit = {},
+ private val nowMs: () -> Long,
+) : LinkEndpoint(LinkRole.Phone, transport, keys, store) {
+ /** Notes the finished pairing with [link], replacing any earlier watch, and tells the watch it stands. */
+ suspend fun onPaired(link: PairedLink): LinkRecord = locked {
+ val record = replace(link, nowMs())
+ publish(record, LinkPaths.CONTROL, encode(ControlDoc(ControlDoc.State.Paired)))
+ record
+ }
+
+ /**
+ * Publishes the phone's settings to the paired watch. [SettingsDoc.changedAtMs] is made later than the last one
+ * sent, whatever the clock did. Nothing happens without a pairing, or while a removal waits.
+ */
+ suspend fun publishSettings(settings: SettingsDoc): Unit = locked {
+ val record = store.load()?.takeIf { it.removal == null } ?: return@locked
+ val changedAtMs = maxOf(settings.changedAtMs, record.settingsChangedAtMs + 1)
+ val counter = publish(record, LinkPaths.SETTINGS, encode(settings.copy(changedAtMs = changedAtMs)))
+ store.update {
+ if (it?.pairingId != record.pairingId) return@update it
+ it.copy(settingsSent = counter, settingsChangedAtMs = changedAtMs)
+ }
+ }
+
+ /**
+ * Asks the watch to forget the phone, and with [isErase] to delete its wallet too. The record stays, marked,
+ * until the watch acknowledges or [forget] drops it: an erase is best effort, since a watch that never
+ * reconnects never reads it.
+ */
+ suspend fun remove(isErase: Boolean): Unit = locked {
+ val record = store.load() ?: throw LinkError.NotPaired()
+ val state = if (isErase) ControlDoc.State.Erase else ControlDoc.State.Revoked
+ val removal = if (isErase) Removal.Erase else Removal.Unpair
+ store.update { if (it?.pairingId == record.pairingId) it.copy(removal = removal) else it }
+ publish(record, LinkPaths.CONTROL, encode(ControlDoc(state)))
+ }
+
+ /**
+ * Drops the pairing on the phone without waiting for the watch: a removal the user stopped waiting for, or the
+ * phone's wallet being wiped or replaced. The watch is told it is revoked first, unless a removal already told
+ * it more; the stored control document stays, so a watch that is away reads it when it returns.
+ */
+ suspend fun forget(): Unit = locked {
+ val record = store.load() ?: return@locked
+ if (record.removal == null) {
+ runSuspendCatching { publish(record, LinkPaths.CONTROL, encode(ControlDoc(ControlDoc.State.Revoked))) }
+ }
+ drop(record, LinkPaths.SETTINGS)
+ }
+
+ override suspend fun apply(record: LinkRecord, name: String, body: ByteArray, counter: Long) {
+ if (name != LinkPaths.STATUS) throw LinkError.Rejected("unknown document")
+ val status = decode(body)
+ if (status.state != StatusDoc.State.Paired) {
+ drop(record, LinkPaths.SETTINGS, LinkPaths.CONTROL)
+ return
+ }
+ store.update {
+ if (it?.pairingId != record.pairingId) return@update it
+ it.copy(
+ settingsApplied = maxOf(it.settingsApplied, status.settingsCounter),
+ isPeerLockSet = status.isLockSet,
+ lastSeenMs = nowMs(),
+ )
+ }
+ if (status.settingsCounter == 0L && record.settingsSent > 0) onSettingsMissed()
+ }
+}
+
+/** What the watch app does with what the phone sends. */
+interface WatchLinkListener {
+ /** Adopts the phone's settings, by the same rules as the import of the phone's backup. */
+ suspend fun applySettings(settings: SettingsDoc)
+
+ /**
+ * Notes durably that the wallet is to be deleted, so that from here on the deletion is finished even when the
+ * app dies first. Fails when the note cannot be written; the erase is then not acknowledged and not run.
+ */
+ suspend fun prepareErase()
+
+ /** Deletes the wallet from the watch, as the phone asked, after [prepareErase]. */
+ suspend fun erase()
+
+ /** The pairing ended; whatever the watch kept of the phone's pushes is dropped. */
+ suspend fun onUnpaired()
+}
+
+/** What the watch reports about itself in its status. */
+class WatchInfo(val appVersion: String, val isLockSet: Boolean)
+
+/** The watch's end: it reads the control and settings documents and publishes its status. */
+class WatchLink(
+ transport: LinkTransport,
+ keys: LinkKeyStore,
+ store: LinkRecordStore,
+ private val listener: WatchLinkListener,
+ private val info: suspend () -> WatchInfo,
+ private val nowMs: () -> Long,
+) : LinkEndpoint(LinkRole.Watch, transport, keys, store) {
+ /** Notes the finished pairing with [link]; the watch keeps one phone, so it replaces any earlier one. */
+ suspend fun onPaired(link: PairedLink): LinkRecord = locked {
+ val record = replace(link, nowMs())
+ publishStatus(record, StatusDoc.State.Paired)
+ record
+ }
+
+ /** The wearer's unpair, also before the wallet is removed from the watch: tells the phone, then forgets it. */
+ suspend fun unpair(): Unit = locked {
+ val record = store.load() ?: return@locked
+ end(record, StatusDoc.State.Unpaired)
+ }
+
+ override suspend fun apply(record: LinkRecord, name: String, body: ByteArray, counter: Long) {
+ when (name) {
+ LinkPaths.SETTINGS -> {
+ val settings = decode(body)
+ listener.applySettings(settings)
+ val updated = store.update {
+ if (it?.pairingId != record.pairingId) return@update it
+ it.copy(settingsApplied = counter, settingsChangedAtMs = settings.changedAtMs, lastSeenMs = nowMs())
+ }
+ if (updated != null) publishStatus(updated, StatusDoc.State.Paired)
+ }
+ LinkPaths.CONTROL -> when (decode(body).state) {
+ ControlDoc.State.Paired -> store.update {
+ if (it?.pairingId == record.pairingId) it.copy(lastSeenMs = nowMs()) else it
+ }
+ ControlDoc.State.Revoked -> end(record, StatusDoc.State.Unpaired)
+ ControlDoc.State.Erase -> {
+ // The phone withdraws the command once it is acknowledged, so the wipe is noted durably first:
+ // from then on it is finished at the next launch at the latest. A note that cannot be written
+ // ends this here, unacknowledged, and the command arrives again. The acknowledgement goes out
+ // before the wipe because the wipe takes the pairing, and with it the keys to say so.
+ listener.prepareErase()
+ runSuspendCatching { publishStatus(record, StatusDoc.State.Erased) }
+ listener.erase()
+ drop(record)
+ }
+ }
+ else -> throw LinkError.Rejected("unknown document")
+ }
+ }
+
+ private suspend fun end(record: LinkRecord, state: StatusDoc.State) {
+ runSuspendCatching { publishStatus(record, state) }
+ drop(record)
+ listener.onUnpaired()
+ }
+
+ private suspend fun publishStatus(record: LinkRecord, state: StatusDoc.State) {
+ val info = info()
+ val status = StatusDoc(state, record.settingsApplied, info.appVersion, info.isLockSet)
+ publish(record, LinkPaths.STATUS, encode(status))
+ }
+}
+
+private inline fun encode(value: T): ByteArray = linkJson.encodeToString(value).encodeToByteArray()
+
+private inline fun decode(body: ByteArray): T =
+ runCatching { linkJson.decodeFromString(body.decodeToString()) }.getOrElse { throw LinkError.Malformed(it) }
diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkError.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkError.kt
new file mode 100644
index 0000000000..276a7bf441
--- /dev/null
+++ b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkError.kt
@@ -0,0 +1,57 @@
+package to.bitkit.wearlink
+
+/** Every failure of the link. A message never holds key material, a recovery phrase or a confirmation code. */
+sealed class LinkError(message: String, cause: Throwable? = null) : Exception(message, cause) {
+ /** A message that is not what this version of the protocol writes. */
+ class Malformed(cause: Throwable? = null) : LinkError("The message cannot be read", cause)
+
+ /** The two apps share no protocol version. */
+ class UpdateRequired : LinkError("The peer speaks another protocol version")
+
+ class Timeout : LinkError("The pairing timed out")
+
+ /** This device's user cancelled. */
+ class Cancelled : LinkError("The pairing was cancelled")
+
+ /** The other device ended the pairing; [reason] is what it said, which nothing authenticates. */
+ class PeerAborted(val reason: AbortReason) : LinkError("The peer ended the pairing with '$reason'")
+
+ /** The watch holds a wallet, and it is not this phone's. */
+ class DifferentWallet : LinkError("The peer holds a different wallet")
+
+ /** The two sides did not derive the same keys: the handshake was altered on the way. */
+ class KeyMismatch : LinkError("The peer derived other keys")
+
+ /** The watch's key could not be shown to live in its secure hardware, so no seed is sent to it. */
+ class AttestationFailed(val failure: AttestationFailure) :
+ LinkError("The watch's key attestation failed with '$failure'")
+
+ /** Too many seed transfers were started and not finished; none starts before [untilMs]. */
+ class Throttled(val untilMs: Long) : LinkError("Seed transfer is locked")
+
+ /** The phone app has no PIN, so its user cannot be checked before a seed is sent; none is. */
+ class PinRequired : LinkError("The phone has no PIN to authorize a seed transfer")
+
+ /** The seed transfer was confirmed without this phone's own authentication. */
+ class NotAuthorized : LinkError("The seed transfer was not authorized")
+
+ /** The watch did not store the seed it was sent. */
+ class TransferFailed(val reason: StoreFailure) : LinkError("The watch did not store the wallet: '$reason'")
+
+ /** The peer cannot be reached now. */
+ class Unreachable(cause: Throwable? = null) : LinkError("The peer is not reachable", cause)
+
+ /** An envelope that is not for this pairing, was altered, or is not newer than the last one taken. */
+ class Rejected(why: String) : LinkError("Rejected an envelope: $why")
+
+ class NotPaired : LinkError("No peer is paired")
+
+ /** A key operation failed in the platform's key store. */
+ class KeyFailure(cause: Throwable? = null) : LinkError("The link key operation failed", cause)
+}
+
+/** Why a side ended a pairing, as told to the other in clear. It only picks the line the other shows. */
+enum class AbortReason { Cancelled, DifferentWallet, UpdateRequired, Unverified, Failed }
+
+/** Why the watch did not store a seed it received. */
+enum class StoreFailure { InvalidPhrase, WrongNetwork, InsecureKey, HasWallet, Failed }
diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkTransport.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkTransport.kt
new file mode 100644
index 0000000000..a4050da49d
--- /dev/null
+++ b/wearlink/src/main/kotlin/to/bitkit/wearlink/LinkTransport.kt
@@ -0,0 +1,87 @@
+package to.bitkit.wearlink
+
+/**
+ * How bytes travel between the phone and the watch. The link treats it as an untrusted carrier: everything it
+ * carries after the first handshake messages is authenticated by the link itself.
+ *
+ * Two kinds of delivery, as the Wear Data Layer offers them. [send] is a one-shot message that only arrives while
+ * the peer is connected, and is never stored: the handshake and the wallet seed only ever travel this way.
+ * [putState] stores one document per path and delivers the latest when the two reconnect; it carries only state the
+ * link has encrypted, and never a seed.
+ */
+interface LinkTransport {
+ /** The devices connected to this one. */
+ suspend fun nodes(): List
+
+ /** Sends [payload] once; fails with [LinkError.Unreachable] when [nodeId] cannot be reached now. */
+ suspend fun send(nodeId: String, path: String, payload: ByteArray)
+
+ /** Stores [payload] as the document at [path], replacing the earlier one, for the peer to receive. */
+ suspend fun putState(path: String, payload: ByteArray)
+
+ suspend fun deleteState(path: String)
+
+ /** Opens [uri] on [nodeId], as when the phone brings the watch app to the front. */
+ suspend fun open(nodeId: String, uri: String)
+
+ /** Hands everything that arrives, by either kind of delivery, to [receiver]. */
+ fun attach(receiver: suspend (LinkPacket) -> Unit)
+}
+
+/**
+ * A connected device. [isNearby] is whether it is reached directly rather than through the cloud, and [hasApp]
+ * whether Bitkit is installed on it.
+ */
+data class LinkNode(
+ val id: String,
+ val name: String,
+ val isNearby: Boolean,
+ val hasApp: Boolean,
+)
+
+/** What arrived from [nodeId] at [path]. */
+class LinkPacket(
+ val nodeId: String,
+ val path: String,
+ val payload: ByteArray,
+)
+
+/** The two ends of a link. A message is always bound to the role that wrote it, so it cannot be sent back. */
+enum class LinkRole(val id: Int) {
+ Phone(1),
+ Watch(2),
+ ;
+
+ val peer: LinkRole get() = if (this == Phone) Watch else Phone
+}
+
+object LinkPaths {
+ const val ROOT = "/bitkit/v1"
+
+ /** The handshake's one-shot messages. */
+ const val PAIR = "$ROOT/pair"
+ const val HELLO = "$PAIR/hello"
+ const val REPLY = "$PAIR/reply"
+ const val REVEAL = "$PAIR/reveal"
+ const val CONFIRM = "$PAIR/confirm"
+ const val ACCEPT = "$PAIR/accept"
+ const val SEED = "$PAIR/seed"
+ const val STORED = "$PAIR/stored"
+ const val ABORT = "$PAIR/abort"
+
+ /** The link the watch app opens its Pair screen for. */
+ const val PAIR_URI = "bitkitwear://pair"
+
+ const val CONTROL = "p2w/control"
+ const val SETTINGS = "p2w/settings"
+ const val STATUS = "w2p/status"
+
+ fun isPairing(path: String): Boolean = path.startsWith("$PAIR/")
+
+ /** The path of the state document [name] of the pairing [pairingId]. */
+ fun state(pairingId: String, name: String): String = "$ROOT/$pairingId/$name"
+
+ /** The document name of a state [path], or null when it is not one of [pairingId]'s. */
+ fun stateName(pairingId: String, path: String): String? =
+ path.removePrefix("$ROOT/$pairingId/").takeIf { it != path }
+}
diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/PairingSession.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/PairingSession.kt
new file mode 100644
index 0000000000..aac5f9348f
--- /dev/null
+++ b/wearlink/src/main/kotlin/to/bitkit/wearlink/PairingSession.kt
@@ -0,0 +1,196 @@
+package to.bitkit.wearlink
+
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.CoroutineStart
+import kotlinx.coroutines.NonCancellable
+import kotlinx.coroutines.async
+import kotlinx.coroutines.channels.BufferOverflow
+import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.selects.select
+import kotlinx.coroutines.withContext
+import kotlinx.coroutines.withTimeoutOrNull
+import java.security.SecureRandom
+
+internal suspend inline fun runSuspendCatching(crossinline block: suspend () -> T): Result =
+ try {
+ Result.success(block())
+ } catch (c: CancellationException) {
+ throw c
+ } catch (e: Throwable) {
+ Result.failure(e)
+ }
+
+/**
+ * One run of the pairing ceremony on one device. [run] is the whole ceremony as one sequence: each step waits for
+ * exactly the message it expects from the one peer, so a message that is early, late, repeated or from another
+ * device is never acted on. It ends once: with the pairing, or with the [LinkError] that ended it, after telling the
+ * peer. Nothing of a session is reused by another.
+ */
+abstract class PairingSession internal constructor(
+ protected val transport: LinkTransport,
+ private val incoming: Flow,
+ protected val random: SecureRandom,
+) {
+ private companion object {
+ const val INBOX_CAPACITY = 32
+ val ACCEPT_BODY = "accept".encodeToByteArray()
+ }
+
+ private val _state = MutableStateFlow(PairingState.Connecting)
+ val state: StateFlow = _state.asStateFlow()
+
+ private val cancelled = CompletableDeferred()
+ private val confirmed = CompletableDeferred()
+ private val inbox = Channel(INBOX_CAPACITY, BufferOverflow.DROP_LATEST)
+
+ /** The one device this session talks to, once known. */
+ protected var peerNodeId: String? = null
+
+ internal var keys: SessionKeys? = null
+
+ protected abstract val role: LinkRole
+
+ /**
+ * This device's user says the code matches the other screen's. [isAuthenticated] is whether the phone's user
+ * passed the phone's own authentication just now; a seed is only ever sent after a confirmation that says so.
+ * It counts only while [code] is the code this session shows: no user can have compared any other.
+ */
+ fun confirm(code: String, isAuthenticated: Boolean = false) {
+ val shown = _state.value as? PairingState.Code ?: return
+ if (shown.code != code || !confirmed.complete(isAuthenticated)) return
+ _state.update { if (it is PairingState.Code) it.copy(isConfirmed = true) else it }
+ }
+
+ /** This device's user ends the pairing. */
+ fun cancel() {
+ cancelled.complete(Unit)
+ }
+
+ /** Runs the ceremony to its end, at most [Handshake.TIMEOUT]. Throws the [LinkError] that ended it. */
+ suspend fun run(): PairedLink = coroutineScope {
+ val collector = launch(start = CoroutineStart.UNDISPATCHED) { incoming.collect { inbox.trySend(it) } }
+ var result: Result? = null
+ try {
+ result = runSuspendCatching {
+ if (cancelled.isCompleted) throw LinkError.Cancelled()
+ withTimeoutOrNull(Handshake.TIMEOUT) { ceremony() } ?: throw LinkError.Timeout()
+ }
+ } finally {
+ collector.cancel()
+ val error = result.let { if (it == null) LinkError.Cancelled() else it.exceptionOrNull() }
+ withContext(NonCancellable) {
+ if (error != null) runSuspendCatching { tellPeer(error) }
+ keys?.clear()
+ runSuspendCatching { cleanUp() }
+ }
+ }
+ checkNotNull(result).getOrThrow()
+ }
+
+ internal abstract suspend fun ceremony(): PairedLink
+
+ internal open suspend fun cleanUp() = Unit
+
+ protected fun show(state: PairingState) = _state.update { state }
+
+ protected fun bytes(size: Int): ByteArray = ByteArray(size).also(random::nextBytes)
+
+ protected suspend fun send(path: String, payload: ByteArray) {
+ val nodeId = peerNodeId ?: throw LinkError.NotPaired()
+ runSuspendCatching { transport.send(nodeId, path, payload) }
+ .getOrElse { throw it as? LinkError ?: LinkError.Unreachable(it) }
+ }
+
+ /**
+ * The next message at [path] from the peer, or from any device while none is known. Whatever else arrives goes to
+ * [onOther] and is otherwise dropped. Ends with [LinkError.Cancelled] or [LinkError.PeerAborted].
+ */
+ protected suspend fun receive(path: String, onOther: suspend (LinkPacket) -> Unit = {}): LinkPacket {
+ while (true) {
+ val packet = select {
+ cancelled.onAwait { throw LinkError.Cancelled() }
+ inbox.onReceive { it }
+ }
+ if (peerNodeId != null && packet.nodeId != peerNodeId) continue
+ if (packet.path == LinkPaths.ABORT && peerNodeId != null) throw LinkError.PeerAborted(abortReason(packet))
+ if (packet.path == path) return packet
+ onOther(packet)
+ }
+ }
+
+ /** Runs [block], which waits for something outside the link, and gives up on it when the user cancels. */
+ protected suspend fun unlessCancelled(block: suspend () -> T): T = coroutineScope {
+ val work = async { block() }
+ select {
+ cancelled.onAwait {
+ work.cancel()
+ throw LinkError.Cancelled()
+ }
+ work.onAwait { it }
+ }
+ }
+
+ /**
+ * Shows the code and waits until this device's user confirmed it and the peer's accept arrived, in either order.
+ * This device's accept is sent the moment its user confirms. A seed transfer needs an authenticated confirmation
+ * on the phone: [mustAuthenticate].
+ */
+ internal suspend fun exchangeAccepts(session: SessionKeys, mustAuthenticate: Boolean) {
+ var isLocal = false
+ var isPeer = false
+ while (!isLocal || !isPeer) {
+ select {
+ cancelled.onAwait { throw LinkError.Cancelled() }
+ if (!isLocal) {
+ confirmed.onAwait { isAuthenticated ->
+ if (mustAuthenticate && !isAuthenticated) throw LinkError.NotAuthorized()
+ send(LinkPaths.ACCEPT, session.seal(role, LinkPaths.ACCEPT, ACCEPT_BODY, random))
+ isLocal = true
+ }
+ }
+ inbox.onReceive { packet ->
+ if (packet.nodeId != peerNodeId) return@onReceive
+ if (packet.path == LinkPaths.ABORT) throw LinkError.PeerAborted(abortReason(packet))
+ if (packet.path != LinkPaths.ACCEPT || isPeer) return@onReceive
+ val body = session.open(role.peer, LinkPaths.ACCEPT, packet.payload)
+ if (!body.contentEquals(ACCEPT_BODY)) throw LinkError.Malformed()
+ isPeer = true
+ }
+ }
+ }
+ }
+
+ /** Imports the two link keys under the pairing's id; from here on only the key store holds them. */
+ internal fun importKeys(session: SessionKeys, store: LinkKeyStore): String {
+ val pairingId = session.pairingId.toHex()
+ store.import(LinkKeyStore.alias(pairingId, LinkRole.Phone), session.linkPhone)
+ store.import(LinkKeyStore.alias(pairingId, LinkRole.Watch), session.linkWatch)
+ return pairingId
+ }
+
+ private suspend fun tellPeer(error: Throwable) {
+ val nodeId = peerNodeId ?: return
+ val reason = when (error) {
+ is LinkError.PeerAborted -> return
+ is LinkError.Cancelled -> AbortReason.Cancelled
+ is LinkError.DifferentWallet -> AbortReason.DifferentWallet
+ is LinkError.UpdateRequired -> AbortReason.UpdateRequired
+ // A status list that could not be read says nothing about the watch.
+ is LinkError.AttestationFailed if error.failure == AttestationFailure.StatusUnknown -> AbortReason.Failed
+ is LinkError.AttestationFailed -> AbortReason.Unverified
+ else -> AbortReason.Failed
+ }
+ transport.send(nodeId, LinkPaths.ABORT, byteArrayOf(reason.ordinal.toByte()))
+ }
+
+ private fun abortReason(packet: LinkPacket): AbortReason =
+ packet.payload.singleOrNull()?.let { AbortReason.entries.getOrNull(it.toInt()) } ?: AbortReason.Failed
+}
diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/PairingThrottle.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/PairingThrottle.kt
new file mode 100644
index 0000000000..4142100a85
--- /dev/null
+++ b/wearlink/src/main/kotlin/to/bitkit/wearlink/PairingThrottle.kt
@@ -0,0 +1,41 @@
+package to.bitkit.wearlink
+
+import kotlin.time.Duration.Companion.minutes
+
+/** [attempts] seed transfers were started and not finished; none starts before [lockedUntilMs]. */
+data class ThrottleState(val attempts: Int = 0, val lockedUntilMs: Long = 0)
+
+interface ThrottleStore {
+ suspend fun load(): ThrottleState
+
+ suspend fun save(state: ThrottleState)
+}
+
+/**
+ * Limits how often a seed transfer can be tried. The confirmation code is all that tells the watch from a relay, and
+ * a relay's code matches by chance once in a million tries, so each try is counted when it starts, before the phone
+ * reveals its key, and only a finished transfer clears the count. After [MAX_ATTEMPTS] unfinished tries nothing
+ * starts for [LOCK].
+ */
+class PairingThrottle(
+ private val store: ThrottleStore,
+ private val nowMs: () -> Long,
+) {
+ companion object {
+ const val MAX_ATTEMPTS = 3
+ val LOCK = 10.minutes
+ }
+
+ /** Counts one more try, or fails with [LinkError.Throttled]. The count is stored before this returns. */
+ suspend fun begin() {
+ val now = nowMs()
+ val state = store.load()
+ if (now < state.lockedUntilMs) throw LinkError.Throttled(state.lockedUntilMs)
+ val attempts = (if (state.lockedUntilMs > 0) 0 else state.attempts) + 1
+ val lockedUntilMs = if (attempts >= MAX_ATTEMPTS) now + LOCK.inWholeMilliseconds else 0
+ store.save(ThrottleState(attempts, lockedUntilMs))
+ }
+
+ /** Forgets the count, after a transfer that finished. */
+ suspend fun reset() = store.save(ThrottleState())
+}
diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/PhonePairing.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/PhonePairing.kt
new file mode 100644
index 0000000000..4f70409715
--- /dev/null
+++ b/wearlink/src/main/kotlin/to/bitkit/wearlink/PhonePairing.kt
@@ -0,0 +1,193 @@
+package to.bitkit.wearlink
+
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.launch
+import java.security.SecureRandom
+
+/** What the phone's side of a pairing needs from the phone app. */
+interface PhonePairingEnv {
+ /** The application id, which the watch app shares. */
+ val appId: String
+
+ /** This install's random id, [Handshake.ID_BYTES] long. */
+ suspend fun phoneId(): ByteArray
+
+ /** The phone's name, shown on the watch next to the code. */
+ val name: String
+
+ val verifier: AttestationVerifier
+
+ /**
+ * Whether a seed may go to a watch whose key attestation was not verified. Only ever true in a debug build, for
+ * the emulators, which have no hardware-backed keys.
+ */
+ val isUnverifiedTransferAllowed: Boolean
+
+ val throttle: PairingThrottle
+
+ /**
+ * Whether the phone app has a PIN. A seed is only sent after the phone's user passed the app's own check, and
+ * without a PIN there is none to pass, so such a phone sends no seed.
+ */
+ suspend fun isPinSet(): Boolean
+
+ /**
+ * Google's list of revoked attestation certificates, read now, or null when it cannot be read. Only asked for
+ * a chain that was verified.
+ */
+ suspend fun attestationStatus(): AttestationStatusList?
+
+ val keys: LinkKeyStore
+
+ /** [WalletLink.secret] of the phone's wallet. The session zeroes it. */
+ suspend fun walletSecret(): ByteArray
+
+ /** The wallet to send. Read only once every check has passed, right before it is encrypted. */
+ suspend fun seed(): SeedPayload
+}
+
+/**
+ * The phone's side of the ceremony with the watch [node].
+ *
+ * 1. Hello: the phone commits to a fresh P-256 key. Reply: the watch's key, generated in its Keystore for this
+ * handshake, with its attestation, and whether the watch holds a wallet.
+ * 2. The attestation is verified, and a verified chain is looked up in Google's list of revoked certificates; a
+ * listed chain, or a list that cannot be read, leaves the watch unverified. For a watch without a wallet, which
+ * is to receive the seed, an unverified watch ends the pairing here, before the phone has revealed its key, and
+ * so does a phone without a PIN. Otherwise the try is counted by the throttle.
+ * 3. Reveal, key agreement, and the session keys from HKDF over the shared secret and the transcript. Both prove
+ * they hold the keys. A watch with a wallet must also prove it is this phone's wallet, and the phone proves the
+ * same to it.
+ * 4. Both screens show the code; the pairing goes on once both users confirmed.
+ * 5. Only for a watch without a wallet: the phone encrypts the seed to the session key, which exists only in this
+ * session's memory and in the watch's Keystore-held agreement, and waits for the watch's proof that it stored
+ * this wallet.
+ */
+class PhonePairing(
+ transport: LinkTransport,
+ incoming: Flow,
+ private val node: LinkNode,
+ private val env: PhonePairingEnv,
+ random: SecureRandom = SecureRandom(),
+) : PairingSession(transport, incoming, random) {
+ private companion object {
+ /** How many hellos in a row may fail to be sent before the watch counts as unreachable. */
+ const val MAX_SEND_FAILURES = 5
+ }
+
+ override val role = LinkRole.Phone
+
+ override suspend fun ceremony(): PairedLink {
+ peerNodeId = node.id
+ runSuspendCatching { transport.open(node.id, LinkPaths.PAIR_URI) }
+ val keyPair = LinkCrypto.generateKeyPair(random)
+ val publicKey = keyPair.public.encoded
+ val commitNonce = bytes(Handshake.NONCE_BYTES)
+ val hello = Hello(
+ minVersion = Handshake.VERSION,
+ maxVersion = Handshake.VERSION,
+ appId = env.appId,
+ phoneId = env.phoneId(),
+ nonce = bytes(Handshake.NONCE_BYTES),
+ commitment = Handshake.commitment(publicKey, commitNonce),
+ name = env.name,
+ ).encode()
+ val replyBytes = helloUntilReply(hello)
+ val reply = Reply.decode(replyBytes)
+ if (reply.version != Handshake.VERSION) throw LinkError.UpdateRequired()
+ val watchKey = LinkCrypto.decodePublicKey(reply.publicKey)
+ val mode = if (reply.hasWallet) PairingMode.Proof else PairingMode.Transfer
+ if (mode == PairingMode.Transfer && !env.isPinSet()) throw LinkError.PinRequired()
+ val attested = env.verifier.verify(reply.chain, Handshake.attestationChallenge(hello), reply.publicKey)
+ val verdict = checkStatus(attested, reply.chain)
+ if (mode == PairingMode.Transfer) {
+ if (verdict is AttestationVerdict.Unverified && !env.isUnverifiedTransferAllowed) {
+ throw LinkError.AttestationFailed(verdict.failure)
+ }
+ env.throttle.begin()
+ }
+ val reveal = Reveal(publicKey, commitNonce).encode()
+ send(LinkPaths.REVEAL, reveal)
+ val shared = LinkCrypto.agree(keyPair.private, watchKey)
+ val session = SessionKeys.derive(shared, Handshake.transcript(hello, replyBytes, reveal))
+ shared.fill(0)
+ keys = session
+ val secret = env.walletSecret()
+ try {
+ prove(session, secret, mode)
+ show(PairingState.Code(session.code, mode, reply.name, verdict))
+ exchangeAccepts(session, mustAuthenticate = mode == PairingMode.Transfer)
+ if (mode == PairingMode.Transfer) transfer(session, secret)
+ } finally {
+ secret.fill(0)
+ }
+ val pairingId = importKeys(session, env.keys)
+ if (mode == PairingMode.Transfer) env.throttle.reset()
+ return PairedLink(
+ pairingId = pairingId,
+ mode = mode,
+ peerId = reply.watchId.toHex(),
+ peerNodeId = node.id,
+ peerName = reply.name,
+ version = reply.version,
+ attestation = verdict,
+ isPeerLockSet = reply.isLockSet,
+ )
+ }
+
+ private suspend fun checkStatus(verdict: AttestationVerdict, chain: List): AttestationVerdict {
+ if (verdict !is AttestationVerdict.Verified) return verdict
+ val list = unlessCancelled { env.attestationStatus() }
+ ?: return AttestationVerdict.Unverified(AttestationFailure.StatusUnknown)
+ return if (list.lists(chain)) AttestationVerdict.Unverified(AttestationFailure.Revoked) else verdict
+ }
+
+ private suspend fun helloUntilReply(hello: ByteArray): ByteArray = coroutineScope {
+ val sender = launch {
+ var failures = 0
+ while (true) {
+ runSuspendCatching { send(LinkPaths.HELLO, hello) }
+ .onSuccess { failures = 0 }
+ .onFailure { if (++failures >= MAX_SEND_FAILURES) throw it }
+ delay(Handshake.HELLO_INTERVAL)
+ }
+ }
+ try {
+ receive(LinkPaths.REPLY).payload
+ } finally {
+ sender.cancel()
+ }
+ }
+
+ private suspend fun prove(session: SessionKeys, secret: ByteArray, mode: PairingMode) {
+ val proof = if (mode == PairingMode.Proof) {
+ WalletLink.proof(secret, LinkRole.Phone, session.transcript)
+ } else {
+ null
+ }
+ send(LinkPaths.CONFIRM, Confirm(session.keyMac(LinkRole.Phone), proof).encode())
+ val confirm = Confirm.decode(receive(LinkPaths.CONFIRM).payload)
+ if (!LinkCrypto.isEqual(confirm.keyMac, session.keyMac(LinkRole.Watch))) throw LinkError.KeyMismatch()
+ if (mode != PairingMode.Proof) return
+ val expected = WalletLink.proof(secret, LinkRole.Watch, session.transcript)
+ val isSameWallet = confirm.walletProof?.let { LinkCrypto.isEqual(it, expected) } == true
+ if (!isSameWallet) throw LinkError.DifferentWallet()
+ }
+
+ private suspend fun transfer(session: SessionKeys, secret: ByteArray) {
+ show(PairingState.Transferring)
+ val plaintext = env.seed().encode()
+ val sealed = try {
+ session.seal(LinkRole.Phone, LinkPaths.SEED, plaintext, random)
+ } finally {
+ plaintext.fill(0)
+ }
+ send(LinkPaths.SEED, sealed)
+ val stored = Stored.decode(session.open(LinkRole.Watch, LinkPaths.STORED, receive(LinkPaths.STORED).payload))
+ stored.failure?.let { throw LinkError.TransferFailed(it) }
+ val expected = WalletLink.proof(secret, LinkRole.Watch, session.transcript)
+ if (!LinkCrypto.isEqual(stored.walletProof, expected)) throw LinkError.TransferFailed(StoreFailure.Failed)
+ }
+}
diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/WalletLink.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/WalletLink.kt
new file mode 100644
index 0000000000..fa072fc13e
--- /dev/null
+++ b/wearlink/src/main/kotlin/to/bitkit/wearlink/WalletLink.kt
@@ -0,0 +1,26 @@
+package to.bitkit.wearlink
+
+/**
+ * What both holders of one wallet can derive from its BIP39 seed and nobody else can. It is how a watch that
+ * already holds the phone's wallet proves it without the seed being sent again.
+ */
+object WalletLink {
+ private val SECRET_LABEL = "bitkit wear link v1".encodeToByteArray()
+ private val PROOF_LABEL = "bitkit wear link v1 proof".encodeToByteArray()
+
+ /**
+ * The link secret of the wallet with BIP39 [seed] (phrase and passphrase) on [network]: an HMAC-SHA256 of a
+ * label and the network name, keyed with the seed, as `SparkSendKey.secret` is under another label.
+ */
+ fun secret(seed: ByteArray, network: String): ByteArray =
+ LinkCrypto.hmac(seed, SECRET_LABEL, byteArrayOf(0), network.lowercase().encodeToByteArray())
+
+ /**
+ * [role]'s proof that it holds [secret], bound to one handshake by its [transcript] hash, so a proof is worth
+ * nothing in another handshake or sent back to its writer.
+ */
+ fun proof(secret: ByteArray, role: LinkRole, transcript: ByteArray): ByteArray {
+ val key = LinkCrypto.hkdf(secret, transcript, PROOF_LABEL, LinkCrypto.KEY_BYTES)
+ return LinkCrypto.hmac(key, byteArrayOf(role.id.toByte()), transcript).also { key.fill(0) }
+ }
+}
diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/WatchPairing.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/WatchPairing.kt
new file mode 100644
index 0000000000..e6c1a99576
--- /dev/null
+++ b/wearlink/src/main/kotlin/to/bitkit/wearlink/WatchPairing.kt
@@ -0,0 +1,159 @@
+package to.bitkit.wearlink
+
+import kotlinx.coroutines.flow.Flow
+import java.security.SecureRandom
+
+/**
+ * The watch's key agreement key: a P-256 key that the watch's Keystore generates for one handshake, usable for a key
+ * agreement and nothing else, and attested with the handshake's challenge. Its private half never leaves the
+ * Keystore, so what the phone encrypts to the agreed secret can only be opened through this key.
+ */
+interface WatchAgreementKey {
+ /** Generates the key for one handshake, replacing the last one, attested with [challenge]. */
+ fun create(challenge: ByteArray): Attested
+
+ /** The ECDH shared secret with [peerPublicKey] (X.509 encoded, already checked to be on P-256). */
+ fun agree(peerPublicKey: ByteArray): ByteArray
+
+ fun delete()
+
+ /** [publicKey] is X.509 encoded; [chain] is the attestation's DER certificates, the key's own first. */
+ class Attested(val publicKey: ByteArray, val chain: List)
+}
+
+sealed interface SeedStoreResult {
+ /** The seed is stored; [secret] is its [WalletLink.secret]. */
+ class Stored(val secret: ByteArray) : SeedStoreResult
+
+ class Refused(val failure: StoreFailure) : SeedStoreResult
+}
+
+/** What the watch's side of a pairing needs from the watch app. */
+interface WatchPairingEnv {
+ val appId: String
+
+ /** This install's random id, [Handshake.ID_BYTES] long. */
+ suspend fun watchId(): ByteArray
+
+ /** The watch's model name, shown on the phone. */
+ val name: String
+
+ val agreementKey: WatchAgreementKey
+
+ val keys: LinkKeyStore
+
+ suspend fun isLockSet(): Boolean
+
+ /** [WalletLink.secret] of the watch's wallet, or null when it holds none. The session zeroes it. */
+ suspend fun walletSecret(): ByteArray?
+
+ /** Checks and stores the received wallet as this watch's, in its seed store. */
+ suspend fun storeSeed(seed: SeedPayload): SeedStoreResult
+}
+
+/**
+ * The watch's side of the ceremony; [PhonePairing] describes the steps. It answers the first hello that arrives
+ * while it runs, which is only while the watch shows its Pair screen, and from then on only that device. A seed is
+ * taken once, only by a watch without a wallet, and only after the wearer confirmed the code.
+ */
+class WatchPairing(
+ transport: LinkTransport,
+ incoming: Flow,
+ private val env: WatchPairingEnv,
+ random: SecureRandom = SecureRandom(),
+) : PairingSession(transport, incoming, random) {
+ override val role = LinkRole.Watch
+
+ override suspend fun ceremony(): PairedLink {
+ val first = receive(LinkPaths.HELLO)
+ val helloBytes = first.payload
+ val hello = Hello.decode(helloBytes)
+ peerNodeId = first.nodeId
+ if (hello.appId != env.appId) throw LinkError.Malformed()
+ if (Handshake.VERSION !in hello.minVersion..hello.maxVersion) throw LinkError.UpdateRequired()
+ val secret = env.walletSecret()
+ try {
+ val session = agree(hello, helloBytes, hasWallet = secret != null)
+ val mode = if (secret != null) PairingMode.Proof else PairingMode.Transfer
+ prove(session, secret)
+ show(PairingState.Code(session.code, mode, hello.name, attestation = null))
+ exchangeAccepts(session, mustAuthenticate = false)
+ if (secret == null) receiveSeed(session)
+ return PairedLink(
+ pairingId = importKeys(session, env.keys),
+ mode = mode,
+ peerId = hello.phoneId.toHex(),
+ peerNodeId = first.nodeId,
+ peerName = hello.name,
+ version = Handshake.VERSION,
+ attestation = null,
+ isPeerLockSet = false,
+ )
+ } finally {
+ secret?.fill(0)
+ }
+ }
+
+ override suspend fun cleanUp() = env.agreementKey.delete()
+
+ private suspend fun agree(hello: Hello, helloBytes: ByteArray, hasWallet: Boolean): SessionKeys {
+ val key = env.agreementKey.create(Handshake.attestationChallenge(helloBytes))
+ val replyBytes = Reply(
+ version = Handshake.VERSION,
+ watchId = env.watchId(),
+ nonce = bytes(Handshake.NONCE_BYTES),
+ hasWallet = hasWallet,
+ publicKey = key.publicKey,
+ chain = key.chain,
+ name = env.name,
+ isLockSet = env.isLockSet(),
+ ).encode()
+ send(LinkPaths.REPLY, replyBytes)
+ val revealBytes = receive(LinkPaths.REVEAL) {
+ // The phone repeats its hello until a reply reaches it.
+ if (it.path == LinkPaths.HELLO && it.payload.contentEquals(helloBytes)) send(LinkPaths.REPLY, replyBytes)
+ }.payload
+ val reveal = Reveal.decode(revealBytes)
+ val commitment = Handshake.commitment(reveal.publicKey, reveal.nonce)
+ if (!LinkCrypto.isEqual(commitment, hello.commitment)) throw LinkError.KeyMismatch()
+ LinkCrypto.decodePublicKey(reveal.publicKey)
+ val shared = env.agreementKey.agree(reveal.publicKey)
+ return SessionKeys.derive(shared, Handshake.transcript(helloBytes, replyBytes, revealBytes))
+ .also {
+ shared.fill(0)
+ keys = it
+ }
+ }
+
+ private suspend fun prove(session: SessionKeys, secret: ByteArray?) {
+ val confirm = Confirm.decode(receive(LinkPaths.CONFIRM).payload)
+ if (!LinkCrypto.isEqual(confirm.keyMac, session.keyMac(LinkRole.Phone))) throw LinkError.KeyMismatch()
+ if (secret != null) {
+ val expected = WalletLink.proof(secret, LinkRole.Phone, session.transcript)
+ val isSameWallet = confirm.walletProof?.let { LinkCrypto.isEqual(it, expected) } == true
+ if (!isSameWallet) throw LinkError.DifferentWallet()
+ }
+ val proof = secret?.let { WalletLink.proof(it, LinkRole.Watch, session.transcript) }
+ send(LinkPaths.CONFIRM, Confirm(session.keyMac(LinkRole.Watch), proof).encode())
+ }
+
+ private suspend fun receiveSeed(session: SessionKeys) {
+ show(PairingState.Transferring)
+ val plaintext = session.open(LinkRole.Phone, LinkPaths.SEED, receive(LinkPaths.SEED).payload)
+ val seed = try {
+ SeedPayload.decode(plaintext)
+ } finally {
+ plaintext.fill(0)
+ }
+ val stored = when (val result = env.storeSeed(seed)) {
+ is SeedStoreResult.Refused -> Stored(result.failure, ByteArray(0))
+ is SeedStoreResult.Stored -> {
+ val proof = WalletLink.proof(result.secret, LinkRole.Watch, session.transcript)
+ result.secret.fill(0)
+ Stored(null, proof)
+ }
+ }
+ send(LinkPaths.STORED, session.seal(LinkRole.Watch, LinkPaths.STORED, stored.encode(), random))
+ stored.failure?.let { throw LinkError.TransferFailed(it) }
+ }
+}
diff --git a/wearlink/src/main/kotlin/to/bitkit/wearlink/Wire.kt b/wearlink/src/main/kotlin/to/bitkit/wearlink/Wire.kt
new file mode 100644
index 0000000000..3481b5da7e
--- /dev/null
+++ b/wearlink/src/main/kotlin/to/bitkit/wearlink/Wire.kt
@@ -0,0 +1,92 @@
+package to.bitkit.wearlink
+
+import java.io.ByteArrayOutputStream
+import java.nio.ByteBuffer
+
+/**
+ * The link's binary layout: fixed-size integers, and every variable field behind its 4-byte length, so two different
+ * lists of fields never encode to the same bytes.
+ */
+internal class WireWriter {
+ private val out = ByteArrayOutputStream()
+
+ fun byte(value: Int) = apply { out.write(value) }
+
+ fun int(value: Int) = apply { out.write(ByteBuffer.allocate(Int.SIZE_BYTES).putInt(value).array()) }
+
+ fun long(value: Long) = apply { out.write(ByteBuffer.allocate(Long.SIZE_BYTES).putLong(value).array()) }
+
+ fun bool(value: Boolean) = byte(if (value) 1 else 0)
+
+ fun fixed(value: ByteArray) = apply { out.write(value) }
+
+ fun bytes(value: ByteArray) = apply {
+ int(value.size)
+ out.write(value)
+ }
+
+ fun string(value: String) = bytes(value.encodeToByteArray())
+
+ fun list(values: List) = apply {
+ int(values.size)
+ values.forEach(::bytes)
+ }
+
+ fun toByteArray(): ByteArray = out.toByteArray()
+}
+
+/** Reads what [WireWriter] wrote. Every read is bounded, and anything unexpected is a [LinkError.Malformed]. */
+internal class WireReader(bytes: ByteArray) {
+ companion object {
+ const val MAX_FIELD = 64 * 1024
+ const val MAX_TEXT = 256
+ }
+
+ private val buffer = ByteBuffer.wrap(bytes)
+
+ fun byte(): Int = guarded { buffer.get().toInt() and BYTE_MASK }
+
+ fun int(): Int = guarded { buffer.getInt() }
+
+ fun long(): Long = guarded { buffer.getLong() }
+
+ fun bool(): Boolean = when (byte()) {
+ 0 -> false
+ 1 -> true
+ else -> throw LinkError.Malformed()
+ }
+
+ fun fixed(size: Int): ByteArray = guarded { ByteArray(size).also { buffer.get(it) } }
+
+ fun bytes(max: Int = MAX_FIELD): ByteArray {
+ val size = int()
+ if (size !in 0..max || size > buffer.remaining()) throw LinkError.Malformed()
+ return fixed(size)
+ }
+
+ fun string(max: Int = MAX_TEXT): String = bytes(max).decodeToString()
+
+ fun list(maxItems: Int, maxItemSize: Int): List {
+ val count = int()
+ if (count !in 0..maxItems) throw LinkError.Malformed()
+ return List(count) { bytes(maxItemSize) }
+ }
+
+ fun end() {
+ if (buffer.hasRemaining()) throw LinkError.Malformed()
+ }
+
+ private inline fun guarded(block: () -> T): T =
+ runCatching(block).getOrElse { throw it as? LinkError ?: LinkError.Malformed(it) }
+}
+
+private const val BYTE_MASK = 0xff
+
+internal fun ByteArray.toHex(): String = joinToString("") { "%02x".format(it) }
+
+internal fun String.hexToBytes(): ByteArray {
+ if (length % 2 != 0 || any { it !in "0123456789abcdef" }) throw LinkError.Malformed()
+ return ByteArray(length / 2) { substring(it * 2, it * 2 + 2).toInt(HEX_RADIX).toByte() }
+}
+
+private const val HEX_RADIX = 16
diff --git a/wearlink/src/test/kotlin/to/bitkit/wearlink/AttestationStatusListTest.kt b/wearlink/src/test/kotlin/to/bitkit/wearlink/AttestationStatusListTest.kt
new file mode 100644
index 0000000000..de2a23f227
--- /dev/null
+++ b/wearlink/src/test/kotlin/to/bitkit/wearlink/AttestationStatusListTest.kt
@@ -0,0 +1,101 @@
+package to.bitkit.wearlink
+
+import java.math.BigInteger
+import java.security.SecureRandom
+import java.security.cert.CertificateFactory
+import java.security.cert.X509Certificate
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertFailsWith
+import kotlin.test.assertFalse
+import kotlin.test.assertNull
+import kotlin.test.assertTrue
+
+class AttestationStatusListTest {
+ private val published = """
+ {
+ "entries": {
+ "1100cacd4407fb6302d6c96c1c14c004": { "status": "REVOKED", "reason": "KEY_COMPROMISE" },
+ "c35747a084470c3135aeefe2b8d40cd6": { "status": "SUSPENDED", "reason": "SOFTWARE_FLAW" },
+ "2d0b": { "status": "WITHDRAWN" },
+ "00AB12": { "status": "REVOKED", "expires": "2030-01-01" },
+ "77": {}
+ }
+ }
+ """.trimIndent()
+
+ private val list = statusList(published)
+
+ private fun serial(hex: String) = BigInteger(hex, 16)
+
+ @Test
+ fun `a revoked certificate is listed as revoked`() =
+ assertEquals(AttestationStatusList.Status.Revoked, list.status(serial("1100cacd4407fb6302d6c96c1c14c004")))
+
+ @Test
+ fun `a suspended certificate is listed as suspended`() =
+ assertEquals(AttestationStatusList.Status.Suspended, list.status(serial("c35747a084470c3135aeefe2b8d40cd6")))
+
+ @Test
+ fun `a certificate listed with a status this version does not know is still listed`() {
+ assertEquals(AttestationStatusList.Status.Unknown, list.status(serial("2d0b")))
+ assertEquals(AttestationStatusList.Status.Unknown, list.status(serial("77")))
+ }
+
+ @Test
+ fun `a certificate that is not listed has no status`() = assertNull(list.status(serial("1100cacd")))
+
+ @Test
+ fun `a serial is found however the list writes it`() =
+ assertEquals(AttestationStatusList.Status.Revoked, list.status(serial("ab12")))
+
+ @Test
+ fun `an empty list names no certificate`() =
+ assertNull(statusList("""{"entries":{}}""").status(BigInteger.ONE))
+
+ @Test
+ fun `a response that is not the list is refused, never taken for an empty one`() {
+ val responses = listOf("", "{}", "[]", "Sign in to the network", """{"entries":[]}""", "null")
+
+ for (response in responses) {
+ assertFailsWith(response) { statusList(response) }
+ }
+ }
+
+ @Test
+ fun `a response beyond the size limit is refused, counted in bytes`() {
+ val padding = "é".repeat(AttestationStatusList.MAX_BYTES / 2)
+ val response = """{"entries":{},"padding":"$padding"}"""
+
+ assertTrue(response.length < AttestationStatusList.MAX_BYTES)
+ assertFailsWith { statusList(response) }
+ }
+
+ @Test
+ fun `a response that is not valid text is refused`() {
+ val body = """{"entries":{}}""".encodeToByteArray() + byteArrayOf(0xC3.toByte())
+
+ assertFailsWith { AttestationStatusList.parse(body) }
+ }
+
+ @Test
+ fun `a chain is listed when any of its certificates is`() {
+ val attestation = TestAttestation()
+ val key = LinkCrypto.generateKeyPair(SecureRandom())
+ val chain = attestation.chain(key.public, ByteArray(32))
+ val factory = CertificateFactory.getInstance("X.509")
+ val serials = chain.map {
+ (factory.generateCertificate(it.inputStream()) as X509Certificate).serialNumber.toString(16)
+ }
+
+ for (serial in serials) {
+ val listed = statusList("""{"entries":{"$serial":{"status":"REVOKED"}}}""")
+ assertTrue(listed.lists(chain), "serial '$serial'")
+ }
+ assertFalse(statusList("""{"entries":{"ffff":{"status":"REVOKED"}}}""").lists(chain))
+ }
+
+ @Test
+ fun `a chain that cannot be read counts as listed`() =
+ assertTrue(statusList("""{"entries":{}}""").lists(listOf(ByteArray(8) { 1 })))
+}
diff --git a/wearlink/src/test/kotlin/to/bitkit/wearlink/AttestationVerifierTest.kt b/wearlink/src/test/kotlin/to/bitkit/wearlink/AttestationVerifierTest.kt
new file mode 100644
index 0000000000..5e02ff0f8e
--- /dev/null
+++ b/wearlink/src/test/kotlin/to/bitkit/wearlink/AttestationVerifierTest.kt
@@ -0,0 +1,184 @@
+package to.bitkit.wearlink
+
+import org.bouncycastle.asn1.x509.KeyUsage
+import java.security.KeyPairGenerator
+import java.security.SecureRandom
+import java.security.cert.CertificateFactory
+import java.security.spec.ECGenParameterSpec
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertTrue
+
+class AttestationVerifierTest {
+ private val attestation = TestAttestation()
+ private val verifier = AttestationVerifier(attestation.policy)
+ private val key = LinkCrypto.generateKeyPair(SecureRandom())
+ private val challenge = ByteArray(32) { 3 }
+
+ private fun verify(chain: List, offered: ByteArray = key.public.encoded) =
+ verifier.verify(chain, challenge, offered)
+
+ private fun assertRefused(expected: AttestationFailure, chain: List) =
+ assertEquals(AttestationVerdict.Unverified(expected), verify(chain))
+
+ @Test
+ fun `a key attested in the trusted environment is verified`() {
+ val verdict = verify(attestation.chain(key.public, challenge))
+
+ assertEquals(AttestationVerdict.Verified(KeyLevel.TrustedEnvironment), verdict)
+ }
+
+ @Test
+ fun `a key attested in StrongBox is verified`() {
+ val verdict = verify(attestation.chain(key.public, challenge, level = 2))
+
+ assertEquals(AttestationVerdict.Verified(KeyLevel.StrongBox), verdict)
+ }
+
+ @Test
+ fun `no chain is unverified`() = assertRefused(AttestationFailure.NoChain, emptyList())
+
+ @Test
+ fun `bytes that are no certificates are unverified`() =
+ assertRefused(AttestationFailure.Malformed, listOf(ByteArray(40) { 1 }))
+
+ @Test
+ fun `a chain that ends in another root is unverified`() {
+ val other = TestAttestation()
+
+ assertRefused(AttestationFailure.UntrustedRoot, other.chain(key.public, challenge))
+ }
+
+ @Test
+ fun `a chain with a certificate swapped in from another root is broken`() {
+ val other = TestAttestation()
+ val chain = listOf(other.chain(key.public, challenge).first()) + attestation.authorities()
+
+ assertRefused(AttestationFailure.BrokenChain, chain)
+ }
+
+ @Test
+ fun `an expired certificate breaks the chain`() {
+ val chain = attestation.chain(key.public, challenge, leafNotAfterMs = TestAttestation.NOW_MS - 1_000)
+
+ assertRefused(AttestationFailure.BrokenChain, chain)
+ }
+
+ @Test
+ fun `an attestation for another key is refused`() {
+ val other = LinkCrypto.generateKeyPair(SecureRandom())
+
+ assertRefused(AttestationFailure.KeyMismatch, attestation.chain(other.public, challenge))
+ }
+
+ @Test
+ fun `a certificate without an attestation record is refused`() =
+ assertRefused(AttestationFailure.NoAttestation, attestation.chain(key.public, challenge, hasRecord = false))
+
+ @Test
+ fun `an attestation made for another handshake is refused`() =
+ assertRefused(AttestationFailure.WrongChallenge, attestation.chain(key.public, ByteArray(32) { 4 }))
+
+ @Test
+ fun `a software key is refused`() =
+ assertRefused(AttestationFailure.SoftwareKey, attestation.chain(key.public, challenge, level = 0))
+
+ @Test
+ fun `a key that may also sign is refused`() {
+ val purposes = setOf(TestAttestation.PURPOSE_AGREE) + TestAttestation.SIGNING_PURPOSES
+
+ assertRefused(AttestationFailure.WrongKeyUse, attestation.chain(key.public, challenge, purposes = purposes))
+ }
+
+ @Test
+ fun `an imported key is refused`() =
+ assertRefused(AttestationFailure.WrongKeyUse, attestation.chain(key.public, challenge, origin = 2))
+
+ @Test
+ fun `an unlocked bootloader is refused`() =
+ assertRefused(AttestationFailure.UnverifiedBoot, attestation.chain(key.public, challenge, isLocked = false))
+
+ @Test
+ fun `a self-signed boot image is refused`() =
+ assertRefused(AttestationFailure.UnverifiedBoot, attestation.chain(key.public, challenge, bootState = 1))
+
+ @Test
+ fun `another app's key is refused`() =
+ assertRefused(AttestationFailure.WrongApp, attestation.chain(key.public, challenge, packageName = "evil.app"))
+
+ @Test
+ fun `a key of an app signed by another certificate is refused`() =
+ assertRefused(
+ AttestationFailure.WrongApp,
+ attestation.chain(key.public, challenge, digest = ByteArray(32) { 9 }),
+ )
+
+ @Test
+ fun `a record forged below a genuinely attested signing key is refused`() {
+ // The attacker holds a hardware key attested for signing, and signs a certificate for a software key with
+ // a record that claims everything the phone wants.
+ val signingKey = LinkCrypto.generateKeyPair(SecureRandom())
+ val genuine = attestation.chain(signingKey.public, challenge, purposes = TestAttestation.SIGNING_PURPOSES)
+ val forged = attestation.certificate(
+ subject = "forged",
+ key = key.public,
+ issuer = "leaf",
+ signer = signingKey.private,
+ isAuthority = false,
+ record = attestation.description(challenge),
+ )
+
+ assertRefused(AttestationFailure.BrokenChain, listOf(forged) + genuine)
+ }
+
+ @Test
+ fun `an issuer that may not sign certificates breaks the chain`() {
+ val leaf = attestation.chain(key.public, challenge).first()
+ val issuers = attestation.authorities(intermediateUsage = KeyUsage.digitalSignature)
+
+ assertRefused(AttestationFailure.BrokenChain, listOf(leaf) + issuers)
+ }
+
+ @Test
+ fun `an issuer that names certificate signing as its use is accepted`() {
+ val leaf = attestation.chain(key.public, challenge).first()
+ val issuers = attestation.authorities(intermediateUsage = KeyUsage.keyCertSign or KeyUsage.cRLSign)
+
+ assertEquals(AttestationVerdict.Verified(KeyLevel.TrustedEnvironment), verify(listOf(leaf) + issuers))
+ }
+
+ @Test
+ fun `a key on another curve is refused`() {
+ val p384 = KeyPairGenerator.getInstance("EC").run {
+ initialize(ECGenParameterSpec("secp384r1"))
+ generateKeyPair()
+ }
+ val verdict = verifier.verify(attestation.chain(p384.public, challenge), challenge, p384.public.encoded)
+
+ assertTrue(verdict is AttestationVerdict.Unverified)
+ }
+
+ @Test
+ fun `the pinned roots are the public keys of Google's published root certificates`() {
+ val factory = CertificateFactory.getInstance("X.509")
+ val published = listOf("google-attestation-root-rsa.pem", "google-attestation-root-ec.pem").map { name ->
+ val stream = requireNotNull(javaClass.classLoader.getResourceAsStream(name))
+ LinkCrypto.sha256(stream.use(factory::generateCertificate).publicKey.encoded).toHex()
+ }
+
+ assertEquals(AttestationPolicy.GOOGLE_HARDWARE_ROOTS, published.toSet())
+ }
+
+ @Test
+ fun `a chain to a test root is not trusted by the default policy`() {
+ val policy = AttestationPolicy(
+ packageName = TestAttestation.PACKAGE,
+ signingDigests = setOf(TestAttestation.DIGEST.toHex()),
+ nowMs = { TestAttestation.NOW_MS },
+ )
+ val verdict = AttestationVerifier(policy)
+ .verify(attestation.chain(key.public, challenge), challenge, key.public.encoded)
+
+ assertEquals(AttestationVerdict.Unverified(AttestationFailure.UntrustedRoot), verdict)
+ }
+}
diff --git a/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkChannelTest.kt b/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkChannelTest.kt
new file mode 100644
index 0000000000..9ad0929194
--- /dev/null
+++ b/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkChannelTest.kt
@@ -0,0 +1,134 @@
+package to.bitkit.wearlink
+
+import kotlinx.coroutines.test.runTest
+import to.bitkit.wearlink.testing.InMemoryLinkKeyStore
+import to.bitkit.wearlink.testing.InMemoryRecordStore
+import kotlin.test.Test
+import kotlin.test.assertContentEquals
+import kotlin.test.assertEquals
+import kotlin.test.assertFailsWith
+
+class LinkChannelTest {
+ private val pairingId = "0102030405060708"
+ private val path = LinkPaths.state(pairingId, LinkPaths.SETTINGS)
+ private val keys = InMemoryLinkKeyStore().apply {
+ import(LinkKeyStore.alias(pairingId, LinkRole.Phone), ByteArray(32) { 1 })
+ import(LinkKeyStore.alias(pairingId, LinkRole.Watch), ByteArray(32) { 2 })
+ }
+
+ private fun record(id: String = pairingId) =
+ LinkRecord(pairingId = id, peerId = "aa", peerNodeId = "node", peerName = "Peer", pairedAtMs = 1)
+
+ private fun channel(role: LinkRole, keys: InMemoryLinkKeyStore = this.keys, id: String = pairingId) =
+ LinkChannel(role, id, keys, RecordCounters(InMemoryRecordStore(record(id)), id))
+
+ private val phone = channel(LinkRole.Phone)
+ private val watch = channel(LinkRole.Watch)
+
+ @Test
+ fun `the peer opens what was sealed`() = runTest {
+ val sealed = phone.seal(path, "body".encodeToByteArray())
+
+ val opened = watch.open(path, sealed.envelope)
+
+ assertContentEquals("body".encodeToByteArray(), opened.body)
+ assertEquals(1, opened.counter)
+ }
+
+ @Test
+ fun `counters rise with every envelope`() = runTest {
+ val first = phone.seal(path, ByteArray(1))
+ val second = phone.seal(path, ByteArray(1))
+
+ assertEquals(listOf(1L, 2L), listOf(first.counter, second.counter))
+ }
+
+ @Test
+ fun `an envelope is not taken twice once committed`() = runTest {
+ val sealed = phone.seal(path, ByteArray(1))
+ watch.commit(path, watch.open(path, sealed.envelope).counter)
+
+ assertFailsWith { watch.open(path, sealed.envelope) }
+ }
+
+ @Test
+ fun `an envelope whose effect was not committed is taken again`() = runTest {
+ val sealed = phone.seal(path, ByteArray(1))
+ watch.open(path, sealed.envelope)
+
+ assertEquals(1, watch.open(path, sealed.envelope).counter)
+ }
+
+ @Test
+ fun `an older envelope never replaces a newer one`() = runTest {
+ val old = phone.seal(path, "quickpay on".encodeToByteArray())
+ val new = phone.seal(path, "quickpay off".encodeToByteArray())
+ watch.commit(path, watch.open(path, new.envelope).counter)
+
+ assertFailsWith { watch.open(path, old.envelope) }
+ }
+
+ @Test
+ fun `an envelope does not open at another path`() = runTest {
+ val sealed = phone.seal(path, ByteArray(1))
+
+ val other = LinkPaths.state(pairingId, LinkPaths.CONTROL)
+
+ assertFailsWith { watch.open(other, sealed.envelope) }
+ }
+
+ @Test
+ fun `an envelope is not reflected to its writer`() = runTest {
+ val sealed = phone.seal(path, ByteArray(1))
+
+ assertFailsWith { phone.open(path, sealed.envelope) }
+ }
+
+ @Test
+ fun `an altered envelope is refused, header or body`() = runTest {
+ val sealed = phone.seal(path, ByteArray(4)).envelope
+
+ for (index in listOf(4, 5, 8, 20, sealed.lastIndex)) {
+ val altered = sealed.copyOf().also { it[index] = (it[index] + 1).toByte() }
+ assertFailsWith { watch.open(path, altered) }
+ }
+ }
+
+ @Test
+ fun `an envelope with a raised counter is refused`() = runTest {
+ val sealed = phone.seal(path, ByteArray(4)).envelope
+ val counterEnd = 4 + 2 + Handshake.PAIRING_ID_BYTES + Long.SIZE_BYTES - 1
+ sealed[counterEnd] = 9
+
+ assertFailsWith { watch.open(path, sealed) }
+ }
+
+ @Test
+ fun `an envelope of an earlier pairing is refused`() = runTest {
+ val otherId = "1112131415161718"
+ val otherKeys = InMemoryLinkKeyStore().apply {
+ import(LinkKeyStore.alias(otherId, LinkRole.Phone), ByteArray(32) { 1 })
+ }
+ val earlier = channel(LinkRole.Phone, otherKeys, otherId)
+ val sealed = earlier.seal(path, ByteArray(1))
+
+ assertFailsWith { watch.open(path, sealed.envelope) }
+ }
+
+ @Test
+ fun `an envelope under the same id and other keys is refused`() = runTest {
+ val otherKeys = InMemoryLinkKeyStore().apply {
+ import(LinkKeyStore.alias(pairingId, LinkRole.Phone), ByteArray(32) { 9 })
+ }
+ val forged = channel(LinkRole.Phone, otherKeys)
+
+ assertFailsWith { watch.open(path, forged.seal(path, ByteArray(1)).envelope) }
+ }
+
+ @Test
+ fun `nothing is sealed without the pairing's record`() = runTest {
+ val orphan = LinkChannel(LinkRole.Phone, pairingId, keys, RecordCounters(InMemoryRecordStore(), pairingId))
+
+ assertFailsWith { orphan.seal(path, ByteArray(1)) }
+ }
+}
diff --git a/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkCryptoTest.kt b/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkCryptoTest.kt
new file mode 100644
index 0000000000..f7b76a795e
--- /dev/null
+++ b/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkCryptoTest.kt
@@ -0,0 +1,133 @@
+package to.bitkit.wearlink
+
+import java.security.KeyPairGenerator
+import java.security.SecureRandom
+import java.security.spec.ECGenParameterSpec
+import kotlin.test.Test
+import kotlin.test.assertContentEquals
+import kotlin.test.assertEquals
+import kotlin.test.assertFailsWith
+import kotlin.test.assertFalse
+import kotlin.test.assertNotEquals
+
+class LinkCryptoTest {
+ private val random = SecureRandom()
+
+ @Test
+ fun `hkdf gives the RFC 5869 test case 1 output`() {
+ val okm = LinkCrypto.hkdf(
+ ikm = "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b".hexToBytes(),
+ salt = "000102030405060708090a0b0c".hexToBytes(),
+ info = "f0f1f2f3f4f5f6f7f8f9".hexToBytes(),
+ length = 42,
+ )
+
+ assertEquals(
+ "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865",
+ okm.toHex(),
+ )
+ }
+
+ @Test
+ fun `hkdf gives the RFC 5869 test case 3 output without salt and info`() {
+ val okm = LinkCrypto.hkdf(
+ ikm = "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b".hexToBytes(),
+ salt = ByteArray(0),
+ info = ByteArray(0),
+ length = 42,
+ )
+
+ assertEquals(
+ "8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8",
+ okm.toHex(),
+ )
+ }
+
+ @Test
+ fun `a sealed message opens with its key and associated data only`() {
+ val key = ByteArray(32) { 1 }
+ val sealed = LinkCrypto.seal(key, "hello".encodeToByteArray(), "aad".encodeToByteArray(), random)
+
+ assertContentEquals("hello".encodeToByteArray(), LinkCrypto.open(key, sealed, "aad".encodeToByteArray()))
+ assertFailsWith { LinkCrypto.open(ByteArray(32) { 2 }, sealed, "aad".encodeToByteArray()) }
+ assertFailsWith { LinkCrypto.open(key, sealed, "other".encodeToByteArray()) }
+ sealed[sealed.lastIndex] = (sealed.last() + 1).toByte()
+ assertFailsWith { LinkCrypto.open(key, sealed, "aad".encodeToByteArray()) }
+ }
+
+ @Test
+ fun `two seals of one message differ`() {
+ val key = ByteArray(32) { 1 }
+ val first = LinkCrypto.seal(key, ByteArray(8), ByteArray(0), random)
+ val second = LinkCrypto.seal(key, ByteArray(8), ByteArray(0), random)
+
+ assertNotEquals(first.toHex(), second.toHex())
+ }
+
+ @Test
+ fun `both sides of a key agreement get one secret`() {
+ val a = LinkCrypto.generateKeyPair(random)
+ val b = LinkCrypto.generateKeyPair(random)
+
+ assertContentEquals(
+ LinkCrypto.agree(a.private, LinkCrypto.decodePublicKey(b.public.encoded)),
+ LinkCrypto.agree(b.private, LinkCrypto.decodePublicKey(a.public.encoded)),
+ )
+ }
+
+ @Test
+ fun `a public key on another curve is refused`() {
+ val p384 = KeyPairGenerator.getInstance("EC").run {
+ initialize(ECGenParameterSpec("secp384r1"))
+ generateKeyPair()
+ }
+
+ assertFailsWith { LinkCrypto.decodePublicKey(p384.public.encoded) }
+ }
+
+ @Test
+ fun `a point outside the curve is refused`() {
+ val encoded = LinkCrypto.generateKeyPair(random).public.encoded
+ encoded[encoded.lastIndex] = (encoded.last() + 1).toByte()
+
+ val isAccepted = runCatching { LinkCrypto.decodePublicKey(encoded) }.isSuccess
+
+ assertFalse(isAccepted)
+ }
+
+ @Test
+ fun `bytes that are no key are refused`() {
+ assertFailsWith { LinkCrypto.decodePublicKey(ByteArray(10)) }
+ }
+
+ @Test
+ fun `the link secret depends on the seed and the network`() {
+ val seed = ByteArray(64) { 5 }
+ val secret = WalletLink.secret(seed, "REGTEST")
+
+ assertContentEquals(secret, WalletLink.secret(seed, "regtest"))
+ assertNotEquals(secret.toHex(), WalletLink.secret(seed, "bitcoin").toHex())
+ assertNotEquals(secret.toHex(), WalletLink.secret(ByteArray(64) { 6 }, "regtest").toHex())
+ }
+
+ @Test
+ fun `a wallet proof is bound to its role and its handshake`() {
+ val secret = ByteArray(32) { 5 }
+ val transcript = ByteArray(32) { 1 }
+ val proof = WalletLink.proof(secret, LinkRole.Phone, transcript)
+
+ assertNotEquals(proof.toHex(), WalletLink.proof(secret, LinkRole.Watch, transcript).toHex())
+ assertNotEquals(proof.toHex(), WalletLink.proof(secret, LinkRole.Phone, ByteArray(32) { 2 }).toHex())
+ assertNotEquals(proof.toHex(), WalletLink.proof(ByteArray(32) { 6 }, LinkRole.Phone, transcript).toHex())
+ }
+
+ @Test
+ fun `the session keys and code are fixed by the shared secret and the transcript`() {
+ val keys = SessionKeys.derive(ByteArray(32) { 1 }, ByteArray(32) { 2 })
+
+ assertEquals("b33fd4b3fdd8cf72", keys.pairingId.toHex())
+ assertEquals("576738", keys.code)
+ assertNotEquals(keys.linkPhone.toHex(), keys.linkWatch.toHex())
+ assertNotEquals(keys.code, SessionKeys.derive(ByteArray(32) { 1 }, ByteArray(32) { 3 }).code)
+ }
+}
diff --git a/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkEndpointsTest.kt b/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkEndpointsTest.kt
new file mode 100644
index 0000000000..50b0c9b976
--- /dev/null
+++ b/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkEndpointsTest.kt
@@ -0,0 +1,424 @@
+package to.bitkit.wearlink
+
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.async
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.test.TestScope
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.runTest
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertFalse
+import kotlin.test.assertIs
+import kotlin.test.assertNotNull
+import kotlin.test.assertNull
+import kotlin.test.assertTrue
+
+@OptIn(ExperimentalCoroutinesApi::class)
+class LinkEndpointsTest {
+ private val quickPayOn = SettingsDoc("BITCOIN", "MODERN", "EUR", true, 5, 5, changedAtMs = 100)
+ private val quickPayOff = quickPayOn.copy(isQuickPayEnabled = false, changedAtMs = 200)
+
+ /** Runs a whole pairing and notes it on both sides, as the two apps do. */
+ private suspend fun TestScope.paired(harness: LinkHarness = LinkHarness(backgroundScope)): LinkHarness {
+ val watchSession = harness.watchPairing()
+ val phoneSession = harness.phonePairing()
+ val watch = async { watchSession.run() }
+ val phone = async { phoneSession.run() }
+ phoneSession.state.first { it is PairingState.Code }
+ watchSession.state.first { it is PairingState.Code }
+ watchSession.confirmShown()
+ phoneSession.confirmShown(isAuthenticated = true)
+ val phoneLink = phone.await()
+ val watchLink = watch.await()
+ harness.phoneLink.onPaired(phoneLink)
+ harness.watchLink.onPaired(watchLink)
+ runCurrent()
+ return harness
+ }
+
+ private fun LinkHarness.statePackets(name: String) = network.sent.filter { it.path.endsWith(name) }
+
+ @Test
+ fun `pairing leaves a record on both sides and tells each the other stands`() = runTest {
+ val harness = paired()
+
+ val phone = assertNotNull(harness.phoneStore.load())
+ val watch = assertNotNull(harness.watchStore.load())
+ assertEquals(phone.pairingId, watch.pairingId)
+ assertEquals("Pixel Watch", phone.peerName)
+ assertEquals("Pixel 9", watch.peerName)
+ assertEquals(KeyLevel.TrustedEnvironment, phone.keyLevel)
+ assertFalse(phone.isSeedTransferred)
+ assertTrue(phone.isPeerLockSet)
+ }
+
+ @Test
+ fun `a seed transfer is noted in the record`() = runTest {
+ val harness = paired(LinkHarness(backgroundScope).apply { watchSeed = null })
+
+ assertTrue(assertNotNull(harness.phoneStore.load()).isSeedTransferred)
+ }
+
+ @Test
+ fun `the phone's settings reach the watch and are acknowledged`() = runTest {
+ val harness = paired()
+
+ harness.phoneLink.publishSettings(quickPayOn)
+ assertFalse(assertNotNull(harness.phoneStore.load()).isSettingsUpToDate)
+ runCurrent()
+
+ assertEquals(listOf(quickPayOn), harness.appliedSettings)
+ assertTrue(assertNotNull(harness.phoneStore.load()).isSettingsUpToDate)
+ assertEquals(100, assertNotNull(harness.watchStore.load()).settingsChangedAtMs)
+ }
+
+ @Test
+ fun `settings published before the watch noted the pairing are asked for again, once`() = runTest {
+ val harness = LinkHarness(backgroundScope)
+ val watchSession = harness.watchPairing()
+ val phoneSession = harness.phonePairing()
+ val watch = async { watchSession.run() }
+ val phone = async { phoneSession.run() }
+ phoneSession.state.first { it is PairingState.Code }
+ watchSession.state.first { it is PairingState.Code }
+ watchSession.confirmShown()
+ phoneSession.confirmShown()
+ val watchLink = watch.await()
+ harness.phoneLink.onPaired(phone.await())
+ harness.phoneLink.publishSettings(quickPayOn)
+ runCurrent()
+ assertTrue(harness.appliedSettings.isEmpty())
+
+ harness.watchLink.onPaired(watchLink)
+ runCurrent()
+ assertEquals(1, harness.missedSettings)
+
+ harness.phoneLink.publishSettings(quickPayOn)
+ runCurrent()
+
+ assertEquals(1, harness.appliedSettings.size)
+ assertEquals(1, harness.missedSettings)
+ assertTrue(assertNotNull(harness.phoneStore.load()).isSettingsUpToDate)
+ }
+
+ @Test
+ fun `settings are encrypted on the carrier`() = runTest {
+ val harness = paired()
+
+ harness.phoneLink.publishSettings(quickPayOn)
+ runCurrent()
+
+ val needle = "isQuickPayEnabled".encodeToByteArray().toHex()
+ assertTrue(harness.statePackets(LinkPaths.SETTINGS).none { needle in it.payload.toHex() })
+ }
+
+ @Test
+ fun `settings changed while apart arrive on reconnect, the latest only once`() = runTest {
+ val harness = paired()
+ harness.network.isConnected = false
+
+ harness.phoneLink.publishSettings(quickPayOn)
+ harness.phoneLink.publishSettings(quickPayOff)
+ runCurrent()
+ assertTrue(harness.appliedSettings.isEmpty())
+ assertFalse(assertNotNull(harness.phoneStore.load()).isSettingsUpToDate)
+
+ harness.network.reconnect()
+ runCurrent()
+
+ assertEquals(listOf(quickPayOff), harness.appliedSettings)
+ assertTrue(assertNotNull(harness.phoneStore.load()).isSettingsUpToDate)
+ }
+
+ @Test
+ fun `a replayed older QuickPay on never replaces a newer off`() = runTest {
+ val harness = paired()
+ harness.phoneLink.publishSettings(quickPayOn)
+ runCurrent()
+ harness.phoneLink.publishSettings(quickPayOff)
+ runCurrent()
+ val old = harness.statePackets(LinkPaths.SETTINGS).first()
+
+ harness.network.replay(old)
+ runCurrent()
+
+ assertEquals(listOf(quickPayOn, quickPayOff), harness.appliedSettings)
+ assertIs(harness.watchErrors.last())
+ }
+
+ @Test
+ fun `settings delivered both ways are applied once`() = runTest {
+ val harness = paired()
+
+ harness.phoneLink.publishSettings(quickPayOn)
+ runCurrent()
+
+ assertEquals(2, harness.statePackets(LinkPaths.SETTINGS).size)
+ assertEquals(1, harness.appliedSettings.size)
+ }
+
+ @Test
+ fun `settings that failed to apply are taken again when delivered again`() = runTest {
+ val harness = paired()
+ harness.phoneLink.publishSettings(quickPayOn)
+ runCurrent()
+ // Roll the watch back to before the document was committed, as after a crash while applying it.
+ harness.watchStore.update { it?.copy(received = emptyMap()) }
+
+ harness.network.replay(harness.statePackets(LinkPaths.SETTINGS).first())
+ runCurrent()
+
+ assertEquals(2, harness.appliedSettings.size)
+ }
+
+ @Test
+ fun `each settings push carries a later time than the last, whatever the clock did`() = runTest {
+ val harness = paired()
+
+ harness.phoneLink.publishSettings(quickPayOn.copy(changedAtMs = 500))
+ harness.phoneLink.publishSettings(quickPayOff.copy(changedAtMs = 400))
+ runCurrent()
+
+ assertEquals(listOf(500L, 501L), harness.appliedSettings.map { it.changedAtMs })
+ }
+
+ @Test
+ fun `unpair from the phone ends the pairing on both sides and keeps the watch's wallet`() = runTest {
+ val harness = paired()
+
+ harness.phoneLink.remove(isErase = false)
+ assertEquals(Removal.Unpair, assertNotNull(harness.phoneStore.load()).removal)
+ runCurrent()
+
+ assertNull(harness.watchStore.load())
+ assertNull(harness.phoneStore.load())
+ assertTrue(harness.watchKeys.keys.isEmpty())
+ assertTrue(harness.phoneKeys.keys.isEmpty())
+ assertEquals(1, harness.unpairs)
+ assertEquals(0, harness.erases)
+ }
+
+ @Test
+ fun `erase from the phone is acknowledged before the wallet goes, then the keys`() = runTest {
+ val harness = paired()
+
+ harness.phoneLink.remove(isErase = true)
+ runCurrent()
+
+ assertEquals(1, harness.erases)
+ val acknowledged = harness.sentAtErase.any {
+ it.from === harness.network.watch && it.path.endsWith(LinkPaths.STATUS) && it.isState
+ }
+ assertTrue(acknowledged)
+ assertTrue(harness.watchKeys.keys.isEmpty())
+ assertNull(harness.watchStore.load())
+ assertNull(harness.phoneStore.load())
+ assertTrue(harness.phoneKeys.keys.isEmpty())
+ }
+
+ @Test
+ fun `an erase reaches a watch that was away, after the phone stopped waiting`() = runTest {
+ val harness = paired()
+ harness.network.isConnected = false
+
+ harness.phoneLink.remove(isErase = true)
+ runCurrent()
+ assertEquals(Removal.Erase, assertNotNull(harness.phoneStore.load()).removal)
+ harness.phoneLink.forget()
+ assertNull(harness.phoneStore.load())
+ assertEquals(0, harness.erases)
+
+ harness.network.reconnect()
+ runCurrent()
+
+ assertEquals(1, harness.erases)
+ assertNull(harness.watchStore.load())
+ }
+
+ @Test
+ fun `an erase that failed is run again when the command is delivered again`() = runTest {
+ val harness = paired()
+ harness.eraseFailure = IllegalStateException("disk")
+ harness.phoneLink.remove(isErase = true)
+ runCurrent()
+ assertEquals(0, harness.erases)
+ assertNotNull(harness.watchStore.load())
+
+ harness.eraseFailure = null
+ harness.network.replay(harness.statePackets(LinkPaths.CONTROL).last())
+ runCurrent()
+
+ assertEquals(1, harness.erases)
+ assertNull(harness.watchStore.load())
+ }
+
+ @Test
+ fun `an erase is noted on the watch before it is acknowledged, and acknowledged before it runs`() = runTest {
+ val harness = paired()
+ val statuses = harness.statePackets(LinkPaths.STATUS).size
+
+ harness.phoneLink.remove(isErase = true)
+ runCurrent()
+
+ assertEquals(1, harness.eraseNotes)
+ assertEquals(statuses, harness.sentAtNote.count { it.path.endsWith(LinkPaths.STATUS) })
+ assertTrue(harness.sentAtErase.count { it.path.endsWith(LinkPaths.STATUS) } > statuses)
+ assertEquals(1, harness.erases)
+ assertNull(harness.phoneStore.load())
+ }
+
+ @Test
+ fun `an erase whose note was cut short is not acknowledged, and the carrier delivers it again`() = runTest {
+ // The watch dies, or its disk fails, before the wipe is noted: nothing says it will ever run.
+ val harness = paired()
+ val statuses = harness.statePackets(LinkPaths.STATUS).size
+ harness.noteFailure = IllegalStateException("crash")
+ harness.phoneLink.remove(isErase = true)
+ runCurrent()
+
+ assertEquals(0, harness.erases)
+ assertEquals(statuses, harness.statePackets(LinkPaths.STATUS).size)
+ assertEquals(Removal.Erase, assertNotNull(harness.phoneStore.load()).removal)
+ assertNotNull(harness.watchStore.load())
+
+ // The watch app is back. The phone never withdrew the command, so the carrier still holds it.
+ harness.noteFailure = null
+ harness.network.reconnect()
+ runCurrent()
+
+ assertEquals(1, harness.eraseNotes)
+ assertEquals(1, harness.erases)
+ assertNull(harness.watchStore.load())
+ assertNull(harness.phoneStore.load())
+ }
+
+ @Test
+ fun `an erase that the watch finished after a crash leaves the phone waiting, never told it is done`() = runTest {
+ // The watch dies right after the note. Its next launch finishes the wipe, which takes the pairing with it.
+ val harness = paired()
+ val statuses = harness.statePackets(LinkPaths.STATUS).size
+ harness.crashAfterNote = IllegalStateException("crash")
+ harness.phoneLink.remove(isErase = true)
+ runCurrent()
+ assertTrue(harness.eraseNotes > 0)
+ assertEquals(statuses, harness.statePackets(LinkPaths.STATUS).size)
+ harness.crashAfterNote = null
+ harness.watchStore.update { null }
+ harness.watchKeys.clear()
+
+ harness.network.reconnect()
+ runCurrent()
+
+ assertEquals(0, harness.erases)
+ assertIs(harness.watchErrors.last())
+ assertEquals(Removal.Erase, assertNotNull(harness.phoneStore.load()).removal)
+ }
+
+ @Test
+ fun `an erase command of an earlier pairing does nothing`() = runTest {
+ val harness = paired()
+ harness.phoneLink.remove(isErase = true)
+ runCurrent()
+ val oldErase = harness.statePackets(LinkPaths.CONTROL).last()
+ assertEquals(1, harness.erases)
+
+ paired(harness)
+ harness.network.replay(oldErase)
+ runCurrent()
+
+ assertEquals(1, harness.erases)
+ assertNotNull(harness.watchStore.load())
+ assertIs(harness.watchErrors.last())
+ }
+
+ @Test
+ fun `a forged erase command does nothing`() = runTest {
+ val harness = paired()
+ val record = assertNotNull(harness.watchStore.load())
+ val path = LinkPaths.state(record.pairingId, LinkPaths.CONTROL)
+
+ harness.watchLink.runCatching { onPacket(LinkPacket("phone-node", path, ByteArray(80) { 1 })) }
+ val genuine = harness.statePackets(LinkPaths.CONTROL).first().payload
+ val altered = genuine.copyOf().also { it[it.lastIndex] = (it.last() + 1).toByte() }
+ val result = runCatching { harness.watchLink.onPacket(LinkPacket("phone-node", path, altered)) }
+
+ assertIs(result.exceptionOrNull())
+ assertEquals(0, harness.erases)
+ assertNotNull(harness.watchStore.load())
+ }
+
+ @Test
+ fun `the watch's own status cannot be turned into a command for it`() = runTest {
+ val harness = paired()
+ val record = assertNotNull(harness.watchStore.load())
+ val status = harness.statePackets(LinkPaths.STATUS).first().payload
+
+ val path = LinkPaths.state(record.pairingId, LinkPaths.CONTROL)
+ val result = runCatching { harness.watchLink.onPacket(LinkPacket("phone-node", path, status)) }
+
+ assertIs(result.exceptionOrNull())
+ }
+
+ @Test
+ fun `unpair from the watch ends the pairing on both sides`() = runTest {
+ val harness = paired()
+
+ harness.watchLink.unpair()
+ runCurrent()
+
+ assertNull(harness.watchStore.load())
+ assertNull(harness.phoneStore.load())
+ assertTrue(harness.phoneKeys.keys.isEmpty())
+ assertEquals(1, harness.unpairs)
+ }
+
+ @Test
+ fun `a phone whose wallet is wiped unpairs the watch and does not erase it`() = runTest {
+ val harness = paired()
+
+ harness.phoneLink.forget()
+ runCurrent()
+
+ assertNull(harness.phoneStore.load())
+ assertNull(harness.watchStore.load())
+ assertEquals(0, harness.erases)
+ assertEquals(1, harness.unpairs)
+ }
+
+ @Test
+ fun `nothing is published once a removal waits`() = runTest {
+ val harness = paired()
+ harness.network.isConnected = false
+ harness.phoneLink.remove(isErase = false)
+ val sent = harness.network.sent.size
+
+ harness.phoneLink.publishSettings(quickPayOn)
+
+ assertEquals(sent, harness.network.sent.size)
+ }
+
+ @Test
+ fun `pairing again replaces the earlier pairing and its keys`() = runTest {
+ val harness = paired()
+ val first = assertNotNull(harness.phoneStore.load()).pairingId
+
+ paired(harness)
+
+ val second = assertNotNull(harness.phoneStore.load()).pairingId
+ assertTrue(first != second)
+ assertTrue(harness.phoneKeys.keys.keys.all { second in it })
+ assertTrue(harness.watchKeys.keys.keys.all { second in it })
+ assertEquals(0, assertNotNull(harness.phoneStore.load()).settingsSent)
+ }
+
+ @Test
+ fun `a document for no pairing is refused`() = runTest {
+ val harness = LinkHarness(backgroundScope)
+
+ val path = LinkPaths.state("00", LinkPaths.CONTROL)
+ val result = runCatching { harness.watchLink.onPacket(LinkPacket("phone-node", path, ByteArray(40))) }
+
+ assertIs(result.exceptionOrNull())
+ }
+}
diff --git a/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkHarness.kt b/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkHarness.kt
new file mode 100644
index 0000000000..4c0eda5f0b
--- /dev/null
+++ b/wearlink/src/test/kotlin/to/bitkit/wearlink/LinkHarness.kt
@@ -0,0 +1,166 @@
+package to.bitkit.wearlink
+
+import kotlinx.coroutines.CoroutineScope
+import to.bitkit.wearlink.testing.FakeLinkNetwork
+import to.bitkit.wearlink.testing.InMemoryLinkKeyStore
+import to.bitkit.wearlink.testing.InMemoryRecordStore
+import to.bitkit.wearlink.testing.InMemoryThrottleStore
+import to.bitkit.wearlink.testing.SoftwareAgreementKey
+import java.security.KeyPair
+
+/** A phone and a watch app's link, wired to each other over [FakeLinkNetwork], with every seam a test may bend. */
+class LinkHarness(scope: CoroutineScope) {
+ companion object {
+ const val NETWORK = "regtest"
+ const val MNEMONIC =
+ "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
+ val PHONE_SEED = ByteArray(64) { 1 }
+ val OTHER_SEED = ByteArray(64) { 2 }
+ }
+
+ val network = FakeLinkNetwork(scope)
+ var now = TestAttestation.NOW_MS
+ val attestation = TestAttestation()
+
+ val phoneKeys = InMemoryLinkKeyStore()
+ val watchKeys = InMemoryLinkKeyStore()
+ val phoneStore = InMemoryRecordStore()
+ val watchStore = InMemoryRecordStore()
+ val throttleStore = InMemoryThrottleStore()
+
+ /** The BIP39 seed of the wallet the watch holds, or null for a watch without one. */
+ var watchSeed: ByteArray? = PHONE_SEED
+
+ /** How the watch's key is attested; by default as a genuine hardware key of this app. */
+ var attest: (KeyPair, ByteArray) -> List =
+ { pair, challenge -> attestation.chain(pair.public, challenge) }
+ var isUnverifiedTransferAllowed = false
+
+ /** Whether the phone app has a PIN. */
+ var isPinSet = true
+
+ /** What reading Google's status list gives; by default a list that names no certificate. */
+ var attestationStatus: suspend () -> AttestationStatusList? = { statusList("""{"entries":{}}""") }
+ var statusReads = 0
+
+ /** What the watch does with a seed it receives; by default it stores it. */
+ var storeSeed: (SeedPayload) -> SeedStoreResult = {
+ storedSeeds += it
+ SeedStoreResult.Stored(WalletLink.secret(PHONE_SEED, NETWORK))
+ }
+ val storedSeeds = mutableListOf()
+ var seedReads = 0
+
+ val agreementKey = SoftwareAgreementKey(attest = { pair, challenge -> attest(pair, challenge) })
+ val phoneErrors = mutableListOf()
+ val watchErrors = mutableListOf()
+
+ val appliedSettings = mutableListOf()
+ var erases = 0
+ var unpairs = 0
+ var eraseFailure: Throwable? = null
+
+ /** How often the watch noted an erase, and what makes the note fail. */
+ var eraseNotes = 0
+ var noteFailure: Throwable? = null
+
+ /** Ends the watch's handling right after the note is written, as when the app dies there. */
+ var crashAfterNote: Throwable? = null
+
+ /** What the watch had sent when it noted an erase, to check nothing was acknowledged before the note. */
+ var sentAtNote = emptyList()
+
+ /** What the watch had sent when its wallet was erased, to check the acknowledgement went out first. */
+ var sentAtErase = emptyList()
+
+ var missedSettings = 0
+ val phoneLink = PhoneLink(network.phone, phoneKeys, phoneStore, onSettingsMissed = { missedSettings++ }) { now }
+ val watchLink = WatchLink(
+ transport = network.watch,
+ keys = watchKeys,
+ store = watchStore,
+ listener = object : WatchLinkListener {
+ override suspend fun applySettings(settings: SettingsDoc) {
+ appliedSettings += settings
+ }
+
+ override suspend fun prepareErase() {
+ sentAtNote = network.sent.toList()
+ noteFailure?.let { throw it }
+ eraseNotes++
+ crashAfterNote?.let { throw it }
+ }
+
+ override suspend fun erase() {
+ sentAtErase = network.sent.toList()
+ eraseFailure?.let { throw it }
+ erases++
+ }
+
+ override suspend fun onUnpaired() {
+ unpairs++
+ }
+ },
+ info = { WatchInfo("1.0 (1)", isLockSet = true) },
+ nowMs = { now },
+ )
+
+ init {
+ network.phone.attach { packet -> runCatching { phoneLink.onPacket(packet) }.onFailure { phoneErrors += it } }
+ network.watch.attach { packet -> runCatching { watchLink.onPacket(packet) }.onFailure { watchErrors += it } }
+ }
+
+ val phoneEnv = object : PhonePairingEnv {
+ override val appId = TestAttestation.PACKAGE
+ override val name = "Pixel 9"
+ override val verifier = AttestationVerifier(attestation.policy)
+ override val isUnverifiedTransferAllowed get() = this@LinkHarness.isUnverifiedTransferAllowed
+ override val throttle = PairingThrottle(throttleStore) { now }
+ override val keys = phoneKeys
+
+ override suspend fun phoneId() = ByteArray(Handshake.ID_BYTES) { 0x11 }
+
+ override suspend fun isPinSet() = this@LinkHarness.isPinSet
+
+ override suspend fun attestationStatus(): AttestationStatusList? {
+ statusReads++
+ return this@LinkHarness.attestationStatus()
+ }
+
+ override suspend fun walletSecret() = WalletLink.secret(PHONE_SEED, NETWORK)
+
+ override suspend fun seed(): SeedPayload {
+ seedReads++
+ return SeedPayload(NETWORK, MNEMONIC, "passphrase")
+ }
+ }
+
+ val watchEnv = object : WatchPairingEnv {
+ override val appId = TestAttestation.PACKAGE
+ override val name = "Pixel Watch"
+ override val agreementKey = this@LinkHarness.agreementKey
+ override val keys = watchKeys
+
+ override suspend fun watchId() = ByteArray(Handshake.ID_BYTES) { 0x22 }
+
+ override suspend fun isLockSet() = true
+
+ override suspend fun walletSecret() = watchSeed?.let { WalletLink.secret(it, NETWORK) }
+
+ override suspend fun storeSeed(seed: SeedPayload) = this@LinkHarness.storeSeed(seed)
+ }
+
+ suspend fun watchNode(): LinkNode = network.phone.nodes().single()
+
+ suspend fun phonePairing() = PhonePairing(network.phone, phoneLink.pairingPackets, watchNode(), phoneEnv)
+
+ fun watchPairing() = WatchPairing(network.watch, watchLink.pairingPackets, watchEnv)
+
+ fun sentPaths(): List = network.sent.map { it.path }
+}
+
+/** The user confirms the code this session shows, as after comparing it with the other screen's. */
+fun PairingSession.confirmShown(isAuthenticated: Boolean = false) =
+ confirm((state.value as PairingState.Code).code, isAuthenticated)
+
+fun statusList(json: String): AttestationStatusList = AttestationStatusList.parse(json.encodeToByteArray())
diff --git a/wearlink/src/test/kotlin/to/bitkit/wearlink/PairingTest.kt b/wearlink/src/test/kotlin/to/bitkit/wearlink/PairingTest.kt
new file mode 100644
index 0000000000..587f28c530
--- /dev/null
+++ b/wearlink/src/test/kotlin/to/bitkit/wearlink/PairingTest.kt
@@ -0,0 +1,906 @@
+package to.bitkit.wearlink
+
+import kotlinx.coroutines.Deferred
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.async
+import kotlinx.coroutines.awaitCancellation
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.test.TestScope
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.runTest
+import to.bitkit.wearlink.testing.FakeLinkNetwork
+import java.security.SecureRandom
+import java.security.cert.CertificateFactory
+import java.security.cert.X509Certificate
+import kotlin.test.Test
+import kotlin.test.assertContentEquals
+import kotlin.test.assertEquals
+import kotlin.test.assertFalse
+import kotlin.test.assertIs
+import kotlin.test.assertNotEquals
+import kotlin.test.assertNull
+import kotlin.test.assertTrue
+
+@OptIn(ExperimentalCoroutinesApi::class)
+class PairingTest {
+ private class Run(
+ val harness: LinkHarness,
+ val phoneSession: PhonePairing,
+ val watchSession: WatchPairing,
+ val phone: Deferred>,
+ val watch: Deferred>,
+ ) {
+ suspend fun phoneCode() = phoneSession.state.first { it is PairingState.Code } as PairingState.Code
+
+ suspend fun watchCode() = watchSession.state.first { it is PairingState.Code } as PairingState.Code
+
+ suspend fun phoneError() = phone.await().exceptionOrNull()
+
+ suspend fun watchError() = watch.await().exceptionOrNull()
+ }
+
+ private suspend fun TestScope.start(harness: LinkHarness = LinkHarness(backgroundScope)): Run {
+ val watchSession = harness.watchPairing()
+ val phoneSession = harness.phonePairing()
+ val watch = async { runCatching { watchSession.run() } }
+ val phone = async { runCatching { phoneSession.run() } }
+ return Run(harness, phoneSession, watchSession, phone, watch)
+ }
+
+ private suspend fun Run.confirmBoth(isAuthenticated: Boolean = true) {
+ phoneCode()
+ watchCode()
+ watchSession.confirmShown()
+ phoneSession.confirmShown(isAuthenticated)
+ }
+
+ private fun LinkHarness.seedPackets() = network.sent.filter { it.path == LinkPaths.SEED }
+
+ // region proof: the watch already holds the wallet
+
+ @Test
+ fun `two holders of one wallet pair without the seed being sent`() = runTest {
+ val run = start()
+ val harness = run.harness
+
+ val phoneCode = run.phoneCode()
+ val watchCode = run.watchCode()
+ run.confirmBoth()
+ val phone = run.phone.await().getOrThrow()
+ val watch = run.watch.await().getOrThrow()
+
+ assertEquals(phoneCode.code, watchCode.code)
+ assertEquals(Handshake.CODE_DIGITS, phoneCode.code.length)
+ assertEquals(PairingMode.Proof, phoneCode.mode)
+ assertEquals("Pixel Watch", phoneCode.peerName)
+ assertEquals("Pixel 9", watchCode.peerName)
+ assertEquals(phone.pairingId, watch.pairingId)
+ assertEquals(PairingMode.Proof, watch.mode)
+ assertTrue(harness.seedPackets().isEmpty())
+ assertEquals(0, harness.seedReads)
+ assertTrue(harness.storedSeeds.isEmpty())
+ assertEquals(listOf(LinkPaths.PAIR_URI), harness.network.opened)
+ }
+
+ @Test
+ fun `both devices import the same two link keys and nothing else keeps them`() = runTest {
+ val run = start()
+ run.confirmBoth()
+ val link = run.phone.await().getOrThrow()
+ run.watch.await().getOrThrow()
+
+ val aliases = LinkRole.entries.map { LinkKeyStore.alias(link.pairingId, it) }.toSet()
+ assertEquals(aliases, run.harness.phoneKeys.keys.keys)
+ assertEquals(aliases, run.harness.watchKeys.keys.keys)
+ for (alias in aliases) assertContentEquals(run.harness.phoneKeys.keys[alias], run.harness.watchKeys.keys[alias])
+ assertNotEquals(
+ run.harness.phoneKeys.keys.getValue(aliases.first()).toHex(),
+ run.harness.phoneKeys.keys.getValue(aliases.last()).toHex(),
+ )
+ assertEquals(1, run.harness.agreementKey.deletes)
+ assertNull(run.harness.agreementKey.keyPair)
+ }
+
+ @Test
+ fun `a watch with another wallet does not pair`() = runTest {
+ val harness = LinkHarness(backgroundScope).apply { watchSeed = LinkHarness.OTHER_SEED }
+ val run = start(harness)
+
+ assertIs(run.watchError())
+ val phoneError = assertIs(run.phoneError())
+ assertEquals(AbortReason.DifferentWallet, phoneError.reason)
+ assertTrue(harness.phoneKeys.keys.isEmpty())
+ assertTrue(harness.watchKeys.keys.isEmpty())
+ assertTrue(harness.seedPackets().isEmpty())
+ }
+
+ @Test
+ fun `a watch that claims the wallet and cannot prove it does not pair`() = runTest {
+ val harness = LinkHarness(backgroundScope)
+ // The watch's own confirm is replaced by one whose wallet proof is made up.
+ harness.network.intercept = { packet ->
+ if (packet.from === harness.network.watch && packet.path == LinkPaths.CONFIRM) {
+ packet.payload.copyOf().also { it[it.lastIndex] = (it.last() + 1).toByte() }
+ } else {
+ packet.payload
+ }
+ }
+ val run = start(harness)
+
+ assertIs(run.phoneError())
+ assertTrue(harness.phoneKeys.keys.isEmpty())
+ }
+
+ @Test
+ fun `the pairing waits for both confirmations`() = runTest {
+ val run = start()
+ run.phoneCode()
+ run.watchCode()
+
+ run.phoneSession.confirmShown(isAuthenticated = true)
+ runCurrent()
+ assertFalse(run.phone.isCompleted)
+ assertFalse(run.watch.isCompleted)
+ assertTrue((run.phoneSession.state.value as PairingState.Code).isConfirmed)
+
+ run.watchSession.confirmShown()
+ assertTrue(run.phone.await().isSuccess)
+ assertTrue(run.watch.await().isSuccess)
+ }
+
+ @Test
+ fun `a cancel on the watch ends both sides`() = runTest {
+ val run = start()
+ run.watchCode()
+ run.phoneCode()
+
+ run.watchSession.cancel()
+
+ assertIs(run.watchError())
+ assertEquals(AbortReason.Cancelled, assertIs(run.phoneError()).reason)
+ assertTrue(run.harness.phoneKeys.keys.isEmpty())
+ }
+
+ @Test
+ fun `a cancel on the phone ends both sides`() = runTest {
+ val run = start()
+ run.watchCode()
+ run.phoneCode()
+
+ run.phoneSession.cancel()
+
+ assertIs(run.phoneError())
+ assertEquals(AbortReason.Cancelled, assertIs(run.watchError()).reason)
+ }
+
+ @Test
+ fun `a pairing cancelled before it started opens nothing on the watch and sends nothing`() = runTest {
+ val harness = LinkHarness(backgroundScope)
+ val session = harness.phonePairing()
+
+ session.cancel()
+ val error = runCatching { session.run() }.exceptionOrNull()
+
+ assertIs(error)
+ assertTrue(harness.network.opened.isEmpty())
+ assertTrue(harness.network.sent.isEmpty())
+ }
+
+ @Test
+ fun `a cancel on the phone while it waits for the watch ends the pairing`() = runTest {
+ val harness = LinkHarness(backgroundScope)
+ val session = harness.phonePairing()
+ val phone = async { runCatching { session.run() } }
+ runCurrent()
+
+ session.cancel()
+
+ assertIs(phone.await().exceptionOrNull())
+ assertEquals(LinkPaths.ABORT, harness.sentPaths().last())
+ }
+
+ @Test
+ fun `an unconfirmed pairing times out on both sides`() = runTest {
+ val run = start()
+ run.phoneCode()
+
+ assertIs(run.phoneError())
+ assertIs(run.watchError())
+ assertTrue(run.harness.phoneKeys.keys.isEmpty())
+ assertTrue(run.harness.watchKeys.keys.isEmpty())
+ }
+
+ @Test
+ fun `a watch that is not on its pair screen is never reached`() = runTest {
+ val harness = LinkHarness(backgroundScope)
+ val session = harness.phonePairing()
+
+ val error = runCatching { session.run() }.exceptionOrNull()
+
+ assertIs(error)
+ assertTrue(harness.sentPaths().all { it == LinkPaths.HELLO || it == LinkPaths.ABORT })
+ }
+
+ @Test
+ fun `an unreachable watch fails the pairing early`() = runTest {
+ val harness = LinkHarness(backgroundScope)
+ val session = harness.phonePairing()
+ harness.network.isConnected = false
+
+ assertIs(runCatching { session.run() }.exceptionOrNull())
+ }
+
+ @Test
+ fun `a repeated hello gets the same reply`() = runTest {
+ val harness = LinkHarness(backgroundScope)
+ var droppedReplies = 0
+ harness.network.intercept = { packet ->
+ if (packet.path == LinkPaths.REPLY && droppedReplies++ == 0) null else packet.payload
+ }
+ val run = start(harness)
+ run.confirmBoth()
+
+ assertTrue(run.phone.await().isSuccess)
+ val replies = harness.network.sent.filter { it.path == LinkPaths.REPLY }
+ assertEquals(2, replies.size)
+ assertContentEquals(replies[0].payload, replies[1].payload)
+ }
+
+ @Test
+ fun `a phone that speaks only a newer version is told to update`() = runTest {
+ val harness = LinkHarness(backgroundScope)
+ harness.network.intercept = { packet ->
+ if (packet.path == LinkPaths.HELLO) {
+ val hello = Hello.decode(packet.payload)
+ Hello(2, 3, hello.appId, hello.phoneId, hello.nonce, hello.commitment, hello.name).encode()
+ } else {
+ packet.payload
+ }
+ }
+ val run = start(harness)
+
+ assertIs(run.watchError())
+ assertEquals(AbortReason.UpdateRequired, assertIs(run.phoneError()).reason)
+ }
+
+ // endregion
+
+ // region tampering
+
+ private fun alterLastByte(harness: LinkHarness, path: String, from: FakeLinkNetwork.Endpoint? = null) {
+ harness.network.intercept = { packet ->
+ if (packet.path == path && (from == null || packet.from === from)) {
+ packet.payload.copyOf().also { it[it.lastIndex] = (it.last() + 1).toByte() }
+ } else {
+ packet.payload
+ }
+ }
+ }
+
+ private suspend fun TestScope.assertNoPairing(harness: LinkHarness) {
+ val run = start(harness)
+ // The sides that get as far as the code confirm it, so only the tampering can stop them.
+ backgroundScope.launch { run.confirmBoth() }
+ assertIs(run.phoneError())
+ assertIs(run.watchError())
+ assertTrue(harness.phoneKeys.keys.isEmpty())
+ assertTrue(harness.watchKeys.keys.isEmpty())
+ assertTrue(harness.storedSeeds.isEmpty())
+ assertNull(harness.phoneStore.load())
+ }
+
+ @Test
+ fun `an altered hello ends the pairing`() = runTest {
+ // The watch attests and commits to the hello it saw, which is not the one the phone sent.
+ val harness = LinkHarness(backgroundScope).apply { watchSeed = null }
+ harness.network.intercept = { packet ->
+ if (packet.path == LinkPaths.HELLO) {
+ val hello = Hello.decode(packet.payload)
+ Hello(1, 1, hello.appId, hello.phoneId, hello.nonce, hello.commitment, "Evil").encode()
+ } else {
+ packet.payload
+ }
+ }
+
+ assertNoPairing(harness)
+ assertTrue(harness.sentPaths().none { it == LinkPaths.REVEAL })
+ }
+
+ @Test
+ fun `an altered reply ends the pairing`() = runTest {
+ val harness = LinkHarness(backgroundScope)
+ alterLastByte(harness, LinkPaths.REPLY)
+
+ assertNoPairing(harness)
+ }
+
+ @Test
+ fun `a reveal of another key than the committed one ends the pairing`() = runTest {
+ val harness = LinkHarness(backgroundScope)
+ val other = LinkCrypto.generateKeyPair(SecureRandom()).public.encoded
+ harness.network.intercept = { packet ->
+ if (packet.path == LinkPaths.REVEAL) {
+ Reveal(other, Reveal.decode(packet.payload).nonce).encode()
+ } else {
+ packet.payload
+ }
+ }
+ val run = start(harness)
+
+ assertIs(run.watchError())
+ assertIs(run.phoneError())
+ }
+
+ @Test
+ fun `a relay that swaps in its own key for the watch's is found out`() = runTest {
+ // Without the watch's private key the relay cannot go on, and the two ends never share keys.
+ val harness = LinkHarness(backgroundScope).apply { isUnverifiedTransferAllowed = true }
+ val relay = LinkCrypto.generateKeyPair(SecureRandom())
+ harness.network.intercept = { packet ->
+ if (packet.path == LinkPaths.REPLY) {
+ val reply = Reply.decode(packet.payload)
+ val key = relay.public.encoded
+ Reply(1, reply.watchId, reply.nonce, reply.hasWallet, key, emptyList(), reply.name, true).encode()
+ } else {
+ packet.payload
+ }
+ }
+
+ assertNoPairing(harness)
+ }
+
+ @Test
+ fun `a relay that completes a handshake with each side leaves two different codes`() = runTest {
+ // The relay answers the phone as the watch and the watch as the phone, each with its own key, and gets as
+ // far as the code on both. It had to pick its key before it saw the phone's, so it cannot steer the codes.
+ val harness = LinkHarness(backgroundScope).apply {
+ watchSeed = null
+ isUnverifiedTransferAllowed = true
+ }
+ val relay = Relay(harness)
+ harness.network.intercept = relay::forward
+ val run = start(harness)
+
+ val phoneCode = run.phoneCode()
+ val watchCode = run.watchCode()
+
+ assertNotEquals(phoneCode.code, watchCode.code)
+ assertEquals(relay.phoneSide().code, phoneCode.code)
+ assertEquals(relay.watchSide().code, watchCode.code)
+ // The wearer taps through; the phone's user sees another code and does not confirm.
+ run.watchSession.confirmShown()
+ runCurrent()
+ assertEquals(0, harness.seedReads)
+ assertTrue(harness.seedPackets().isEmpty())
+ run.phoneSession.cancel()
+ assertIs(run.phoneError())
+ assertTrue(harness.storedSeeds.isEmpty())
+ assertTrue(harness.phoneKeys.keys.isEmpty())
+ }
+
+ private class Relay(private val harness: LinkHarness) {
+ private val key = LinkCrypto.generateKeyPair(SecureRandom())
+ private val nonce = ByteArray(Handshake.NONCE_BYTES) { 9 }
+ private val reveal = Reveal(key.public.encoded, nonce).encode()
+ private var phoneHello = ByteArray(0)
+ private var relayHello = ByteArray(0)
+ private var watchReply = ByteArray(0)
+ private var relayReply = ByteArray(0)
+ private var phoneReveal = ByteArray(0)
+
+ fun phoneSide(): SessionKeys = keys(Reveal.decode(phoneReveal).publicKey, phoneHello, relayReply, phoneReveal)
+
+ fun watchSide(): SessionKeys = keys(Reply.decode(watchReply).publicKey, relayHello, watchReply, reveal)
+
+ fun forward(packet: FakeLinkNetwork.Sent): ByteArray? {
+ val isFromPhone = packet.from === harness.network.phone
+ return when (packet.path) {
+ LinkPaths.HELLO -> {
+ phoneHello = packet.payload
+ val hello = Hello.decode(packet.payload)
+ val commitment = Handshake.commitment(key.public.encoded, nonce)
+ Hello(1, 1, hello.appId, hello.phoneId, hello.nonce, commitment, hello.name).encode()
+ .also { relayHello = it }
+ }
+ LinkPaths.REPLY -> {
+ watchReply = packet.payload
+ val reply = Reply.decode(packet.payload)
+ Reply(1, reply.watchId, reply.nonce, false, key.public.encoded, emptyList(), reply.name, true)
+ .encode().also { relayReply = it }
+ }
+ LinkPaths.REVEAL -> {
+ phoneReveal = packet.payload
+ reveal
+ }
+ LinkPaths.CONFIRM if isFromPhone -> Confirm(watchSide().keyMac(LinkRole.Phone), null).encode()
+ LinkPaths.CONFIRM -> Confirm(phoneSide().keyMac(LinkRole.Watch), null).encode()
+ LinkPaths.ACCEPT if !isFromPhone -> {
+ val accept = watchSide().open(LinkRole.Watch, LinkPaths.ACCEPT, packet.payload)
+ phoneSide().seal(LinkRole.Watch, LinkPaths.ACCEPT, accept, SecureRandom())
+ }
+ else -> packet.payload
+ }
+ }
+
+ private fun keys(peerKey: ByteArray, hello: ByteArray, reply: ByteArray, reveal: ByteArray): SessionKeys {
+ val shared = LinkCrypto.agree(key.private, LinkCrypto.decodePublicKey(peerKey))
+ return SessionKeys.derive(shared, Handshake.transcript(hello, reply, reveal))
+ }
+ }
+
+ @Test
+ fun `an altered confirm ends the pairing`() = runTest {
+ val harness = LinkHarness(backgroundScope)
+ harness.network.intercept = { packet ->
+ if (packet.path == LinkPaths.CONFIRM && packet.from === harness.network.phone) {
+ packet.payload.copyOf().also { it[0] = (it[0] + 1).toByte() }
+ } else {
+ packet.payload
+ }
+ }
+ val run = start(harness)
+
+ assertIs(run.watchError())
+ assertIs(run.phoneError())
+ }
+
+ @Test
+ fun `an altered accept ends the pairing`() = runTest {
+ val harness = LinkHarness(backgroundScope)
+ alterLastByte(harness, LinkPaths.ACCEPT)
+
+ assertNoPairing(harness)
+ }
+
+ @Test
+ fun `an accept from an earlier pairing is not taken`() = runTest {
+ val harness = LinkHarness(backgroundScope)
+ val first = start(harness)
+ first.confirmBoth()
+ first.phone.await().getOrThrow()
+ first.watch.await().getOrThrow()
+ val oldAccept = harness.network.sent.first { it.path == LinkPaths.ACCEPT && it.from === harness.network.watch }
+
+ val second = start(harness)
+ second.phoneCode()
+ second.watchCode()
+ harness.network.replay(oldAccept)
+ second.phoneSession.confirmShown(isAuthenticated = true)
+
+ assertIs(second.phoneError())
+ }
+
+ @Test
+ fun `messages from another device are ignored`() = runTest {
+ val harness = LinkHarness(backgroundScope)
+ val run = start(harness)
+ run.phoneCode()
+ run.watchCode()
+
+ harness.phoneLink.onPacket(LinkPacket("stranger", LinkPaths.ABORT, byteArrayOf(0)))
+ harness.phoneLink.onPacket(LinkPacket("stranger", LinkPaths.ACCEPT, ByteArray(40)))
+ run.confirmBoth()
+
+ assertTrue(run.phone.await().isSuccess)
+ }
+
+ // endregion
+
+ // region transfer: the watch holds no wallet
+
+ private fun TestScope.transferHarness() = LinkHarness(backgroundScope).apply { watchSeed = null }
+
+ @Test
+ fun `a watch without a wallet receives the seed after both confirmations`() = runTest {
+ val harness = transferHarness()
+ val run = start(harness)
+
+ val code = run.phoneCode()
+ assertEquals(PairingMode.Transfer, code.mode)
+ assertEquals(PairingMode.Transfer, run.watchCode().mode)
+ assertEquals(AttestationVerdict.Verified(KeyLevel.TrustedEnvironment), code.attestation)
+ run.confirmBoth()
+ val link = run.phone.await().getOrThrow()
+ run.watch.await().getOrThrow()
+
+ val stored = harness.storedSeeds.single()
+ assertEquals(LinkHarness.MNEMONIC, stored.mnemonic)
+ assertEquals("passphrase", stored.passphrase)
+ assertEquals(LinkHarness.NETWORK, stored.network)
+ assertEquals(PairingMode.Transfer, link.mode)
+ assertEquals(1, harness.seedReads)
+ assertEquals(1, harness.seedPackets().size)
+ assertEquals(0, harness.throttleStore.state.attempts)
+ }
+
+ @Test
+ fun `the seed never crosses the carrier in clear, and never as a stored document`() = runTest {
+ val harness = transferHarness()
+ val run = start(harness)
+ run.confirmBoth()
+ run.phone.await().getOrThrow()
+
+ val needles = listOf(LinkHarness.MNEMONIC, "abandon", "passphrase").map { it.encodeToByteArray().toHex() }
+ for (packet in harness.network.sent) {
+ val hex = packet.payload.toHex()
+ assertTrue(needles.none { it in hex }, "Found seed material at '${packet.path}'")
+ }
+ assertTrue(harness.network.sent.filter { LinkPaths.isPairing(it.path) }.none { it.isState })
+ assertFalse(harness.seedPackets().single().isState)
+ }
+
+ @Test
+ fun `no seed is read or sent before the watch confirmed`() = runTest {
+ val harness = transferHarness()
+ val run = start(harness)
+ run.phoneCode()
+ run.watchCode()
+
+ run.phoneSession.confirmShown(isAuthenticated = true)
+ runCurrent()
+
+ assertEquals(0, harness.seedReads)
+ assertTrue(harness.seedPackets().isEmpty())
+ run.watchSession.confirmShown()
+ assertTrue(run.phone.await().isSuccess)
+ assertEquals(1, harness.seedReads)
+ }
+
+ @Test
+ fun `no seed is read or sent before the phone's user confirmed`() = runTest {
+ val harness = transferHarness()
+ val run = start(harness)
+ run.phoneCode()
+ run.watchCode()
+
+ run.watchSession.confirmShown()
+ runCurrent()
+
+ assertEquals(0, harness.seedReads)
+ assertTrue(harness.seedPackets().isEmpty())
+ }
+
+ @Test
+ fun `a confirmation made before the code shows, or of another code, sends no seed`() = runTest {
+ val harness = transferHarness()
+ val run = start(harness)
+ run.phoneSession.confirm("000000", isAuthenticated = true)
+ val code = run.phoneCode().code
+ run.watchCode()
+ run.phoneSession.confirm(if (code == "000000") "000001" else "000000", isAuthenticated = true)
+
+ run.watchSession.confirmShown()
+ runCurrent()
+
+ assertFalse((run.phoneSession.state.value as PairingState.Code).isConfirmed)
+ assertFalse(run.phone.isCompleted)
+ assertEquals(0, harness.seedReads)
+ assertTrue(harness.seedPackets().isEmpty())
+ }
+
+ @Test
+ fun `a confirmation without the phone's authentication sends no seed`() = runTest {
+ val harness = transferHarness()
+ val run = start(harness)
+ run.confirmBoth(isAuthenticated = false)
+
+ assertIs(run.phoneError())
+ assertIs(run.watchError())
+ assertEquals(0, harness.seedReads)
+ assertTrue(harness.seedPackets().isEmpty())
+ assertTrue(harness.storedSeeds.isEmpty())
+ }
+
+ @Test
+ fun `a pairing of two wallet holders needs no authentication`() = runTest {
+ val run = start()
+ run.confirmBoth(isAuthenticated = false)
+
+ assertTrue(run.phone.await().isSuccess)
+ }
+
+ @Test
+ fun `an unverified attestation refuses the transfer before the phone reveals its key`() = runTest {
+ val harness = transferHarness().apply { attest = { _, _ -> emptyList() } }
+ val run = start(harness)
+
+ val error = assertIs(run.phoneError())
+ assertEquals(AttestationFailure.NoChain, error.failure)
+ assertEquals(AbortReason.Unverified, assertIs(run.watchError()).reason)
+ assertTrue(harness.sentPaths().none { it == LinkPaths.REVEAL || it == LinkPaths.SEED })
+ assertEquals(0, harness.seedReads)
+ assertEquals(0, harness.throttleStore.state.attempts)
+ }
+
+ @Test
+ fun `a software key refuses the transfer`() = runTest {
+ val harness = transferHarness()
+ harness.attest = { pair, challenge -> harness.attestation.chain(pair.public, challenge, level = 0) }
+ val run = start(harness)
+
+ assertEquals(AttestationFailure.SoftwareKey, assertIs(run.phoneError()).failure)
+ assertTrue(harness.seedPackets().isEmpty())
+ }
+
+ @Test
+ fun `an attestation of another handshake refuses the transfer`() = runTest {
+ val harness = transferHarness()
+ harness.attest = { pair, _ -> harness.attestation.chain(pair.public, ByteArray(32) { 5 }) }
+ val run = start(harness)
+
+ assertEquals(AttestationFailure.WrongChallenge, assertIs(run.phoneError()).failure)
+ }
+
+ @Test
+ fun `an attestation of another key than the offered one refuses the transfer`() = runTest {
+ val harness = transferHarness()
+ val other = LinkCrypto.generateKeyPair(SecureRandom())
+ harness.attest = { _, challenge -> harness.attestation.chain(other.public, challenge) }
+ val run = start(harness)
+
+ assertEquals(AttestationFailure.KeyMismatch, assertIs(run.phoneError()).failure)
+ }
+
+ @Test
+ fun `a debug build may transfer to an unattested watch, and says it is unverified`() = runTest {
+ val harness = transferHarness().apply {
+ attest = { _, _ -> emptyList() }
+ isUnverifiedTransferAllowed = true
+ }
+ val run = start(harness)
+
+ assertEquals(AttestationVerdict.Unverified(AttestationFailure.NoChain), run.phoneCode().attestation)
+ run.confirmBoth()
+ val link = run.phone.await().getOrThrow()
+
+ assertIs(link.attestation)
+ assertEquals(1, harness.storedSeeds.size)
+ }
+
+ @Test
+ fun `an unverified attestation does not stop two wallet holders from pairing`() = runTest {
+ val harness = LinkHarness(backgroundScope).apply { attest = { _, _ -> emptyList() } }
+ val run = start(harness)
+ run.confirmBoth()
+
+ assertIs(run.phone.await().getOrThrow().attestation)
+ }
+
+ private fun serial(certificate: ByteArray): String {
+ val parsed = CertificateFactory.getInstance("X.509").generateCertificate(certificate.inputStream())
+ return (parsed as X509Certificate).serialNumber.toString(16)
+ }
+
+ /** Has the watch attest its key as a genuine hardware key, and lists the certificate at [index] of its chain. */
+ private fun LinkHarness.listCertificate(index: Int, status: String) {
+ var chain = emptyList()
+ attest = { pair, challenge -> attestation.chain(pair.public, challenge).also { chain = it } }
+ attestationStatus = {
+ statusList("""{"entries":{"${serial(chain[index])}":{"status":"$status"}}}""")
+ }
+ }
+
+ private suspend fun assertStatusRefuses(run: Run, expected: AttestationFailure, toldWatch: AbortReason) {
+ val harness = run.harness
+ assertEquals(expected, assertIs(run.phoneError()).failure)
+ assertEquals(toldWatch, assertIs(run.watchError()).reason)
+ assertTrue(harness.sentPaths().none { it == LinkPaths.REVEAL || it == LinkPaths.SEED })
+ assertEquals(0, harness.seedReads)
+ assertTrue(harness.storedSeeds.isEmpty())
+ assertEquals(0, harness.throttleStore.state.attempts)
+ }
+
+ @Test
+ fun `a revoked attestation certificate refuses the transfer before the phone reveals its key`() = runTest {
+ val harness = transferHarness().apply { listCertificate(index = 1, status = "REVOKED") }
+
+ assertStatusRefuses(start(harness), AttestationFailure.Revoked, AbortReason.Unverified)
+ }
+
+ @Test
+ fun `a suspended attestation certificate refuses the transfer`() = runTest {
+ val harness = transferHarness().apply { listCertificate(index = 0, status = "SUSPENDED") }
+
+ assertStatusRefuses(start(harness), AttestationFailure.Revoked, AbortReason.Unverified)
+ }
+
+ @Test
+ fun `a certificate listed with a status this version does not know refuses the transfer`() = runTest {
+ val harness = transferHarness().apply { listCertificate(index = 2, status = "SOMETHING_NEW") }
+
+ assertStatusRefuses(start(harness), AttestationFailure.Revoked, AbortReason.Unverified)
+ }
+
+ @Test
+ fun `a status list that cannot be read refuses the transfer`() = runTest {
+ val harness = transferHarness().apply { attestationStatus = { null } }
+
+ assertStatusRefuses(start(harness), AttestationFailure.StatusUnknown, AbortReason.Failed)
+ }
+
+ @Test
+ fun `a chain that the status list does not name transfers`() = runTest {
+ val harness = transferHarness().apply {
+ attestationStatus = { statusList("""{"entries":{"ffffffff":{"status":"REVOKED"}}}""") }
+ }
+ val run = start(harness)
+
+ assertEquals(AttestationVerdict.Verified(KeyLevel.TrustedEnvironment), run.phoneCode().attestation)
+ run.confirmBoth()
+
+ assertTrue(run.phone.await().isSuccess)
+ assertEquals(1, harness.statusReads)
+ assertEquals(1, harness.storedSeeds.size)
+ }
+
+ @Test
+ fun `a debug build goes on without the status list, and says the watch is unverified`() = runTest {
+ val harness = transferHarness().apply {
+ attestationStatus = { null }
+ isUnverifiedTransferAllowed = true
+ }
+ val run = start(harness)
+
+ assertEquals(AttestationVerdict.Unverified(AttestationFailure.StatusUnknown), run.phoneCode().attestation)
+ run.confirmBoth()
+
+ assertIs(run.phone.await().getOrThrow().attestation)
+ }
+
+ @Test
+ fun `the status list is not read for a chain that was not verified`() = runTest {
+ val harness = transferHarness().apply { attest = { _, _ -> emptyList() } }
+ val run = start(harness)
+
+ assertIs(run.phoneError())
+ assertEquals(0, harness.statusReads)
+ }
+
+ @Test
+ fun `two wallet holders pair with a revoked or unread status, and the watch counts as unverified`() = runTest {
+ val revoked = LinkHarness(backgroundScope).apply { listCertificate(index = 1, status = "REVOKED") }
+ val unread = LinkHarness(backgroundScope).apply { attestationStatus = { null } }
+
+ val cases = listOf(revoked to AttestationFailure.Revoked, unread to AttestationFailure.StatusUnknown)
+ for ((harness, failure) in cases) {
+ val run = start(harness)
+ run.confirmBoth()
+
+ assertEquals(AttestationVerdict.Unverified(failure), run.phone.await().getOrThrow().attestation)
+ assertTrue(harness.seedPackets().isEmpty())
+ }
+ }
+
+ @Test
+ fun `a cancel on the phone while the status list is read ends the pairing`() = runTest {
+ val harness = transferHarness().apply { attestationStatus = { awaitCancellation() } }
+ val run = start(harness)
+ runCurrent()
+ assertEquals(1, harness.statusReads)
+
+ run.phoneSession.cancel()
+
+ assertIs(run.phoneError())
+ assertEquals(AbortReason.Cancelled, assertIs(run.watchError()).reason)
+ assertTrue(harness.sentPaths().none { it == LinkPaths.REVEAL })
+ }
+
+ @Test
+ fun `a phone without a PIN sends no seed, and ends before it reveals its key`() = runTest {
+ val harness = transferHarness().apply { isPinSet = false }
+ val run = start(harness)
+
+ assertIs(run.phoneError())
+ assertEquals(AbortReason.Failed, assertIs(run.watchError()).reason)
+ assertTrue(harness.sentPaths().none { it == LinkPaths.REVEAL || it == LinkPaths.SEED })
+ assertEquals(0, harness.seedReads)
+ assertEquals(0, harness.statusReads)
+ assertEquals(0, harness.throttleStore.state.attempts)
+ }
+
+ @Test
+ fun `a phone without a PIN pairs with a watch that already holds its wallet`() = runTest {
+ val run = start(LinkHarness(backgroundScope).apply { isPinSet = false })
+ run.confirmBoth(isAuthenticated = false)
+
+ assertEquals(PairingMode.Proof, run.phone.await().getOrThrow().mode)
+ assertTrue(run.harness.seedPackets().isEmpty())
+ }
+
+ @Test
+ fun `an altered seed message stores nothing`() = runTest {
+ val harness = transferHarness()
+ alterLastByte(harness, LinkPaths.SEED)
+
+ assertNoPairing(harness)
+ }
+
+ @Test
+ fun `a seed message of an earlier transfer is not taken by a later one`() = runTest {
+ val harness = transferHarness()
+ val first = start(harness)
+ first.confirmBoth()
+ first.phone.await().getOrThrow()
+ first.watch.await().getOrThrow()
+ val oldSeed = harness.seedPackets().single()
+ harness.storedSeeds.clear()
+
+ // The second transfer's own seed message is replaced by the first one's.
+ harness.network.intercept = { if (it.path == LinkPaths.SEED) oldSeed.payload else it.payload }
+ val second = start(harness)
+ second.confirmBoth()
+
+ assertIs(second.watchError())
+ assertTrue(harness.storedSeeds.isEmpty())
+ }
+
+ @Test
+ fun `a seed sent to a watch that holds a wallet is never stored`() = runTest {
+ val harness = LinkHarness(backgroundScope)
+ val run = start(harness)
+ run.confirmBoth()
+ run.phone.await().getOrThrow()
+ run.watch.await().getOrThrow()
+
+ assertTrue(harness.storedSeeds.isEmpty())
+ }
+
+ @Test
+ fun `a watch that refuses to store the seed fails the transfer on both sides`() = runTest {
+ val harness = transferHarness().apply {
+ storeSeed = { SeedStoreResult.Refused(StoreFailure.InsecureKey) }
+ }
+ val run = start(harness)
+ run.confirmBoth()
+
+ assertEquals(StoreFailure.InsecureKey, assertIs(run.phoneError()).reason)
+ assertIs(run.watchError())
+ assertTrue(harness.phoneKeys.keys.isEmpty())
+ assertTrue(harness.watchKeys.keys.isEmpty())
+ assertEquals(1, harness.throttleStore.state.attempts)
+ }
+
+ @Test
+ fun `a watch that stored another wallet than the one sent fails the transfer`() = runTest {
+ val harness = transferHarness().apply {
+ storeSeed = { SeedStoreResult.Stored(WalletLink.secret(LinkHarness.OTHER_SEED, LinkHarness.NETWORK)) }
+ }
+ val run = start(harness)
+ run.confirmBoth()
+
+ assertEquals(StoreFailure.Failed, assertIs(run.phoneError()).reason)
+ assertTrue(harness.phoneKeys.keys.isEmpty())
+ }
+
+ @Test
+ fun `three unfinished transfers lock the next one out`() = runTest {
+ val harness = transferHarness()
+ repeat(PairingThrottle.MAX_ATTEMPTS) {
+ val run = start(harness)
+ run.phoneCode()
+ run.watchCode()
+ run.phoneSession.cancel()
+ run.phone.await()
+ run.watch.await()
+ }
+
+ val run = start(harness)
+
+ assertIs(run.phoneError())
+ assertEquals(PairingThrottle.MAX_ATTEMPTS, harness.network.sent.count { it.path == LinkPaths.REVEAL })
+ assertTrue(harness.seedPackets().isEmpty())
+ }
+
+ @Test
+ fun `the handshake messages carry no confirmation code`() = runTest {
+ val run = start(transferHarness())
+ val code = run.phoneCode().code.encodeToByteArray().toHex()
+ run.confirmBoth()
+ run.phone.await().getOrThrow()
+
+ assertTrue(run.harness.network.sent.none { code in it.payload.toHex() })
+ }
+
+ // endregion
+}
diff --git a/wearlink/src/test/kotlin/to/bitkit/wearlink/PairingThrottleTest.kt b/wearlink/src/test/kotlin/to/bitkit/wearlink/PairingThrottleTest.kt
new file mode 100644
index 0000000000..4bdb7bef77
--- /dev/null
+++ b/wearlink/src/test/kotlin/to/bitkit/wearlink/PairingThrottleTest.kt
@@ -0,0 +1,49 @@
+package to.bitkit.wearlink
+
+import kotlinx.coroutines.test.runTest
+import to.bitkit.wearlink.testing.InMemoryThrottleStore
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertFailsWith
+
+class PairingThrottleTest {
+ private var now = 1_000_000L
+ private val store = InMemoryThrottleStore()
+ private val throttle = PairingThrottle(store) { now }
+
+ @Test
+ fun `the fourth unfinished try within the lock is refused`() = runTest {
+ repeat(PairingThrottle.MAX_ATTEMPTS) { throttle.begin() }
+
+ val error = assertFailsWith { throttle.begin() }
+
+ assertEquals(now + PairingThrottle.LOCK.inWholeMilliseconds, error.untilMs)
+ }
+
+ @Test
+ fun `tries start again once the lock is over`() = runTest {
+ repeat(PairingThrottle.MAX_ATTEMPTS) { throttle.begin() }
+ now += PairingThrottle.LOCK.inWholeMilliseconds
+
+ throttle.begin()
+
+ assertEquals(ThrottleState(attempts = 1), store.state)
+ }
+
+ @Test
+ fun `a finished transfer clears the count`() = runTest {
+ repeat(PairingThrottle.MAX_ATTEMPTS - 1) { throttle.begin() }
+ throttle.reset()
+
+ repeat(PairingThrottle.MAX_ATTEMPTS - 1) { throttle.begin() }
+
+ assertEquals(0, store.state.lockedUntilMs)
+ }
+
+ @Test
+ fun `the count survives a restart`() = runTest {
+ repeat(PairingThrottle.MAX_ATTEMPTS) { throttle.begin() }
+
+ assertFailsWith { PairingThrottle(InMemoryThrottleStore(store.state)) { now }.begin() }
+ }
+}
diff --git a/wearlink/src/test/kotlin/to/bitkit/wearlink/TestAttestation.kt b/wearlink/src/test/kotlin/to/bitkit/wearlink/TestAttestation.kt
new file mode 100644
index 0000000000..7a1be551ac
--- /dev/null
+++ b/wearlink/src/test/kotlin/to/bitkit/wearlink/TestAttestation.kt
@@ -0,0 +1,174 @@
+package to.bitkit.wearlink
+
+import org.bouncycastle.asn1.ASN1Boolean
+import org.bouncycastle.asn1.ASN1Encodable
+import org.bouncycastle.asn1.ASN1Enumerated
+import org.bouncycastle.asn1.ASN1Integer
+import org.bouncycastle.asn1.ASN1ObjectIdentifier
+import org.bouncycastle.asn1.DEROctetString
+import org.bouncycastle.asn1.DERSequence
+import org.bouncycastle.asn1.DERSet
+import org.bouncycastle.asn1.DERTaggedObject
+import org.bouncycastle.asn1.x500.X500Name
+import org.bouncycastle.asn1.x509.BasicConstraints
+import org.bouncycastle.asn1.x509.Extension
+import org.bouncycastle.asn1.x509.KeyUsage
+import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder
+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder
+import java.math.BigInteger
+import java.security.KeyPair
+import java.security.PrivateKey
+import java.security.PublicKey
+import java.security.SecureRandom
+import java.util.Date
+
+/**
+ * Builds key attestation chains as a watch's Keystore would, signed by a test root, with every field a test may
+ * want to get wrong.
+ */
+class TestAttestation(
+ private val nowMs: Long = NOW_MS,
+ val root: KeyPair = LinkCrypto.generateKeyPair(SecureRandom()),
+) {
+ companion object {
+ const val NOW_MS = 1_800_000_000_000L
+ const val PACKAGE = "to.bitkit.dev"
+ val DIGEST = ByteArray(32) { 7 }
+ private const val DAY_MS = 86_400_000L
+ private const val PURPOSE_SIGN = 2
+ const val PURPOSE_AGREE = 6
+ val SIGNING_PURPOSES = setOf(PURPOSE_SIGN)
+ }
+
+ private val intermediate = LinkCrypto.generateKeyPair(SecureRandom())
+ private var serial = 1L
+
+ val policy = AttestationPolicy(
+ packageName = PACKAGE,
+ signingDigests = setOf(DIGEST.toHex()),
+ trustedRoots = setOf(LinkCrypto.sha256(root.public.encoded).toHex()),
+ nowMs = { nowMs },
+ )
+
+ @Suppress("LongParameterList")
+ fun chain(
+ key: PublicKey,
+ challenge: ByteArray,
+ level: Int = 1,
+ purposes: Set = setOf(PURPOSE_AGREE),
+ packageName: String = PACKAGE,
+ digest: ByteArray = DIGEST,
+ isLocked: Boolean = true,
+ bootState: Int = 0,
+ origin: Int = 0,
+ hasRecord: Boolean = true,
+ leafNotAfterMs: Long = nowMs + DAY_MS,
+ ): List {
+ val record = description(challenge, level, purposes, packageName, digest, isLocked, bootState, origin)
+ val leaf = certificate(
+ "leaf",
+ key,
+ "intermediate",
+ intermediate.private,
+ isAuthority = false,
+ record = record.takeIf { hasRecord },
+ notAfterMs = leafNotAfterMs,
+ )
+ return listOf(leaf) + authorities()
+ }
+
+ /**
+ * The intermediate and root certificates, as the end of every chain. [intermediateUsage] is the intermediate's
+ * key usage, or null for a certificate that names none.
+ */
+ fun authorities(intermediateUsage: Int? = null): List = listOf(
+ certificate(
+ "intermediate",
+ intermediate.public,
+ "root",
+ root.private,
+ isAuthority = true,
+ keyUsage = intermediateUsage,
+ ),
+ certificate("root", root.public, "root", root.private, isAuthority = true),
+ )
+
+ /** A certificate for [key] signed by [signer], named as issued by [issuer]. */
+ @Suppress("LongParameterList")
+ fun certificate(
+ subject: String,
+ key: PublicKey,
+ issuer: String,
+ signer: PrivateKey,
+ isAuthority: Boolean,
+ record: ASN1Encodable? = null,
+ notAfterMs: Long = nowMs + DAY_MS,
+ keyUsage: Int? = null,
+ ): ByteArray {
+ val builder = JcaX509v3CertificateBuilder(
+ X500Name("CN=$issuer"),
+ BigInteger.valueOf(serial++),
+ Date(nowMs - DAY_MS),
+ Date(notAfterMs),
+ X500Name("CN=$subject"),
+ key,
+ )
+ if (isAuthority) builder.addExtension(Extension.basicConstraints, true, BasicConstraints(true))
+ keyUsage?.let { builder.addExtension(Extension.keyUsage, true, KeyUsage(it)) }
+ record?.let {
+ builder.addExtension(ASN1ObjectIdentifier(AttestationVerifier.KEY_DESCRIPTION_OID), false, it)
+ }
+ return builder.build(JcaContentSignerBuilder("SHA256withECDSA").build(signer)).encoded
+ }
+
+ @Suppress("LongParameterList", "MagicNumber")
+ fun description(
+ challenge: ByteArray,
+ level: Int = 1,
+ purposes: Set = setOf(PURPOSE_AGREE),
+ packageName: String = PACKAGE,
+ digest: ByteArray = DIGEST,
+ isLocked: Boolean = true,
+ bootState: Int = 0,
+ origin: Int = 0,
+ ): ASN1Encodable {
+ val applicationId = DERSequence(
+ arrayOf(
+ DERSet(DERSequence(arrayOf(DEROctetString(packageName.encodeToByteArray()), ASN1Integer(1)))),
+ DERSet(DEROctetString(digest)),
+ ),
+ )
+ val software = DERSequence(arrayOf(tag(709, DEROctetString(applicationId.encoded))))
+ val rootOfTrust = DERSequence(
+ arrayOf(
+ DEROctetString(ByteArray(32)),
+ ASN1Boolean.getInstance(isLocked),
+ ASN1Enumerated(bootState),
+ DEROctetString(ByteArray(32)),
+ ),
+ )
+ val hardware = DERSequence(
+ arrayOf(
+ tag(1, DERSet(purposes.map { ASN1Integer(it.toLong()) }.toTypedArray())),
+ tag(2, ASN1Integer(3)),
+ tag(10, ASN1Integer(1)),
+ tag(702, ASN1Integer(origin.toLong())),
+ tag(704, rootOfTrust),
+ ),
+ )
+ return DERSequence(
+ arrayOf(
+ ASN1Integer(300),
+ ASN1Enumerated(level),
+ ASN1Integer(300),
+ ASN1Enumerated(level),
+ DEROctetString(challenge),
+ DEROctetString(ByteArray(0)),
+ software,
+ hardware,
+ ),
+ )
+ }
+
+ private fun tag(number: Int, value: ASN1Encodable) = DERTaggedObject(true, number, value)
+}
diff --git a/wearlink/src/test/resources/google-attestation-root-ec.pem b/wearlink/src/test/resources/google-attestation-root-ec.pem
new file mode 100644
index 0000000000..31da2feabd
--- /dev/null
+++ b/wearlink/src/test/resources/google-attestation-root-ec.pem
@@ -0,0 +1,14 @@
+-----BEGIN CERTIFICATE-----
+MIICIjCCAaigAwIBAgIRAISp0Cl7DrWK5/8OgN52BgUwCgYIKoZIzj0EAwMwUjEc
+MBoGA1UEAwwTS2V5IEF0dGVzdGF0aW9uIENBMTEQMA4GA1UECwwHQW5kcm9pZDET
+MBEGA1UECgwKR29vZ2xlIExMQzELMAkGA1UEBhMCVVMwHhcNMjUwNzE3MjIzMjE4
+WhcNMzUwNzE1MjIzMjE4WjBSMRwwGgYDVQQDDBNLZXkgQXR0ZXN0YXRpb24gQ0Ex
+MRAwDgYDVQQLDAdBbmRyb2lkMRMwEQYDVQQKDApHb29nbGUgTExDMQswCQYDVQQG
+EwJVUzB2MBAGByqGSM49AgEGBSuBBAAiA2IABCPaI3FO3z5bBQo8cuiEas4HjqCt
+G/mLFfRT0MsIssPBEEU5Cfbt6sH5yOAxqEi5QagpU1yX4HwnGb7OtBYpDTB57uH5
+Eczm34A5FNijV3s0/f0UPl7zbJcTx6xwqMIRq6NCMEAwDwYDVR0TAQH/BAUwAwEB
+/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFFIyuyz7RkOb3NaBqQ5lZuA0QepA
+MAoGCCqGSM49BAMDA2gAMGUCMETfjPO/HwqReR2CS7p0ZWoD/LHs6hDi422opifH
+EUaYLxwGlT9SLdjkVpz0UUOR5wIxAIoGyxGKRHVTpqpGRFiJtQEOOTp/+s1GcxeY
+uR2zh/80lQyu9vAFCj6E4AXc+osmRg==
+-----END CERTIFICATE-----
\ No newline at end of file
diff --git a/wearlink/src/test/resources/google-attestation-root-rsa.pem b/wearlink/src/test/resources/google-attestation-root-rsa.pem
new file mode 100644
index 0000000000..71231a009f
--- /dev/null
+++ b/wearlink/src/test/resources/google-attestation-root-rsa.pem
@@ -0,0 +1,30 @@
+-----BEGIN CERTIFICATE-----
+MIIFHDCCAwSgAwIBAgIJAPHBcqaZ6vUdMA0GCSqGSIb3DQEBCwUAMBsxGTAXBgNV
+BAUTEGY5MjAwOWU4NTNiNmIwNDUwHhcNMjIwMzIwMTgwNzQ4WhcNNDIwMzE1MTgw
+NzQ4WjAbMRkwFwYDVQQFExBmOTIwMDllODUzYjZiMDQ1MIICIjANBgkqhkiG9w0B
+AQEFAAOCAg8AMIICCgKCAgEAr7bHgiuxpwHsK7Qui8xUFmOr75gvMsd/dTEDDJdS
+Sxtf6An7xyqpRR90PL2abxM1dEqlXnf2tqw1Ne4Xwl5jlRfdnJLmN0pTy/4lj4/7
+tv0Sk3iiKkypnEUtR6WfMgH0QZfKHM1+di+y9TFRtv6y//0rb+T+W8a9nsNL/ggj
+nar86461qO0rOs2cXjp3kOG1FEJ5MVmFmBGtnrKpa73XpXyTqRxB/M0n1n/W9nGq
+C4FSYa04T6N5RIZGBN2z2MT5IKGbFlbC8UrW0DxW7AYImQQcHtGl/m00QLVWutHQ
+oVJYnFPlXTcHYvASLu+RhhsbDmxMgJJ0mcDpvsC4PjvB+TxywElgS70vE0XmLD+O
+JtvsBslHZvPBKCOdT0MS+tgSOIfga+z1Z1g7+DVagf7quvmag8jfPioyKvxnK/Eg
+sTUVi2ghzq8wm27ud/mIM7AY2qEORR8Go3TVB4HzWQgpZrt3i5MIlCaY504LzSRi
+igHCzAPlHws+W0rB5N+er5/2pJKnfBSDiCiFAVtCLOZ7gLiMm0jhO2B6tUXHI/+M
+RPjy02i59lINMRRev56GKtcd9qO/0kUJWdZTdA2XoS82ixPvZtXQpUpuL12ab+9E
+aDK8Z4RHJYYfCT3Q5vNAXaiWQ+8PTWm2QgBR/bkwSWc+NpUFgNPN9PvQi8WEg5Um
+AGMCAwEAAaNjMGEwHQYDVR0OBBYEFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMB8GA1Ud
+IwQYMBaAFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMA8GA1UdEwEB/wQFMAMBAf8wDgYD
+VR0PAQH/BAQDAgIEMA0GCSqGSIb3DQEBCwUAA4ICAQB8cMqTllHc8U+qCrOlg3H7
+174lmaCsbo/bJ0C17JEgMLb4kvrqsXZs01U3mB/qABg/1t5Pd5AORHARs1hhqGIC
+W/nKMav574f9rZN4PC2ZlufGXb7sIdJpGiO9ctRhiLuYuly10JccUZGEHpHSYM2G
+tkgYbZba6lsCPYAAP83cyDV+1aOkTf1RCp/lM0PKvmxYN10RYsK631jrleGdcdkx
+oSK//mSQbgcWnmAEZrzHoF1/0gso1HZgIn0YLzVhLSA/iXCX4QT2h3J5z3znluKG
+1nv8NQdxei2DIIhASWfu804CA96cQKTTlaae2fweqXjdN1/v2nqOhngNyz1361mF
+mr4XmaKH/ItTwOe72NI9ZcwS1lVaCvsIkTDCEXdm9rCNPAY10iTunIHFXRh+7KPz
+lHGewCq/8TOohBRn0/NNfh7uRslOSZ/xKbN9tMBtw37Z8d2vvnXq/YWdsm1+JLVw
+n6yYD/yacNJBlwpddla8eaVMjsF6nBnIgQOf9zKSe06nSTqvgwUHosgOECZJZ1Eu
+zbH4yswbt02tKtKEFhx+v+OTge/06V+jGsqTWLsfrOCNLuA8H++z+pUENmpqnnHo
+vaI47gC+TNpkgYGkkBT6B/m/U01BuOBBTzhIlMEZq9qkDWuM2cA5kW5V3FJUcfHn
+w1IdYIg2Wxg7yHcQZemFQg==
+-----END CERTIFICATE-----
\ No newline at end of file
diff --git a/wearlink/src/testFixtures/kotlin/to/bitkit/wearlink/testing/Fakes.kt b/wearlink/src/testFixtures/kotlin/to/bitkit/wearlink/testing/Fakes.kt
new file mode 100644
index 0000000000..ff72a34901
--- /dev/null
+++ b/wearlink/src/testFixtures/kotlin/to/bitkit/wearlink/testing/Fakes.kt
@@ -0,0 +1,182 @@
+package to.bitkit.wearlink.testing
+
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+import to.bitkit.wearlink.LinkCrypto
+import to.bitkit.wearlink.LinkError
+import to.bitkit.wearlink.LinkKeyStore
+import to.bitkit.wearlink.LinkNode
+import to.bitkit.wearlink.LinkPacket
+import to.bitkit.wearlink.LinkRecord
+import to.bitkit.wearlink.LinkRecordStore
+import to.bitkit.wearlink.LinkTransport
+import to.bitkit.wearlink.ThrottleState
+import to.bitkit.wearlink.ThrottleStore
+import to.bitkit.wearlink.WatchAgreementKey
+import java.security.KeyPair
+import java.security.SecureRandom
+
+/**
+ * A phone and a watch joined in one process, for tests of both roles together. Delivery is asynchronous and in
+ * order, as on the real carrier, and the test can cut the connection, or drop, alter and replay what travels.
+ */
+class FakeLinkNetwork(private val scope: CoroutineScope) {
+ val phone = Endpoint("phone-node", "Phone")
+ val watch = Endpoint("watch-node", "Watch")
+
+ /** While false, one-shot messages fail and state documents wait. */
+ var isConnected = true
+
+ /** Whether the watch has Bitkit installed, and whether it is reached directly. */
+ var hasWatchApp = true
+ var isWatchNearby = true
+
+ /** Sees every packet on its way and returns what is delivered instead, or null to drop it. */
+ var intercept: (Sent) -> ByteArray? = { it.payload }
+
+ /** Everything that was handed to the carrier, in order. */
+ val sent = mutableListOf()
+
+ /** URIs the phone asked the watch to open. */
+ val opened = mutableListOf