Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
c83e504
feat: add wake gateway client and install credentials
coreyphillips Nov 10, 2026
7c844ba
feat: register with the wake gateway when opted in
coreyphillips Nov 10, 2026
5ef861f
feat: receive, dedupe and acknowledge wakes in a worker
coreyphillips Nov 10, 2026
1f81310
feat: hold a wake presence lease while the app is open
coreyphillips Nov 10, 2026
250d905
feat: unregister the wake device when wiping the wallet
coreyphillips Nov 10, 2026
7111bb7
feat: add a debug wake section to dev settings
coreyphillips Nov 10, 2026
de038d2
docs: point agents at the wake classes
coreyphillips Nov 10, 2026
9e1b4ba
test: cover wake registration, receiving and identity selection
coreyphillips Nov 10, 2026
864b679
fix: start no wake work in builds without a gateway
coreyphillips Nov 10, 2026
a46f3b0
fix: retry failed wake syncs and resend registrations whose answer wa…
coreyphillips Nov 13, 2026
095ad59
fix: renew wake presence only inside the presence loop
coreyphillips Nov 13, 2026
b455fb3
fix: give each wake alert a stable notification id
coreyphillips Nov 13, 2026
ea85604
fix: decide the wake pk identity without reading the Ring key
coreyphillips Nov 13, 2026
b429c92
fix: renew and clear wake presence while an update is unconfirmed
coreyphillips Nov 13, 2026
e237cd6
fix: retry wake syncs for a new push token
coreyphillips Nov 13, 2026
50c243b
Merge remote-tracking branch 'origin/master' into feat/wake-gateway-p…
coreyphillips Nov 16, 2026
54903f5
fix: follow Retry-After for at most an hour, as on iOS
coreyphillips Nov 16, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -578,6 +578,6 @@ suspend fun getData(): Result<Data> = withContext(Dispatchers.IO) {
- Use `LightningNodeService` to manage background notifications while the node is running
- Use `LightningService` to wrap node's RUST APIs and manage the inner lifecycle of the node
- Use `LightningRepo` to defining the business logic for the node operations, usually delegating to `LightningService`
- Use `WakeNodeWorker` to manage the handling of remote notifications received via cloud messages
- Use `WakeRepo` to register with the wake gateway, and `WakeWorker` with `WakeInbox` to handle the wakes received via cloud messages; add a topic's handler to `WakeHandlers`
- Use `*Services` to wrap rust library code exposed via bindings
- Use CQRS pattern of Command + Handler like it's done in the `NotifyPaymentReceived` + `NotifyPaymentReceivedHandler` setup
10 changes: 9 additions & 1 deletion app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -423,7 +423,15 @@ androidComponents {
buildConfigFields.put("E2E_HOMEGATE_OVERRIDE", e2eHomegateOverrideEnv.stringField())
buildConfigFields.put("PUBKY_SWAPS_ROUTES", pubkySwapsRoutesEnv.booleanField())
buildConfigFields.put("PUBKY_SWAPS_PROVIDERS", pubkySwapsProvidersEnv.stringField())
for (key in listOf("E2E_VSS_SERVER_URL", "E2E_LNURL_AUTH_SERVER_URL", "E2E_BLOCKTANK_API_URL", "BLOCKTANK_REGTEST_AUTH")) {
val debugOnlyFields = listOf(
"E2E_VSS_SERVER_URL",
"E2E_LNURL_AUTH_SERVER_URL",
"E2E_BLOCKTANK_API_URL",
"BLOCKTANK_REGTEST_AUTH",
// A local wake gateway to test wakes against; see Env.wakeGatewayUrl.
"WAKE_GATEWAY_URL",
)
for (key in debugOnlyFields) {
val value = if (variant.buildType == "debug") localProp(key).orElse("") else provider { "" }
buildConfigFields.put(key, value.stringField())
}
Expand Down
79 changes: 79 additions & 0 deletions app/src/main/java/to/bitkit/data/WakeCredentialStore.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package to.bitkit.data

import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable
import to.bitkit.data.keychain.Keychain
import to.bitkit.di.IoDispatcher
import to.bitkit.di.json
import to.bitkit.services.WakeCredentials
import to.bitkit.services.WakeService
import to.bitkit.utils.Logger
import javax.inject.Inject
import javax.inject.Singleton

/**
* Keeps this install's wake credentials and registration state in the [Keychain]. They belong to the install, so they
* are reused across launches, left out of backups, and deleted with the wallet.
*/
@Singleton
class WakeCredentialStore @Inject constructor(
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
private val keychain: Keychain,
private val wakeService: WakeService,
) {
companion object {
private const val TAG = "WakeCredentialStore"
}

private val mutex = Mutex()

/** The credentials, or null before this install first registered. */
suspend fun load(): WakeCredentials? = withContext(ioDispatcher) {
keychain.loadString(Keychain.Key.WAKE_CREDENTIALS.name)?.let { json.decodeFromString<WakeCredentials>(it) }
}

/** The credentials, generated and saved on first use. */
suspend fun loadOrCreate(): WakeCredentials = withContext(ioDispatcher) {
mutex.withLock {
load() ?: wakeService.generateCredentials().also {
keychain.upsertString(Keychain.Key.WAKE_CREDENTIALS.name, json.encodeToString(it))
Logger.info("Created wake credentials", context = TAG)
}
}
}

suspend fun registrationState(): WakeRegistrationState = withContext(ioDispatcher) {
keychain.loadString(Keychain.Key.WAKE_REGISTRATION.name)
?.let { json.decodeFromString<WakeRegistrationState>(it) }
?: WakeRegistrationState()
}

suspend fun updateRegistrationState(transform: (WakeRegistrationState) -> WakeRegistrationState) {
withContext(ioDispatcher) {
mutex.withLock {
val next = transform(registrationState())
keychain.upsertString(Keychain.Key.WAKE_REGISTRATION.name, json.encodeToString(next))
}
}
}
}

/** What this install last sent to the gateway. */
@Serializable
data class WakeRegistrationState(
/** Unix seconds of the last registration sent, answered or not, so the next one is later. */
val lastTimestampSecs: Long? = null,
/**
* Hash of the last registration the gateway accepted. Cleared before each registration is sent, so one whose answer
* was lost is sent again, and null while this install is not registered.
*/
val fingerprint: String? = null,
/**
* Set before a registration is sent and cleared once the gateway confirms the unregister: a registration whose
* answer was lost may still be stored there, so an opt-out has to unregister it.
*/
val mayBeRegistered: Boolean = false,
)
84 changes: 84 additions & 0 deletions app/src/main/java/to/bitkit/data/WakeStore.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
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.first
import kotlinx.serialization.Serializable
import to.bitkit.data.serializers.WakeStoreSerializer
import javax.inject.Inject
import javax.inject.Singleton

private val Context.wakeDataStore: DataStore<WakeStoreData> by dataStore(
fileName = "wake.json",
serializer = WakeStoreSerializer,
)

/**
* The wakes this install received and the gateway's topic texts. Like the wake credentials it belongs to the install,
* so it stays out of the backed up app cache.
*/
@Singleton
class WakeStore internal constructor(
private val store: DataStore<WakeStoreData>,
) {
companion object {
/** Most wakes remembered at once. Each is forgotten at its deadline long before this fills. */
const val MAX_RECEIVED = 200
}

@Inject
constructor(@ApplicationContext context: Context) : this(context.wakeDataStore)

val data: Flow<WakeStoreData> = store.data

suspend fun received(id: String): ReceivedWake? = store.data.first().received.find { it.id == id }

/** Remembers [wake], and forgets the wakes whose deadline passed before [nowSecs]. */
suspend fun saveReceived(wake: ReceivedWake, nowSecs: Long) {
store.updateData { data ->
val kept = data.received.filter { it.id != wake.id && it.deadlineSecs >= nowSecs }
data.copy(received = (kept + wake).takeLast(MAX_RECEIVED))
}
}

suspend fun markAcked(id: String) {
store.updateData { data ->
data.copy(received = data.received.map { if (it.id == id) it.copy(acked = true) else it })
}
}

suspend fun saveTopics(topics: List<WakeTopicText>, fetchedAtMs: Long) {
store.updateData { it.copy(topics = topics, topicsFetchedAtMs = fetchedAtMs) }
}
}

@Serializable
data class WakeStoreData(
val received: List<ReceivedWake> = emptyList(),
val topics: List<WakeTopicText> = emptyList(),
val topicsFetchedAtMs: Long = 0L,
)

/**
* A wake this install received, kept until its deadline so a second delivery acknowledges it without doing its work
* again. Delivery is at least once, and the process can die between two deliveries.
*/
@Serializable
data class ReceivedWake(
val id: String,
val deadlineSecs: Long,
/** The name of the `WakeAckOutcome` to acknowledge. */
val outcome: String,
val acked: Boolean = false,
)

/** A topic's display text from the gateway, for the alert Android has to post itself. */
@Serializable
data class WakeTopicText(
val name: String,
val title: String? = null,
val body: String? = null,
)
3 changes: 2 additions & 1 deletion app/src/main/java/to/bitkit/data/keychain/Keychain.kt
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,6 @@ class Keychain @Inject constructor(

enum class Key {
PUSH_NOTIFICATION_TOKEN,
PUSH_NOTIFICATION_PRIVATE_KEY,
BIP39_MNEMONIC,
BIP39_PASSPHRASE,
PIN,
Expand All @@ -253,6 +252,8 @@ class Keychain @Inject constructor(
PAYKIT_ALLOWANCE_RESTORE_PAUSE,
PUBKY_SECRET_KEY,
SHARED_PUBKY_SOURCE,
WAKE_CREDENTIALS,
WAKE_REGISTRATION,
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package to.bitkit.data.serializers

import androidx.datastore.core.Serializer
import to.bitkit.data.WakeStoreData
import to.bitkit.di.json
import to.bitkit.utils.Logger
import java.io.InputStream
import java.io.OutputStream

object WakeStoreSerializer : Serializer<WakeStoreData> {
private const val TAG = "WakeStoreSerializer"

override val defaultValue: WakeStoreData = WakeStoreData()

override suspend fun readFrom(input: InputStream): WakeStoreData {
return runCatching {
json.decodeFromString<WakeStoreData>(input.readBytes().decodeToString())
}.getOrElse {
Logger.error("Failed to deserialize WakeStoreData", it, context = TAG)
defaultValue
}
}

override suspend fun writeTo(t: WakeStoreData, output: OutputStream) {
output.write(json.encodeToString(t).encodeToByteArray())
}
}
9 changes: 9 additions & 0 deletions app/src/main/java/to/bitkit/env/Env.kt
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,15 @@ internal object Env {
else -> "https://bitkit.stag0.blocktank.to/backups-ldk"
}

/**
* The wake gateway this build registers with for background pushes, or null to leave wakes off. No gateway is
* deployed yet (synonymdev/wake#2), so only a debug build with `WAKE_GATEWAY_URL` set has one, for local testing.
*/
val wakeGatewayUrl: String?
get() = BuildConfig.WAKE_GATEWAY_URL.takeIf { isDebug && it.isNotBlank() } ?: when (network) {
Network.BITCOIN, Network.TESTNET, Network.SIGNET, Network.REGTEST -> null
}

fun electrumUrlForNetwork(network: BitkitCoreNetwork): String {
val isE2eLocal = isE2eTest && e2eBackend == "local"
return when (network) {
Expand Down
16 changes: 15 additions & 1 deletion app/src/main/java/to/bitkit/fcm/FcmService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,25 @@ import android.os.Bundle
import androidx.core.os.toPersistableBundle
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import dagger.Lazy
import dagger.hilt.android.AndroidEntryPoint
import to.bitkit.env.Env
import to.bitkit.repositories.WakeRepo
import to.bitkit.ui.pushNotification
import to.bitkit.utils.Logger
import java.util.Date
import javax.inject.Inject

@AndroidEntryPoint
class FcmService : FirebaseMessagingService() {
companion object {
private const val TAG = "FcmService"
}

/** Resolved only on a token change, so a push does not build the wallet graph. */
@Inject
lateinit var wakeRepo: Lazy<WakeRepo>

/**
* Act on received messages. [Debug](https://goo.gl/39bRNJ)
*/
Expand All @@ -26,13 +34,19 @@ class FcmService : FirebaseMessagingService() {
Logger.debug("FCM body: $body", context = TAG)
sendNotification(title, body, Bundle(message.data.toPersistableBundle()))
}

if (Env.wakeGatewayUrl != null && message.data.isNotEmpty()) {
WakeWorker.enqueue(applicationContext, wakePushJson(message.data))
}
}

private fun sendNotification(title: String?, body: String?, extras: Bundle? = null) {
applicationContext.pushNotification(title, body, extras)
}

override fun onNewToken(token: String) {
Logger.debug("Got new FCM token via FirebaseMessagingService.onNewToken: '$token'", context = TAG)
Logger.debug("Received new FCM token", context = TAG)
if (Env.wakeGatewayUrl == null) return
wakeRepo.get().onNewPushToken(token)
}
}
Loading
Loading