summaryrefslogtreecommitdiff
path: root/src/backend/taler-merchant-httpd_track-transaction.c
blob: edf323f344e5c7990adc005a31c145e2e980288f (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
/*
  This file is part of TALER
  (C) 2014, 2015, 2016 INRIA

  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_track-transaction.c
 * @brief implement API for tracking deposits and wire transfers
 * @author Marcello Stanisci
 * @author Christian Grothoff
 */
#include "platform.h"
#include <jansson.h>
#include <taler/taler_signatures.h>
#include <taler/taler_json_lib.h>
#include "taler-merchant-httpd.h"
#include "taler-merchant-httpd_mhd.h"
#include "taler-merchant-httpd_parsing.h"
#include "taler-merchant-httpd_auditors.h"
#include "taler-merchant-httpd_exchanges.h"
#include "taler-merchant-httpd_responses.h"
#include "taler-merchant-httpd_track-transaction.h"


/**
 * Map containing all the known merchant instances
 */
extern struct GNUNET_CONTAINER_MultiHashMap *by_id_map;

/**
 * How long to wait before giving up processing with the exchange?
 */
#define TRACK_TIMEOUT (GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30))


/**
 * Context for a /track/transaction operation.
 */
struct TrackTransactionContext;

/**
 * Merchant instance being tracked
 */
struct MerchantInstance;

/**
 * Information we keep for each coin in a /track/transaction operation.
 */
struct TrackCoinContext
{
  /**
   * Kept in a DLL.
   */
  struct TrackCoinContext *next;

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

  /**
   * Our Context for a /track/transaction operation.
   */
  struct TrackTransactionContext *tctx;

  /**
   * Public key of the coin.
   */
  struct TALER_CoinSpendPublicKeyP coin_pub;

  /**
   * Handle for the request to resolve the WTID for this coin.
   */
  struct TALER_EXCHANGE_TrackTransactionHandle *dwh;

  /**
   * Wire transfer identifier for this coin.
   */
  struct TALER_WireTransferIdentifierRawP wtid;

  /**
   * Execution time of the wire transfer @e wtid.
   */
  struct GNUNET_TIME_Absolute execution_time;

  /**
   * Value of the coin including deposit fee.
   */
  struct TALER_Amount amount_with_fee;

  /**
   * Deposit fee for the coin.
   */
  struct TALER_Amount deposit_fee;

  /**
   * Have we obtained the WTID for this coin yet?
   */
  int have_wtid;

};


/**
 * Context for a /track/transaction operation.
 */
struct TrackTransactionContext
{

  /**
   * This field MUST be first.
   */
  struct TM_HandlerContext hc;

  /**
   * HTTP request we are handling.
   */
  struct MHD_Connection *connection;

  /**
   * Kept in a DLL.
   */
  struct TrackCoinContext *tcc_head;

  /**
   * Kept in a DLL.
   */
  struct TrackCoinContext *tcc_tail;

  /**
   * Exchange that was used for the transaction.
   */
  char *exchange_uri;

  /**
   * Task run on timeout.
   */
  struct GNUNET_SCHEDULER_Task *timeout_task;

  /**
   * Handle for operation to lookup /keys (and auditors) from
   * the exchange used for this transaction; NULL if no operation is
   * pending.
   */
  struct TMH_EXCHANGES_FindOperation *fo;

  /**
   * Handle to our exchange, once we found it.
   */
  struct TALER_EXCHANGE_Handle *eh;

  /**
   * Handle we use to resolve transactions for a given WTID.
   */
  struct TALER_EXCHANGE_TrackTransferHandle *wdh;

  /**
   * Response to return upon resume.
   */
  struct MHD_Response *response;

  /**
   * Wire transfer identifier we are currently looking up in @e wdh.
   */
  struct TALER_WireTransferIdentifierRawP current_wtid;

  /**
   * Execution time of the wire transfer we are currently looking up in @e wdh.
   */
  struct GNUNET_TIME_Absolute current_execution_time;

  /**
   * Hash of wire details for the transaction.
   */
  struct GNUNET_HashCode h_wire;

  /**
   * Hash of the contract.
   */
  struct GNUNET_HashCode h_contract;

  /**
   * Timestamp of the transaction.
   */
  struct GNUNET_TIME_Absolute timestamp;

  /**
   * Refund deadline for the transaction.
   */
  struct GNUNET_TIME_Absolute refund_deadline;

  /**
   * Total value of the transaction.
   */
  struct TALER_Amount total_amount;

  /**
   * Transaction this request is about.
   */
  uint64_t transaction_id;

  /**
   * Response code to return upon resume.
   */
  unsigned int response_code;

  /**
   * Which merchant instance is being tracked
   */
  struct MerchantInstance *mi;

};


/**
 * Free the @a tctx.
 *
 * @param tctx data to free
 */
static void
free_tctx (struct TrackTransactionContext *tctx)
{
  struct TrackCoinContext *tcc;

  while (NULL != (tcc = tctx->tcc_head))
  {
    GNUNET_CONTAINER_DLL_remove (tctx->tcc_head,
                                 tctx->tcc_tail,
                                 tcc);
    if (NULL != tcc->dwh)
    {
      TALER_EXCHANGE_track_transaction_cancel (tcc->dwh);
      tcc->dwh = NULL;
    }
    GNUNET_free (tcc);
  }
  if (NULL != tctx->wdh)
  {
    TALER_EXCHANGE_track_transfer_cancel (tctx->wdh);
    tctx->wdh = NULL;
  }
  if (NULL != tctx->fo)
  {
    TMH_EXCHANGES_find_exchange_cancel (tctx->fo);
    tctx->fo = NULL;
  }
  if (NULL != tctx->timeout_task)
  {
    GNUNET_SCHEDULER_cancel (tctx->timeout_task);
    tctx->timeout_task = NULL;
  }
  if (NULL != tctx->exchange_uri)
  {
    GNUNET_free (tctx->exchange_uri);
    tctx->exchange_uri = NULL;
  }
  GNUNET_free (tctx);
}


/**
 * Custom cleanup routine for a `struct TrackTransactionContext`.
 *
 * @param hc the `struct PayContext` to clean up.
 */
static void
track_transaction_cleanup (struct TM_HandlerContext *hc)
{
  struct TrackTransactionContext *tctx = (struct TrackTransactionContext *) hc;

  free_tctx (tctx);
}


/**
 * Resume the given /track/transaction operation and send the given
 * response.  Stores the response in the @a tctx and signals MHD to
 * resume the connection.  Also ensures MHD runs immediately.
 *
 * @param tctx transaction tracking context
 * @param response_code response code to use
 * @param response response data to send back
 */
static void
resume_track_transaction_with_response (struct TrackTransactionContext *tctx,
                                        unsigned int response_code,
                                        struct MHD_Response *response)
{
  tctx->response_code = response_code;
  tctx->response = response;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Resuming /track/transaction handling as exchange interaction is done (%u)\n",
              response_code);
  if (NULL != tctx->timeout_task)
  {
    GNUNET_SCHEDULER_cancel (tctx->timeout_task);
    tctx->timeout_task = NULL;
  }
  MHD_resume_connection (tctx->connection);
  TMH_trigger_daemon (); /* we resumed, kick MHD */
}


