taler-android

Android apps for GNU Taler (wallet, PoS, cashier)
Log | Files | Refs | README | LICENSE

PeerManager.kt (18525B)


      1 /*
      2  * This file is part of GNU Taler
      3  * (C) 2022 Taler Systems S.A.
      4  *
      5  * GNU Taler is free software; you can redistribute it and/or modify it under the
      6  * terms of the GNU General Public License as published by the Free Software
      7  * Foundation; either version 3, or (at your option) any later version.
      8  *
      9  * GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
     10  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
     11  * A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
     12  *
     13  * You should have received a copy of the GNU General Public License along with
     14  * GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
     15  */
     16 
     17 package net.taler.wallet.peer
     18 
     19 import android.util.Log
     20 import androidx.annotation.UiThread
     21 import kotlinx.coroutines.CoroutineScope
     22 import kotlinx.coroutines.Dispatchers
     23 import kotlinx.coroutines.flow.MutableStateFlow
     24 import kotlinx.coroutines.flow.StateFlow
     25 import kotlinx.coroutines.flow.update
     26 import kotlinx.coroutines.launch
     27 import kotlinx.serialization.Serializable
     28 import kotlinx.serialization.json.Json
     29 import net.taler.common.Amount
     30 import net.taler.common.CurrencySpecification
     31 import net.taler.common.RelativeTime
     32 import net.taler.common.Timestamp
     33 import net.taler.wallet.main.TAG
     34 import net.taler.wallet.backend.BackendManager
     35 import net.taler.wallet.backend.TalerErrorInfo
     36 import net.taler.wallet.backend.WalletBackendApi
     37 import net.taler.wallet.balances.ScopeInfo
     38 import net.taler.wallet.cleanExchange
     39 import net.taler.wallet.exchanges.ExchangeItem
     40 import net.taler.wallet.exchanges.ExchangeManager
     41 import net.taler.wallet.exchanges.ExchangeTosStatus
     42 import net.taler.wallet.payment.InsufficientBalanceHint
     43 import org.json.JSONObject
     44 import java.util.concurrent.TimeUnit.HOURS
     45 import net.taler.wallet.peer.CheckPeerPushDebitResponse.*
     46 
     47 const val MAX_LENGTH_SUBJECT = 100
     48 val DEFAULT_EXPIRY = ExpirationOption.DAYS_1
     49 
     50 sealed class CheckFeeResult {
     51     abstract val maxDepositAmountEffective: Amount?
     52     abstract val maxDepositAmountRaw: Amount?
     53 
     54     data class None(
     55         override val maxDepositAmountEffective: Amount? = null,
     56         override val maxDepositAmountRaw: Amount? = null,
     57     ): CheckFeeResult()
     58 
     59     data class InsufficientBalance(
     60         val maxAmountEffective: Amount?,
     61         val maxAmountRaw: Amount?,
     62         val causeHint: InsufficientBalanceHint? = null,
     63         override val maxDepositAmountEffective: Amount? = null,
     64         override val maxDepositAmountRaw: Amount? = null,
     65     ): CheckFeeResult()
     66 
     67     data class Success(
     68         val amountRaw: Amount,
     69         val amountEffective: Amount,
     70         val exchangeBaseUrl: String,
     71         val defaultExpiration: RelativeTime,
     72         override val maxDepositAmountEffective: Amount? = null,
     73         override val maxDepositAmountRaw: Amount? = null,
     74     ): CheckFeeResult()
     75 
     76     data class Error(
     77         val error: TalerErrorInfo,
     78         override val maxDepositAmountEffective: Amount? = null,
     79         override val maxDepositAmountRaw: Amount? = null,
     80     ): CheckFeeResult()
     81 }
     82 
     83 @Serializable
     84 data class GetMaxPeerPushDebitAmountResponse(
     85     val effectiveAmount: Amount,
     86     val rawAmount: Amount,
     87     val exchangeBaseUrl: String? = null,
     88 )
     89 
     90 class PeerManager(
     91     private val api: WalletBackendApi,
     92     private val exchangeManager: ExchangeManager,
     93     private val scope: CoroutineScope,
     94 ) {
     95 
     96     private val _outgoingPullState = MutableStateFlow<OutgoingState>(OutgoingIntro)
     97     val pullState: StateFlow<OutgoingState> = _outgoingPullState
     98 
     99     private val _outgoingPushState = MutableStateFlow<OutgoingState>(OutgoingIntro)
    100     val pushState: StateFlow<OutgoingState> = _outgoingPushState
    101 
    102     private val _incomingPullState = MutableStateFlow<IncomingState>(IncomingChecking)
    103     val incomingPullState: StateFlow<IncomingState> = _incomingPullState
    104 
    105     private val _incomingPushState = MutableStateFlow<IncomingState>(IncomingChecking)
    106     val incomingPushState: StateFlow<IncomingState> = _incomingPushState
    107 
    108     private suspend fun getSpecForCurrency(currency: String): CurrencySpecification? =
    109         exchangeManager.getCachedSpecForCurrency(currency)
    110             ?: exchangeManager.getSpecForScopeInfo(ScopeInfo.Global(currency))
    111 
    112     suspend fun checkPeerPullCredit(
    113         amount: Amount,
    114         scopeInfo: ScopeInfo,
    115         loading: Boolean = false,
    116     ): CheckPeerPullCreditResult? {
    117         var response: CheckPeerPullCreditResult? = null
    118         val exchangeItem = exchangeManager.findExchange(scopeInfo) ?: return null
    119 
    120         if (loading) {
    121             _outgoingPullState.value = OutgoingChecking
    122         }
    123 
    124         if (!exchangeItem.tosStatus.isAccepted()) {
    125             _outgoingPullState.value = OutgoingIntro
    126             return CheckPeerPullCreditResult(
    127                 tosStatus = exchangeItem.tosStatus,
    128                 exchangeBaseUrl = exchangeItem.exchangeBaseUrl,
    129             )
    130         } else if (amount.isZero()) {
    131             _outgoingPullState.value = OutgoingIntro
    132             return CheckPeerPullCreditResult(
    133                 tosStatus = exchangeItem.tosStatus,
    134                 exchangeBaseUrl = exchangeItem.exchangeBaseUrl,
    135                 amountRaw = amount,
    136                 amountEffective = amount,
    137             )
    138         }
    139 
    140         api.request(
    141             "checkPeerPullCredit",
    142             CheckPeerPullCreditResponse.serializer(),
    143             progressToken = "checkPeerPullCredit",
    144         ) {
    145             put("restrictScope", JSONObject(BackendManager.json.encodeToString(scopeInfo)))
    146             put("amount", amount.toJSONString())
    147         }.onSuccess {
    148             response = CheckPeerPullCreditResult(
    149                 amountEffective = it.amountEffective,
    150                 amountRaw = it.amountRaw,
    151                 exchangeBaseUrl = it.exchangeBaseUrl,
    152                 tosStatus = exchangeItem.tosStatus,
    153             )
    154         }.onError { error ->
    155             Log.e(TAG, "got checkPeerPullCredit error result $error")
    156         }
    157 
    158         if (loading) {
    159             _outgoingPullState.value = OutgoingIntro
    160         }
    161 
    162         return response
    163     }
    164 
    165     fun initiatePeerPullCredit(amount: Amount, summary: String, expirationHours: Long, exchangeBaseUrl: String) {
    166         _outgoingPullState.value = OutgoingCreating
    167         scope.launch(Dispatchers.IO) {
    168             val expiry = Timestamp.fromMillis(System.currentTimeMillis() + HOURS.toMillis(expirationHours))
    169             api.request("initiatePeerPullCredit", InitiatePeerPullPaymentResponse.serializer()) {
    170                 put("exchangeBaseUrl", exchangeBaseUrl)
    171                 put("partialContractTerms", JSONObject().apply {
    172                     put("amount", amount.toJSONString())
    173                     put("summary", summary)
    174                     put("purse_expiration", JSONObject(Json.encodeToString(expiry)))
    175                 })
    176             }.onSuccess {
    177                 _outgoingPullState.value = OutgoingResponse(it.transactionId)
    178             }.onError { error ->
    179                 Log.e(TAG, "got initiatePeerPullCredit error result $error")
    180                 _outgoingPullState.value = OutgoingError(error)
    181             }
    182         }
    183     }
    184 
    185     fun resetPullPayment() {
    186         _outgoingPullState.value = OutgoingIntro
    187     }
    188 
    189     suspend fun checkPeerPushFees(
    190         amount: Amount,
    191         exchangeBaseUrl: String? = null,
    192         restrictScope: ScopeInfo? = null,
    193     ): CheckFeeResult {
    194         var max: GetMaxPeerPushDebitAmountResponse? = null
    195         var maxError: TalerErrorInfo? = null
    196         getMaxPeerPushDebitAmount(
    197             amount.currency,
    198             exchangeBaseUrl,
    199             restrictScope = restrictScope,
    200             onSuccess = { max = it },
    201             onError = { maxError = it },
    202         )
    203         maxError?.let { return CheckFeeResult.Error(it) }
    204         val maxAmount = max ?: return CheckFeeResult.Error(
    205             TalerErrorInfo.makeCustomError("Could not determine the maximum send amount."),
    206         )
    207 
    208         val none = CheckFeeResult.None(
    209             maxDepositAmountEffective = maxAmount.effectiveAmount,
    210             maxDepositAmountRaw = maxAmount.rawAmount,
    211         )
    212         if (amount.isZero()) return none
    213 
    214         var response: CheckFeeResult = none
    215 
    216         api.request(
    217             "checkPeerPushDebitV2",
    218             CheckPeerPushDebitResponse.serializer(),
    219             progressToken = "checkPeerPushDebitV2",
    220         ) {
    221             exchangeBaseUrl?.let { put("exchangeBaseUrl", it) }
    222             restrictScope?.let { put("restrictScope", JSONObject(BackendManager.json.encodeToString(it))) }
    223             put("amount", amount.toJSONString())
    224         }.onSuccess { res ->
    225             response = when (val r = res) {
    226                 is CheckPeerPushDebitOkResponse -> CheckFeeResult.Success(
    227                     amountRaw = r.amountRaw,
    228                     amountEffective = r.amountEffective,
    229                     maxDepositAmountEffective = maxAmount.effectiveAmount,
    230                     maxDepositAmountRaw = maxAmount.rawAmount,
    231                     exchangeBaseUrl = r.exchangeBaseUrl,
    232                     defaultExpiration = r.defaultExpiration,
    233                 )
    234 
    235                 is CheckPeerPushDebitInsufficientBalanceResponse -> CheckFeeResult.InsufficientBalance(
    236                     maxAmountEffective = r.insufficientBalanceDetails.maxEffectiveSpendAmount,
    237                     maxAmountRaw = r.insufficientBalanceDetails.balanceAvailable,
    238                     maxDepositAmountEffective = maxAmount.effectiveAmount,
    239                     maxDepositAmountRaw = maxAmount.rawAmount,
    240                     causeHint = r.insufficientBalanceDetails.causeHint,
    241                 )
    242             }
    243         }.onError { error ->
    244             Log.e(TAG, "got checkPeerPushDebit error result $error")
    245             response = CheckFeeResult.Error(error)
    246         }
    247 
    248         return response
    249     }
    250 
    251     private suspend fun getMaxPeerPushDebitAmount(
    252         currency: String,
    253         exchangeBaseUrl: String? = null,
    254         restrictScope: ScopeInfo? = null,
    255         onSuccess: (GetMaxPeerPushDebitAmountResponse) -> Unit,
    256         onError: (TalerErrorInfo) -> Unit,
    257     ) {
    258         api.request(
    259             "getMaxPeerPushDebitAmount",
    260             GetMaxPeerPushDebitAmountResponse.serializer(),
    261         ) {
    262             exchangeBaseUrl?.let { put("exchangeBaseUrl", it) }
    263             restrictScope?.let { put("restrictScope", JSONObject(BackendManager.json.encodeToString(it))) }
    264             put("currency", currency)
    265         }.onSuccess {
    266             onSuccess(it)
    267         }.onError { error ->
    268             Log.e(TAG, "got getMaxPeerPushDebitAmount error result $error")
    269             onError(error)
    270         }
    271     }
    272 
    273     fun initiatePeerPushDebit(
    274         amount: Amount,
    275         summary: String,
    276         expirationHours: Long,
    277         restrictScope: ScopeInfo? = null,
    278     ) {
    279         _outgoingPushState.value = OutgoingCreating
    280         scope.launch(Dispatchers.IO) {
    281             val expiry = Timestamp.fromMillis(System.currentTimeMillis() + HOURS.toMillis(expirationHours))
    282             api.request("initiatePeerPushDebit", InitiatePeerPushDebitResponse.serializer()) {
    283                 restrictScope?.let { put("restrictScope", JSONObject(BackendManager.json.encodeToString(it))) }
    284                 put("amount", amount.toJSONString())
    285                 put("partialContractTerms", JSONObject().apply {
    286                     put("amount", amount.toJSONString())
    287                     put("summary", summary)
    288                     put("purse_expiration", JSONObject(Json.encodeToString(expiry)))
    289                 })
    290             }.onSuccess { response ->
    291                 _outgoingPushState.value = OutgoingResponse(response.transactionId)
    292             }.onError { error ->
    293                 Log.e(TAG, "got initiatePeerPushDebit error result $error")
    294                 _outgoingPushState.value = OutgoingError(error)
    295             }
    296         }
    297     }
    298 
    299     fun resetPushPayment() {
    300         _outgoingPushState.value = OutgoingIntro
    301     }
    302 
    303     fun preparePeerPullDebit(
    304         talerUri: String? = null,
    305         transactionId: String? = null,
    306     ) {
    307         _incomingPullState.value = IncomingChecking
    308         scope.launch(Dispatchers.IO) {
    309             api.request(
    310                 "preparePeerPullDebit",
    311                 PreparePeerPullDebitResponse.serializer(),
    312                 progressToken = talerUri ?: transactionId ?: "preparePeerPullDebit",
    313             ) {
    314                 talerUri?.let { put("talerUri", talerUri) }
    315                 transactionId?.let { put("transactionId", transactionId) }
    316                 this
    317             }.onSuccess { response ->
    318                 val spec = getSpecForCurrency(response.amountRaw.currency)
    319                 _incomingPullState.value = IncomingTerms(
    320                     amountRaw = response.amountRaw.withSpec(spec),
    321                     amountEffective = response.amountEffective.withSpec(spec),
    322                     contractTerms = response.contractTerms.copy(
    323                         amount = response.contractTerms.amount.withSpec(spec),
    324                     ),
    325                     id = response.transactionId,
    326                 )
    327             }.onError { error ->
    328                 Log.e(TAG, "got preparePeerPullDebit error result $error")
    329                 _incomingPullState.value = IncomingError(error)
    330             }
    331         }
    332     }
    333 
    334     fun confirmPeerPullDebit(terms: IncomingTerms) {
    335         _incomingPullState.value = IncomingAccepting(terms)
    336         scope.launch(Dispatchers.IO) {
    337             api.request<Unit>("confirmPeerPullDebit") {
    338                 put("transactionId", terms.id)
    339             }.onSuccess {
    340                 _incomingPullState.value = IncomingAccepted(terms.id)
    341             }.onError { error ->
    342                 Log.e(TAG, "got confirmPeerPullDebit error result $error")
    343                 _incomingPullState.value = IncomingError(error)
    344             }
    345         }
    346     }
    347 
    348     fun preparePeerPushCredit(
    349         talerUri: String? = null,
    350         transactionId: String? = null,
    351     ) {
    352         _incomingPushState.value = IncomingChecking
    353         scope.launch(Dispatchers.IO) a@ {
    354             api.request(
    355                 "preparePeerPushCredit",
    356                 PreparePeerPushCreditResponse.serializer(),
    357                 progressToken = talerUri ?: transactionId ?: "preparePeerPushCredit",
    358             ) {
    359                 talerUri?.let { put("talerUri", talerUri) }
    360                 transactionId?.let { put("transactionId", transactionId) }
    361                 this
    362             }.onSuccess { response ->
    363                 scope.launch(Dispatchers.IO) b@ {
    364                     val exchange = exchangeManager.findExchangeByUrl(response.exchangeBaseUrl)
    365 
    366                     if (exchange == null) {
    367                         Log.d(TAG, "exchange entry for ${response.exchangeBaseUrl} was not found")
    368                         _incomingPushState.value = IncomingError(
    369                             TalerErrorInfo.makeCustomError( // TODO: localize error
    370                                 "No provider with URL ${cleanExchange(response.exchangeBaseUrl)} was found in the wallet",
    371                             )
    372                         )
    373                         return@b
    374                     }
    375 
    376                     val spec = exchangeManager.getSpecForScopeInfo(
    377                         exchange.scopeInfo ?: ScopeInfo.Exchange(
    378                             response.amountRaw.currency,
    379                             response.exchangeBaseUrl,
    380                         ),
    381                     )
    382                     val amountRaw = response.amountRaw.withSpec(spec)
    383                     val amountEffective = response.amountEffective.withSpec(spec)
    384                     val contractTerms = response.contractTerms.copy(
    385                         amount = response.contractTerms.amount.withSpec(spec),
    386                     )
    387 
    388                     _incomingPushState.value = if (exchange.tosStatus.isAccepted()) {
    389                         IncomingTerms(
    390                             amountRaw = amountRaw,
    391                             amountEffective = amountEffective,
    392                             contractTerms = contractTerms,
    393                             id = response.transactionId,
    394                         )
    395                     } else {
    396                         IncomingTosReview(
    397                             amountRaw = amountRaw,
    398                             amountEffective = amountEffective,
    399                             contractTerms = contractTerms,
    400                             exchangeBaseUrl = response.exchangeBaseUrl,
    401                             id = response.transactionId,
    402                         )
    403                     }
    404                 }
    405             }.onError { error ->
    406                 Log.e(TAG, "got preparePeerPushCredit error result $error")
    407                 _incomingPushState.value = IncomingError(error)
    408             }
    409         }
    410     }
    411 
    412     fun confirmPeerPushCredit(terms: IncomingTerms) {
    413         _incomingPushState.value = IncomingAccepting(terms)
    414         scope.launch(Dispatchers.IO) {
    415             api.request<Unit>("confirmPeerPushCredit") {
    416                 put("transactionId", terms.id)
    417             }.onSuccess {
    418                 _incomingPushState.value = IncomingAccepted(terms.id)
    419             }.onError { error ->
    420                 Log.e(TAG, "got confirmPeerPushCredit error result $error")
    421                 _incomingPushState.value = IncomingError(error)
    422             }
    423         }
    424     }
    425 
    426     @UiThread
    427     fun refreshPeerPushCreditTos(exchanges: List<ExchangeItem>) = scope.launch {
    428         _incomingPushState.update { state ->
    429             var newState = state
    430             if (state is IncomingTosReview) {
    431                 exchanges.find { it.exchangeBaseUrl == state.exchangeBaseUrl }?.let { exchange ->
    432                     // only an actual acceptance may lift a review we asked for: a list
    433                     // fetched before the provider was known still says missing-tos,
    434                     // which isAccepted() treats as good enough
    435                     if (exchange.tosStatus == ExchangeTosStatus.Accepted) {
    436                         newState = IncomingTerms(
    437                             amountRaw = state.amountRaw,
    438                             amountEffective = state.amountEffective,
    439                             contractTerms = state.contractTerms,
    440                             id = state.id,
    441                         )
    442                     }
    443                 } ?: run {
    444                     Log.d(TAG, "could not refresh ToS status, exchange ${state.exchangeBaseUrl} was not found")
    445                 }
    446             }
    447             newState
    448         }
    449     }
    450 }