summaryrefslogtreecommitdiff
path: root/src/backend/taler-merchant-httpd_tip-reserve-helper.c
blob: 0ded8ace9ac0ace4488c76bc00989469f3580e45 (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
/*
  This file is part of TALER
  (C) 2018--2019 Taler Systems SA

  TALER 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.

  TALER 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 General Public License for more details.

  You should have received a copy of the GNU General Public License along with
  TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
*/
/**
 * @file backend/taler-merchant-httpd_tip-reserve-helper.c
 * @brief helper functions to check the status of a tipping reserve
 * @author Christian Grothoff
 */
#include "platform.h"
#include "taler-merchant-httpd_tip-reserve-helper.h"


/**
 * Head of active ctr context DLL.
 */
static struct CheckTipReserve *ctr_head;

/**
 * Tail of active ctr context DLL.
 */
static struct CheckTipReserve *ctr_tail;


/**
 * Resume connection underlying @a ctr.
 *
 * @param ctr what to resume
 */
static void
resume_ctr (struct CheckTipReserve *ctr)
{
  GNUNET_assert (GNUNET_YES == ctr->suspended);
  GNUNET_CONTAINER_DLL_remove (ctr_head,
                               ctr_tail,
                               ctr);
  MHD_resume_connection (ctr->connection);
  TMH_trigger_daemon (); /* we resumed, kick MHD */
}


/**
 * Resume the given context and send the given response.  Stores the response
 * in the @a ctr and signals MHD to resume the connection.  Also ensures MHD
 * runs immediately.
 *
 * @param ctr tip reserve query helper context
 * @param response_code response code to use
 * @param response response data to send back
 */
static void
resume_with_response (struct CheckTipReserve *ctr,
                      unsigned int response_code,
                      struct MHD_Response *response)
{
  ctr->response_code = response_code;
  ctr->response = response;
  resume_ctr (ctr);
  ctr->suspended = GNUNET_NO;
}


/**
 * Function called with the result of the /reserve/status request
 * for the tipping reserve.  Update our database balance with the
 * result.
 *
 * @param cls closure with a `struct CheckTipReserve *'
 * @param http_status HTTP response code, #MHD_HTTP_OK (200) for successful status request
 *                    0 if the exchange's reply is bogus (fails to follow the protocol)
 * @param ec taler-specific error code, #TALER_EC_NONE on success
 * @param[in] json original response in JSON format (useful only for diagnostics)
 * @param balance current balance in the reserve, NULL on error
 * @param history_length number of entries in the transaction history, 0 on error
 * @param history detailed transaction history, NULL on error
 */
static void
handle_status (void *cls,
               unsigned int http_status,
               enum TALER_ErrorCode ec,
               const json_t *json,
               const struct TALER_Amount *balance,
               unsigned int history_length,
               const struct TALER_EXCHANGE_ReserveHistory *history)
{
  struct CheckTipReserve *ctr = cls;

  ctr->rsh = NULL;
  ctr->reserve_expiration = GNUNET_TIME_UNIT_ZERO_ABS;
  if (MHD_HTTP_NOT_FOUND == http_status)
  {
    resume_with_response (ctr,
                          MHD_HTTP_NOT_FOUND,
                          TALER_MHD_make_error (ec,
                                                "Reserve unknown at exchange"));
    return;
  }
  if (MHD_HTTP_OK != http_status)
  {
    GNUNET_break_op (0);
    resume_with_response (ctr,
                          MHD_HTTP_SERVICE_UNAVAILABLE,
                          TALER_MHD_make_error (ec,
                                                "Exchange returned error code for reserve status"));
    return;
  }

  if (0 == history_length)
  {
    GNUNET_break_op (0);
    resume_with_response (ctr,
                          MHD_HTTP_SERVICE_UNAVAILABLE,
                          TALER_MHD_make_error (
                            TALER_EC_TIP_QUERY_RESERVE_HISTORY_FAILED_EMPTY,
                            "Exchange returned empty reserve history"));
    return;
  }

  if (TALER_EXCHANGE_RTT_CREDIT != history[0].type)
  {
    GNUNET_break_op (0);
    resume_with_response (ctr,
                          MHD_HTTP_SERVICE_UNAVAILABLE,
                          TALER_MHD_make_error (
                            TALER_EC_TIP_QUERY_RESERVE_HISTORY_INVALID_NO_DEPOSIT,
                            "Exchange returned invalid reserve history"));
    return;
  }

  if (GNUNET_OK !=
      TALER_amount_get_zero (history[0].amount.currency,
                             &ctr->amount_withdrawn))
  {
    GNUNET_break_op (0);
    resume_with_response (ctr,
                          MHD_HTTP_SERVICE_UNAVAILABLE,
                          TALER_MHD_make_error (
                            TALER_EC_TIP_QUERY_RESERVE_HISTORY_INVALID_CURRENCY,
                            "Exchange returned invalid reserve history"));
    return;
  }

  if (0 != strcasecmp (TMH_currency,
                       history[0].amount.currency))
  {
    GNUNET_break_op (0);
    resume_with_response (ctr,
                          MHD_HTTP_SERVICE_UNAVAILABLE,
                          TALER_MHD_make_error (
                            TALER_EC_TIP_QUERY_RESERVE_CURRENCY_MISMATCH,
                            "Exchange currency unexpected"));
    return;
  }

  if (GNUNET_YES == ctr->none_authorized)
    ctr->amount_authorized = ctr->amount_withdrawn;
  ctr->amount_deposited = ctr->amount_withdrawn;

  /* Update DB based on status! */
  for (unsigned int i = 0; i<history_length; i++)
  {
    switch (history[i].type)
    {
    case TALER_EXCHANGE_RTT_CREDIT:
      {
        enum GNUNET_DB_QueryStatus qs;
        struct GNUNET_HashCode uuid;
        struct GNUNET_TIME_Absolute deposit_expiration;

        deposit_expiration = GNUNET_TIME_absolute_add (
          history[i].details.in_details.timestamp,
          ctr->
          idle_reserve_expiration_time);
        /* We're interested in the latest DEPOSIT timestamp, since this determines the
         * reserve's expiration date. Note that the history isn't chronologically ordered. */
        ctr->reserve_expiration = GNUNET_TIME_absolute_max (
          ctr->reserve_expiration,
          deposit_expiration);
        GNUNET_CRYPTO_hash (history[i].details.in_details.wire_reference,
                            history[i].details.in_details.wire_reference_size,
                            &uuid);
        db->preflight (db->cls);
        qs = db->enable_tip_reserve_TR (db->cls,
                                        &ctr->reserve_priv,
                                        &uuid,
                                        &history[i].amount,
                                        deposit_expiration);
        if (GNUNET_OK !=
            TALER_amount_add (&ctr->amount_deposited,
                              &ctr->amount_deposited,
                              &history[i].amount))
        {
          GNUNET_break_op (0);
          resume_with_response (ctr,
                                MHD_HTTP_INTERNAL_SERVER_ERROR,
                                TALER_MHD_make_error (
                                  TALER_EC_TIP_QUERY_RESERVE_HISTORY_ARITHMETIC_ISSUE_DEPOSIT,
                                  "Exchange returned invalid reserve history (amount overflow)"));
          return;
        }

        if (0 > qs)
        {
          GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                      _ (
                        "Database error updating tipping reserve status: %d\n"),
                      qs);
        }
      }
      break;
    case TALER_EXCHANGE_RTT_WITHDRAWAL:
      if (GNUNET_OK !=
          TALER_amount_add (&ctr->amount_withdrawn,
                            &ctr->amount_withdrawn,
                            &history[i].amount))
      {
        GNUNET_break_op (0);
        resume_with_response (ctr,
                              MHD_HTTP_INTERNAL_SERVER_ERROR,
                              TALER_MHD_make_error (
                                TALER_EC_TIP_QUERY_RESERVE_HISTORY_ARITHMETIC_ISSUE_WITHDRAW,
                                "Exchange returned invalid reserve history (amount overflow)"));
        return;
      }
      break;
    case TALER_EXCHANGE_RTT_RECOUP:
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  _ (
                    "Encountered unsupported /recoup operation on tipping reserve\n"));
      /* FIXME: probably should count these like deposits!? */
      break;
    case TALER_EXCHANGE_RTT_CLOSE:
      /* We count 'closing' amounts just like withdrawals */
      if (GNUNET_OK !=
          TALER_amount_add (&ctr->amount_withdrawn,
                            &ctr->amount_withdrawn,
                            &history[i].amount))
      {
        GNUNET_break_op (0);
        resume_with_response (ctr,
                              MHD_HTTP_INTERNAL_SERVER_ERROR,
                              TALER_MHD_make_error (
                                TALER_EC_TIP_QUERY_RESERVE_HISTORY_ARITHMETIC_ISSUE_CLOSED,
                                "Exchange returned invalid reserve history (amount overflow)"));
        return;
      }
      break;
    }
  }

  /* normal, non-error continuation */
  resume_with_response (ctr,
                        0,
                        NULL);
}