/**
 * This function is called to trace the wire transfers for
 * all of the coins of the transaction of the @a tctx.  Once
 * we have traced all coins, we build the response.
 *
 * @param tctx track context with established connection to exchange
 */
static void
trace_coins (struct TrackTransactionContext *tctx);


/**
 * Function called with detailed wire transfer data, including all
 * of the coin transactions that were combined into the wire transfer.
 *
 * We now store this information.  Then we check if we still have
 * any coins of the original wire transfer not taken care of.
 *
 * @param cls closure
 * @param http_status HTTP status code we got, 0 on exchange protocol violation
 * @param ec taler-specific error code
 * @param exchange_pub public key of the exchange used for signing
 * @param json original json reply (may include signatures, those have then been
 *        validated already)
 * @param execution_time time when the exchange claims to have performed the wire transfer
 * @param wtid extracted wire transfer identifier, or NULL if the exchange could
 *             not provide any (set only if @a http_status is #MHD_HTTP_OK)
 * @param total_amount total amount of the wire transfer, or NULL if the exchange could
 *             not provide any @a wtid (set only if @a http_status is #MHD_HTTP_OK)
 * @param details_length length of the @a details array
 * @param details array with details about the combined transactions
 */
static void
wire_deposits_cb (void *cls,
                  unsigned int http_status,
		  enum TALER_ErrorCode ec,
                  const struct TALER_ExchangePublicKeyP *exchange_pub,
                  const json_t *json,
                  const struct GNUNET_HashCode *h_wire,
                  struct GNUNET_TIME_Absolute execution_time,
                  const struct TALER_Amount *total_amount,
                  unsigned int details_length,
                  const struct TALER_TrackTransferDetails *details)
{
  struct TrackTransactionContext *tctx = cls;
  struct TrackCoinContext *tcc;
  unsigned int i;

  tctx->wdh = NULL;
  if (MHD_HTTP_OK != http_status)
  {
    resume_track_transaction_with_response
      (tctx,
       MHD_HTTP_FAILED_DEPENDENCY,
       TMH_RESPONSE_make_json_pack ("{s:I, s:I, s:I, s:O}",
				    "code", (json_int_t) TALER_EC_TRACK_TRANSACTION_WIRE_TRANSFER_TRACE_ERROR,
                                    "exchange-http-status", (json_int_t) http_status,
				    "exchange-code", (json_int_t) ec,
                                    "details", json));
    return;
  }
  if (GNUNET_OK !=
      db->store_transfer_to_proof (db->cls,
                                   tctx->exchange_uri,
                                   &tctx->current_wtid,
                                   tctx->current_execution_time,
                                   exchange_pub,
                                   json))
  {
    /* Not good, but not fatal either, log error and continue */
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Failed to store transfer-to-proof mapping in DB\n");
  }
  for (tcc=tctx->tcc_head;NULL != tcc;tcc=tcc->next)
  {
    if (GNUNET_YES == tcc->have_wtid)
      continue;
    for (i=0;i<details_length;i++)
    {

      if (0 == memcmp (&details[i].coin_pub,
                       &tcc->coin_pub,
                       sizeof (struct TALER_CoinSpendPublicKeyP)))
      {
        tcc->wtid = tctx->current_wtid;
        tcc->execution_time = tctx->current_execution_time;
        tcc->have_wtid = GNUNET_YES;
      }

      if (GNUNET_OK !=
          db->store_coin_to_transfer (db->cls,
                                      details[i].transaction_id,
                                      &details[i].coin_pub,
                                      &tctx->current_wtid))
      {
        /* Not good, but not fatal either, log error and continue */
        GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                    "Failed to store coin-to-transfer mapping in DB\n");
      }
    }
  }
  /* Continue tracing (will also handle case that we are done) */
  trace_coins (tctx);
}


