Skip to content

Commit 87594bc

Browse files
committed
feat: Indexed keychain values
1 parent d5dae14 commit 87594bc

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

app/src/main/java/to/bitkit/data/keychain/KeychainStore.kt

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
@file:Suppress("unused")
2+
13
package to.bitkit.data.keychain
24

35
import android.content.Context
@@ -10,29 +12,38 @@ import androidx.datastore.preferences.preferencesDataStore
1012
import dagger.hilt.android.qualifiers.ApplicationContext
1113
import kotlinx.coroutines.flow.first
1214
import kotlinx.coroutines.flow.map
15+
import to.bitkit.data.AppDb
1316
import javax.inject.Inject
1417

1518
class KeychainStore @Inject constructor(
1619
@ApplicationContext private val context: Context,
20+
db: AppDb,
1721
) {
1822
private val Context.prefs: DataStore<Preferences> by preferencesDataStore("keychain")
1923
private val prefs: DataStore<Preferences> by lazy { context.prefs }
2024

25+
private val walletIndex by lazy { db.configDao().getAll().map { it.first().walletIndex }.toString() }
26+
2127
suspend fun get(key: String): ByteArray? {
22-
val prefKey = stringPreferencesKey(key)
28+
val prefKey = indexed(key)
2329
return prefs.data.map { it[prefKey].fromBase64() }.first()
2430
}
2531

2632
suspend fun add(key: String, encryptedValue: ByteArray) {
27-
val prefKey = stringPreferencesKey(key)
33+
val prefKey = indexed(key)
2834
prefs.edit { it[prefKey] = encryptedValue.toBase64() }
2935
}
3036

3137
suspend fun remove(key: String) {
32-
val prefKey = stringPreferencesKey(key)
38+
val prefKey = indexed(key)
3339
prefs.edit { it.remove(prefKey) }
3440
}
3541

42+
/**
43+
* Generates a preferences key for storing a string value associated with a specific wallet index.
44+
*/
45+
private fun indexed(key: String) = "$walletIndex:$key".let(::stringPreferencesKey)
46+
3647
private fun ByteArray.toBase64(flags: Int = Base64.DEFAULT) = Base64.encodeToString(this, flags)
3748
private fun String?.fromBase64(flags: Int = Base64.DEFAULT) = Base64.decode(this, flags)
3849
}

0 commit comments

Comments
 (0)