aboutsummaryrefslogtreecommitdiff
path: root/src/backend/taler-merchant-httpd_private-get-instances-ID-kyc.c
blob: 9c2158724cdc5cb26c7b0ad3118e4f96b172bc22 (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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
/*
  This file is part of GNU Taler
  (C) 2021-2024 Taler Systems SA

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

  GNU 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 taler-merchant-httpd_private-get-instances-ID-kyc.c
 * @brief implementing GET /instances/$ID/kyc request handling
 * @author Christian Grothoff
 */
#include "platform.h"
#include "taler-merchant-httpd_private-get-instances-ID-kyc.h"
#include "taler-merchant-httpd_helper.h"
#include "taler-merchant-httpd_exchanges.h"
#include <taler/taler_json_lib.h>


/**
 * We do not re-check an acceptable KYC status for
 * a month, as usually a KYC never expires.
 */
#define STALE_KYC_TIMEOUT GNUNET_TIME_UNIT_MONTHS

/**
 * How long should clients cache a KYC failure response?
 */
#define EXPIRATION_KYC_FAILURE GNUNET_TIME_relative_multiply ( \
          GNUNET_TIME_UNIT_MINUTES, 5)

/**
 * How long should clients cache a KYC success response?
 */
#define EXPIRATION_KYC_SUCCESS GNUNET_TIME_relative_multiply ( \
          GNUNET_TIME_UNIT_HOURS, 1)


/**
 * Information we keep per /kyc request.
 */
struct KycContext;


/**
 * Structure for tracking requests to the exchange's
 * ``/kyc-check`` API.
 */
struct ExchangeKycRequest
{
  /**
   * Kept in a DLL.
   */
  struct ExchangeKycRequest *next;

  /**
   * Kept in a DLL.
   */
  struct ExchangeKycRequest *prev;

  /**
   * Find operation where we connect to the respective exchange.
   */
  struct TMH_EXCHANGES_KeysOperation *fo;

  /**
   * KYC request this exchange request is made for.
   */
  struct KycContext *kc;

  /**
   * Hash of the wire account (with salt) we are checking.
   */
  struct TALER_MerchantWireHashP h_wire;

  /**
   * Handle for the actual HTTP request to the exchange.
   */
  struct TALER_EXCHANGE_KycCheckHandle *kyc;

  /**
   * KYC number used by the exchange.
   */
  uint64_t exchange_kyc_serial;

  /**
   * Our account's payto URI.
   */
  char *payto_uri;

  /**
   * Base URL of the exchange.
   */
  char *exchange_url;

  /**
   * Timestamp when we last got a reply from the exchange.
   */
  struct GNUNET_TIME_Timestamp last_check;

};


/**
 * Information we keep per /kyc request.
 */
struct KycContext
{
  /**
   * Stored in a DLL.
   */
  struct KycContext *next;

  /**
   * Stored in a DLL.
   */
  struct KycContext *prev;

  /**
   * Connection we are handling.
   */
  struct MHD_Connection *connection;

  /**
   * Instance we are serving.
   */
  struct TMH_MerchantInstance *mi;

  /**
   * Our handler context.
   */
  struct TMH_HandlerContext *hc;

  /**
   * Task to trigger on request timeout, or NULL.
   */
  struct GNUNET_SCHEDULER_Task *timeout_task;

  /**
   * Response to return, NULL if we don't have one yet.
   */
  struct MHD_Response *response;

  /**
   * JSON array where we are building up the array with
   * pending KYC operations.
   */
  json_t *pending_kycs;

  /**
   * JSON array where we are building up the array with
   * troubled KYC operations.
   */
  json_t *timeout_kycs;

  /**
   * Head of DLL of requests we are making to an
   * exchange to inquire about the latest KYC status.
   */
  struct ExchangeKycRequest *exchange_pending_head;

  /**
   * Tail of DLL of requests we are making to an
   * exchange to inquire about the latest KYC status.
   */
  struct ExchangeKycRequest *exchange_pending_tail;

  /**
   * Set to the exchange URL, or NULL to not filter by
   * exchange.
   */
  const char *exchange_url;

  /**
   * Set to the h_wire of the merchant account if
   * @a have_h_wire is true, used to filter by account.
   */
  struct TALER_MerchantWireHashP h_wire;

