merchant

Merchant backend to process payments, run by merchants
Log | Files | Refs | Submodules | README | LICENSE

taler-merchant-httpd_exchanges.c (34738B)


      1 /*
      2   This file is part of TALER
      3   (C) 2014-2024 Taler Systems SA
      4 
      5   TALER is free software; you can redistribute it and/or modify it under the
      6   terms of the GNU Affero General Public License as published by the Free Software
      7   Foundation; either version 3, or (at your option) any later version.
      8 
      9   TALER is distributed in the hope that it will be useful, but WITHOUT ANY
     10   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
     11   A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
     12 
     13   You should have received a copy of the GNU General Public License along with
     14   TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
     15 */
     16 /**
     17  * @file src/backend/taler-merchant-httpd_exchanges.c
     18  * @brief logic this HTTPD keeps for each exchange we interact with
     19  * @author Marcello Stanisci
     20  * @author Christian Grothoff
     21  */
     22 #include "platform.h"
     23 #include <taler/taler_json_lib.h>
     24 #include <taler/taler_dbevents.h>
     25 #include "taler-merchant-httpd_exchanges.h"
     26 #include "taler-merchant-httpd.h"
     27 #include <regex.h>
     28 #include "merchant-database/get_kyc_limits.h"
     29 #include "merchant-database/select_exchange_keys.h"
     30 #include "merchant-database/event_listen.h"
     31 #include "merchant-database/event_notify.h"
     32 
     33 
     34 /**
     35  * How often do we retry DB transactions with soft errors?
     36  */
     37 #define MAX_RETRIES 3
     38 
     39 /**
     40  * Threshold after which exponential backoff should not increase.
     41  */
     42 #define RETRY_BACKOFF_THRESHOLD GNUNET_TIME_relative_multiply ( \
     43           GNUNET_TIME_UNIT_SECONDS, 60)
     44 
     45 /**
     46  * This is how long /keys long-polls for, so we should
     47  * allow this time between requests if there is no
     48  * answer. See exchange_api_handle.c.
     49  */
     50 #define LONG_POLL_THRESHOLD GNUNET_TIME_relative_multiply ( \
     51           GNUNET_TIME_UNIT_SECONDS, 120)
     52 
     53 
     54 /**
     55  * Information we keep for a pending #MMH_EXCHANGES_keys4exchange() operation.
     56  */
     57 struct TMH_EXCHANGES_KeysOperation
     58 {
     59 
     60   /**
     61    * Kept in a DLL.
     62    */
     63   struct TMH_EXCHANGES_KeysOperation *next;
     64 
     65   /**
     66    * Kept in a DLL.
     67    */
     68   struct TMH_EXCHANGES_KeysOperation *prev;
     69 
     70   /**
     71    * Function to call with the result.
     72    */
     73   TMH_EXCHANGES_Find2Continuation fc;
     74 
     75   /**
     76    * Closure for @e fc.
     77    */
     78   void *fc_cls;
     79 
     80   /**
     81    * Exchange we wait for the /keys for.
     82    */
     83   struct TMH_Exchange *my_exchange;
     84 
     85   /**
     86    * Task scheduled to asynchronously return the result to
     87    * the find continuation.
     88    */
     89   struct GNUNET_SCHEDULER_Task *at;
     90 
     91 };
     92 
     93 
     94 /**
     95  * Information about wire transfer fees of an exchange, by wire method.
     96  */
     97 struct FeesByWireMethod
     98 {
     99 
    100   /**
    101    * Kept in a DLL.
    102    */
    103   struct FeesByWireMethod *next;
    104 
    105   /**
    106    * Kept in a DLL.
    107    */
    108   struct FeesByWireMethod *prev;
    109 
    110   /**
    111    * Wire method these fees are for.
    112    */
    113   char *wire_method;
    114 
    115   /**
    116    * Applicable fees, NULL if unknown/error.
    117    */
    118   struct TALER_EXCHANGE_WireAggregateFees *af;
    119 
    120 };
    121 
    122 
    123 /**
    124  * Internal representation for an exchange
    125  */
    126 struct TMH_Exchange
    127 {
    128 
    129   /**
    130    * Kept in a DLL.
    131    */
    132   struct TMH_Exchange *next;
    133 
    134   /**
    135    * Kept in a DLL.
    136    */
    137   struct TMH_Exchange *prev;
    138 
    139   /**
    140    * Head of FOs pending for this exchange.
    141    */
    142   struct TMH_EXCHANGES_KeysOperation *keys_head;
    143 
    144   /**
    145    * Tail of FOs pending for this exchange.
    146    */
    147   struct TMH_EXCHANGES_KeysOperation *keys_tail;
    148 
    149   /**
    150    * (base) URL of the exchange.
    151    */
    152   char *url;
    153 
    154   /**
    155    * Currency offered by the exchange according to OUR configuration.
    156    */
    157   char *currency;
    158 
    159   /**
    160    * The keys of this exchange.
    161    */
    162   struct TALER_EXCHANGE_Keys *keys;
    163 
    164   /**
    165    * Head of wire fees from /wire request.
    166    */
    167   struct FeesByWireMethod *wire_fees_head;
    168 
    169   /**
    170    * Tail of wire fees from /wire request.
    171    */
    172   struct FeesByWireMethod *wire_fees_tail;
    173 
    174   /**
    175    * Task to retry downloading /keys again.
    176    */
    177   struct GNUNET_SCHEDULER_Task *retry_task;
    178 
    179   /**
    180    * When are we willing to force downloading again?
    181    */
    182   struct GNUNET_TIME_Absolute first_retry;
    183 
    184   /**
    185    * Current exponential back-off for @e retry_task.
    186    */
    187   struct GNUNET_TIME_Relative retry_delay;
    188 
    189   /**
    190    * Master public key of the exchange.
    191    */
    192   struct TALER_MasterPublicKeyP master_pub;
    193 
    194   /**
    195    * true if this exchange is from our configuration and
    196    * explicitly trusted, false if we need to check each
    197    * key to be sure it is trusted.
    198    */
    199   bool trusted;
    200 
    201 };
    202 
    203 
    204 /**
    205  * Head of exchanges we know about.
    206  */
    207 static struct TMH_Exchange *exchange_head;
    208 
    209 /**
    210  * Tail of exchanges we know about.
    211  */
    212 static struct TMH_Exchange *exchange_tail;
    213 
    214 /**
    215  * Our event handler listening for /keys downloads
    216  * being put into the database.
    217  */
    218 static struct GNUNET_DB_EventHandler *keys_eh;
    219 
    220 /**
    221  * How many exchanges do we trust (for our configured
    222  * currency) as per our configuration? Used for a
    223  * sanity-check on startup.
    224  */
    225 static int trusted_exchange_count;
    226 
    227 
    228 const struct TALER_MasterPublicKeyP *
    229 TMH_EXCHANGES_get_master_pub (
    230   const struct TMH_Exchange *exchange)
    231 {
    232   GNUNET_break ( (exchange->trusted) ||
    233                  (NULL != exchange->keys) );
    234   return &exchange->master_pub;
    235 }
    236 
    237 
    238 const char *
    239 TMH_EXCHANGES_get_currency (
    240   const struct TMH_Exchange *exchange)
    241 {
    242   return exchange->currency;
    243 }
    244 
    245 
    246 struct TMH_Exchange *
    247 TMH_EXCHANGES_lookup_exchange (const char *exchange_url)
    248 {
    249   for (struct TMH_Exchange *exchange = exchange_head;
    250        NULL != exchange;
    251        exchange = exchange->next)
    252     if (0 == strcmp (exchange->url,
    253                      exchange_url))
    254       return exchange;
    255   return NULL;
    256 }
    257 
    258 
    259 bool
    260 TMH_EXCHANGES_check_trusted (
    261   const char *exchange_url)
    262 {
    263   struct TMH_Exchange *exchange = TMH_EXCHANGES_lookup_exchange (exchange_url);
    264 
    265   if (NULL == exchange)
    266     return false;
    267   return exchange->trusted;
    268 }
    269 
    270 
    271 /**
    272  * Check if we have any remaining pending requests for the
    273  * given @a exchange, and if we have the required data, call
    274  * the callback.
    275  *
    276  * @param exchange the exchange to check for pending find operations
    277  */
    278 static void
    279 process_find_operations (struct TMH_Exchange *exchange)
    280 {
    281   struct GNUNET_TIME_Timestamp now;
    282 
    283   now = GNUNET_TIME_timestamp_get ();
    284   for (struct FeesByWireMethod *fbw = exchange->wire_fees_head;
    285        NULL != fbw;
    286        fbw = fbw->next)
    287   {
    288     while ( (NULL != fbw->af) &&
    289             (GNUNET_TIME_timestamp_cmp (fbw->af->end_date,
    290                                         <,
    291                                         now)) )
    292     {
    293       struct TALER_EXCHANGE_WireAggregateFees *af = fbw->af;
    294 
    295       fbw->af = af->next;
    296       GNUNET_free (af);
    297     }
    298     if (NULL == fbw->af)
    299     {
    300       /* Disagreement on the current time */
    301       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
    302                   "Exchange has no wire fees configured for `%s' wire method\n",
    303                   fbw->wire_method);
    304     }
    305     else if (GNUNET_TIME_timestamp_cmp (fbw->af->start_date,
    306                                         >,
    307                                         now))
    308     {
    309       /* Disagreement on the current time */
    310       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
    311                   "Exchange's earliest fee is %s ahead of our time. Clock skew issue?\n",
    312                   GNUNET_TIME_relative2s (
    313                     GNUNET_TIME_absolute_get_remaining (
    314                       fbw->af->start_date.abs_time),
    315                     true));
    316     }
    317   } /* for all wire methods */
    318 
    319   {
    320     struct TMH_EXCHANGES_KeysOperation *kon;
    321 
    322     kon = NULL;
    323     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    324                 "Processing find operations for `%s'\n",
    325                 exchange->url);
    326     for (struct TMH_EXCHANGES_KeysOperation *ko = exchange->keys_head;
    327          NULL != ko;
    328          ko = kon)
    329     {
    330       kon = ko->next;
    331       ko->fc (ko->fc_cls,
    332               exchange->keys,
    333               exchange);
    334       TMH_EXCHANGES_keys4exchange_cancel (ko);
    335     }
    336   }
    337 }
    338 
    339 
    340 /**
    341  * Function called with information about the wire fees for each wire method.
    342  * Stores the wire fees within our internal data structures for later use.
    343  *
    344  * @param exchange connection to the exchange
    345  * @param master_pub public key of the exchange
    346  * @param num_methods number of wire methods supported
    347  * @param fbm wire fees by method
    348  * @return #GNUNET_OK on success
    349  */
    350 static enum GNUNET_GenericReturnValue
    351 process_wire_fees (
    352   struct TMH_Exchange *exchange,
    353   const struct TALER_MasterPublicKeyP *master_pub,
    354   unsigned int num_methods,
    355   const struct TALER_EXCHANGE_WireFeesByMethod fbm[static num_methods])
    356 {
    357   for (unsigned int i = 0; i<num_methods; i++)
    358   {
    359     const char *wire_method = fbm[i].method;
    360     const struct TALER_EXCHANGE_WireAggregateFees *fees = fbm[i].fees_head;
    361     struct FeesByWireMethod *f;
    362     struct TALER_EXCHANGE_WireAggregateFees *endp;
    363 
    364     for (f = exchange->wire_fees_head; NULL != f; f = f->next)
    365       if (0 == strcasecmp (wire_method,
    366                            f->wire_method))
    367         break;
    368     if (NULL == f)
    369     {
    370       f = GNUNET_new (struct FeesByWireMethod);
    371       f->wire_method = GNUNET_strdup (wire_method);
    372       GNUNET_CONTAINER_DLL_insert (exchange->wire_fees_head,
    373                                    exchange->wire_fees_tail,
    374                                    f);
    375     }
    376     endp = f->af;
    377     while ( (NULL != endp) &&
    378             (NULL != endp->next) )
    379       endp = endp->next;
    380     while ( (NULL != endp) &&
    381             (NULL != fees) &&
    382             (GNUNET_TIME_timestamp_cmp (fees->start_date,
    383                                         <,
    384                                         endp->end_date)) )
    385       fees = fees->next;
    386     if ( (NULL != endp) &&
    387          (NULL != fees) &&
    388          (GNUNET_TIME_timestamp_cmp (fees->start_date,
    389                                      !=,
    390                                      endp->end_date)) )
    391     {
    392       /* Hole or overlap in the fee structure, not allowed! */
    393       GNUNET_break_op (0);
    394       return GNUNET_SYSERR;
    395     }
    396     while (NULL != fees)
    397     {
    398       struct TALER_EXCHANGE_WireAggregateFees *af;
    399 
    400       af = GNUNET_new (struct TALER_EXCHANGE_WireAggregateFees);
    401       *af = *fees;
    402       af->next = NULL;
    403       if (NULL == endp)
    404         f->af = af;
    405       else
    406         endp->next = af;
    407       endp = af;
    408       fees = fees->next;
    409     } /* all fees for this method */
    410   } /* for all methods (i) */
    411   return GNUNET_OK;
    412 }
    413 
    414 
    415 /**
    416  * Retry getting keys from the given exchange in the closure.
    417  *
    418  * @param cls the `struct TMH_Exchange *`
    419  */
    420 static void
    421 retry_exchange (void *cls)
    422 {
    423   struct TMH_Exchange *exchange = cls;
    424   struct GNUNET_DB_EventHeaderP es = {
    425     .size = htons (sizeof (es)),
    426     .type = htons (TALER_DBEVENT_MERCHANT_EXCHANGE_FORCE_KEYS)
    427   };
    428 
    429   exchange->retry_task = NULL;
    430   exchange->retry_delay
    431     = GNUNET_TIME_randomized_backoff (exchange->retry_delay,
    432                                       RETRY_BACKOFF_THRESHOLD);
    433   exchange->first_retry
    434     = GNUNET_TIME_relative_to_absolute (
    435         exchange->retry_delay);
    436 
    437   TALER_MERCHANTDB_event_notify (TMH_db,
    438                                  &es,
    439                                  exchange->url,
    440                                  strlen (exchange->url) + 1);
    441 }
    442 
    443 
    444 /**
    445  * Task to asynchronously return keys operation result to caller.
    446  *
    447  * @param cls a `struct TMH_EXCHANGES_KeysOperation`
    448  */
    449 static void
    450 return_keys (void *cls)
    451 {
    452   struct TMH_EXCHANGES_KeysOperation *fo = cls;
    453   struct TMH_Exchange *exchange = fo->my_exchange;
    454 
    455   fo->at = NULL;
    456   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    457               "Returning key data for %s instantly\n",
    458               exchange->url);
    459   process_find_operations (exchange);
    460 }
    461 
    462 
    463 struct TMH_EXCHANGES_KeysOperation *
    464 TMH_EXCHANGES_keys4exchange (
    465   const char *chosen_exchange,
    466   bool force_download,
    467   TMH_EXCHANGES_Find2Continuation fc,
    468   void *fc_cls)
    469 {
    470   struct TMH_Exchange *exchange;
    471   struct TMH_EXCHANGES_KeysOperation *fo;
    472 
    473   if (NULL == TMH_curl_ctx)
    474   {
    475     GNUNET_break (0);
    476     return NULL;
    477   }
    478   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    479               "Trying to find chosen exchange `%s'\n",
    480               chosen_exchange);
    481   exchange = TMH_EXCHANGES_lookup_exchange (chosen_exchange);
    482   if (NULL == exchange)
    483   {
    484     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
    485                 "Exchange `%s' not configured\n",
    486                 chosen_exchange);
    487     return NULL;
    488   }
    489   if (! exchange->trusted)
    490   {
    491     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
    492                 "Exchange `%s' not trusted\n",
    493                 chosen_exchange);
    494     return NULL;
    495   }
    496   fo = GNUNET_new (struct TMH_EXCHANGES_KeysOperation);
    497   fo->fc = fc;
    498   fo->fc_cls = fc_cls;
    499   fo->my_exchange = exchange;
    500   GNUNET_CONTAINER_DLL_insert (exchange->keys_head,
    501                                exchange->keys_tail,
    502                                fo);
    503   if ( (NULL == exchange->keys) &&
    504        (! force_download) )
    505   {
    506     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    507                 "Waiting for `%skeys' already, failing query instantly\n",
    508                 exchange->url);
    509     GNUNET_assert (NULL == fo->at);
    510     fo->at = GNUNET_SCHEDULER_add_now (&return_keys,
    511                                        fo);
    512     return fo;
    513   }
    514   if ( (NULL != exchange->keys) &&
    515        (! force_download) &&
    516        (GNUNET_TIME_absolute_is_future (
    517           exchange->keys->key_data_expiration.abs_time)) )
    518   {
    519     /* We have a valid reply, immediately return result */
    520     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    521                 "The exchange `%s' is ready\n",
    522                 exchange->url);
    523     GNUNET_assert (NULL == fo->at);
    524     fo->at = GNUNET_SCHEDULER_add_now (&return_keys,
    525                                        fo);
    526     return fo;
    527   }
    528   if ( (force_download) &&
    529        (GNUNET_TIME_absolute_is_future (exchange->first_retry)) &&
    530        (NULL != exchange->keys) )
    531   {
    532     /* Return results immediately. */
    533     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    534                 "Earliest retry is in the future, returning keys now\n");
    535     fo->at = GNUNET_SCHEDULER_add_now (&return_keys,
    536                                        fo);
    537     /* *no* return here, we MAY schedule a 'retry_task' in the
    538        next block if there isn't one yet */
    539   }
    540   if (NULL == exchange->retry_task)
    541     exchange->retry_task
    542       = GNUNET_SCHEDULER_add_at (exchange->first_retry,
    543                                  &retry_exchange,
    544                                  exchange);
    545   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    546               "Next %skeys request scheduled for %s\n",
    547               exchange->url,
    548               GNUNET_TIME_absolute2s (
    549                 exchange->first_retry));
    550   /* No activity to launch, we are already doing so. */
    551   return fo;
    552 }
    553 
    554 
    555 void
    556 TMH_EXCHANGES_keys4exchange_cancel (
    557   struct TMH_EXCHANGES_KeysOperation *fo)
    558 {
    559   struct TMH_Exchange *exchange = fo->my_exchange;
    560 
    561   if (NULL != fo->at)
    562   {
    563     GNUNET_SCHEDULER_cancel (fo->at);
    564     fo->at = NULL;
    565   }
    566   GNUNET_CONTAINER_DLL_remove (exchange->keys_head,
    567                                exchange->keys_tail,
    568                                fo);
    569   GNUNET_free (fo);
    570 }
    571 
    572 
    573 /**
    574  * Obtain applicable fees for @a exchange and @a wire_method.
    575  *
    576  * @param exchange the exchange to query
    577  * @param now current time
    578  * @param wire_method the wire method we want the fees for
    579  * @return NULL if we do not have fees for this method yet
    580  */
    581 static const struct FeesByWireMethod *
    582 get_wire_fees (const struct TMH_Exchange *exchange,
    583                struct GNUNET_TIME_Timestamp now,
    584                const char *wire_method)
    585 {
    586   for (struct FeesByWireMethod *fbw = exchange->wire_fees_head;
    587        NULL != fbw;
    588        fbw = fbw->next)
    589   {
    590     if (0 == strcasecmp (fbw->wire_method,
    591                          wire_method) )
    592     {
    593       struct TALER_EXCHANGE_WireAggregateFees *af;
    594 
    595       /* Advance through list up to current time */
    596       while ( (NULL != (af = fbw->af)) &&
    597               (GNUNET_TIME_timestamp_cmp (now,
    598                                           >=,
    599                                           af->end_date)) )
    600       {
    601         fbw->af = af->next;
    602         GNUNET_free (af);
    603       }
    604       return fbw;
    605     }
    606     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    607                 "Exchange supports `%s' as a wire method (but we do not use that one)\n",
    608                 fbw->wire_method);
    609   }
    610   return NULL;
    611 }
    612 
    613 
    614 /**
    615  * Free @a exchange.
    616  *
    617  * @param[in] exchange entry to free
    618  */
    619 static void
    620 free_exchange_entry (struct TMH_Exchange *exchange)
    621 {
    622   struct FeesByWireMethod *f;
    623 
    624   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    625               "Releasing %s exchange %s\n",
    626               exchange->trusted ? "trusted" : "untrusted",
    627               exchange->url);
    628   GNUNET_CONTAINER_DLL_remove (exchange_head,
    629                                exchange_tail,
    630                                exchange);
    631   while (NULL != (f = exchange->wire_fees_head))
    632   {
    633     struct TALER_EXCHANGE_WireAggregateFees *af;
    634 
    635     GNUNET_CONTAINER_DLL_remove (exchange->wire_fees_head,
    636                                  exchange->wire_fees_tail,
    637                                  f);
    638     while (NULL != (af = f->af))
    639     {
    640       f->af = af->next;
    641       GNUNET_free (af);
    642     }
    643     GNUNET_free (f->wire_method);
    644     GNUNET_free (f);
    645   }
    646   TALER_EXCHANGE_keys_decref (exchange->keys);
    647   exchange->keys = NULL;
    648   if (NULL != exchange->retry_task)
    649   {
    650     GNUNET_SCHEDULER_cancel (exchange->retry_task);
    651     exchange->retry_task = NULL;
    652   }
    653   GNUNET_assert (NULL == exchange->keys_head);
    654   GNUNET_assert (NULL == exchange->keys_tail);
    655   GNUNET_free (exchange->currency);
    656   GNUNET_free (exchange->url);
    657   GNUNET_free (exchange);
    658 }
    659 
    660 
    661 enum GNUNET_GenericReturnValue
    662 TMH_EXCHANGES_lookup_wire_fee (
    663   const struct TMH_Exchange *exchange,
    664   const char *wire_method,
    665   struct TALER_Amount *wire_fee)
    666 {
    667   const struct FeesByWireMethod *fbm;
    668   const struct TALER_EXCHANGE_WireAggregateFees *af;
    669 
    670   fbm = get_wire_fees (exchange,
    671                        GNUNET_TIME_timestamp_get (),
    672                        wire_method);
    673   if (NULL == fbm)
    674     return GNUNET_NO;
    675   af = fbm->af;
    676   *wire_fee = af->fees.wire;
    677   return GNUNET_OK;
    678 }
    679 
    680 
    681 enum TMH_ExchangeStatus
    682 TMH_exchange_check_debit (
    683   const char *instance_id,
    684   const struct TMH_Exchange *exchange,
    685   const struct TMH_WireMethod *wm,
    686   struct TALER_Amount *max_amount)
    687 {
    688   const struct TALER_EXCHANGE_Keys *keys = exchange->keys;
    689   bool have_kyc = false;
    690   bool no_access_token = true;
    691   enum TMH_ExchangeStatus retry_ok = 0;
    692 
    693   if (GNUNET_TIME_absolute_is_past (exchange->first_retry))
    694     retry_ok = TMH_ES_RETRY_OK;
    695 
    696   if (NULL == keys)
    697     return TMH_ES_NO_KEYS | retry_ok;
    698   if (0 != strcasecmp (keys->currency,
    699                        max_amount->currency))
    700   {
    701     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    702                 "Currency mismatch: exchange %s uses %s, we need %s\n",
    703                 exchange->url,
    704                 keys->currency,
    705                 max_amount->currency);
    706     return TMH_ES_NO_CURR | retry_ok;
    707   }
    708   {
    709     struct TALER_NormalizedPayto np;
    710     bool account_ok;
    711 
    712     np = TALER_payto_normalize (wm->payto_uri);
    713     account_ok = TALER_EXCHANGE_keys_test_account_allowed (keys,
    714                                                            false,
    715                                                            np);
    716     GNUNET_free (np.normalized_payto);
    717     if (! account_ok)
    718       return TMH_ES_NO_ACC | retry_ok;
    719   }
    720   if (! keys->kyc_enabled)
    721     return TMH_ES_OK | retry_ok;
    722 
    723   {
    724     json_t *jlimits = NULL;
    725     enum GNUNET_DB_QueryStatus qs;
    726 
    727     qs = TALER_MERCHANTDB_get_kyc_limits (TMH_db,
    728                                           wm->payto_uri,
    729                                           instance_id,
    730                                           exchange->url,
    731                                           &have_kyc,
    732                                           &no_access_token,
    733                                           &jlimits);
    734     GNUNET_break (qs >= 0);
    735     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    736                 "get_kyc_limits for %s at %s returned %s/%s\n",
    737                 wm->payto_uri.full_payto,
    738                 exchange->url,
    739                 have_kyc ? "KYC OK" : "KYC missing",
    740                 NULL == jlimits ? "default limits" : "custom limits");
    741     if ( (qs > 0) &&
    742          (NULL != jlimits) )
    743     {
    744       json_t *jlimit;
    745       size_t idx;
    746       struct TALER_Amount kyc_limit;
    747       bool unlimited = true;
    748 
    749       json_array_foreach (jlimits, idx, jlimit)
    750       {
    751         enum TALER_KYCLOGIC_KycTriggerEvent ot;
    752         struct TALER_Amount threshold;
    753         bool soft_limit = false;
    754         struct GNUNET_JSON_Specification spec[] = {
    755           TALER_JSON_spec_kycte ("operation_type",
    756                                  &ot),
    757           TALER_JSON_spec_amount_any ("threshold",
    758                                       &threshold),
    759           GNUNET_JSON_spec_mark_optional (
    760             GNUNET_JSON_spec_bool ("soft_limit",
    761                                    &soft_limit),
    762             NULL),
    763           GNUNET_JSON_spec_end ()
    764         };
    765 
    766         if (GNUNET_OK !=
    767             GNUNET_JSON_parse (jlimit,
    768                                spec,
    769                                NULL, NULL))
    770         {
    771           GNUNET_break (0);
    772           continue;
    773         }
    774         if (soft_limit)
    775           continue;
    776         if ( (TALER_KYCLOGIC_KYC_TRIGGER_DEPOSIT != ot) &&
    777              (TALER_KYCLOGIC_KYC_TRIGGER_TRANSACTION != ot) )
    778           continue;
    779         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    780                     "KYC rule %u with limit %s applies\n",
    781                     (unsigned int) idx,
    782                     TALER_amount2s (&threshold));
    783         if (unlimited)
    784         {
    785           unlimited = false;
    786           kyc_limit = threshold;
    787         }
    788         else
    789         {
    790           TALER_amount_min (&kyc_limit,
    791                             &kyc_limit,
    792                             &threshold);
    793         }
    794       }
    795       json_decref (jlimits);
    796       /* We had custom rules, do not evaluate default rules */
    797       if (! unlimited)
    798         TALER_amount_min (max_amount,
    799                           max_amount,
    800                           &kyc_limit);
    801       return TMH_ES_OK | retry_ok;
    802     } /* END of if qs > 0, NULL != jlimits */
    803   }
    804 
    805   /* Check zero limits *only* if we did no KYC process at all yet.
    806      Because if we did, there is at least a chance that those have
    807      been lifted. */
    808   if ( (no_access_token) ||
    809        ( (! have_kyc) &&
    810          (TALER_EXCHANGE_keys_evaluate_zero_limits (
    811             keys,
    812             TALER_KYCLOGIC_KYC_TRIGGER_DEPOSIT) ||
    813           TALER_EXCHANGE_keys_evaluate_zero_limits (
    814             keys,
    815             TALER_KYCLOGIC_KYC_TRIGGER_TRANSACTION)) ) )
    816   {
    817     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    818                 "KYC requirements of %s not satisfied\n",
    819                 exchange->url);
    820     GNUNET_assert (GNUNET_OK ==
    821                    TALER_amount_set_zero (
    822                      max_amount->currency,
    823                      max_amount));
    824     return TMH_ES_OK | retry_ok;
    825   }
    826   /* In any case, abide by hard limits (unless we have custom rules). */
    827   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    828               "Evaluating default hard limits of %s\n",
    829               exchange->url);
    830   TALER_EXCHANGE_keys_evaluate_hard_limits (
    831     keys,
    832     TALER_KYCLOGIC_KYC_TRIGGER_DEPOSIT,
    833     max_amount);
    834   TALER_EXCHANGE_keys_evaluate_hard_limits (
    835     keys,
    836     TALER_KYCLOGIC_KYC_TRIGGER_TRANSACTION,
    837     max_amount);
    838   if (TALER_EXCHANGE_keys_evaluate_zero_limits (
    839         keys,
    840         TALER_KYCLOGIC_KYC_TRIGGER_DEPOSIT) ||
    841       TALER_EXCHANGE_keys_evaluate_zero_limits (
    842         keys,
    843         TALER_KYCLOGIC_KYC_TRIGGER_TRANSACTION))
    844   {
    845     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    846                 "Operation is zero-limited by default\n");
    847     GNUNET_assert (GNUNET_OK ==
    848                    TALER_amount_set_zero (max_amount->currency,
    849                                           max_amount));
    850   }
    851   return TMH_ES_OK | retry_ok;
    852 }
    853 
    854 
    855 void
    856 TMH_exchange_get_trusted (TMH_ExchangeCallback cb,
    857                           void *cb_cls)
    858 {
    859   for (const struct TMH_Exchange *exchange = exchange_head;
    860        NULL != exchange;
    861        exchange = exchange->next)
    862   {
    863     if (! exchange->trusted)
    864     {
    865       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    866                   "Exchange %s not trusted, skipping!\n",
    867                   exchange->url);
    868       continue;
    869     }
    870     cb (cb_cls,
    871         exchange->url,
    872         exchange);
    873   }
    874 }
    875 
    876 
    877 bool
    878 TMH_test_exchange_configured_for_currency (
    879   const char *currency)
    880 {
    881   for (const struct TMH_Exchange *exchange = exchange_head;
    882        NULL != exchange;
    883        exchange = exchange->next)
    884   {
    885     if (! exchange->trusted)
    886       continue;
    887     if (NULL == exchange->currency)
    888       continue;
    889     if (0 == strcmp (currency,
    890                      exchange->currency))
    891       return true;
    892   }
    893   return false;
    894 }
    895 
    896 
    897 /**
    898  * (Re)load of keys from DB.
    899  *
    900  * @param exchange exchange to reload keys of
    901  */
    902 static void
    903 reload_exchange_keys (struct TMH_Exchange *exchange)
    904 {
    905   enum GNUNET_DB_QueryStatus qs;
    906   struct TALER_EXCHANGE_Keys *keys;
    907   struct GNUNET_TIME_Absolute first_retry;
    908 
    909   qs = TALER_MERCHANTDB_select_exchange_keys (TMH_db,
    910                                               exchange->url,
    911                                               &first_retry,
    912                                               &keys);
    913   if (qs < 0)
    914   {
    915     GNUNET_break (0);
    916     return;
    917   }
    918   if ( (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == qs) ||
    919        (NULL == keys) )
    920   {
    921     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
    922                 "No keys yet for `%s'\n",
    923                 exchange->url);
    924     return;
    925   }
    926   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    927               "Loading latest keys of `%s' from database\n",
    928               exchange->url);
    929   exchange->retry_delay = GNUNET_TIME_UNIT_ZERO;
    930   exchange->first_retry = first_retry;
    931   if (NULL == exchange->currency)
    932     exchange->currency = GNUNET_strdup (keys->currency);
    933   if (0 != strcmp (keys->currency,
    934                    exchange->currency))
    935   {
    936     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
    937                 "/keys cached in our database are for currency `%s', but we expected `%s'\n",
    938                 keys->currency,
    939                 exchange->currency);
    940     return;
    941   }
    942   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    943               "Loaded /keys from database with %u accounts, %u fees\n",
    944               keys->accounts_len,
    945               keys->fees_len);
    946   if (GNUNET_OK !=
    947       process_wire_fees (exchange,
    948                          &keys->master_pub,
    949                          keys->fees_len,
    950                          keys->fees))
    951   {
    952     /* invalid wire fee specification given */
    953     GNUNET_break_op (0);
    954     /* but: we can continue anyway, things may just not
    955        work, but probably better than to not keep going. */
    956     return;
    957   }
    958 
    959   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    960               "Reloaded /keys of %s from database\n",
    961               exchange->url);
    962   TALER_EXCHANGE_keys_decref (exchange->keys);
    963   exchange->keys = keys;
    964   if ( (exchange->trusted) &&
    965        (0 != GNUNET_memcmp (&exchange->master_pub,
    966                             &keys->master_pub)) )
    967   {
    968     /* master pub differs => do not trust the exchange (without auditor) */
    969     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
    970                 "Master public key of exchange `%s' differs from our configuration. Not trusting exchange.\n",
    971                 exchange->url);
    972     exchange->trusted = false;
    973   }
    974   if (! exchange->trusted)
    975   {
    976     exchange->master_pub = keys->master_pub;
    977     for (struct TMH_Exchange *e = exchange_head;
    978          NULL != e;
    979          e = e->next)
    980     {
    981       if (e == exchange)
    982         continue;
    983       if (! e->trusted)
    984         continue;
    985       if (0 ==
    986           GNUNET_memcmp (&e->master_pub,
    987                          &exchange->master_pub))
    988         exchange->trusted = true; /* same exchange, different URL => trust applies */
    989     }
    990   }
    991 
    992   process_find_operations (exchange);
    993 }
    994 
    995 
    996 /**
    997  * Function called on each configuration section. Finds sections
    998  * about exchanges, parses the entries.
    999  *
   1000  * @param cls closure, with a `const struct GNUNET_CONFIGURATION_Handle *`
   1001  * @param section name of the section
   1002  */
   1003 static void
   1004 accept_exchanges (void *cls,
   1005                   const char *section)
   1006 {
   1007   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
   1008   char *url;
   1009   char *mks;
   1010   struct TMH_Exchange *exchange;
   1011   char *currency;
   1012 
   1013   if (GNUNET_SYSERR == trusted_exchange_count)
   1014     return;
   1015   if (0 != strncasecmp (section,
   1016                         "merchant-exchange-",
   1017                         strlen ("merchant-exchange-")))
   1018     return;
   1019   if (GNUNET_YES ==
   1020       GNUNET_CONFIGURATION_get_value_yesno (cfg,
   1021                                             section,
   1022                                             "DISABLED"))
   1023     return;
   1024   if (GNUNET_OK !=
   1025       GNUNET_CONFIGURATION_get_value_string (cfg,
   1026                                              section,
   1027                                              "EXCHANGE_BASE_URL",
   1028                                              &url))
   1029   {
   1030     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
   1031                                section,
   1032                                "EXCHANGE_BASE_URL");
   1033     return;
   1034   }
   1035   exchange = TMH_EXCHANGES_lookup_exchange (url);
   1036   if (NULL != exchange)
   1037   {
   1038     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
   1039                                section,
   1040                                "EXCHANGE_BASE_URL",
   1041                                "same base URL specified again");
   1042     GNUNET_free (url);
   1043     return;
   1044   }
   1045   if (GNUNET_OK !=
   1046       GNUNET_CONFIGURATION_get_value_string (cfg,
   1047                                              section,
   1048                                              "CURRENCY",
   1049                                              &currency))
   1050   {
   1051     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
   1052                                section,
   1053                                "CURRENCY");
   1054     GNUNET_free (url);
   1055     return;
   1056   }
   1057   exchange = GNUNET_new (struct TMH_Exchange);
   1058   exchange->url = url;
   1059   exchange->currency = currency;
   1060   GNUNET_CONTAINER_DLL_insert (exchange_head,
   1061                                exchange_tail,
   1062                                exchange);
   1063   if (GNUNET_OK ==
   1064       GNUNET_CONFIGURATION_get_value_string (cfg,
   1065                                              section,
   1066                                              "MASTER_KEY",
   1067                                              &mks))
   1068   {
   1069     if (GNUNET_OK ==
   1070         GNUNET_CRYPTO_eddsa_public_key_from_string (
   1071           mks,
   1072           strlen (mks),
   1073           &exchange->master_pub.eddsa_pub))
   1074     {
   1075       exchange->trusted = true;
   1076       trusted_exchange_count++;
   1077     }
   1078     else
   1079     {
   1080       GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
   1081                                  section,
   1082                                  "MASTER_KEY",
   1083                                  "malformed EdDSA key");
   1084     }
   1085     GNUNET_free (mks);
   1086   }
   1087   else
   1088   {
   1089     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
   1090                 "MASTER_KEY missing in section '%s', not trusting exchange\n",
   1091                 section);
   1092   }
   1093   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
   1094               "Setup exchange %s as %s\n",
   1095               exchange->url,
   1096               exchange->trusted ? "trusted" : "untrusted");
   1097   reload_exchange_keys (exchange);
   1098   if (NULL != exchange->retry_task)
   1099   {
   1100     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
   1101                 "Exchange at `%s' configured in multiple configuration sections (see `%s')!\n",
   1102                 exchange->url,
   1103                 section);
   1104     trusted_exchange_count = GNUNET_SYSERR;
   1105     return;
   1106   }
   1107   exchange->retry_task
   1108     = GNUNET_SCHEDULER_add_now (&retry_exchange,
   1109                                 exchange);
   1110 }
   1111 
   1112 
   1113 /**
   1114  * Trigger (re)loading of keys from DB.
   1115  *
   1116  * @param cls NULL
   1117  * @param extra base URL of the exchange that changed
   1118  * @param extra_len number of bytes in @a extra
   1119  */
   1120 static void
   1121 update_exchange_keys (void *cls,
   1122                       const void *extra,
   1123                       size_t extra_len)
   1124 {
   1125   const char *url = extra;
   1126   struct TMH_Exchange *exchange;
   1127 
   1128   if ( (NULL == extra) ||
   1129        (0 == extra_len) )
   1130   {
   1131     GNUNET_break (0);
   1132     return;
   1133   }
   1134   if ('\0' != url[extra_len - 1])
   1135   {
   1136     GNUNET_break (0);
   1137     return;
   1138   }
   1139   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
   1140               "Received keys change notification: reload `%s'\n",
   1141               url);
   1142   exchange = TMH_EXCHANGES_lookup_exchange (url);
   1143   GNUNET_break (NULL != exchange);
   1144   if (NULL != exchange)
   1145     reload_exchange_keys (exchange);
   1146 }
   1147 
   1148 
   1149 bool
   1150 TMH_EXCHANGES_is_below_limit (
   1151   const struct TALER_EXCHANGE_Keys *keys,
   1152   enum TALER_KYCLOGIC_KycTriggerEvent operation_type,
   1153   const struct TALER_Amount *amount)
   1154 {
   1155   if (NULL == keys)
   1156   {
   1157     /* should only be called after we have keys! */
   1158     GNUNET_break (0);
   1159     return false;
   1160   }
   1161   for (unsigned int i = 0; i<keys->hard_limits_length; i++)
   1162   {
   1163     const struct TALER_EXCHANGE_AccountLimit *al
   1164       = &keys->hard_limits[i];
   1165 
   1166     if (operation_type != al->operation_type)
   1167       continue;
   1168     if (-1 ==
   1169         TALER_amount_cmp (&al->threshold,
   1170                           amount))
   1171       /* -1: threshold < amount */
   1172       return false;
   1173   }
   1174   return true;
   1175 }
   1176 
   1177 
   1178 void
   1179 TMH_EXCHANGES_get_limit (
   1180   const char *exchange_url,
   1181   enum TALER_KYCLOGIC_KycTriggerEvent operation_type,
   1182   struct TALER_Amount *amount)
   1183 {
   1184   struct TMH_Exchange *exchange;
   1185   const struct TALER_EXCHANGE_Keys *keys;
   1186 
   1187   exchange = TMH_EXCHANGES_lookup_exchange (exchange_url);
   1188   if ( (NULL == exchange) ||
   1189        (NULL == (keys = exchange->keys)) )
   1190   {
   1191     GNUNET_assert (GNUNET_OK ==
   1192                    TALER_amount_set_zero (
   1193                      amount->currency,
   1194                      amount));
   1195     return;
   1196   }
   1197   for (unsigned int i = 0; i<keys->hard_limits_length; i++)
   1198   {
   1199     const struct TALER_EXCHANGE_AccountLimit *al
   1200       = &keys->hard_limits[i];
   1201 
   1202     if (operation_type != al->operation_type)
   1203       continue;
   1204     TALER_amount_min (amount,
   1205                       amount,
   1206                       &al->threshold);
   1207   }
   1208 }
   1209 
   1210 
   1211 enum GNUNET_GenericReturnValue
   1212 TMH_EXCHANGES_init (const struct GNUNET_CONFIGURATION_Handle *cfg)
   1213 {
   1214   /* get exchanges from the merchant configuration and try to connect to them */
   1215   {
   1216     struct GNUNET_DB_EventHeaderP es = {
   1217       .size = htons (sizeof (es)),
   1218       .type = htons (TALER_DBEVENT_MERCHANT_EXCHANGE_KEYS)
   1219     };
   1220 
   1221     GNUNET_assert (NULL == keys_eh);
   1222     keys_eh = TALER_MERCHANTDB_event_listen (TMH_db,
   1223                                              &es,
   1224                                              GNUNET_TIME_UNIT_FOREVER_REL,
   1225                                              &update_exchange_keys,
   1226                                              NULL);
   1227   }
   1228   GNUNET_CONFIGURATION_iterate_sections (cfg,
   1229                                          &accept_exchanges,
   1230                                          (void *) cfg);
   1231   /* build JSON with list of trusted exchanges (will be included in contracts) */
   1232   return trusted_exchange_count;
   1233 }
   1234 
   1235 
   1236 void
   1237 TMH_EXCHANGES_done ()
   1238 {
   1239   if (NULL != keys_eh)
   1240   {
   1241     TALER_MERCHANTDB_event_listen_cancel (keys_eh);
   1242     keys_eh = NULL;
   1243   }
   1244   while (NULL != exchange_head)
   1245     free_exchange_entry (exchange_head);
   1246 }
   1247 
   1248 
   1249 /* end of taler-merchant-httpd_get-exchanges.c */