/**
 * Closure for #proof_cb().
 */
struct ProofCheckContext
{
  /**
   * Proof returned from #proof_cb.  The reference counter was
   * increased for this reference and it must thus be freed.
   * NULL if we did not find any proof.  The JSON should
   * match the `TrackTransferResponse` of the exchange API
   * (https://api.taler.net/api-exchange.html#tracktransferresponse)
   */
  json_t *p_ret;

};


/**
 * Function called with information about a wire transfer identifier.
 * We actually never expect this to be called.
 *
 * @param cls closure with a `struct ProofCheckContext`
 * @param proof proof from exchange about what the wire transfer was for
 */
static void
proof_cb (void *cls,
          const json_t *proof)
{
  struct ProofCheckContext *pcc = cls;

  GNUNET_break (NULL == pcc->p_ret);
  pcc->p_ret = json_incref ((json_t *) proof);
}


/**
 * Function called with detailed wire transfer data.
 * We were trying to find out in which wire transfer one of the
 * coins was involved in. Now we know. What we do now is first
 * obtain the inverse: all other coins of that wire transfer,
 * which is what we prefer to store.
 *
 * @param cls closure with a `struct TrackCoinContext`
 * @param http_status HTTP status code we got, 0 on exchange protocol violation
 * @param ec taler-specific error code, #TALER_EC_NONE on success
 * @param exchange_pub public key of the exchange used for signing @a json
 * @param json original json reply (may include signatures, those have then been
 *        validated already), should be a `TrackTransactionResponse`
 *        from the exchange API
 * @param wtid wire transfer identifier used by the exchange, NULL if exchange did not
 *                  yet execute the transaction
 * @param execution_time actual or planned execution time for the wire transfer
 * @param coin_contribution contribution to the @a total_amount of the deposited coin (may be NULL)
 */