  /**
   * How long are we willing to wait for the exchange(s)?
   */
  struct GNUNET_TIME_Absolute timeout;

  /**
   * HTTP status code to use for the reply, i.e 200 for "OK".
   * Special value UINT_MAX is used to indicate hard errors
   * (no reply, return #MHD_NO).
   */
  unsigned int response_code;

  /**
   * #GNUNET_NO if the @e connection was not suspended,
   * #GNUNET_YES if the @e connection was suspended,
   * #GNUNET_SYSERR if @e connection was resumed to as
   * part of #MH_force_pc_resume during shutdown.
   */
  enum GNUNET_GenericReturnValue suspended;

  /**
   * True if @e h_wire was given.
   */
  bool have_h_wire;

  /**
   * We're still waiting on the exchange to determine
   * the KYC status of our deposit(s).
   */
  bool kyc_serial_pending;

};


/**
 * Head of DLL.
 */
static struct KycContext *kc_head;

/**
 * Tail of DLL.
 */
static struct KycContext *kc_tail;


void
TMH_force_kyc_resume ()
{
  for (struct KycContext *kc = kc_head;
       NULL != kc;
       kc = kc->next)
  {
    if (NULL != kc->timeout_task)
    {
      GNUNET_SCHEDULER_cancel (kc->timeout_task);
      kc->timeout_task = NULL;
    }
    if (GNUNET_YES == kc->suspended)
    {
      kc->suspended = GNUNET_SYSERR;
      MHD_resume_connection (kc->connection);
    }
  }
}


/**
 * Custom cleanup routine for a `struct KycContext`.
 *
 * @param cls the `struct KycContext` to clean up.
 */
static void
kyc_context_cleanup (void *cls)
{
  struct KycContext *kc = cls;
  struct ExchangeKycRequest *ekr;

  while (NULL != (ekr = kc->exchange_pending_head))
  {
    GNUNET_CONTAINER_DLL_remove (kc->exchange_pending_head,
                                 kc->exchange_pending_tail,
                                 ekr);
    if (NULL != ekr->kyc)
    {
      TALER_EXCHANGE_kyc_check_cancel (ekr->kyc);
      ekr->kyc = NULL;
    }
    if (NULL != ekr->fo)
    {
      TMH_EXCHANGES_keys4exchange_cancel (ekr->fo);
      ekr->fo = NULL;
    }
    GNUNET_free (ekr->exchange_url);
    GNUNET_free (ekr->payto_uri);
    GNUNET_free (ekr);
  }
  if (NULL != kc->timeout_task)
  {
    GNUNET_SCHEDULER_cancel (kc->timeout_task);
    kc->timeout_task = NULL;
  }
  if (NULL != kc->response)
  {
    MHD_destroy_response (kc->response);
    kc->response = NULL;
  }
  GNUNET_CONTAINER_DLL_remove (kc_head,
                               kc_tail,
                               kc);
  json_decref (kc->pending_kycs);
  json_decref (kc->timeout_kycs);
  GNUNET_free (kc);
}


/**
 * Resume the given KYC context and send the given response.  Stores the
 * response in the @a kc and signals MHD to resume the connection.  Also
 * ensures MHD runs immediately.
 *
 * @param kc KYC context
 * @param response_code response code to use
 * @param response response data to send back
 */
static void
resume_kyc_with_response (struct KycContext *kc,
                          unsigned int response_code,
                          struct MHD_Response *response)
{
  char dat[128];

