1+ @file:Suppress(" unused" )
2+
13package to.bitkit.data.keychain
24
35import android.content.Context
@@ -10,29 +12,38 @@ import androidx.datastore.preferences.preferencesDataStore
1012import dagger.hilt.android.qualifiers.ApplicationContext
1113import kotlinx.coroutines.flow.first
1214import kotlinx.coroutines.flow.map
15+ import to.bitkit.data.AppDb
1316import javax.inject.Inject
1417
1518class 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