static void
wtid_cb (void *cls,
         unsigned int http_status,
	 enum TALER_ErrorCode ec,
         const struct TALER_ExchangePublicKeyP *exchange_pub,
         const json_t *json,
         const struct TALER_WireTransferIdentifierRawP *wtid,
         struct GNUNET_TIME_Absolute execution_time,
         const struct TALER_Amount *coin_contribution)
{
  struct TrackCoinContext *tcc = cls;
  struct TrackTransactionContext *tctx = tcc->tctx;
  struct ProofCheckContext pcc;

  tcc->dwh = NULL;
  if (MHD_HTTP_OK != http_status)
  {
    /* Transaction not resolved for one of the coins, report error!
       We keep the status code for #MHD_HTTP_ACCEPTED, but box all the
       others (as #MHD_HTTP_ACCEPTED is not an error). */
    resume_track_transaction_with_response
      (tcc->tctx,
       (MHD_HTTP_ACCEPTED == http_status)
       ? MHD_HTTP_ACCEPTED
       : MHD_HTTP_FAILED_DEPENDENCY,
       TMH_RESPONSE_make_json_pack ("{s:I, s:I, s:I, s:O}",
                                    "code", (json_int_t) TALER_EC_TRACK_TRANSACTION_COIN_TRACE_ERROR,
                                    "exchange-http-status", (json_int_t) http_status,
                                    "exchange-code", (json_int_t) ec,
                                    "details", json));
    return;
  }
  tctx->current_wtid = *wtid;
  tctx->current_execution_time = execution_time;
  pcc.p_ret = NULL;
  /* WARNING: if two transactions got aggregated under the same
     WTID, then this branch is always taken (when attempting to
     track the second transaction). */
  if (GNUNET_OK == 
      db->find_proof_by_wtid (db->cls,
                              tctx->exchange_uri,
                              wtid,
                              &proof_cb,
                              &pcc))
  {
    /**
     * Conflict semantics: when the *first* call to /track/transaction
     * at the exchange returns, the merchant issues a call to /track/transfer
     * (at the exchange) and when that second call returns, it updates
     * the information for all other coins using that returned information.
     * Thus since this function is only called as callback to /track/transaction
     * at the exchange, then if we already know this WTID, then some coin was not
     * accounted in what /track/transfer returned (otherwise we wouldn't have
     * tried to track it).
     */
    GNUNET_break_op (0);
    resume_track_transaction_with_response
      (tcc->tctx,
       MHD_HTTP_FAILED_DEPENDENCY,
       TMH_RESPONSE_make_json_pack ("{s:I, s:s, s:O, s:o, s:o}",
				    "code", (json_int_t) TALER_EC_TRACK_TRANSACTION_CONFLICTING_REPORTS,
                                    "error", "conflicting transfer data from exchange",
                                    "transaction_tracking_claim", json,
                                    "wtid_tracking_claim", pcc.p_ret,
                                    "coin_pub", GNUNET_JSON_from_data_auto (&tcc->coin_pub)));
    return;
  }
  tctx->wdh = TALER_EXCHANGE_track_transfer (tctx->eh,
                                             wtid,
                                             &wire_deposits_cb,
                                             tctx);
}