/**
 * Function called with the result of a #TMH_EXCHANGES_find_exchange()
 * operation.  Given the exchange handle, we will then interrogate
 * the exchange about the status of the tipping reserve.
 *
 * @param cls closure with a `struct CheckTipReserve *`
 * @param eh handle to the exchange context
 * @param wire_fee current applicable wire fee for dealing with @a eh, NULL if not available
 * @param exchange_trusted #GNUNET_YES if this exchange is trusted by config
 */
static void
exchange_cont (void *cls,
               struct TALER_EXCHANGE_Handle *eh,
               const struct TALER_Amount *wire_fee,
               int exchange_trusted)
{
  struct CheckTipReserve *ctr = cls;
  struct TALER_ReservePublicKeyP reserve_pub;
  const struct TALER_EXCHANGE_Keys *keys;

  ctr->fo = NULL;
  if (NULL == eh)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                _ ("Failed to contact exchange configured for tipping!\n"));
    resume_with_response (ctr,
                          MHD_HTTP_SERVICE_UNAVAILABLE,
                          TALER_MHD_make_error (
                            TALER_EC_TIP_QUERY_RESERVE_STATUS_FAILED_EXCHANGE_DOWN,
                            "Unable to obtain /keys from exchange"));
    return;
  }
  keys = TALER_EXCHANGE_get_keys (eh);
  GNUNET_assert (NULL != keys);
  ctr->idle_reserve_expiration_time
    = keys->reserve_closing_delay;
  GNUNET_CRYPTO_eddsa_key_get_public (&ctr->reserve_priv.eddsa_priv,
                                      &reserve_pub.eddsa_pub);
  ctr->rsh = TALER_EXCHANGE_reserves_get (eh,
                                          &reserve_pub,
                                          &handle_status,
                                          ctr);
}