  kc->response_code = response_code;
  kc->response = response;
  switch (response_code)
  {
  case MHD_HTTP_OK:
    /* KYC failed, cache briefly */
    TALER_MHD_get_date_string (GNUNET_TIME_relative_to_absolute (
                                 EXPIRATION_KYC_FAILURE),
                               dat);
    GNUNET_break (MHD_YES ==
                  MHD_add_response_header (response,
                                           MHD_HTTP_HEADER_EXPIRES,
                                           dat));
    GNUNET_break (MHD_YES ==
                  MHD_add_response_header (response,
                                           MHD_HTTP_HEADER_CACHE_CONTROL,
                                           "max-age=300"));
    break;
  case MHD_HTTP_NO_CONTENT:
    /* KYC passed, cache for a long time! */
    TALER_MHD_get_date_string (GNUNET_TIME_relative_to_absolute (
                                 EXPIRATION_KYC_SUCCESS),
                               dat);
    GNUNET_break (MHD_YES ==
                  MHD_add_response_header (response,
                                           MHD_HTTP_HEADER_EXPIRES,
                                           dat));
    GNUNET_break (MHD_YES ==
                  MHD_add_response_header (response,
                                           MHD_HTTP_HEADER_CACHE_CONTROL,
                                           "max-age=3600"));
    break;
  case MHD_HTTP_BAD_GATEWAY:
  case MHD_HTTP_GATEWAY_TIMEOUT:
    break; /* no caching */
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Resuming /kyc handling as exchange interaction is done (%u)\n",
              response_code);
  if (NULL != kc->timeout_task)
  {
    GNUNET_SCHEDULER_cancel (kc->timeout_task);
    kc->timeout_task = NULL;
  }
  GNUNET_assert (GNUNET_YES == kc->suspended);
  kc->suspended = GNUNET_NO;
  MHD_resume_connection (kc->connection);
  TALER_MHD_daemon_trigger (); /* we resumed, kick MHD */
}


/**
 * Handle a timeout for the processing of the kyc request.
 *
 * @param cls our `struct KycContext`
 */
static void
handle_kyc_timeout (void *cls)
{
  struct KycContext *kc = cls;
  struct ExchangeKycRequest *ekr;

  kc->timeout_task = NULL;
  while (NULL != (ekr = kc->exchange_pending_head))
  {
    GNUNET_CONTAINER_DLL_remove (kc->exchange_pending_head,
                                 kc->exchange_pending_tail,
                                 ekr);
    if (NULL != ekr->kyc)
    {
      TALER_EXCHANGE_kyc_check_cancel (ekr->kyc);
      ekr->kyc = NULL;
    }
    if (NULL != ekr->fo)
    {
      TMH_EXCHANGES_keys4exchange_cancel (ekr->fo);
      ekr->fo = NULL;
    }
    GNUNET_assert (
      0 ==
      json_array_append_new (
        kc->timeout_kycs,
        GNUNET_JSON_PACK (
          GNUNET_JSON_pack_string ("exchange_url",
                                   ekr->exchange_url),
          GNUNET_JSON_pack_uint64 ("exchange_code",
                                   TALER_EC_MERCHANT_GENERIC_EXCHANGE_TIMEOUT),
          GNUNET_JSON_pack_uint64 ("exchange_http_status",
                                   0))));
    GNUNET_free (ekr->exchange_url);
    GNUNET_free (ekr->payto_uri);
    GNUNET_free (ekr);
  }
  GNUNET_assert (GNUNET_YES == kc->suspended);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Resuming KYC with gateway timeout\n");
  resume_kyc_with_response (
    kc,
    MHD_HTTP_GATEWAY_TIMEOUT,
    TALER_MHD_MAKE_JSON_PACK (
      GNUNET_JSON_pack_array_incref ("pending_kycs",
                                     kc->pending_kycs),
      GNUNET_JSON_pack_array_incref ("timeout_kycs",
                                     kc->timeout_kycs)));
}


/**
 * We are done with the KYC request @a ekr.  Remove it from the work list and
 * check if we are done overall.
 *
 * @param[in] ekr key request that is done (and will be freed)
 */
static void
ekr_finished (struct ExchangeKycRequest *ekr)
{
  struct KycContext *kc = ekr->kc;

  GNUNET_CONTAINER_DLL_remove (kc->exchange_pending_head,
                               kc->exchange_pending_tail,
                               ekr);
  GNUNET_free (ekr->exchange_url);
  GNUNET_free (ekr->payto_uri);
  GNUNET_free (ekr);
  if (NULL != kc->exchange_pending_head)
    return; /* wait for more */
  /* All exchange requests done, create final
     big response from cumulated replies */
  if ( (0 == json_array_size (kc->pending_kycs)) &&
       (0 == json_array_size (kc->timeout_kycs)) )
  {
    /* special case: all KYC operations did succeed
       after we asked at the exchanges => 204 */
    struct MHD_Response *response;

    response = MHD_create_response_from_buffer (0,
                                                "",
                                                MHD_RESPMEM_PERSISTENT);
    resume_kyc_with_response (kc,
                              MHD_HTTP_NO_CONTENT,
                              response);
    return;
  }
  resume_kyc_with_response (
    kc,
    kc->response_code, /* MHD_HTTP_OK or MHD_HTTP_BAD_GATEWAY */
    TALER_MHD_MAKE_JSON_PACK (
      GNUNET_JSON_pack_array_incref ("pending_kycs",
                                     kc->pending_kycs),
      GNUNET_JSON_pack_array_incref ("timeout_kycs",
                                     kc->timeout_kycs)));
}