/**
 * This function is called to trace the wire transfers for
 * all of the coins of the transaction of the @a tctx.  Once
 * we have traced all coins, we build the response.
 *
 * @param tctx track context with established connection to exchange
 */
static void
trace_coins (struct TrackTransactionContext *tctx)
{
  struct TrackCoinContext *tcc;
  unsigned int num_wtid;

  GNUNET_assert (NULL != tctx->eh);
  for (tcc = tctx->tcc_head; NULL != tcc; tcc = tcc->next)
    if (GNUNET_YES != tcc->have_wtid)
      break;
  if (NULL != tcc)
  {
    /* we are not done requesting WTIDs, do the next one */
    tcc->dwh = TALER_EXCHANGE_track_transaction (tctx->eh,
                                                 &tctx->mi->privkey,
                                                 &tctx->h_wire,
                                                 &tctx->h_contract,
                                                 &tcc->coin_pub,
                                                 tctx->transaction_id,
                                                 &wtid_cb,
                                                 tcc);
    return;
  }
  /* We have obtained all WTIDs, now prepare the response */
  num_wtid = 0;
  /* count how many disjoint wire transfer identifiers there are;
     note that there should only usually be one, so while this
     is worst-case O(n^2), in pracitce this is O(n) */
  for (tcc = tctx->tcc_head; NULL != tcc; tcc = tcc->next)
  {
    struct TrackCoinContext *tcc2;
    int found = GNUNET_NO;

    for (tcc2 = tctx->tcc_head; tcc2 != tcc; tcc2 = tcc2->next)
    {
      if (0 == memcmp (&tcc->wtid,
                       &tcc2->wtid,
                       sizeof (struct TALER_WireTransferIdentifierRawP)))
      {
        found = GNUNET_YES;
        break;
      }
    }
    if (GNUNET_NO == found)
      num_wtid++;
  }

  {
    /* on-stack allocation is fine, as the number of coins and the
       number of wire-transfers per-transaction is expected to be tiny. */
    struct MHD_Response *resp;
    struct TALER_MERCHANT_TransactionWireTransfer wts[num_wtid];
    unsigned int wtid_off;

    wtid_off = 0;
    for (tcc = tctx->tcc_head; NULL != tcc; tcc = tcc->next)
    {
      struct TrackCoinContext *tcc2;
      int found = GNUNET_NO;

      for (tcc2 = tctx->tcc_head; tcc2 != tcc; tcc2 = tcc2->next)
      {
        if (0 == memcmp (&tcc->wtid,
                         &tcc2->wtid,
                         sizeof (struct TALER_WireTransferIdentifierRawP)))
        {
          found = GNUNET_YES;
          break;
        }
      }
      if (GNUNET_NO == found)
      {
        unsigned int num_coins;
        struct TALER_MERCHANT_TransactionWireTransfer *wt;

        wt = &wts[wtid_off++];
        wt->wtid = tcc->wtid;
        wt->execution_time = tcc->execution_time;
        /* count number of coins with this wtid */
        num_coins = 0;
        for (tcc2 = tctx->tcc_head; NULL != tcc2; tcc2 = tcc2->next)
        {
          if (0 == memcmp (&wt->wtid,
                           &tcc2->wtid,
                           sizeof (struct TALER_WireTransferIdentifierRawP)))
            num_coins++;
        }
        /* initialize coins array */
        wt->num_coins = num_coins;
        wt->coins = GNUNET_new_array (num_coins,
                                      struct TALER_MERCHANT_CoinWireTransfer);
        num_coins = 0;
        for (tcc2 = tctx->tcc_head; NULL != tcc2; tcc2 = tcc2->next)
        {
          if (0 == memcmp (&wt->wtid,
                           &tcc2->wtid,
                           sizeof (struct TALER_WireTransferIdentifierRawP)))
          {
            struct TALER_MERCHANT_CoinWireTransfer *coin = &wt->coins[num_coins++];

            coin->coin_pub = tcc2->coin_pub;
            coin->amount_with_fee = tcc2->amount_with_fee;
            coin->deposit_fee = tcc2->deposit_fee;
          }
        }
      } /* GNUNET_NO == found */
    } /* for all tcc */
    GNUNET_assert (wtid_off == num_wtid);

    resp = TMH_RESPONSE_make_track_transaction_ok (num_wtid,
                                                   wts,
                                                   tctx->exchange_uri);
    for (wtid_off=0;wtid_off < num_wtid; wtid_off++)
      GNUNET_free (wts[wtid_off].coins);
    resume_track_transaction_with_response (tctx,
                                            MHD_HTTP_OK,
                                            resp);
  } /* end of scope for 'wts' and 'resp' */
}


