aboutsummaryrefslogtreecommitdiff
path: root/src/donau/donau-httpd_batch-issue.c
blob: c785e00d2f17175f4836d284abd3b9500a9f24ec (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
/*
  This file is part of TALER
  Copyright (C) 2024 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 Affero General Public License for more details.

  You should have received a copy of the GNU Affero General Public License along with
  TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
*/
/**
 * @file donau-httpd_batch-issue.c
 * @brief Handle request to issue receipts.
 * @author Lukas Matyja
 */
#include <taler/platform.h>
#include <gnunet/gnunet_util_lib.h>
#include <gnunet/gnunet_json_lib.h>
#include <jansson.h>
#include <microhttpd.h>
#include <pthread.h>
#include <taler/taler_json_lib.h>
#include <taler/taler_mhd_lib.h>
#include <taler/taler_signatures.h>
#include "donaudb_plugin.h"
#include "donau-httpd_batch-issue.h"
#include "donau-httpd_db.h"
#include "donau-httpd_metrics.h"
#include "donau_json_lib.h"
#include "donau-httpd_keys.h"


/**
 * Parse a bkp encoded in JSON.
 *
 * @param[out] bkp where to return the result
 * @param bkp_key_obj json to parse
 * @return #GNUNET_OK if all is fine, #GNUNET_SYSERR if @a bkp_key_obj
 * is malformed.
 */
static enum GNUNET_GenericReturnValue
parse_json_bkp (struct DONAU_BlindedUniqueDonorIdentifierKeyPair *bkp,
                const json_t *bkp_key_obj)
{
  struct GNUNET_JSON_Specification spec[] = {
    GNUNET_JSON_spec_fixed_auto ("h_du_pub",
                                 &bkp->h_donation_unit_pub),
    DONAU_JSON_spec_blinded_donation_identifier ("blinded_udi",
                                                 &bkp->blinded_udi),
    GNUNET_JSON_spec_end ()
  };

  if (GNUNET_OK !=
      GNUNET_JSON_parse (bkp_key_obj,
                         spec,
                         NULL, NULL))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  /* TODO: Check for duplicate blinded UDIs.*/
  return GNUNET_OK;
}


/**
 * Parse signatures to JSON.
 *
 * @param num_sig number of signatures
 * @param signatures
 * @param[out] j_signatures JSON object
 * @return #GNUNET_OK if all is fine, #GNUNET_SYSERR if we could not parse
 * is malformed.
 */
static void
signatures_to_JSON (const size_t num_sig,
                    struct DONAU_BlindedDonationUnitSignature *signatures,
                    json_t *j_signatures)
{
  for (size_t i = 0; i < num_sig; i++)
  {
    struct DONAU_BlindedDonationUnitSignature *signature = &signatures[i];
    GNUNET_assert (
      0 == json_array_append (
        j_signatures,
        GNUNET_JSON_PACK (
          DONAU_JSON_pack_blinded_donation_unit_sig ("blinded_signature",
                                                     signature))));
  }
}


MHD_RESULT
DH_handler_issue_receipts_post (struct DH_RequestContext *rc,
                                const json_t *root,
                                const char *const args[1])
{
  struct DONAU_CharitySignatureP charity_sig;
  uint64_t year;
  bool second_time = false;
  unsigned long long charity_id;
  char dummy;

  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "issue receipts request! \n");

  if ( (NULL == args[0]) ||
       (1 != sscanf (args[0],
                     "%llu%c",
                     &charity_id,
                     &dummy)) )
  {
    GNUNET_break_op (0);
    return TALER_MHD_reply_with_error (rc->connection,
                                       MHD_HTTP_BAD_REQUEST,
                                       TALER_EC_GENERIC_PARAMETER_MALFORMED,
                                       "charity_id");
  }
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "issue receipts for charity id: %llu\n",
              charity_id);

  const json_t *budikeypairs;
  struct GNUNET_JSON_Specification spec[] = {
    GNUNET_JSON_spec_array_const ("budikeypairs",
                                  &budikeypairs),
    GNUNET_JSON_spec_fixed_auto ("charity_sig",
                                 &charity_sig),
    GNUNET_JSON_spec_uint64 ("year",
                             &year),
    GNUNET_JSON_spec_end ()
  };

  {
    enum GNUNET_GenericReturnValue res;

    res = TALER_MHD_parse_json_data (rc->connection,
                                     root,
                                     spec);
    if (GNUNET_SYSERR == res)
      return MHD_NO; /* hard failure */
    if (GNUNET_NO == res)
    {
      GNUNET_break_op (0);
      return MHD_YES; /* failure */
    }
  }

  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "parse some values!\n");
  /* parse the budikeypairs array */
  const size_t num_bkps
    = json_array_size (budikeypairs);
  struct DONAU_BlindedUniqueDonorIdentifierKeyPair *bkps;
  if (0 != num_bkps)
  {
    json_t *bkp_obj;
    size_t index;


    bkps = GNUNET_new_array
             (num_bkps,
             struct DONAU_BlindedUniqueDonorIdentifierKeyPair);
    json_array_foreach (budikeypairs, index, bkp_obj)
    {
      if (GNUNET_SYSERR ==
          parse_json_bkp (&bkps[index], bkp_obj))
      {
        GNUNET_break_op (0);
        return TALER_MHD_reply_with_error (rc->connection,
                                           MHD_HTTP_BAD_REQUEST,
                                           TALER_EC_GENERIC_PARAMETER_MALFORMED,
                                           "budikeypairs");
      }
    }
  }
  else
  {
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "Empty array of budi key pairs!\n");
    return TALER_MHD_reply_with_error (rc->connection,
                                       MHD_HTTP_BAD_REQUEST,
                                       TALER_EC_GENERIC_PARAMETER_MALFORMED,
                                       "budikeypairs");
  }

  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "budi key pairs array is parsed!\n");
  // Get charity pub
  struct DONAUDB_CharityMetaData charity_meta;
  enum GNUNET_DB_QueryStatus qs_charity;

  qs_charity = DH_plugin->lookup_charity (DH_plugin->cls,
                                          (uint64_t) charity_id,
                                          &charity_meta);
  switch (qs_charity)
  {
  case GNUNET_DB_STATUS_HARD_ERROR:
  case GNUNET_DB_STATUS_SOFT_ERROR:
	  GNUNET_break_op (0);
    return TALER_MHD_reply_with_error (rc->connection,
                                       MHD_HTTP_INTERNAL_SERVER_ERROR,
                                       TALER_EC_GENERIC_DB_FETCH_FAILED,
                                       NULL);
  case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
	GNUNET_break_op (0);
    return TALER_MHD_reply_with_error (
      rc->connection,
      MHD_HTTP_NOT_FOUND,
      TALER_EC_DONAU_CHARITY_NOT_FOUND,
      NULL);
    break;
  case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
    break;
  }

  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "got charity from db!\n");
  /* verify charity signature */
  if (GNUNET_OK !=
      DONAU_charity_bkp_verify (num_bkps,
                                bkps,
                                &charity_meta.charity_pub,
                                &charity_sig))
  {
    GNUNET_break_op (0);
    return TALER_MHD_reply_with_error (
      rc->connection,
      MHD_HTTP_FORBIDDEN,
      TALER_EC_DONAU_CHARITY_SIGNATURE_INVALID,
      NULL);
  }

  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "charity signature valid!\n");
  /* request already made? -> idempotent */
  enum GNUNET_DB_QueryStatus qs_check_receipts;
  struct DONAUDB_IssuedReceiptsMetaData check_receipts_meta;
  struct DONAU_DonationReceiptHashP h_receipts = {0};
  json_t *blind_signatures = json_array ();
  GNUNET_assert (NULL != blind_signatures);

  struct GNUNET_HashContext *hc;
  hc = GNUNET_CRYPTO_hash_context_start ();
  for (unsigned int i = 0; i < num_bkps; i++)
  {
    GNUNET_CRYPTO_hash_context_read (hc,
                                     &bkps[i].h_donation_unit_pub,
                                     sizeof (bkps[i].h_donation_unit_pub));
    GNUNET_CRYPTO_hash_context_read (hc,
                                     bkps[i].blinded_udi.blinded_message,
                                     sizeof (bkps[i].blinded_udi.blinded_message
                                             ));
  }
  GNUNET_CRYPTO_hash_context_read (hc,
                                   &charity_sig,
                                   sizeof (struct DONAU_CharitySignatureP));
  GNUNET_CRYPTO_hash_context_read (hc,
                                   &year,
                                   sizeof (uint64_t));
  GNUNET_CRYPTO_hash_context_finish (hc,
                                     &h_receipts.hash);

