summaryrefslogtreecommitdiff
path: root/c2ec/wire-gateway.go
blob: 424c69c779613751bffec57aaee9c5835c9a2789 (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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
package main

import (
	"context"
	"log"
	http "net/http"
	"strconv"
	"time"
)

const WIRE_GATEWAY_CONFIG_ENDPOINT = "/config"
const WIRE_GATEWAY_HISTORY_ENDPOINT = "/history"

const WIRE_GATEWAY_CONFIG_PATTERN = WIRE_GATEWAY_CONFIG_ENDPOINT
const WIRE_TRANSFER_PATTERN = "/transfer"
const WIRE_HISTORY_INCOMING_PATTERN = WIRE_GATEWAY_HISTORY_ENDPOINT + "/incoming"
const WIRE_HISTORY_OUTGOING_PATTERN = WIRE_GATEWAY_HISTORY_ENDPOINT + "/outgoing"
const WIRE_ADMIN_ADD_INCOMING_PATTERN = "/admin/add-incoming"

const INCOMING_RESERVE_TRANSACTION_TYPE = "RESERVE"

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

// https://docs.taler.net/core/api-bank-wire.html#tsref-type-TransferRequest
type TransferRequest struct {
	RequestUid      HashCode      `json:"request_uid"`
	Amount          Amount        `json:"amount"`
	ExchangeBaseUrl string        `json:"exchange_base_url"`
	Wtid            ShortHashCode `json:"wtid"`
	CreditAccount   string        `json:"credit_account"`
}

// https://docs.taler.net/core/api-bank-wire.html#tsref-type-TransferResponse
type TransferResponse struct {
	Timestamp Timestamp `json:"timestamp"`
	RowId     int       `json:"row_id"`
}

// https://docs.taler.net/core/api-bank-wire.html#tsref-type-IncomingHistory
type IncomingHistory struct {
	IncomingTransactions []IncomingReserveTransaction `json:"incoming_transactions"`
	CreditAccount        string                       `json:"credit_account"`
}

// type RESERVE | https://docs.taler.net/core/api-bank-wire.html#tsref-type-IncomingReserveTransaction
type IncomingReserveTransaction struct {
	Type         string         `json:"type"`
	RowId        int            `json:"row_id"`
	Date         Timestamp      `json:"date"`
	Amount       Amount         `json:"amount"`
	DebitAccount string         `json:"debit_account"`
	ReservePub   EddsaPublicKey `json:"reserve_pub"`
}

type OutgoingHistory struct {
	OutgoingTransactions []*OutgoingBankTransaction `json:"outgoing_transactions"`
	DebitAccount         string                     `json:"debit_account"`
}

type OutgoingBankTransaction struct {
	RowId           uint64        `json:"row_id"`
	Date            Timestamp     `json:"date"`
	Amount          Amount        `json:"amount"`
	CreditAccount   string        `json:"credit_account"`
	Wtid            ShortHashCode `json:"wtid"`
	ExchangeBaseUrl string        `json:"exchange_base_url"`
}

func NewIncomingReserveTransaction(w *Withdrawal) *IncomingReserveTransaction {
	t := new(IncomingReserveTransaction)
	t.Amount = Amount{
		Value:    uint64(w.Amount.Val),
		Fraction: uint64(w.Amount.Frac),
		Currency: w.Amount.Curr,
	}
	t.Date = Timestamp{
		Ts: int(w.RegistrationTs),
	}
	t.DebitAccount = "" // TODO provider specific payto uri -> needs new interface operation
	t.ReservePub = EddsaPublicKey(w.ReservePubKey)
	t.RowId = int(w.WithdrawalId)
	t.Type = INCOMING_RESERVE_TRANSACTION_TYPE
	return t
}

func NewOutgoingBankTransaction(tr *Transfer) *OutgoingBankTransaction {
	t := new(OutgoingBankTransaction)
	t.Amount = Amount{
		Value:    uint64(tr.Amount.Val),
		Fraction: uint64(tr.Amount.Frac),
		Currency: tr.Amount.Curr,
	}
	t.Date = Timestamp{
		Ts: int(tr.TransactionTs),
	}
	t.CreditAccount = tr.CreditAccount
	t.ExchangeBaseUrl = tr.ExchangeBaseUrl
	t.RowId = uint64(tr.RowId)
	t.Wtid = ShortHashCode(tr.Wtid)
	return t
}

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

	cfg := WireConfig{
		Name:    "taler-wire-gateway",
		Version: "0:0:1",
	}

	serializedCfg, err := NewJsonCodec[WireConfig]().EncodeToBytes(&cfg)
	if err != nil {
		log.Default().Printf("failed serializing config: %s", err.Error())
		res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
		return
	}

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

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

	jsonCodec := NewJsonCodec[TransferRequest]()
	transfer, err := ReadStructFromBody(req, jsonCodec)
	if err != nil {

		err := WriteProblem(res, HTTP_BAD_REQUEST, &RFC9457Problem{
			TypeUri:  TALER_URI_PROBLEM_PREFIX + "/C2EC_TRANSFER_INVALID_REQ",
			Title:    "invalid request",
			Detail:   "the transfer request is malformed (error: " + err.Error() + ")",
			Instance: req.RequestURI,
		})
		if err != nil {
			res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
		}
		return
	}

	paytoTargetType, tid, err := ParsePaytoWalleeTransaction(transfer.CreditAccount)
	if err != nil {
		err := WriteProblem(res, HTTP_BAD_REQUEST, &RFC9457Problem{
			TypeUri:  TALER_URI_PROBLEM_PREFIX + "/C2EC_TRANSFER_INVALID_REQ",
			Title:    "invalid payto-uri",
			Detail:   "the transfer request contains an invalid payto-uri (error: " + err.Error() + ")",
			Instance: req.RequestURI,
		})
		if err != nil {
			res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
		}
		return
	}

	p, err := DB.GetTerminalProviderByPaytoTargetType(paytoTargetType)
	if err != nil {
		err := WriteProblem(res, HTTP_INTERNAL_SERVER_ERROR, &RFC9457Problem{
			TypeUri:  TALER_URI_PROBLEM_PREFIX + "/C2EC_DATABASE_FAILURE",
			Title:    "database request failed",
			Detail:   "failed to retrieve the provider for the payto target type '" + paytoTargetType + "'",
			Instance: req.RequestURI,
		})
		if err != nil {
			res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
		}
		return
	}

	t, err := DB.GetTransferById(transfer.RequestUid)
	if err != nil {
		err := WriteProblem(res, HTTP_INTERNAL_SERVER_ERROR, &RFC9457Problem{
			TypeUri:  TALER_URI_PROBLEM_PREFIX + "/C2EC_DATABASE_FAILURE",
			Title:    "database request failed",
			Detail:   "there was an error processing the database query",
			Instance: req.RequestURI,
		})
		if err != nil {
			res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
		}
		return
	}

	if t == nil {
		// no transfer for this request_id -> generate new
		err := DB.AddTransfer(
			transfer.RequestUid,
			&transfer.Amount,
			transfer.ExchangeBaseUrl,
			string(transfer.Wtid),
			transfer.CreditAccount,
		)
		if err != nil {
			err := WriteProblem(res, HTTP_INTERNAL_SERVER_ERROR, &RFC9457Problem{
				TypeUri:  TALER_URI_PROBLEM_PREFIX + "/C2EC_DATABASE_FAILURE",
				Title:    "database request failed",
				Detail:   "there was an error creating the transfer",
				Instance: req.RequestURI,
			})
			if err != nil {
				res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
			}
			return
		}
	} else {
		// the transfer is only processed if the body matches.
		if transfer.Amount.Value != uint64(t.Amount.Val) ||
			transfer.Amount.Fraction != uint64(t.Amount.Frac) ||
			transfer.Amount.Currency != t.Amount.Curr ||
			transfer.ExchangeBaseUrl != t.ExchangeBaseUrl ||
			transfer.Wtid != ShortHashCode(t.Wtid) ||
			transfer.CreditAccount != t.CreditAccount {

			err := WriteProblem(res, HTTP_CONFLICT, &RFC9457Problem{
				TypeUri:  TALER_URI_PROBLEM_PREFIX + "/C2EC_TRANSFER_INVALID_REQ",
				Title:    "invalid request",
				Detail:   "the transfer request did not match previous request with the same request identifier",
				Instance: req.RequestURI,
			})
			if err != nil {
				res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
			}
			return
		}

		ptid := strconv.Itoa(tid)
		w, err := DB.GetWithdrawalByProviderTransactionId(ptid)
		if err != nil || w == nil {
			err := WriteProblem(res, HTTP_INTERNAL_SERVER_ERROR, &RFC9457Problem{
				TypeUri:  TALER_URI_PROBLEM_PREFIX + "/C2EC_DATABASE_FAILURE",
				Title:    "database request failed",
				Detail:   "there was an error processing the database query or no withdrawal could been found.",
				Instance: req.RequestURI,
			})
			if err != nil {
				res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
			}
			return
		}

		refundClient := PROVIDER_CLIENTS[p.Name]
		if refundClient == nil {
			err := WriteProblem(res, HTTP_INTERNAL_SERVER_ERROR, &RFC9457Problem{
				TypeUri:  TALER_URI_PROBLEM_PREFIX + "/C2EC_UNKNOWN_TRANSFER_MECHANISM",
				Title:    "unknown refund mechanism",
				Detail:   "the target type of the payto uri for the transfer is not registered",
				Instance: req.RequestURI,
			})
			if err != nil {
				res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
			}
			return
		}
		refundClient.Refund(ptid)
	}
}

