aboutsummaryrefslogtreecommitdiff
path: root/bank/src/main/kotlin/tech/libeufin/bank/WireGatewayApi.kt
blob: 67de9f060bd145c40063335d1b76794dd403d1f2 (plain)
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
/*
 * This file is part of LibEuFin.
 * Copyright (C) 2023 Taler Systems S.A.

 * LibEuFin is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation; either version 3, or
 * (at your option) any later version.

 * LibEuFin is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General
 * Public License for more details.

 * You should have received a copy of the GNU Affero General Public
 * License along with LibEuFin; see the file COPYING.  If not, see
 * <http://www.gnu.org/licenses/>
 */

// This file contains the Taler Wire Gateway API handlers.

package tech.libeufin.bank

import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.util.pipeline.PipelineContext
import java.time.Instant
import net.taler.common.errorcodes.TalerErrorCode
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import tech.libeufin.bank.ExchangeDAO.*

private val logger: Logger = LoggerFactory.getLogger("tech.libeufin.nexus")

fun Routing.wireGatewayApi(db: Database, ctx: BankConfig) {
    get("/taler-wire-gateway/config") {
        call.respond(TWGConfigResponse(
            currency = ctx.regionalCurrency
        ))
        return@get
    }
    auth(db, TokenScope.readwrite) {
        post("/accounts/{USERNAME}/taler-wire-gateway/transfer") {
            val req = call.receive<TransferRequest>()
            ctx.checkRegionalCurrency(req.amount)
            val res = db.exchange.transfer(
                req = req,
                login = username,
                now = Instant.now()
            )
            when (res) {
                is TransferResult.UnknownExchange -> throw unknownAccount(username)
                is TransferResult.NotAnExchange -> throw conflict(
                    "$username is not an exchange account.",
                    TalerErrorCode.BANK_ACCOUNT_IS_NOT_EXCHANGE
                )
                is TransferResult.UnknownCreditor -> throw conflict(
                    "Creditor account was not found",
                    TalerErrorCode.BANK_UNKNOWN_CREDITOR
                )
                is TransferResult.BothPartyAreExchange -> throw conflict(
                    "Wire transfer attempted with credit and debit party being both exchange account",
                    TalerErrorCode.BANK_ACCOUNT_IS_EXCHANGE
                )
                is TransferResult.ReserveUidReuse -> throw conflict(
                    "request_uid used already",
                    TalerErrorCode.BANK_TRANSFER_REQUEST_UID_REUSED
                )
                is TransferResult.BalanceInsufficient -> throw conflict(
                    "Insufficient balance for exchange",
                    TalerErrorCode.BANK_UNALLOWED_DEBIT
                )
                is TransferResult.Success -> call.respond(
                    TransferResponse(
                        timestamp = res.timestamp,
                        row_id = res.id
                    )
                )
            }
        }
    }
    auth(db, TokenScope.readonly) {
        suspend fun <T> PipelineContext<Unit, ApplicationCall>.historyEndpoint(
            reduce: (List<T>, String) -> Any, 
            dbLambda: suspend ExchangeDAO.(HistoryParams, Long) -> List<T>
        ) {
            val params = HistoryParams.extract(context.request.queryParameters)
            val bankAccount = call.bankInfo(db)
            
            if (!bankAccount.isTalerExchange)
                throw conflict(
                    "$username is not an exchange account.",
                    TalerErrorCode.BANK_ACCOUNT_IS_NOT_EXCHANGE
                )

            val items = db.exchange.dbLambda(params, bankAccount.bankAccountId);
        
            if (items.isEmpty()) {
                call.respond(HttpStatusCode.NoContent)
            } else {
                call.respond(reduce(items, bankAccount.internalPaytoUri))
            }
        }
        get("/accounts/{USERNAME}/taler-wire-gateway/history/incoming") {
            historyEndpoint(::IncomingHistory, ExchangeDAO::incomingHistory)
        }
        get("/accounts/{USERNAME}/taler-wire-gateway/history/outgoing") {
            historyEndpoint(::OutgoingHistory, ExchangeDAO::outgoingHistory)
        }
    }
    authAdmin(db, TokenScope.readwrite) {
        post("/accounts/{USERNAME}/taler-wire-gateway/admin/add-incoming") {
            val req = call.receive<AddIncomingRequest>()
            ctx.checkRegionalCurrency(req.amount)
            val timestamp = Instant.now()
            val res = db.exchange.addIncoming(
                req = req,
                login = username,
                now = timestamp
            )
            when (res) {
                is AddIncomingResult.UnknownExchange -> throw unknownAccount(username)
                is AddIncomingResult.NotAnExchange -> throw conflict(
                    "$username is not an exchange account.",
                    TalerErrorCode.BANK_ACCOUNT_IS_NOT_EXCHANGE
                )
                is AddIncomingResult.UnknownDebtor -> throw conflict(
                    "Debtor account was not found",
                    TalerErrorCode.BANK_UNKNOWN_DEBTOR
                )
                is AddIncomingResult.BothPartyAreExchange -> throw conflict(
                    "Wire transfer attempted with credit and debit party being both exchange account",
                    TalerErrorCode.BANK_ACCOUNT_IS_EXCHANGE
                )
                is AddIncomingResult.ReservePubReuse -> throw conflict(
                    "reserve_pub used already",
                    TalerErrorCode.BANK_DUPLICATE_RESERVE_PUB_SUBJECT
                )
                is AddIncomingResult.BalanceInsufficient -> throw conflict(
                    "Insufficient balance for debitor",
                    TalerErrorCode.BANK_UNALLOWED_DEBIT
                )
                is AddIncomingResult.Success -> call.respond(
                    AddIncomingResponse(
                        timestamp = TalerProtocolTimestamp(timestamp),
                        row_id = res.id
                    )
                )
            }
        }
    }
}