/**
 * Function called with the result of our exchange lookup.
 *
 * @param cls the `struct TrackTransactionContext`
 * @param eh NULL if exchange was not found to be acceptable
 * @param exchange_trusted #GNUNET_YES if this exchange is trusted by config
 */
static void
process_track_transaction_with_exchange (void *cls,
                                         struct TALER_EXCHANGE_Handle *eh,
                                         int exchange_trusted)
{
  struct TrackTransactionContext *tctx = cls;

  tctx->fo = NULL;
  tctx->eh = eh;
  trace_coins (tctx);
}


/**
 * Handle a timeout for the processing of the track transaction request.
 *
 * @param cls closure
 */
static void
handle_track_transaction_timeout (void *cls)
{
  struct TrackTransactionContext *tctx = cls;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Resuming /track/transaction with error after timeout\n");
  tctx->timeout_task = NULL;

  if (NULL != tctx->fo)
  {
    TMH_EXCHANGES_find_exchange_cancel (tctx->fo);
    tctx->fo = NULL;
  }
  resume_track_transaction_with_response (tctx,
                                          MHD_HTTP_SERVICE_UNAVAILABLE,
                                          TMH_RESPONSE_make_internal_error (TALER_EC_PAY_EXCHANGE_TIMEOUT,
									    "exchange not reachable"));
}


/**
 * Function called with information about a transaction.
 *
 * @param cls closure
 * @param transaction_id of the contract
 * @param merchant's public key
 * @param exchange_uri URI of the exchange
 * @param h_contract hash of the contract
 * @param h_wire hash of our wire details
 * @param timestamp time of the confirmation
 * @param refund refund deadline
 * @param total_amount total amount we receive for the contract after fees
 */
static void
transaction_cb (void *cls,
                uint64_t transaction_id,
		const struct TALER_MerchantPublicKeyP *merchant_pub,
                const char *exchange_uri,
                const struct GNUNET_HashCode *h_contract,
                const struct GNUNET_HashCode *h_wire,
                struct GNUNET_TIME_Absolute timestamp,
                struct GNUNET_TIME_Absolute refund,
                const struct TALER_Amount *total_amount)
{
  struct TrackTransactionContext *tctx = cls;

  tctx->transaction_id = transaction_id;
  tctx->exchange_uri = GNUNET_strdup (exchange_uri);
  tctx->h_contract = *h_contract;
  tctx->h_wire = *h_wire;
  tctx->timestamp = timestamp;
  tctx->refund_deadline = refund;
  tctx->total_amount = *total_amount;
}


