summaryrefslogtreecommitdiff
path: root/c2ec/bank-integration.go
blob: 89f9c26ea74809473e6b8a2362be51c76833745e (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
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
package main

import (
	"bytes"
	"context"
	"fmt"
	http "net/http"
	"strconv"
	"time"
)

const BANK_INTEGRATION_CONFIG_ENDPOINT = "/config"
const WITHDRAWAL_OPERATION = "/withdrawal-operation"

const WOPID_PARAMETER = "wopid"
const BANK_INTEGRATION_CONFIG_PATTERN = BANK_INTEGRATION_CONFIG_ENDPOINT
const WITHDRAWAL_OPERATION_PATTERN = WITHDRAWAL_OPERATION
const WITHDRAWAL_OPERATION_BY_WOPID_PATTERN = WITHDRAWAL_OPERATION + "/{" + WOPID_PARAMETER + "}"
const WITHDRAWAL_OPERATION_PAYMENT_PATTERN = WITHDRAWAL_OPERATION_BY_WOPID_PATTERN + "/payment"
const WITHDRAWAL_OPERATION_ABORTION_PATTERN = WITHDRAWAL_OPERATION_BY_WOPID_PATTERN + "/abort"

const DEFAULT_LONG_POLL_MS = 1000
const DEFAULT_OLD_STATE = PENDING

// https://docs.taler.net/core/api-exchange.html#tsref-type-CurrencySpecification
type CurrencySpecification struct {
	Name                            string `json:"name"`
	Currency                        string `json:"currency"`
	NumFractionalInputDigits        int    `json:"num_fractional_input_digits"`
	NumFractionalNormalDigits       int    `json:"num_fractional_normal_digits"`
	NumFractionalTrailingZeroDigits int    `json:"num_fractional_trailing_zero_digits"`
	AltUnitNames                    string `json:"alt_unit_names"`
}

// https://docs.taler.net/core/api-bank-integration.html#tsref-type-BankIntegrationConfig
type BankIntegrationConfig struct {
	Name                  string                `json:"name"`
	Version               string                `json:"version"`
	Implementation        string                `json:"implementation"`
	Currency              string                `json:"currency"`
	CurrencySpecification CurrencySpecification `json:"currency_specification"`
}

type C2ECWithdrawRegistration struct {
	ReservePubKey EddsaPublicKey `json:"reserve_pub_key"`
	TerminalId    uint64         `json:"terminal_id"`
}

type C2ECWithdrawalStatus struct {
	Status        WithdrawalOperationStatus `json:"status"`
	Amount        Amount                    `json:"amount"`
	SenderWire    string                    `json:"sender_wire"`
	WireTypes     []string                  `json:"wire_types"`
	ReservePubKey EddsaPublicKey            `json:"selected_reserve_pub"`
}

type C2ECPaymentNotification struct {
	ProviderTransactionId string `json:"provider_transaction_id"`
	Amount                Amount `json:"amount"`
	Fees                  Amount `json:"fees"`
}

func bankIntegrationConfig(res http.ResponseWriter, req *http.Request) {

	cfg := BankIntegrationConfig{
		Name:    "taler-bank-integration",
		Version: "0:0:1",
	}

	serializedCfg, err := NewJsonCodec[BankIntegrationConfig]().EncodeToBytes(&cfg)
	if err != nil {
		LogInfo("bank-integration-api", fmt.Sprintf("failed serializing config: %s", err.Error()))
		res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
		return
	}

	res.WriteHeader(HTTP_OK)
	res.Write(serializedCfg)
}

func handleWithdrawalRegistration(res http.ResponseWriter, req *http.Request) {

	jsonCodec := NewJsonCodec[C2ECWithdrawRegistration]()
	registration, err := ReadStructFromBody(req, jsonCodec)
	if err != nil {
		LogWarn("bank-integration-api", fmt.Sprintf("invalid body for withdrawal registration error=%s", err.Error()))
		err := WriteProblem(res, HTTP_BAD_REQUEST, &RFC9457Problem{
			TypeUri:  TALER_URI_PROBLEM_PREFIX + "/C2EC_WITHDRAW_REGISTRATION_INVALID_REQ",
			Title:    "invalid request",
			Detail:   "the registration request for the withdrawal is malformed (error: " + err.Error() + ")",
			Instance: req.RequestURI,
		})
		if err != nil {
			res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
		}
		return
	}

	// read and validate the wopid path parameter
	wopid := req.PathValue(WOPID_PARAMETER)
	wopid, err = ParseWopid(wopid)
	if err != nil {
		LogWarn("bank-integration-api", "wopid "+wopid+" not valid")
		if wopid == "" {
			err := WriteProblem(res, HTTP_BAD_REQUEST, &RFC9457Problem{
				TypeUri:  TALER_URI_PROBLEM_PREFIX + "/C2EC_INVALID_PATH_PARAMETER",
				Title:    "invalid request path parameter",
				Detail:   "the withdrawal status request path parameter 'wopid' is malformed",
				Instance: req.RequestURI,
			})
			if err != nil {
				res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
			}
			return
		}
	}

	err = DB.RegisterWithdrawal(
		WithdrawalIdentifier(wopid),
		registration.ReservePubKey,
		registration.TerminalId,
	)

	if err != nil {

		err := WriteProblem(res, HTTP_INTERNAL_SERVER_ERROR, &RFC9457Problem{
			TypeUri:  TALER_URI_PROBLEM_PREFIX + "/C2EC_WITHDRAW_REGISTRATION_DB_FAILURE",
			Title:    "database failure",
			Detail:   "the registration of the withdrawal failed due to db failure (error:" + err.Error() + ")",
			Instance: req.RequestURI,
		})
		if err != nil {
			res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
		}
		return
	}

	res.WriteHeader(HTTP_NO_CONTENT)
}

// Get status of withdrawal associated with the given WOPID
//
// Parameters:
//   - long_poll_ms (optional):
//     milliseconds to wait for state to change
//     given old_state until responding
//   - old_state (optional):
//     Default is 'pending'
func handleWithdrawalStatus(res http.ResponseWriter, req *http.Request) {

	// read and validate request query parameters
	shouldStartLongPoll := true
	longPollMilli := DEFAULT_LONG_POLL_MS
	if longPollMilliPtr, accepted := AcceptOptionalParamOrWriteResponse(
		"long_poll_ms", strconv.Atoi, req, res,
	); accepted {
		if longPollMilliPtr != nil {
			longPollMilli = *longPollMilliPtr
		} else {
			// this means parameter was not given.
			// no long polling (simple get)
			shouldStartLongPoll = false
		}
	} else {
		shouldStartLongPoll = false
	}

	// read and validate the wopid path parameter
	wopid := req.PathValue(WOPID_PARAMETER)
	wopid, err := ParseWopid(wopid)
	if err != nil {
		LogWarn("bank-integration-api", "wopid "+wopid+" not valid")
		if wopid == "" {
			err := WriteProblem(res, HTTP_BAD_REQUEST, &RFC9457Problem{
				TypeUri:  TALER_URI_PROBLEM_PREFIX + "/C2EC_INVALID_PATH_PARAMETER",
				Title:    "invalid request path parameter",
				Detail:   "the withdrawal status request path parameter 'wopid' is malformed",
				Instance: req.RequestURI,
			})
			if err != nil {
				res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
			}
			return
		}
	}

	if shouldStartLongPoll {

		timeoutCtx, cancelFunc := context.WithTimeout(
			req.Context(),
			time.Duration(longPollMilli)*time.Millisecond,
		)
		defer cancelFunc()

		statusChannel := make(chan WithdrawalOperationStatus)
		errChan := make(chan error)

		go DB.ListenForWithdrawalStatusChange(timeoutCtx, WithdrawalIdentifier(wopid), statusChannel, errChan)
		for {
			select {
			case <-timeoutCtx.Done():
				err := WriteProblem(res, HTTP_NO_CONTENT, &RFC9457Problem{
					TypeUri:  TALER_URI_PROBLEM_PREFIX + "/C2EC_LONG_POLL_TIME_EXCEEDED",
					Title:    "time exceeded",
					Detail:   fmt.Sprintf("long poll ended due to timeout: %dms", longPollMilli),
					Instance: req.RequestURI,
				})
				if err != nil {
					res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
				}
				return
			case err := <-errChan:
				err = WriteProblem(res, HTTP_INTERNAL_SERVER_ERROR, &RFC9457Problem{
					TypeUri:  TALER_URI_PROBLEM_PREFIX + "/C2EC_INTERNAL_SERVER_ERROR",
					Title:    "internal server error",
					Detail:   err.Error(),
					Instance: req.RequestURI,
				})
				if err != nil {
					res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
				}
				return
			case <-statusChannel:
				getWithdrawalOrWriteError(wopid, res, req.RequestURI)
				return
			}
		}
	}

	getWithdrawalOrWriteError(wopid, res, req.RequestURI)
}

func handlePaymentNotification(res http.ResponseWriter, req *http.Request) {

	wopid := req.PathValue(WOPID_PARAMETER)
	wopid, err := ParseWopid(wopid)
	if err != nil {
		LogWarn("bank-integration-api", "wopid "+wopid+" not valid")
		if wopid == "" {
			err := WriteProblem(res, HTTP_BAD_REQUEST, &RFC9457Problem{
				TypeUri:  TALER_URI_PROBLEM_PREFIX + "/C2EC_INVALID_PATH_PARAMETER",
				Title:    "invalid request path parameter",
				Detail:   "the withdrawal status request path parameter 'wopid' is malformed",
				Instance: req.RequestURI,
			})
			if err != nil {
				res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
			}
			return
		}
	}

	jsonCodec := NewJsonCodec[C2ECPaymentNotification]()
	paymentNotification, err := ReadStructFromBody(req, jsonCodec)
	if err != nil {
		LogWarn("bank-integration-api", fmt.Sprintf("invalid body for payment notification error=%s", err.Error()))
		err := WriteProblem(res, HTTP_BAD_REQUEST, &RFC9457Problem{
			TypeUri:  TALER_URI_PROBLEM_PREFIX + "/C2EC_WITHDRAW_REGISTRATION_INVALID_REQ",
			Title:    "invalid request",
			Detail:   "the payment notification request for the withdrawal is malformed (error: " + err.Error() + ")",
			Instance: req.RequestURI,
		})
		if err != nil {
			res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
		}
		return
	}

	err = DB.NotifyPayment(
		WithdrawalIdentifier(wopid),
		paymentNotification.ProviderTransactionId,
		paymentNotification.Amount,
		paymentNotification.Amount,
	)
	if err != nil {
		err := WriteProblem(res, HTTP_BAD_REQUEST, &RFC9457Problem{
			TypeUri:  TALER_URI_PROBLEM_PREFIX + "/C2EC_PAYMENT_NOTIFICATION_FAILED",
			Title:    "payment notification failed",
			Detail:   "the payment notification failed during the processing of the message: " + err.Error(),
			Instance: req.RequestURI,
		})
		if err != nil {
			res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
		}
		return
	}

	res.WriteHeader(HTTP_NO_CONTENT)
}

func handleWithdrawalAbort(res http.ResponseWriter, req *http.Request) {

	res.WriteHeader(HTTP_OK)
	res.Write(bytes.NewBufferString("retrieved withdrawal operation abortion request").Bytes())
}

// Tries to load a WithdrawalOperationStatus from the database. If no
// entry could been found, it will write the correct error to the response.
func getWithdrawalOrWriteError(wopid string, res http.ResponseWriter, reqUri string) {
	// read the withdrawal from the database
	withdrawal, err := DB.GetWithdrawalByWopid(wopid)
	if err != nil {

		err := WriteProblem(res, HTTP_INTERNAL_SERVER_ERROR, &RFC9457Problem{
			TypeUri:  TALER_URI_PROBLEM_PREFIX + "/C2EC_WITHDRAWAL_STATUS_DB_FAILURE",
			Title:    "database failure",
			Detail:   "db failure while requesting withdrawal (error=" + err.Error() + ")",
			Instance: reqUri,
		})
		if err != nil {
			res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
		}
		return
	}

	if withdrawal == nil {
		// not found -> 404
		err := WriteProblem(res, HTTP_NOT_FOUND, &RFC9457Problem{
			TypeUri:  TALER_URI_PROBLEM_PREFIX + "/C2EC_WITHDRAWAL_NOT_FOUND",
			Title:    "Not Found",
			Detail:   "No withdrawal with wopid=" + wopid + " could been found.",
			Instance: reqUri,
		})
		if err != nil {
			res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
		}
		return
	}

	// return the C2ECWithdrawalStatus
	if amount, err := ToAmount(withdrawal.Amount); err != nil {
		err := WriteProblem(res, HTTP_INTERNAL_SERVER_ERROR, &RFC9457Problem{
			TypeUri:  TALER_URI_PROBLEM_PREFIX + "/C2EC_WITHDRAWAL_STATUS_CONVERSION_FAILURE",
			Title:    "conversion failure",
			Detail:   "failed converting amount object (error:" + err.Error() + ")",
			Instance: reqUri,
		})
		if err != nil {
			res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
		}
		return
	} else {
		withdrawalStatusBytes, err := NewJsonCodec[C2ECWithdrawalStatus]().EncodeToBytes(&C2ECWithdrawalStatus{
			Status: withdrawal.WithdrawalStatus,
			Amount: *amount,
		})
		if err != nil {
			err := WriteProblem(res, HTTP_INTERNAL_SERVER_ERROR, &RFC9457Problem{
				TypeUri:  TALER_URI_PROBLEM_PREFIX + "/C2EC_WITHDRAWAL_STATUS_CONVERSION_FAILURE",
				Title:    "conversion failure",
				Detail:   "failed converting C2ECWithdrawalStatus object (error:" + err.Error() + ")",
				Instance: reqUri,
			})
			if err != nil {
				res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
			}
			return
		}
		res.WriteHeader(HTTP_OK)
		res.Write(withdrawalStatusBytes)
	}
}