/**
 * Store KYC response from the exchange in the
 * local database.
 *
 * @param ekr request context
 * @param ks HTTP response details
 * @param aks account KYC status details
 * @return true if the operation was successful
 */
static bool
store_kyc_status (
  const struct ExchangeKycRequest *ekr,
  const struct TALER_EXCHANGE_KycStatus *ks,
  const struct TALER_EXCHANGE_AccountKycStatus *aks)
{
  unsigned int dl_cnt = 0;

  for (unsigned int i = 0; i<aks->limits_length; i++)
  {
    const struct TALER_EXCHANGE_AccountLimit *limit
      = &aks->limits[i];

    if (TALER_KYCLOGIC_KYC_TRIGGER_DEPOSIT ==
        limit->operation_type)
      dl_cnt++;
  }

  {
    struct TALER_MERCHANTDB_DepositLimits dls[GNUNET_NZL (dl_cnt)];
    enum GNUNET_DB_QueryStatus qs;
    unsigned int off = 0;

    for (unsigned int i = 0; i<aks->limits_length; i++)
    {
      const struct TALER_EXCHANGE_AccountLimit *limit
        = &aks->limits[i];
      struct TALER_MERCHANTDB_DepositLimits *dl
        = &dls[off];

      if (TALER_KYCLOGIC_KYC_TRIGGER_DEPOSIT !=
          limit->operation_type)
        continue;
      dl->timeframe = limit->timeframe;
      dl->threshold = limit->threshold;
      dl->soft_limit = limit->soft_limit;
      off++;
    }
    qs = TMH_db->account_kyc_set_status (
      TMH_db->cls,
      ekr->kc->mi->settings.id,
      &ekr->h_wire,
      ekr->exchange_url,
      ekr->exchange_kyc_serial,
      GNUNET_TIME_timestamp_get (),
      ks->hr.http_status,
      ks->hr.ec,
      &aks->access_token,
      dl_cnt,
      dls,
      aks->aml_review,
      false);
    if (qs < 0)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  "Failed to store KYC status in database!\n");
      return false;
    }
  }
  return true;
}


/**
 * Function called with the result of a KYC check.
 *
 * @param cls a `struct ExchangeKycRequest *`
 * @param ks the account's KYC status details
 */