/**
 * Information about the wire transfer corresponding to
 * a deposit operation.  Note that it is in theory possible
 * that we have a @a transaction_id and @a coin_pub in the
 * result that do not match a deposit that we know about,
 * for example because someone else deposited funds into
 * our account.
 *
 * @param cls closure
 * @param transaction_id ID of the contract
 * @param coin_pub public key of the coin
 * @param wtid identifier of the wire transfer in which the exchange
 *             send us the money for the coin deposit
 * @param execution_time when was the wire transfer executed?
 * @param exchange_proof proof from exchange about what the deposit was for
 *             NULL if we have not asked for this signature
 */
static void
transfer_cb (void *cls,
             uint64_t transaction_id,
             const struct TALER_CoinSpendPublicKeyP *coin_pub,
             const struct TALER_WireTransferIdentifierRawP *wtid,
             struct GNUNET_TIME_Absolute execution_time,
             const json_t *exchange_proof)
{
  struct TrackCoinContext *tcc = cls;

  if (0 != memcmp (coin_pub,
                   &tcc->coin_pub,
                   sizeof (struct TALER_CoinSpendPublicKeyP)))
    return;
  tcc->wtid = *wtid;
  tcc->execution_time = execution_time;
  tcc->have_wtid = GNUNET_YES;
}


/**
 * Function called with information about a coin that was deposited.
 *
 * @param cls closure
 * @param transaction_id of the contract
 * @param coin_pub public key of the coin
 * @param amount_with_fee amount the exchange will deposit for this coin
 * @param deposit_fee fee the exchange will charge for this coin
 * @param exchange_proof proof from exchange that coin was accepted
 */
static void
coin_cb (void *cls,
         uint64_t transaction_id,
         const struct TALER_CoinSpendPublicKeyP *coin_pub,
         const struct TALER_Amount *amount_with_fee,
         const struct TALER_Amount *deposit_fee,
         const json_t *exchange_proof)
{
  struct TrackTransactionContext *tctx = cls;
  struct TrackCoinContext *tcc;

  tcc = GNUNET_new (struct TrackCoinContext);
  tcc->tctx = tctx;
  tcc->coin_pub = *coin_pub;
  tcc->amount_with_fee = *amount_with_fee;
  tcc->deposit_fee = *deposit_fee;
  GNUNET_CONTAINER_DLL_insert (tctx->tcc_head,
                               tctx->tcc_tail,
                               tcc);
  GNUNET_break (GNUNET_SYSERR !=
                db->find_transfers_by_id (db->cls,
                                          transaction_id,
                                          &transfer_cb,
                                          tcc));
}

/**
 * Handle a "/track/transaction" request.
 *
 * @param rh context of the handler
 * @param connection the MHD connection to handle
 * @param[in,out] connection_cls the connection's closure (can be updated)
 * @param upload_data upload data
 * @param[in,out] upload_data_size number of bytes (left) in @a upload_data
 * @return MHD result code
 */