/**
 * Check the status of the given reserve at the given exchange.
 * Suspends the MHD connection while this is happening and resumes
 * processing once we know the reserve status (or once an error
 * code has been determined).
 *
 * @param[in,out] ctr context for checking the reserve status
 * @param tip_exchange the URL of the exchange to query
 */
void
TMH_check_tip_reserve (struct CheckTipReserve *ctr,
                       const char *tip_exchange)
{
  MHD_suspend_connection (ctr->connection);
  db->preflight (db->cls);
  GNUNET_CONTAINER_DLL_insert (ctr_head,
                               ctr_tail,
                               ctr);
  ctr->suspended = GNUNET_YES;
  ctr->fo = TMH_EXCHANGES_find_exchange (tip_exchange,
                                         NULL,
                                         &exchange_cont,
                                         ctr);
  if (NULL == ctr->fo)
  {
    GNUNET_break (0);
    resume_with_response (ctr,
                          MHD_HTTP_INTERNAL_SERVER_ERROR,
                          TALER_MHD_make_error (
                            TALER_EC_INTERNAL_INVARIANT_FAILURE,
                            "Unable to find exchange handle"));
  }
}


/**
 * Clean up any state that might be left in @a ctr.
 *
 * @param[in] context to clean up
 */
void
TMH_check_tip_reserve_cleanup (struct CheckTipReserve *ctr)
{
  if (NULL != ctr->rsh)
  {
    TALER_EXCHANGE_reserves_get_cancel (ctr->rsh);
    ctr->rsh = NULL;
  }
  if (NULL != ctr->fo)
  {
    TMH_EXCHANGES_find_exchange_cancel (ctr->fo);
    ctr->fo = NULL;
  }
  if (NULL != ctr->response)
  {
    MHD_destroy_response (ctr->response);
    ctr->response = NULL;
  }
  if (MHD_YES == ctr->suspended)
  {
    resume_ctr (ctr);
    ctr->suspended = GNUNET_NO;
  }
}


/**
 * Force all tip reserve helper contexts to be resumed as we are about to shut
 * down MHD.
 */
void
MH_force_trh_resume ()
{
  struct CheckTipReserve *n;

  for (struct CheckTipReserve *ctr = ctr_head;
       NULL != ctr;
       ctr = n)
  {
    n = ctr->next;
    resume_ctr (ctr);
    ctr->suspended = GNUNET_SYSERR;
  }
}


/* end of taler-merchant-httpd_tip-reserve-helper.c */