static void
exchange_check_cb (
  void *cls,
  const struct TALER_EXCHANGE_KycStatus *ks)
{
  struct ExchangeKycRequest *ekr = cls;
  struct KycContext *kc = ekr->kc;

  ekr->kyc = NULL;
  switch (ks->hr.http_status)
  {
  case MHD_HTTP_OK:
    {
      const struct TALER_EXCHANGE_AccountKycStatus *aks;

      aks = &ks->details.ok;
      GNUNET_break (store_kyc_status (ekr,
                                      ks,
                                      aks));
    }
    break;
  case MHD_HTTP_ACCEPTED:
    {
      const struct TALER_EXCHANGE_AccountKycStatus *aks
        = &ks->details.accepted;
      char *kyc_url;

      GNUNET_break (store_kyc_status (ekr,
                                      ks,
                                      aks));
      {
        char *ats;

        ats = GNUNET_STRINGS_data_to_string_alloc (
          &aks->access_token,
          sizeof (aks->access_token));
        GNUNET_asprintf (&kyc_url,
                         "%s/kyc-spa/%s",
                         ekr->exchange_url,
                         ats);
        GNUNET_free (ats);
      }
      GNUNET_assert (
        0 ==
        json_array_append_new (
          kc->pending_kycs,
          GNUNET_JSON_PACK (
            GNUNET_JSON_pack_data_auto ("access_token",
                                        &aks->access_token),
            GNUNET_JSON_pack_string ("kyc_url",
                                     kyc_url),
            GNUNET_JSON_pack_string ("exchange_url",
                                     ekr->exchange_url),
            GNUNET_JSON_pack_string ("payto_uri",
                                     ekr->payto_uri))));
      GNUNET_free (kyc_url);
      break;
    }
  case MHD_HTTP_NO_CONTENT:
    {
      enum GNUNET_DB_QueryStatus qs;

      qs = TMH_db->account_kyc_set_status (
        TMH_db->cls,
        kc->mi->settings.id,
        &ekr->h_wire,
        ekr->exchange_url,
        ekr->exchange_kyc_serial,
        GNUNET_TIME_timestamp_get (),
        MHD_HTTP_NO_CONTENT,
        TALER_EC_NONE,
        NULL,
        0,
        NULL,
        false,
        true);
      if (qs < 0)
      {
        GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                    "Failed to store KYC status in database!\n");
      }
    }
    break;
  case MHD_HTTP_FORBIDDEN:
  case MHD_HTTP_NOT_FOUND:
  case MHD_HTTP_CONFLICT:
  case MHD_HTTP_UNAVAILABLE_FOR_LEGAL_REASONS: // FIXME: real?
    {
      enum GNUNET_DB_QueryStatus qs;

      GNUNET_assert (
        0 ==
        json_array_append_new (
          kc->pending_kycs,
          GNUNET_JSON_PACK (
            GNUNET_JSON_pack_string ("exchange_url",
                                     ekr->exchange_url),
            GNUNET_JSON_pack_uint64 ("exchange_code",
                                     ks->hr.ec),
            GNUNET_JSON_pack_uint64 ("exchange_http_status",
                                     ks->hr.http_status),
            GNUNET_JSON_pack_string ("payto_uri",
                                     ekr->payto_uri))));
      qs = TMH_db->account_kyc_set_status (
        TMH_db->cls,
        kc->mi->settings.id,
        &ekr->h_wire,
        ekr->exchange_url,
        ekr->exchange_kyc_serial,
        GNUNET_TIME_timestamp_get (),
        ks->hr.http_status,
        ks->hr.ec,
        NULL,
        0,
        NULL,
        false,
        true);
      if (qs < 0)
      {
        GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                    "Failed to store KYC status in database!\n");
      }
    }
    break;
  default:
    {
      enum GNUNET_DB_QueryStatus qs;

      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  "Exchange responded with HTTP status %u (%d) to /kyc-check request!\n",
                  ks->hr.http_status,
                  ks->hr.ec);
      kc->response_code = MHD_HTTP_BAD_GATEWAY;
      GNUNET_assert (
        0 ==
        json_array_append_new (
          kc->timeout_kycs,
          GNUNET_JSON_PACK (
            GNUNET_JSON_pack_string ("exchange_url",
                                     ekr->exchange_url),
            GNUNET_JSON_pack_uint64 ("exchange_code",
                                     ks->hr.ec),
            GNUNET_JSON_pack_uint64 ("exchange_http_status",
                                     ks->hr.http_status))));
      qs = TMH_db->account_kyc_set_status (
        TMH_db->cls,
        kc->mi->settings.id,
        &ekr->h_wire,
        ekr->exchange_url,
        ekr->exchange_kyc_serial,
        GNUNET_TIME_timestamp_get (),
        ks->hr.http_status,
        ks->hr.ec,
        NULL,
        0,
        NULL,
        false,
        true);
      if (qs < 0)
      {
        GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                    "Failed to store KYC status in database!\n");
      }
      break;
    }
  }
  ekr_finished (ekr);
}


/**
 * Function called with the result of a #TMH_EXCHANGES_keys4exchange()
 * operation.  Runs the KYC check against the exchange.
 *
 * @param cls closure with our `struct ExchangeKycRequest *`
 * @param keys keys of the exchange context
 * @param exchange representation of the exchange
 */
static void
kyc_with_exchange (void *cls,
                   struct TALER_EXCHANGE_Keys *keys,
                   struct TMH_Exchange *exchange)
{
  struct ExchangeKycRequest *ekr = cls;
  struct KycContext *kc = ekr->kc;
  struct TALER_PaytoHashP h_payto;
  union TALER_AccountPrivateKeyP ap;