int
MH_handler_track_transaction (struct TMH_RequestHandler *rh,
                              struct MHD_Connection *connection,
                              void **connection_cls,
                              const char *upload_data,
                              size_t *upload_data_size)
{
  struct TrackTransactionContext *tctx;
  unsigned long long transaction_id;
  const char *str;
  const char *instance;
  int ret;
  struct GNUNET_HashCode h_instance;

  if (NULL == *connection_cls)
  {
    tctx = GNUNET_new (struct TrackTransactionContext);
    tctx->hc.cc = &track_transaction_cleanup;
    tctx->connection = connection;
    *connection_cls = tctx;
  }
  else
  {
    /* not first call, recover state */
    tctx = *connection_cls;
  }

  if (0 != tctx->response_code)
  {
    /* We are *done* processing the request, just queue the response (!) */
    if (UINT_MAX == tctx->response_code)
    {
      GNUNET_break (0);
      return MHD_NO; /* hard error */
    }
    ret = MHD_queue_response (connection,
                              tctx->response_code,
                              tctx->response);
    if (NULL != tctx->response)
    {
      MHD_destroy_response (tctx->response);
      tctx->response = NULL;
    }
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Queueing response (%u) for /track/transaction (%s).\n",
                (unsigned int) tctx->response_code,
                ret ? "OK" : "FAILED");
    return ret;
  }
  if ( (NULL != tctx->fo) ||
       (NULL != tctx->eh) )
  {
    /* likely old MHD version */
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Not sure why we are here, should be suspended\n");
    return MHD_YES; /* still work in progress */
  }
  str = MHD_lookup_connection_value (connection,
                                     MHD_GET_ARGUMENT_KIND,
                                     "id");
  if (NULL == str)
    return TMH_RESPONSE_reply_arg_missing (connection,
                                           TALER_EC_PARAMETER_MISSING,
					   "id");
  instance = MHD_lookup_connection_value (connection,
                                          MHD_GET_ARGUMENT_KIND,
                                          "instance");
  if (NULL == instance)
    instance = "default";
  GNUNET_CRYPTO_hash (instance,
                      strlen (instance),
                      &h_instance);
  tctx->mi = GNUNET_CONTAINER_multihashmap_get (by_id_map,
                                                &h_instance);
  if (NULL == tctx->mi)
    return TMH_RESPONSE_reply_not_found (connection,
					 TALER_EC_TRACK_TRANSACTION_INSTANCE_UNKNOWN,
					 "unknown instance");
  if (1 !=
      sscanf (str,
              "%llu",
              &transaction_id))
    return TMH_RESPONSE_reply_arg_invalid (connection,
					   TALER_EC_PARAMETER_MALFORMED,
                                           "id");

  ret = db->find_transaction (db->cls,
                              transaction_id,
			      &tctx->mi->pubkey,
                              &transaction_cb,
                              tctx);
  if (GNUNET_NO == ret)
  {
    return TMH_RESPONSE_reply_not_found (connection,
					 TALER_EC_TRACK_TRANSACTION_TRANSACTION_UNKNOWN,
                                         "id");
  }
  if ( (GNUNET_SYSERR == ret) ||
       (tctx->transaction_id != (uint64_t) transaction_id) ||
       (NULL == tctx->exchange_uri) )
  {
    GNUNET_break (0);
    return TMH_RESPONSE_reply_internal_error (connection,
					      TALER_EC_TRACK_TRANSACTION_DB_FETCH_TRANSACTION_ERROR,
                                              "Database error");
  }
  ret = db->find_payments (db->cls,
                           transaction_id,
                           &tctx->mi->pubkey,
                           &coin_cb,
                           tctx);
  if (GNUNET_SYSERR == ret)
  {
    GNUNET_break (0);
    return TMH_RESPONSE_reply_internal_error (connection,
                                              TALER_EC_TRACK_TRANSACTION_DB_FETCH_PAYMENT_ERROR,
					      "Database error");
  }
  if (GNUNET_NO == ret)
  {
    return TMH_RESPONSE_reply_not_found (connection,
					 TALER_EC_TRACK_TRANSACTION_DB_NO_DEPOSITS_ERROR,
                                         "deposits");
  }
  *connection_cls = tctx;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Suspending /track/transaction handling while working with the exchange\n");
  MHD_suspend_connection (connection);
  tctx->fo = TMH_EXCHANGES_find_exchange (tctx->exchange_uri,
                                          &process_track_transaction_with_exchange,
                                          tctx);

  tctx->timeout_task
    = GNUNET_SCHEDULER_add_delayed (TRACK_TIMEOUT,
				    &handle_track_transaction_timeout,
				    tctx);
  return MHD_YES;
}


/* end of taler-merchant-httpd_track-transaction.c */