start:
  qs_check_receipts = DH_plugin->lookup_issued_receipts (DH_plugin->cls,
                                                         &h_receipts,
                                                         &check_receipts_meta);
  switch (qs_check_receipts)
  {
  case GNUNET_DB_STATUS_HARD_ERROR:
  case GNUNET_DB_STATUS_SOFT_ERROR:
    GNUNET_break (0);
    return TALER_MHD_reply_with_error (rc->connection,
                                       MHD_HTTP_INTERNAL_SERVER_ERROR,
                                       TALER_EC_GENERIC_DB_FETCH_FAILED,
                                       NULL);
  case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "request has not been made yet (first time)!\n");
    break; // it's the first request from the charity, we can proceed
  case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "request has been made already!\n");
    signatures_to_JSON (num_bkps, check_receipts_meta.blinded_sig,
                        blind_signatures);
    return TALER_MHD_REPLY_JSON_PACK (
      rc->connection,
      MHD_HTTP_OK,
      GNUNET_JSON_pack_array_steal ("blind_signatures",
                                    blind_signatures));
  }
  /* calculate the sum of all receipts */
  struct TALER_Amount receipts_sum;

  GNUNET_assert (GNUNET_OK ==
                 TALER_amount_set_zero (DH_currency,
                                        &receipts_sum));
  for (size_t i = 0; i < num_bkps; i++)
  {
    struct DH_DonationUnitKey *dk;

    if (NULL == (dk = DH_keys_donation_unit_by_hash (
                   &bkps[i].h_donation_unit_pub))) {
      GNUNET_break_op (0);
      return TALER_MHD_reply_with_error (rc->connection,
                                         MHD_HTTP_NOT_FOUND,
                                         TALER_EC_DONAU_GENERIC_KEYS_MISSING,
                                         NULL);
    }
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "public key value: %lu.%u\n",
                dk->value.value, dk->value.fraction);
    GNUNET_assert (0 <= TALER_amount_add (&receipts_sum,
                                          &receipts_sum,
                                          &dk->value));
  }

  /* sign budis and send the signatures back */
  struct DONAU_BlindedDonationUnitSignature du_sigs[num_bkps];
  struct DONAU_BkpSignData bkps_sign_data[num_bkps];

  for (int i = 0; i < num_bkps; i++)
  {
    bkps_sign_data[i].h_donation_unit_pub = &bkps[i].h_donation_unit_pub;
    bkps_sign_data[i].budi = &bkps[i].blinded_udi;
  }
  enum TALER_ErrorCode batch_sign_ec;
  batch_sign_ec = DH_keys_donation_unit_batch_sign (num_bkps,
                                                    bkps_sign_data,
                                                    du_sigs);
  if (TALER_EC_NONE != batch_sign_ec) {
	GNUNET_break_op (0);
    return TALER_MHD_reply_with_error (rc->connection,
                                       MHD_HTTP_INTERNAL_SERVER_ERROR,
                                       batch_sign_ec,   // TODO:other EC
                                       NULL);
  }
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "made blind signatures!\n");
  /* save new receipts to date and save receipts Request (blinded signatures,
   * charity id, amount, hash over bkps) to make it idempotent*/
  enum GNUNET_DB_QueryStatus qs_insert_ir;
  bool smaller_than_max_per_year = false;
  qs_insert_ir = DH_plugin->insert_issued_receipt (
    DH_plugin->cls,
    num_bkps,
    du_sigs,
    (uint64_t) charity_id,
    &h_receipts,
    &receipts_sum,
    &smaller_than_max_per_year);
  switch (qs_insert_ir)
  {
  case GNUNET_DB_STATUS_HARD_ERROR:
  case GNUNET_DB_STATUS_SOFT_ERROR:
    GNUNET_break (0);
    return TALER_MHD_reply_with_error (rc->connection,
                                       MHD_HTTP_INTERNAL_SERVER_ERROR,
                                       TALER_EC_GENERIC_DB_FETCH_FAILED,
                                       NULL);
  case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
    GNUNET_assert (! second_time);
    second_time = true;
    goto start;
  case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
    if (! smaller_than_max_per_year) {
      GNUNET_break_op (0);
      return TALER_MHD_reply_with_error (rc->connection,
                                         MHD_HTTP_BAD_REQUEST,
                                         TALER_EC_DONAU_EXCEEDING_DONATION_LIMIT,
                                         NULL);
    }
    break;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "issue receipts request is saved! (idempotent)\n");

  signatures_to_JSON (num_bkps, du_sigs, blind_signatures);
  return TALER_MHD_REPLY_JSON_PACK (
    rc->connection,
    MHD_HTTP_CREATED,
    GNUNET_JSON_pack_array_steal ("blind_signatures",
                                  blind_signatures),
    TALER_JSON_pack_amount ("issued_amount",
                            &receipts_sum));
}


/* end of donau-httpd_batch-issue.c */