  (void) exchange;
  ekr->fo = NULL;
  if (NULL == keys)
  {
    kc->response_code = MHD_HTTP_BAD_GATEWAY;
    GNUNET_assert (
      0 ==
      json_array_append_new (
        kc->timeout_kycs,
        GNUNET_JSON_PACK (
          TALER_JSON_pack_ec (
            TALER_EC_MERCHANT_GENERIC_EXCHANGE_KEYS_FAILURE))));
    ekr_finished (ekr);
    return;
  }
  TALER_payto_hash (ekr->payto_uri,
                    &h_payto);
  ap.merchant_priv = kc->mi->merchant_priv;
  ekr->kyc = TALER_EXCHANGE_kyc_check (
    TMH_curl_ctx,
    ekr->exchange_url,
    ekr->exchange_kyc_serial,
    &ap,
    GNUNET_TIME_absolute_get_remaining (kc->timeout),
    &exchange_check_cb,
    ekr);
}


/**
 * Function called from account_kyc_get_status() with KYC status information
 * for this merchant.
 *
 * @param cls our `struct KycContext *`
 * @param h_wire hash of the wire account
 * @param exchange_kyc_serial serial number for the KYC process at the exchange, 0 if unknown
 * @param payto_uri payto:// URI of the merchant's bank account
 * @param exchange_url base URL of the exchange for which this is a status
 * @param last_check when did we last get an update on our KYC status from the exchange
 * @param kyc_ok true if we satisfied the KYC requirements
 */
static void
kyc_status_cb (
  void *cls,
  const struct TALER_MerchantWireHashP *h_wire,
  uint64_t exchange_kyc_serial,
  const char *payto_uri,
  const char *exchange_url,
  struct GNUNET_TIME_Timestamp last_check,
  bool kyc_ok)
{
  struct KycContext *kc = cls;
  struct ExchangeKycRequest *ekr;

  if (kyc_ok &&
      (GNUNET_TIME_relative_cmp (
         GNUNET_TIME_absolute_get_duration (last_check.abs_time),
         <,
         STALE_KYC_TIMEOUT)) )
    return; /* KYC ok, ignore! */
  if (0 == exchange_kyc_serial)
  {
    kc->kyc_serial_pending = true;
    return;
  }
  kc->response_code = MHD_HTTP_ACCEPTED;
  ekr = GNUNET_new (struct ExchangeKycRequest);
  GNUNET_CONTAINER_DLL_insert (kc->exchange_pending_head,
                               kc->exchange_pending_tail,
                               ekr);
  ekr->h_wire = *h_wire;
  ekr->exchange_kyc_serial = exchange_kyc_serial;
  ekr->exchange_url = GNUNET_strdup (exchange_url);
  ekr->payto_uri = GNUNET_strdup (payto_uri);
  ekr->last_check = last_check;
  ekr->kc = kc;
  ekr->fo = TMH_EXCHANGES_keys4exchange (
    exchange_url,
    false,
    &kyc_with_exchange,
    ekr);
}


/**
 * Check the KYC status of an instance.
 *
 * @param mi instance to check KYC status of
 * @param connection the MHD connection to handle
 * @param[in,out] hc context with further information about the request
 * @return MHD result code
 */
static MHD_RESULT
get_instances_ID_kyc (
  struct TMH_MerchantInstance *mi,
  struct MHD_Connection *connection,
  struct TMH_HandlerContext *hc)
{
  struct KycContext *kc = hc->ctx;

