-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathDevToolsProvider.kt
More file actions
183 lines (156 loc) · 6.47 KB
/
DevToolsProvider.kt
File metadata and controls
183 lines (156 loc) · 6.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package to.bitkit.dev
import android.content.ContentProvider
import android.content.ContentValues
import android.net.Uri
import android.os.Binder
import android.os.Bundle
import android.os.Process
import androidx.core.os.bundleOf
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.android.EntryPointAccessors
import dagger.hilt.components.SingletonComponent
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import to.bitkit.async.ServiceQueue
import to.bitkit.models.msatCeilOf
import to.bitkit.repositories.LightningRepo
import to.bitkit.repositories.ProbeOutcome
import to.bitkit.utils.Logger
import kotlin.time.Duration.Companion.seconds
private const val TAG = "DevToolsProvider"
private val DEV_JSON = Json { encodeDefaults = true }
class DevToolsProvider : ContentProvider() {
@EntryPoint
@InstallIn(SingletonComponent::class)
interface Dependencies {
fun lightningRepo(): LightningRepo
}
private val deps: Dependencies by lazy {
val ctx = requireNotNull(context) { "DevToolsProvider context is null" }
EntryPointAccessors.fromApplication(ctx, Dependencies::class.java)
}
override fun call(method: String, arg: String?, extras: Bundle?): Bundle {
check(Binder.getCallingUid() == Process.SHELL_UID) { "Only ADB shell callers are allowed" }
return runCatching {
val command = requireNotNull(DevCommand.parse(method, arg)) { "Unknown command: '$method'" }
ServiceQueue.LDK.blocking { command.execute(deps) }
}.getOrElse {
Logger.error("Failed to execute command '$method'", it, context = TAG)
DevResult.Error(it.message)
}.toBundle()
}
override fun onCreate() = true
override fun getType(uri: Uri): String? = null
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
override fun delete(uri: Uri, sel: String?, args: Array<String>?) = 0
override fun update(uri: Uri, values: ContentValues?, sel: String?, args: Array<String>?) = 0
override fun query(uri: Uri, proj: Array<String>?, sel: String?, args: Array<String>?, sort: String?) = null
}
private sealed interface DevCommand {
companion object {
fun parse(method: String, arg: String?): DevCommand? = when (method) {
CreateInvoice.METHOD -> CreateInvoice.parse(arg)
ProbeInvoice.METHOD -> ProbeInvoice.parse(arg)
else -> null
}
}
suspend fun execute(deps: DevToolsProvider.Dependencies): DevResult
data class CreateInvoice(val args: Args) : DevCommand {
companion object {
const val METHOD = "createInvoice"
fun parse(arg: String?) = CreateInvoice(arg.deserialize<Args>())
}
@Serializable
data class Args(val amount: ULong? = null, val description: String = "dev-invoice")
override suspend fun execute(deps: DevToolsProvider.Dependencies) =
deps.lightningRepo().createInvoice(args.amount, args.description).fold(
onSuccess = { DevResult.Invoice(it) },
onFailure = {
Logger.error("Failed to create invoice", it, context = TAG)
DevResult.Error(it.message)
},
)
}
data class ProbeInvoice(val args: Args) : DevCommand {
companion object {
const val METHOD = "probeInvoice"
fun parse(arg: String?) = ProbeInvoice(arg.deserialize<Args>())
}
@Serializable
data class Args(
val targetName: String? = null,
val bolt11: String,
val amountMsat: ULong? = null,
val amountSats: ULong? = null,
val timeoutSeconds: Long = 90,
)
override suspend fun execute(deps: DevToolsProvider.Dependencies): DevResult {
val amountSats = args.amountSats ?: args.amountMsat?.let { msatCeilOf(it) }
val timeout = args.timeoutSeconds.coerceAtLeast(1).seconds
Logger.info(
"Sending probe for target '${args.targetName ?: "unknown"}' amountSats='${amountSats ?: "invoice"}'",
context = TAG,
)
return deps.lightningRepo().sendProbeForInvoice(args.bolt11, amountSats)
.fold(
onSuccess = {
deps.lightningRepo().waitForProbeOutcome(it.paymentIds, timeout)
.fold(
onSuccess = { outcome -> outcome.toDevResult(it.paymentIds) },
onFailure = { error -> DevResult.ProbeFailure.from(error, it.paymentIds) },
)
},
onFailure = { DevResult.ProbeFailure.from(it) },
)
}
}
}
@Serializable
private sealed interface DevResult {
companion object {
private const val KEY_RESULT = "result"
}
@Serializable data class Invoice(val bolt11: String) : DevResult
@Serializable
data class ProbeSuccess(
val success: Boolean = true,
val paymentId: String,
val paymentHash: String,
val paymentIds: List<String>,
) : DevResult
@Serializable
data class ProbeFailure(
val success: Boolean = false,
val message: String? = null,
val paymentId: String? = null,
val paymentHash: String? = null,
val shortChannelId: ULong? = null,
val paymentIds: List<String> = emptyList(),
) : DevResult {
companion object {
fun from(error: Throwable, paymentIds: Set<String> = emptySet()) = ProbeFailure(
message = error.message,
paymentIds = paymentIds.toList(),
)
}
}
@Serializable data class Error(val message: String? = null) : DevResult
fun toBundle() = bundleOf(KEY_RESULT to DEV_JSON.encodeToString(this))
}
private fun ProbeOutcome.toDevResult(paymentIds: Set<String>): DevResult = when (this) {
is ProbeOutcome.Success -> DevResult.ProbeSuccess(
paymentId = paymentId,
paymentHash = paymentHash,
paymentIds = paymentIds.toList(),
)
is ProbeOutcome.Failure -> DevResult.ProbeFailure(
message = "Probe failed",
paymentId = paymentId,
paymentHash = paymentHash,
shortChannelId = shortChannelId,
paymentIds = paymentIds.toList(),
)
}
private inline fun <reified T> String?.deserialize(): T =
if (isNullOrBlank()) Json.decodeFromString("{}") else Json.decodeFromString(this)