aboutsummaryrefslogtreecommitdiff
path: root/src/bank-lib/taler-bank-transfer.c
blob: 3eed2e5ff801f636870843e2a1ab0ed4753ee08b (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
/*
  This file is part of TALER
  Copyright (C) 2017-2020 Taler Systems SA

  TALER is free software; you can redistribute it and/or modify it under the
  terms of the GNU 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 taler-bank-transfer.c
 * @brief Execute wire transfer.
 * @author Christian Grothoff
 */
#include "platform.h"
#include <gnunet/gnunet_util_lib.h>
#include <gnunet/gnunet_json_lib.h>
#include <jansson.h>
#include "taler_bank_service.h"

/**
 * If set to #GNUNET_YES, then we'll ask the bank for a list
 * of incoming transactions from the account.
 */
static int incoming_history;

/**
 * If set to #GNUNET_YES, then we'll ask the bank for a list
 * of outgoing transactions from the account.
 */
static int outgoing_history;

/**
 * Amount to transfer.
 */
static struct TALER_Amount amount;

/**
 * Credit account payto://-URI.
 */
static char *credit_account;

/**
 * Debit account payto://-URI.
 */
static char *debit_account;

/**
 * Wire transfer subject.
 */
static char *subject;

/**
 * Which config section has the credentials to access the bank.
 */
static char *account_section;

/**
 * Starting row.
 */
static unsigned long long start_row;

/**
 * Authentication data.
 */
static struct TALER_BANK_AuthenticationData auth;

/**
 * Return value from main().
 */
static int global_ret = 1;

/**
 * Main execution context for the main loop.
 */
static struct GNUNET_CURL_Context *ctx;

/**
 * Handle to ongoing credit history operation.
 */
static struct TALER_BANK_CreditHistoryHandle *chh;

/**
 * Handle to ongoing debit history operation.
 */
static struct TALER_BANK_DebitHistoryHandle *dhh;

/**
 * Handle for executing the wire transfer.
 */
static struct TALER_BANK_TransferHandle *eh;

/**
 * Handle to access the exchange.
 */
static struct TALER_BANK_AdminAddIncomingHandle *op;

/**
 * Context for running the CURL event loop.
 */
static struct GNUNET_CURL_RescheduleContext *rc;


/**
 * Function run when the test terminates (good or bad).
 * Cleans up our state.
 *
 * @param cls NULL
 */
static void
do_shutdown (void *cls)
{
  (void) cls;
  if (NULL != op)
  {
    TALER_BANK_admin_add_incoming_cancel (op);
    op = NULL;
  }
  if (NULL != chh)
  {
    TALER_BANK_credit_history_cancel (chh);
    chh = NULL;
  }
  if (NULL != dhh)
  {
    TALER_BANK_debit_history_cancel (dhh);
    dhh = NULL;
  }
  if (NULL != eh)
  {
    TALER_BANK_transfer_cancel (eh);
    eh = NULL;
  }
  if (NULL != ctx)
  {
    GNUNET_CURL_fini (ctx);
    ctx = NULL;
  }
  if (NULL != rc)
  {
    GNUNET_CURL_gnunet_rc_destroy (rc);
    rc = NULL;
  }
  TALER_BANK_auth_free (&auth);
}


/**
 * Callback used to process ONE entry in the transaction
 * history returned by the bank.
 *
 * @param cls closure
 * @param http_status HTTP status code from server
 * @param ec taler error code
 * @param serial_id identification of the position at
 *        which we are returning data
 * @param details details about the wire transfer
 * @param json original full response from server
 * @return #GNUNET_OK to continue, #GNUNET_SYSERR to
 *         abort iteration
 */
static int
credit_history_cb (void *cls,
                   unsigned int http_status,
                   enum TALER_ErrorCode ec,
                   uint64_t serial_id,
                   const struct TALER_BANK_CreditDetails *details,
                   const json_t *json)
{
  (void) cls;

  if (MHD_HTTP_OK != http_status)
  {
    if ( (MHD_HTTP_NO_CONTENT != http_status) ||
         (TALER_EC_NONE != ec) ||
         (NULL == details) )
    {
      fprintf (stderr,
               "Failed to obtain credit history: %u/%d\n",
               http_status,
               ec);
      if (NULL != json)
        json_dumpf (json,
                    stderr,
                    JSON_INDENT (2));
      global_ret = 2;
      GNUNET_SCHEDULER_shutdown ();
      return GNUNET_NO;
    }
    fprintf (stdout,
             "End of transactions list.\n");
    global_ret = 0;
    GNUNET_SCHEDULER_shutdown ();
    return GNUNET_NO;
  }

  /* If credit/debit accounts were specified, use as a filter */
  if ( (NULL != credit_account) &&
       (0 != strcasecmp (credit_account,
                         details->credit_account_url) ) )
    return GNUNET_OK;
  if ( (NULL != debit_account) &&
       (0 != strcasecmp (debit_account,
                         details->debit_account_url) ) )
    return GNUNET_OK;

  fprintf (stdout,
           "%llu: %s->%s (%s) over %s at %s\n",
           (unsigned long long) serial_id,
           details->debit_account_url,
           details->credit_account_url,
           TALER_B2S (&details->reserve_pub),
           TALER_amount2s (&details->amount),
           GNUNET_STRINGS_absolute_time_to_string (details->execution_date));
  return GNUNET_OK;
}


/**
 * Ask the bank the list of transactions for the bank account
 * mentioned in the config section given by the user.
 */
static void
execute_credit_history ()
{
  if (NULL != subject)
  {
    fprintf (stderr,
             "Specifying subject is not supported when inspecting credit history\n");
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
  chh = TALER_BANK_credit_history (ctx,
                                   &auth,
                                   start_row,
                                   -10,
                                   &credit_history_cb,
                                   NULL);
  if (NULL == chh)
  {
    fprintf (stderr,
             "Could not request the credit transaction history.\n");
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
}


/**
 * Function with the debit debit transaction history.
 *
 * @param cls closure
 * @param http_status HTTP response code, #MHD_HTTP_OK (200) for successful status request
 *                    0 if the bank's reply is bogus (fails to follow the protocol),
 *                    #MHD_HTTP_NO_CONTENT if there are no more results; on success the
 *                    last callback is always of this status (even if `abs(num_results)` were
 *                    already returned).
 * @param ec detailed error code
 * @param serial_id monotonically increasing counter corresponding to the transaction
 * @param details details about the wire transfer
 * @param json detailed response from the HTTPD, or NULL if reply was not in JSON
 * @return #GNUNET_OK to continue, #GNUNET_SYSERR to abort iteration
 */
static int
debit_history_cb (void *cls,
                  unsigned int http_status,
                  enum TALER_ErrorCode ec,
                  uint64_t serial_id,
                  const struct TALER_BANK_DebitDetails *details,
                  const json_t *json)
{
  (void) cls;

  if (MHD_HTTP_OK != http_status)
  {
    if ( (MHD_HTTP_NO_CONTENT != http_status) ||
         (TALER_EC_NONE != ec) ||
         (NULL == details) )
    {
      fprintf (stderr,
               "Failed to obtain debit history: %u/%d\n",
               http_status,
               ec);
      if (NULL != json)
        json_dumpf (json,
                    stderr,
                    JSON_INDENT (2));
      global_ret = 2;
      GNUNET_SCHEDULER_shutdown ();
      return GNUNET_NO;
    }
    fprintf (stdout,
             "End of transactions list.\n");
    global_ret = 0;
    GNUNET_SCHEDULER_shutdown ();
    return GNUNET_NO;
  }

  /* If credit/debit accounts were specified, use as a filter */
  if ( (NULL != credit_account) &&
       (0 != strcasecmp (credit_account,
                         details->credit_account_url) ) )
    return GNUNET_OK;
  if ( (NULL != debit_account) &&
       (0 != strcasecmp (debit_account,
                         details->debit_account_url) ) )
    return GNUNET_OK;

  fprintf (stdout,
           "%llu: %s->%s (%s) over %s at %s\n",
           (unsigned long long) serial_id,
           details->debit_account_url,
           details->credit_account_url,
           TALER_B2S (&details->wtid),
           TALER_amount2s (&details->amount),
           GNUNET_STRINGS_absolute_time_to_string (details->execution_date));
  return GNUNET_OK;
}


/**
 * Ask the bank the list of transactions for the bank account
 * mentioned in the config section given by the user.
 */
static void
execute_debit_history ()
{
  if (NULL != subject)
  {
    fprintf (stderr,
             "Specifying subject is not supported when inspecting debit history\n");
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
  dhh = TALER_BANK_debit_history (ctx,
                                  &auth,
                                  start_row,
                                  -10,
                                  &debit_history_cb,
                                  NULL);
  if (NULL == dhh)
  {
    fprintf (stderr,
             "Could not request the debit transaction history.\n");
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
}


/**
 * Callback that processes the outcome of a wire transfer
 * execution.
 *
 * @param cls closure
 * @param response_code HTTP status code
 * @param ec taler error code
 * @param row_id unique ID of the wire transfer in the bank's records
 * @param timestamp when did the transaction go into effect
 */
static void
confirmation_cb (void *cls,
                 unsigned int response_code,
                 enum TALER_ErrorCode ec,
                 uint64_t row_id,
                 struct GNUNET_TIME_Absolute timestamp)
{
  (void) cls;
  eh = NULL;
  if (MHD_HTTP_OK != response_code)
  {
    fprintf (stderr,
             "The wire transfer didn't execute correctly (%u/%d).\n",
             response_code,
             ec);
    GNUNET_SCHEDULER_shutdown ();
    return;
  }

  fprintf (stdout,
           "Wire transfer #%llu executed successfully at %s.\n",
           (unsigned long long) row_id,
           GNUNET_STRINGS_absolute_time_to_string (timestamp));
  global_ret = 0;
  GNUNET_SCHEDULER_shutdown ();
}


/**
 * Ask the bank to execute a wire transfer.
 */
static void
execute_wire_transfer ()
{
  struct TALER_WireTransferIdentifierRawP wtid;
  void *buf;
  size_t buf_size;
  char *params;

  if (NULL != debit_account)
  {
    fprintf (stderr,
             "Invalid option -C specified, conflicts with -D\n");
    GNUNET_SCHEDULER_shutdown ();
    return;
  }

  // See if subject was given as a payto-parameter.
  if (NULL == subject)
    subject = TALER_payto_get_subject (credit_account);
  if (NULL != subject)
  {
    if (GNUNET_OK !=
        GNUNET_STRINGS_string_to_data (subject,
                                       strlen (subject),
                                       &wtid,
                                       sizeof (wtid)))
    {
      fprintf (stderr,
               "Error: wire transfer subject must be a WTID\n");
      return;
    }
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
  else
  {
    /* pick one at random */
    GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE,
                                &wtid,
                                sizeof (wtid));
  }
  params = strchr (credit_account,
                   (unsigned char) '&');
  if (NULL != params)
    params = '\0';
  TALER_BANK_prepare_transfer (credit_account,
                               &amount,
                               "http://exchange.example.com/",
                               &wtid,
                               &buf,
                               &buf_size);
  eh = TALER_BANK_transfer (ctx,
                            &auth,
                            buf,
                            buf_size,
                            &confirmation_cb,
                            NULL);
  if (NULL == eh)
  {
    fprintf (stderr,
             "Could not execute the wire transfer\n");
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
}


/**
 * Function called with the result of the operation.
 *
 * @param cls closure
 * @param http_status HTTP response code, #MHD_HTTP_OK (200) for successful status request
 *                    0 if the bank's reply is bogus (fails to follow the protocol)
 * @param ec detailed error code
 * @param serial_id unique ID of the wire transfer in the bank's records; UINT64_MAX on error
 * @param timestamp timestamp when the transaction got settled at the bank.
 * @param json detailed response from the HTTPD, or NULL if reply was not in JSON
 */
static void
res_cb (void *cls,
        unsigned int http_status,
        enum TALER_ErrorCode ec,
        uint64_t serial_id,
        struct GNUNET_TIME_Absolute timestamp,
        const json_t *json)
{
  (void) cls;
  (void) timestamp;
  op = NULL;
  switch (ec)
  {
  case TALER_EC_NONE:
    global_ret = 0;
    fprintf (stdout,
             "%llu\n",
             (unsigned long long) serial_id);
    break;
  default:
    fprintf (stderr,
             "Operation failed with status code %u/%u\n",
             (unsigned int) ec,
             http_status);
    if (NULL != json)
      json_dumpf (json,
                  stderr,
                  JSON_INDENT (2));
    break;
  }
  GNUNET_SCHEDULER_shutdown ();
}


/**
 * Ask the bank to execute a wire transfer to the exchange.
 */
static void
execute_admin_transfer ()
{
  struct TALER_ReservePublicKeyP reserve_pub;

  if (NULL != subject)
  {
    if (GNUNET_OK !=
        GNUNET_STRINGS_string_to_data (subject,
                                       strlen (subject),
                                       &reserve_pub,
                                       sizeof (reserve_pub)))
    {
      fprintf (stderr,
               "Error: wire transfer subject must be a reserve public key\n");
      return;
    }
  }
  else
  {
    /* pick one that is kind-of well-formed at random */
    GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE,
                                &reserve_pub,
                                sizeof (reserve_pub));
  }
  op = TALER_BANK_admin_add_incoming (ctx,
                                      &auth,
                                      &reserve_pub,
                                      &amount,
                                      credit_account,
                                      &res_cb,
                                      NULL);
  if (NULL == op)
  {
    fprintf (stderr,
             "Could not execute the wire transfer to the exchange\n");
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
}


/**
 * Main function that will be run.
 *
 * @param cls closure
 * @param args remaining command-line arguments
 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
 * @param cfg configuration
 */
static void
run (void *cls,
     char *const *args,
     const char *cfgfile,
     const struct GNUNET_CONFIGURATION_Handle *cfg)
{
  (void) cls;
  (void) args;
  (void) cfgfile;
  (void) cfg;

  GNUNET_SCHEDULER_add_shutdown (&do_shutdown,
                                 NULL);
  ctx = GNUNET_CURL_init (&GNUNET_CURL_gnunet_scheduler_reschedule,
                          &rc);
  GNUNET_assert (NULL != ctx);
  rc = GNUNET_CURL_gnunet_rc_create (ctx);
  if (NULL != account_section)
  {
    if ( (NULL != auth.wire_gateway_url) ||
         (NULL != auth.details.basic.username) ||
         (NULL != auth.details.basic.password) )
    {
      fprintf (stderr,
               "Conflicting authentication options provided. Please only use one method.\n");
      GNUNET_SCHEDULER_shutdown ();
      return;
    }
    if (GNUNET_OK !=
        TALER_BANK_auth_parse_cfg (cfg,
                                   account_section,
                                   &auth))
    {
      fprintf (stderr,
               "Authentication information not found in configuration section `%s'\n",
               account_section);
      GNUNET_SCHEDULER_shutdown ();
      return;
    }
  }
  else
  {
    if ( (NULL != auth.wire_gateway_url) &&
         (NULL != auth.details.basic.username) &&
         (NULL != auth.details.basic.password) )
    {
      auth.method = TALER_BANK_AUTH_BASIC;
    }
    else if (NULL == auth.wire_gateway_url)
    {
      fprintf (stderr,
               "No account specified (use -b or -s options).\n");
      GNUNET_SCHEDULER_shutdown ();
      return;
    }
  }
  if ( (GNUNET_YES == incoming_history) &&
       (GNUNET_YES == incoming_history) )
  {
    fprintf (stderr,
             "Please specify only -i or -o, but not both.\n");
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
  if (GNUNET_YES == incoming_history)
  {
    execute_credit_history ();
    return;
  }
  if (GNUNET_YES == outgoing_history)
  {
    execute_debit_history ();
    return;
  }
  if (NULL != credit_account)
  {
    execute_wire_transfer ();
    return;
  }
  if (NULL != debit_account)
  {
    execute_admin_transfer ();
    return;
  }

  GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
              "No operation specified.\n");
  global_ret = 0;
  GNUNET_SCHEDULER_shutdown ();
}


/**
 * The main function of the taler-bank-transfer tool
 *
 * @param argc number of arguments from the command line
 * @param argv command line arguments
 * @return 0 ok, 1 on error
 */
int
main (int argc,
      char *const *argv)
{
  const struct GNUNET_GETOPT_CommandLineOption options[] = {
    TALER_getopt_get_amount ('a',
                             "amount",
                             "VALUE",
                             "value to transfer",
                             &amount),
    GNUNET_GETOPT_option_string ('b',
                                 "bank",
                                 "URL",
                                 "Wire gateway URL to use to talk to the bank",
                                 &auth.wire_gateway_url),
    GNUNET_GETOPT_option_help ("Deposit funds into a Taler reserve"),
    GNUNET_GETOPT_option_string ('C',
                                 "credit",
                                 "ACCOUNT",
                                 "payto URI of the bank account to credit (when making outgoing transfers)",
                                 &credit_account),
    GNUNET_GETOPT_option_string ('D',
                                 "debit",
                                 "PAYTO-URL",
                                 "payto URI of the bank account to debit (when making incoming transfers)",
                                 &debit_account),
    GNUNET_GETOPT_option_flag ('i',
                               "credit-history",
                               "Ask to get a list of 10 incoming transactions.",
                               &incoming_history),
    GNUNET_GETOPT_option_flag ('o',
                               "debit-history",
                               "Ask to get a list of 10 outgoing transactions.",
                               &outgoing_history),
    GNUNET_GETOPT_option_string ('p',
                                 "pass",
                                 "PASSPHRASE",
                                 "passphrase to use for authentication",
                                 &auth.details.basic.password),
    GNUNET_GETOPT_option_string ('s',
                                 "section",
                                 "ACCOUNT-SECTION",
                                 "Which config section has the credentials to access the bank. Conflicts with -b -u and -p options.\n",
                                 &account_section),
    GNUNET_GETOPT_option_string ('S',
                                 "subject",
                                 "SUBJECT",
                                 "specifies the wire transfer subject",
                                 &subject),
    GNUNET_GETOPT_option_string ('u',
                                 "user",
                                 "USERNAME",
                                 "username to use for authentication",
                                 &auth.details.basic.username),
    GNUNET_GETOPT_option_ulong ('w',
                                "since-when",
                                "ROW",
                                "When asking the bank for transactions history, this option commands that all the results should have IDs settled after SW.  If not given, then the 10 youngest transactions are returned.",
                                &start_row),
    GNUNET_GETOPT_OPTION_END
  };

  GNUNET_assert (GNUNET_OK ==
                 GNUNET_log_setup ("taler-bank-transfer",
                                   "WARNING",
                                   NULL));
  global_ret = 1;
  if (GNUNET_OK !=
      GNUNET_PROGRAM_run (argc, argv,
                          "taler-bank-transfer",
                          "Execute bank transfer to the exchange",
                          options,
                          &run, NULL))
    return 1;
  return global_ret;
}


/* end taler-bank-transfer.c */