-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathRNBackupClient.kt
More file actions
323 lines (275 loc) · 12.3 KB
/
Copy pathRNBackupClient.kt
File metadata and controls
323 lines (275 loc) · 12.3 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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
package to.bitkit.services
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.statement.HttpResponse
import io.ktor.http.isSuccess
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import org.lightningdevkit.ldknode.Network
import org.lightningdevkit.ldknode.deriveNodeSecretFromMnemonic
import to.bitkit.data.keychain.Keychain
import to.bitkit.di.IoDispatcher
import to.bitkit.di.json
import to.bitkit.env.Env
import to.bitkit.ext.toHex
import to.bitkit.utils.AppError
import to.bitkit.utils.Crypto
import to.bitkit.utils.Logger
import javax.crypto.Cipher
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class RNBackupClient @Inject constructor(
private val httpClient: HttpClient,
private val crypto: Crypto,
private val keychain: Keychain,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
private val json: Json,
) {
companion object {
private const val TAG = "RNBackup"
private const val VERSION = "v1"
private const val SIGNED_MESSAGE_PREFIX = "react-native-ldk backup server auth:"
private const val GCM_IV_LENGTH = 12
private const val GCM_TAG_LENGTH = 16
}
@Volatile
private var cachedBearer: AuthBearerResponse? = null
private val authMutex = Mutex()
suspend fun listFiles(fileGroup: String? = "ldk"): RNBackupListResponse? = withContext(ioDispatcher) {
runCatching {
val mnemonic = keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name)
?: throw RNBackupError.NotSetup
val passphrase = keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name)
val bearer = authenticate(mnemonic, passphrase)
val url = buildUrl("list", fileGroup = fileGroup, network = getNetworkString())
val response: HttpResponse = httpClient.get(url) {
header("Authorization", bearer.bearer)
}
if (!response.status.isSuccess()) {
throw RNBackupError.RequestFailed("Status: ${response.status.value}")
}
response.body<RNBackupListResponse>()
}.onFailure { e ->
Logger.error("Failed to list files for fileGroup=$fileGroup", e, context = TAG)
}.getOrNull()
}
suspend fun retrieve(label: String, fileGroup: String? = null): ByteArray? = withContext(ioDispatcher) {
runCatching {
val mnemonic = keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name)
?: throw RNBackupError.NotSetup
val passphrase = keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name)
val bearer = authenticate(mnemonic, passphrase)
val url = buildUrl("retrieve", label = label, fileGroup = fileGroup, network = getNetworkString())
val response: HttpResponse = httpClient.get(url) {
header("Authorization", bearer.bearer)
}
if (!response.status.isSuccess()) {
throw RNBackupError.RequestFailed("Status: ${response.status.value}")
}
val encryptedData = response.body<ByteArray>()
if (encryptedData.isEmpty()) throw RNBackupError.RequestFailed("Retrieved data is empty")
val encryptionKey = deriveEncryptionKey(mnemonic, passphrase)
decrypt(encryptedData, encryptionKey).also {
if (it.isEmpty()) throw RNBackupError.DecryptFailed("Decrypted data is empty")
}
}.onFailure { e ->
Logger.error("Failed to retrieve $label", e, context = TAG)
}.getOrNull()
}
suspend fun retrieveChannelMonitor(channelId: String): ByteArray? = withContext(ioDispatcher) {
runCatching {
val mnemonic = keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name)
?: throw RNBackupError.NotSetup
val passphrase = keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name)
val bearer = authenticate(mnemonic, passphrase)
val url = buildUrl(
method = "retrieve",
label = "channel_monitor",
fileGroup = "ldk",
channelId = channelId,
network = getNetworkString(),
)
val response: HttpResponse = httpClient.get(url) {
header("Authorization", bearer.bearer)
}
if (!response.status.isSuccess()) {
throw RNBackupError.RequestFailed("Status: ${response.status.value}")
}
val encryptedData = response.body<ByteArray>()
if (encryptedData.isEmpty()) throw RNBackupError.RequestFailed("Retrieved data is empty")
val encryptionKey = deriveEncryptionKey(mnemonic, passphrase)
decrypt(encryptedData, encryptionKey).also {
if (it.isEmpty()) throw RNBackupError.DecryptFailed("Decrypted data is empty")
}
}.onFailure { e ->
Logger.error("Failed to retrieve channel monitor $channelId", e, context = TAG)
}.getOrNull()
}
suspend fun hasBackup(): Boolean = withContext(ioDispatcher) {
runCatching {
val ldkFiles = listFiles(fileGroup = "ldk")
val bitkitFiles = listFiles(fileGroup = "bitkit")
val hasLdkFiles = !ldkFiles?.list.isNullOrEmpty() || !ldkFiles?.channelMonitors.isNullOrEmpty()
val hasBitkitFiles = !bitkitFiles?.list.isNullOrEmpty()
hasLdkFiles || hasBitkitFiles
}.onFailure { e ->
Logger.error("Failed to check if backup exists", e, context = TAG)
}.getOrDefault(false)
}
suspend fun getLatestBackupTimestamp(): ULong? = withContext(ioDispatcher) {
runCatching {
val bitkitFiles = listFiles(fileGroup = "bitkit")?.list ?: return@withContext null
if (bitkitFiles.isEmpty()) return@withContext null
@Serializable
data class BackupMetadata(val timestamp: Long? = null)
@Serializable
data class BackupWithMetadata(val metadata: BackupMetadata? = null)
val labels = listOf(
"bitkit_settings",
"bitkit_metadata",
"bitkit_widgets",
"bitkit_lightning_activity",
"bitkit_wallet",
"bitkit_blocktank_orders",
)
var latestTimestamp: ULong? = null
for (label in labels) {
if ("$label.bin" !in bitkitFiles) continue
val data = retrieve(label, fileGroup = "bitkit") ?: continue
val timestamp = runCatching {
json.decodeFromString<BackupWithMetadata>(String(data)).metadata?.timestamp
}.getOrNull() ?: continue
val ts = (timestamp / 1000).toULong()
latestTimestamp = maxOf(latestTimestamp ?: 0uL, ts)
}
latestTimestamp
}.onFailure { e ->
Logger.error("Failed to get latest backup timestamp", e, context = TAG)
}.getOrNull()
}
private fun buildUrl(
method: String,
label: String? = null,
fileGroup: String? = null,
channelId: String? = null,
network: String,
): String {
var url = "${Env.rnBackupServerHost}/$VERSION/$method?network=$network"
label?.let { url += "&label=$it" }
fileGroup?.let { url += "&fileGroup=$it" }
channelId?.let { url += "&channelId=$it" }
return url
}
private suspend fun authenticate(mnemonic: String, passphrase: String?): AuthBearerResponse {
fun isBearerValid(bearer: AuthBearerResponse): Boolean {
val now = System.currentTimeMillis() / 1000.0
return bearer.expires / 1000.0 > now
}
cachedBearer?.takeIf { isBearerValid(it) }?.let { return it }
return authMutex.withLock {
cachedBearer?.takeIf { isBearerValid(it) }?.let { return@withLock it }
cachedBearer = null
val secretKey = deriveSigningKey(mnemonic, passphrase)
val pubKeyHex = crypto.getPublicKey(secretKey).toHex()
val networkString = getNetworkString()
val timestamp = System.currentTimeMillis() / 1000
val challengeBody = json.encodeToString(
buildJsonObject {
put("timestamp", timestamp.toString())
put("signature", signMessage(timestamp.toString(), secretKey))
}
)
val challengeResponse: HttpResponse = httpClient.post(
"${Env.rnBackupServerHost}/$VERSION/auth/challenge?network=$networkString"
) {
header("Public-Key", pubKeyHex)
header("Content-Type", "application/json")
setBody(challengeBody)
}
if (!challengeResponse.status.isSuccess()) {
throw RNBackupError.AuthFailed
}
val challengeResult = challengeResponse.body<AuthChallengeResponse>()
val authBody = json.encodeToString(
buildJsonObject {
put("signature", signMessage(challengeResult.challenge, secretKey))
}
)
val authResponse: HttpResponse = httpClient.post(
"${Env.rnBackupServerHost}/$VERSION/auth/response?network=$networkString"
) {
header("Public-Key", pubKeyHex)
header("Content-Type", "application/json")
setBody(authBody)
}
if (!authResponse.status.isSuccess()) {
throw RNBackupError.AuthFailed
}
authResponse.body<AuthBearerResponse>().also { cachedBearer = it }
}
}
private fun getNetworkString(): String {
return when (Env.network) {
Network.BITCOIN -> "bitcoin"
Network.TESTNET -> "testnet"
Network.REGTEST -> "regtest"
Network.SIGNET -> "signet"
}
}
private fun signMessage(message: String, privateKey: ByteArray): String {
val fullMessage = "$SIGNED_MESSAGE_PREFIX$message"
return crypto.sign(fullMessage, privateKey)
}
private fun deriveSigningKey(mnemonic: String, passphrase: String?): ByteArray =
deriveNodeSecretFromMnemonic(mnemonic, passphrase).map { it.toByte() }.toByteArray()
private fun deriveEncryptionKey(mnemonic: String, passphrase: String?): ByteArray =
deriveSigningKey(mnemonic, passphrase)
private fun decrypt(blob: ByteArray, encryptionKey: ByteArray): ByteArray {
if (blob.size < GCM_IV_LENGTH + GCM_TAG_LENGTH) {
throw RNBackupError.DecryptFailed("Data too short")
}
val nonce = blob.sliceArray(0 until GCM_IV_LENGTH)
val tag = blob.sliceArray(blob.size - GCM_TAG_LENGTH until blob.size)
val ciphertext = blob.sliceArray(GCM_IV_LENGTH until blob.size - GCM_TAG_LENGTH)
val key = SecretKeySpec(encryptionKey, "AES")
val spec = GCMParameterSpec(GCM_TAG_LENGTH * 8, nonce)
val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply {
init(Cipher.DECRYPT_MODE, key, spec)
}
return cipher.doFinal(ciphertext + tag)
}
}
@Serializable
private data class AuthChallengeResponse(
val challenge: String,
)
@Serializable
private data class AuthBearerResponse(
val bearer: String,
val expires: Long,
)
@Serializable
data class RNBackupListResponse(
val list: List<String> = emptyList(),
@SerialName("channel_monitors") val channelMonitors: List<String> = emptyList(),
)
sealed class RNBackupError(message: String) : AppError(message) {
data object NotSetup : RNBackupError("RN backup client not setup")
data object AuthFailed : RNBackupError("Authentication failed")
data class RequestFailed(override val message: String) : RNBackupError(message)
data class DecryptFailed(override val message: String) : RNBackupError(message)
}