// :query start: *Optional.*
//
//	Row identifier to explicitly set the *starting point* of the query.
//
// :query delta:
//
//	The *delta* value that determines the range of the query.
//
// :query long_poll_ms: *Optional.*
//
//	If this parameter is specified and the result of the query would be empty,
//	the bank will wait up to ``long_poll_ms`` milliseconds for new transactions
//	that match the query to arrive and only then send the HTTP response.
//	A client must never rely on this behavior, as the bank may return a response
//	immediately or after waiting only a fraction of ``long_poll_ms``.
func historyIncoming(res http.ResponseWriter, req *http.Request) {

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

	var start int
	if startPtr, accepted := AcceptOptionalParamOrWriteResponse(
		"start", strconv.Atoi, req, res,
	); accepted {
	} else {
		if startPtr != nil {
			start = *startPtr
		}
	}

	var delta int
	if deltaPtr, accepted := AcceptOptionalParamOrWriteResponse(
		"delta", strconv.Atoi, req, res,
	); accepted {
	} else {
		if deltaPtr != nil {
			delta = *deltaPtr
		} else {
			// this means parameter was not given.
			// no long polling (simple get)
			shouldStartLongPoll = false
		}
	}

	if shouldStartLongPoll {

		// wait for the completion of the context
		waitMs, cancelFunc := context.WithTimeout(req.Context(), time.Duration(longPollMilli)*time.Millisecond)
		defer cancelFunc()

		// this will just wait / block until the milliseconds are exceeded.
		<-waitMs.Done()
	}

	withdrawals, err := DB.GetConfirmedWithdrawals(start, delta)

	if err != nil {
		err := WriteProblem(res, HTTP_INTERNAL_SERVER_ERROR, &RFC9457Problem{
			TypeUri:  TALER_URI_PROBLEM_PREFIX + "/C2EC_DATABASE_FAILURE",
			Title:    "database request failed",
			Detail:   "there was an error processing the database query",
			Instance: req.RequestURI,
		})
		if err != nil {
			res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
		}
		return
	}

	if len(withdrawals) < 1 {
		res.WriteHeader(HTTP_NOT_FOUND)
		return
	}

	transactions := make([]*IncomingReserveTransaction, len(withdrawals))
	for _, w := range withdrawals {
		transactions = append(transactions, NewIncomingReserveTransaction(w))
	}

	enc, err := NewJsonCodec[[]*IncomingReserveTransaction]().EncodeToBytes(&transactions)
	if err != nil {
		err := WriteProblem(res, HTTP_INTERNAL_SERVER_ERROR, &RFC9457Problem{
			TypeUri:  TALER_URI_PROBLEM_PREFIX + "/C2EC_RESPONSE_ENCODING_FAILED",
			Title:    "encoding failed",
			Detail:   "the encoding of the response failed (error:" + err.Error() + ")",
			Instance: req.RequestURI,
		})
		if err != nil {
			res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
		}
		return
	}

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

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

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

	var start int
	if startPtr, accepted := AcceptOptionalParamOrWriteResponse(
		"start", strconv.Atoi, req, res,
	); accepted {
	} else {
		if startPtr != nil {
			start = *startPtr
		}
	}

	var delta int
	if deltaPtr, accepted := AcceptOptionalParamOrWriteResponse(
		"delta", strconv.Atoi, req, res,
	); accepted {
	} else {
		if deltaPtr != nil {
			delta = *deltaPtr
		} else {
			// this means parameter was not given.
			// no long polling (simple get)
			shouldStartLongPoll = false
		}
	}

	if shouldStartLongPoll {

		// wait for the completion of the context
		waitMs, cancelFunc := context.WithTimeout(req.Context(), time.Duration(longPollMilli)*time.Millisecond)
		defer cancelFunc()

		// this will just wait / block until the milliseconds are exceeded.
		<-waitMs.Done()
	}

	transfers, err := DB.GetTransfers(start, delta)

	if err != nil {
		err := WriteProblem(res, HTTP_INTERNAL_SERVER_ERROR, &RFC9457Problem{
			TypeUri:  TALER_URI_PROBLEM_PREFIX + "/C2EC_DATABASE_FAILURE",
			Title:    "database request failed",
			Detail:   "there was an error processing the database query",
			Instance: req.RequestURI,
		})
		if err != nil {
			res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
		}
		return
	}

	if len(transfers) < 1 {
		res.WriteHeader(HTTP_NOT_FOUND)
		return
	}

	transactions := make([]*OutgoingBankTransaction, len(transfers))
	for _, t := range transfers {
		transactions = append(transactions, NewOutgoingBankTransaction(t))
	}

	outgoingHistory := OutgoingHistory{
		OutgoingTransactions: transactions,
		DebitAccount:         CONFIG.Server.CreditAccount,
	}
	enc, err := NewJsonCodec[OutgoingHistory]().EncodeToBytes(&outgoingHistory)
	if err != nil {
		err := WriteProblem(res, HTTP_INTERNAL_SERVER_ERROR, &RFC9457Problem{
			TypeUri:  TALER_URI_PROBLEM_PREFIX + "/C2EC_RESPONSE_ENCODING_FAILED",
			Title:    "encoding failed",
			Detail:   "the encoding of the response failed (error:" + err.Error() + ")",
			Instance: req.RequestURI,
		})
		if err != nil {
			res.WriteHeader(HTTP_INTERNAL_SERVER_ERROR)
		}
		return
	}

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

// This method is currently dead and implemented for API conformance
func adminAddIncoming(res http.ResponseWriter, req *http.Request) {

	// not implemented, because not used
	res.WriteHeader(HTTP_BAD_REQUEST)
}