  if (NULL == kc)
  {
    kc = GNUNET_new (struct KycContext);
    kc->mi = mi;
    hc->ctx = kc;
    hc->cc = &kyc_context_cleanup;
    GNUNET_CONTAINER_DLL_insert (kc_head,
                                 kc_tail,
                                 kc);
    kc->connection = connection;
    kc->hc = hc;
    kc->pending_kycs = json_array ();
    GNUNET_assert (NULL != kc->pending_kycs);
    kc->timeout_kycs = json_array ();
    GNUNET_assert (NULL != kc->timeout_kycs);

    TALER_MHD_parse_request_timeout (connection,
                                     &kc->timeout);
    if (! GNUNET_TIME_absolute_is_past (kc->timeout))
      kc->timeout_task
        = GNUNET_SCHEDULER_add_at (kc->timeout,
                                   &handle_kyc_timeout,
                                   kc);

    /* process 'exchange_url' argument */
    kc->exchange_url = MHD_lookup_connection_value (
      connection,
      MHD_GET_ARGUMENT_KIND,
      "exchange_url");
    if ( (NULL != kc->exchange_url) &&
         (! TALER_url_valid_charset (kc->exchange_url) ||
          ( (0 != strncasecmp (kc->exchange_url,
                               "http://",
                               strlen ("http://"))) &&
            (0 != strncasecmp (kc->exchange_url,
                               "https://",
                               strlen ("https://"))) ) ) )
    {
      GNUNET_break_op (0);
      return TALER_MHD_reply_with_error (
        connection,
        MHD_HTTP_BAD_REQUEST,
        TALER_EC_GENERIC_PARAMETER_MALFORMED,
        "exchange_url must be a valid HTTP(s) URL");
    }

    TALER_MHD_parse_request_arg_auto (connection,
                                      "h_wire",
                                      &kc->h_wire,
                                      kc->have_h_wire);
    /* Check our database */
    {
      enum GNUNET_DB_QueryStatus qs;

      qs = TMH_db->account_kyc_get_status (
        TMH_db->cls,
        mi->settings.id,
        kc->have_h_wire
        ? &kc->h_wire
        : NULL,
        kc->exchange_url,
        &kyc_status_cb,
        kc);
      if (qs < 0)
      {
        GNUNET_break (0);
        return TALER_MHD_reply_with_ec (
          connection,
          TALER_EC_GENERIC_DB_FETCH_FAILED,
          "account_kyc_get_status");
      }
    }
    if (kc->kyc_serial_pending)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                  "Exchange legitimization UUID unknown, assuming KYC pending\n");
      return TALER_MHD_REPLY_JSON_PACK (
        connection,
        MHD_HTTP_SERVICE_UNAVAILABLE,
        GNUNET_JSON_pack_string ("hint",
                                 "awaiting legitimization UUID"));
    }
    if (NULL == kc->exchange_pending_head)
      return TALER_MHD_reply_static (connection,
                                     MHD_HTTP_NO_CONTENT,
                                     NULL,
                                     NULL,
                                     0);
    MHD_suspend_connection (connection);
    kc->suspended = GNUNET_YES;
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Suspending KYC request handling while checking with the exchange(s)\n");
    return MHD_YES;
  }
  if (GNUNET_SYSERR == kc->suspended)
    return MHD_NO; /* during shutdown, we don't generate any more replies */
  GNUNET_assert (GNUNET_NO == kc->suspended);
  if (0 != kc->response_code)
  {
    /* We are *done* processing the request, just queue the response (!) */
    if (UINT_MAX == kc->response_code)
    {
      GNUNET_break (0);
      return MHD_NO; /* hard error */
    }
    return MHD_queue_response (connection,
                               kc->response_code,
                               kc->response);
  }
  /* we should never get here */
  GNUNET_break (0);
  return MHD_NO;
}


MHD_RESULT
TMH_private_get_instances_ID_kyc (
  const struct TMH_RequestHandler *rh,
  struct MHD_Connection *connection,
  struct TMH_HandlerContext *hc)
{
  struct TMH_MerchantInstance *mi = hc->instance;

  (void) rh;
  return get_instances_ID_kyc (mi,
                               connection,
                               hc);
}


MHD_RESULT
TMH_private_get_instances_default_ID_kyc (
  const struct TMH_RequestHandler *rh,
  struct MHD_Connection *connection,
  struct TMH_HandlerContext *hc)
{
  struct TMH_MerchantInstance *mi;

  (void) rh;
  mi = TMH_lookup_instance (hc->infix);
  if (NULL == mi)
  {
    return TALER_MHD_reply_with_error (
      connection,
      MHD_HTTP_NOT_FOUND,
      TALER_EC_MERCHANT_GENERIC_INSTANCE_UNKNOWN,
      hc->infix);
  }
  return get_instances_ID_kyc (mi,
                               connection,
                               hc);
}


/* end of taler-merchant-httpd_private-get-instances-ID-kyc.c */