/* This file is part of TALER Copyright (C) 2014, 2015, 2016, 2017, 2020 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1, 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with TALER; see the file COPYING.LGPL. If not, see */ /** * @file lib/merchant_api_post_order_pay.c * @brief Implementation of the POST /order/$ID/pay request * of the merchant's HTTP API * @author Christian Grothoff * @author Marcello Stanisci */ #include "platform.h" #include #include #include /* just for HTTP status codes */ #include #include #include "taler_merchant_service.h" #include #include #include #include /** * @brief A Pay Handle */ struct TALER_MERCHANT_OrderPayHandle { /** * The url for this request. */ char *url; /** * Handle for the request. */ struct GNUNET_CURL_Job *job; /** * Function to call with the result in "pay" @e mode. */ TALER_MERCHANT_OrderPayCallback pay_cb; /** * Closure for @a pay_cb. */ void *pay_cb_cls; /** * Reference to the execution context. */ struct GNUNET_CURL_Context *ctx; /** * Minor context that holds body and headers. */ struct TALER_CURL_PostContext post_ctx; /** * The coins we are paying with. */ struct TALER_MERCHANT_PaidCoin *coins; /** * Hash of the contract we are paying, set * if @e am_wallet is true. */ struct GNUNET_HashCode h_contract_terms; /** * Public key of the merchant (instance) being paid, set * if @e am_wallet is true. */ struct TALER_MerchantPublicKeyP merchant_pub; /** * Number of @e coins we are paying with. */ unsigned int num_coins; /** * Set to true if this is the wallet API and we have * initialized @e h_contract_terms and @e merchant_pub. */ bool am_wallet; }; /** * We got a 409 response back from the exchange (or the merchant). * Now we need to check the provided cryptograophic proof that the * coin was actually already spent! * * @param pc handle of the original coin we paid with * @param json cryptograophic proof of coin's transaction * history as was returned by the exchange/merchant * @return #GNUNET_OK if proof checks out */ static int check_coin_history (const struct TALER_MERCHANT_PaidCoin *pc, json_t *json) { struct TALER_Amount spent; struct TALER_Amount spent_plus_contrib; struct GNUNET_HashCode h_denom_pub; struct GNUNET_HashCode h_denom_pub_pc; if (GNUNET_OK != TALER_EXCHANGE_verify_coin_history (NULL, /* do not verify fees */ pc->amount_with_fee.currency, &pc->coin_pub, json, &h_denom_pub, &spent)) { /* Exchange's history fails to verify */ GNUNET_break_op (0); return GNUNET_SYSERR; } if (0 > TALER_amount_add (&spent_plus_contrib, &spent, &pc->amount_with_fee)) { /* We got an integer overflow? Bad application! */ GNUNET_break (0); return GNUNET_SYSERR; } GNUNET_CRYPTO_rsa_public_key_hash (pc->denom_pub.rsa_public_key, &h_denom_pub_pc); if ( (-1 != TALER_amount_cmp (&pc->denom_value, &spent_plus_contrib)) && (0 != GNUNET_memcmp (&h_denom_pub, &h_denom_pub_pc)) ) { /* according to our calculations, the transaction should have still worked, AND we did not get any proof of coin public key re-use; hence: exchange error! */ GNUNET_break_op (0); return GNUNET_SYSERR; } GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Accepting proof of double-spending (or coin public key re-use)\n"); return GNUNET_OK; } /** * We got a 409 response back from the exchange (or the merchant). * Now we need to check the provided cryptograophic proof that the * coin was actually already spent! * * @param oph handle of the original pay operation * @param json cryptograophic proof returned by the * exchange/merchant * @return #GNUNET_OK if proof checks out */ static int check_conflict (struct TALER_MERCHANT_OrderPayHandle *oph, const json_t *json) { json_t *history; json_t *ereply; struct TALER_CoinSpendPublicKeyP coin_pub; struct GNUNET_JSON_Specification spec[] = { GNUNET_JSON_spec_json ("exchange_reply", &ereply), GNUNET_JSON_spec_fixed_auto ("coin_pub", &coin_pub), GNUNET_JSON_spec_end () }; struct GNUNET_JSON_Specification hspec[] = { GNUNET_JSON_spec_json ("history", &history), GNUNET_JSON_spec_end () }; if (GNUNET_OK != GNUNET_JSON_parse (json, spec, NULL, NULL)) { GNUNET_break_op (0); return GNUNET_SYSERR; } if (GNUNET_OK != GNUNET_JSON_parse (ereply, hspec, NULL, NULL)) { GNUNET_break_op (0); GNUNET_JSON_parse_free (spec); return GNUNET_SYSERR; } GNUNET_JSON_parse_free (spec); for (unsigned int i = 0; inum_coins; i++) { if (0 == memcmp (&oph->coins[i].coin_pub, &coin_pub, sizeof (struct TALER_CoinSpendPublicKeyP))) { int ret; ret = check_coin_history (&oph->coins[i], history); GNUNET_JSON_parse_free (hspec); return ret; } } GNUNET_break_op (0); /* complaint is not about any of the coins that we actually paid with... */ GNUNET_JSON_parse_free (hspec); return GNUNET_SYSERR; } /** * Function called when we're done processing the * HTTP /pay request. * * @param cls the `struct TALER_MERCHANT_Pay` * @param response_code HTTP response code, 0 on error * @param json response body, NULL if not in JSON */ static void handle_pay_finished (void *cls, long response_code, const void *response) { struct TALER_MERCHANT_OrderPayHandle *oph = cls; const json_t *json = response; struct TALER_MERCHANT_HttpResponse hr = { .http_status = (unsigned int) response_code, .reply = json }; struct TALER_MerchantSignatureP *merchant_sigp = NULL; struct TALER_MerchantSignatureP merchant_sig; oph->job = NULL; GNUNET_log (GNUNET_ERROR_TYPE_INFO, "/pay completed with response code %u\n", (unsigned int) response_code); switch (response_code) { case 0: hr.ec = TALER_EC_INVALID_RESPONSE; break; case MHD_HTTP_OK: if (oph->am_wallet) { /* Here we can (and should) verify the merchant's signature */ struct PaymentResponsePS pr = { .purpose.purpose = htonl (TALER_SIGNATURE_MERCHANT_PAYMENT_OK), .purpose.size = htonl (sizeof (pr)), .h_contract_terms = oph->h_contract_terms }; struct GNUNET_JSON_Specification spec[] = { GNUNET_JSON_spec_fixed_auto ("sig", &merchant_sig), GNUNET_JSON_spec_end () }; if (GNUNET_OK != GNUNET_JSON_parse (json, spec, NULL, NULL)) { GNUNET_break_op (0); hr.ec = TALER_EC_INVALID_RESPONSE; hr.http_status = 0; hr.hint = "sig field missing in response"; break; } if (GNUNET_OK != GNUNET_CRYPTO_eddsa_verify (TALER_SIGNATURE_MERCHANT_PAYMENT_OK, &pr, &merchant_sig.eddsa_sig, &oph->merchant_pub.eddsa_pub)) { GNUNET_break_op (0); hr.ec = TALER_EC_INVALID_RESPONSE; hr.http_status = 0; hr.hint = "signature invalid"; } merchant_sigp = &merchant_sig; } break; /* Tolerating Not Acceptable because sometimes * - especially in tests - we might want to POST * coins one at a time. */ case MHD_HTTP_NOT_ACCEPTABLE: hr.ec = TALER_JSON_get_error_code (json); hr.hint = TALER_JSON_get_error_hint (json); break; case MHD_HTTP_BAD_REQUEST: hr.ec = TALER_JSON_get_error_code (json); hr.hint = TALER_JSON_get_error_hint (json); /* This should never happen, either us * or the merchant is buggy (or API version conflict); * just pass JSON reply to the application */ break; case MHD_HTTP_PAYMENT_REQUIRED: /* was originally paid, but then refunded */ hr.ec = TALER_JSON_get_error_code (json); hr.hint = TALER_JSON_get_error_hint (json); break; case MHD_HTTP_FORBIDDEN: hr.ec = TALER_JSON_get_error_code (json); hr.hint = TALER_JSON_get_error_hint (json); /* Nothing really to verify, merchant says we tried to abort the payment * after it was successful. We should pass the JSON reply to the * application */ break; case MHD_HTTP_NOT_FOUND: hr.ec = TALER_JSON_get_error_code (json); hr.hint = TALER_JSON_get_error_hint (json); /* Nothing really to verify, this should never happen, we should pass the JSON reply to the application */ break; case MHD_HTTP_PRECONDITION_FAILED: TALER_MERCHANT_parse_error_details_ (json, response_code, &hr); /* Nothing really to verify, the merchant is blaming us for failing to satisfy some constraint (likely it does not like our exchange because of some disagreement on the PKI). We should pass the JSON reply to the application */ break; case MHD_HTTP_REQUEST_TIMEOUT: hr.ec = TALER_JSON_get_error_code (json); hr.hint = TALER_JSON_get_error_hint (json); /* The merchant couldn't generate a timely response, likely because it itself waited too long on the exchange. Pass on to application. */ break; case MHD_HTTP_CONFLICT: hr.ec = TALER_JSON_get_error_code (json); hr.hint = TALER_JSON_get_error_hint (json); if (GNUNET_OK != check_conflict (oph, json)) { GNUNET_break_op (0); response_code = 0; } break; case MHD_HTTP_GONE: hr.ec = TALER_JSON_get_error_code (json); hr.hint = TALER_JSON_get_error_hint (json); /* The merchant says we are too late, the offer has expired or some denomination key of a coin involved has expired. Might be a disagreement in timestamps? Still, pass on to application. */ break; case MHD_HTTP_FAILED_DEPENDENCY: TALER_MERCHANT_parse_error_details_ (json, response_code, &hr); /* Nothing really to verify, the merchant is blaming the exchange. We should pass the JSON reply to the application */ break; case MHD_HTTP_INTERNAL_SERVER_ERROR: hr.ec = TALER_JSON_get_error_code (json); hr.hint = TALER_JSON_get_error_hint (json); /* Server had an internal issue; we should retry, but this API leaves this to the application */ break; case MHD_HTTP_SERVICE_UNAVAILABLE: TALER_MERCHANT_parse_error_details_ (json, response_code, &hr); /* Exchange couldn't respond properly; the retry is left to the application */ break; default: TALER_MERCHANT_parse_error_details_ (json, response_code, &hr); /* unexpected response code */ GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unexpected response code %u/%d\n", (unsigned int) response_code, (int) hr.ec); GNUNET_break_op (0); break; } oph->pay_cb (oph->pay_cb_cls, &hr, merchant_sigp); TALER_MERCHANT_order_pay_cancel (oph); } /** * PAY a merchant. API for frontends talking to backends. Here, * the frontend does not have the coin's private keys, but just * the public keys and signatures. Note the subtle difference * in the type of @a coins compared to #TALER_MERCHANT_pay(). * * @param ctx the execution loop context * @param merchant_url base URL of the merchant's backend * @param order_id order to pay * @param session_id session to pay for, or NULL for none * @param num_coins number of coins used to pay * @param coins array of coins we use to pay * @param pay_cb the callback to call when a reply for this request is available * @param pay_cb_cls closure for @a pay_cb * @return a handle for this request */ struct TALER_MERCHANT_OrderPayHandle * TALER_MERCHANT_order_pay_frontend ( struct GNUNET_CURL_Context *ctx, const char *merchant_url, const char *order_id, const char *session_id, unsigned int num_coins, const struct TALER_MERCHANT_PaidCoin coins[], TALER_MERCHANT_OrderPayCallback pay_cb, void *pay_cb_cls) { struct TALER_MERCHANT_OrderPayHandle *oph; json_t *pay_obj; json_t *j_coins; CURL *eh; struct TALER_Amount total_fee; struct TALER_Amount total_amount; if (0 == num_coins) { GNUNET_break (0); return NULL; } j_coins = json_array (); for (unsigned int i = 0; i TALER_amount_subtract (&fee, &pc->amount_with_fee, &pc->amount_without_fee)) { /* Integer underflow, fee larger than total amount? This should not happen (client violated API!) */ GNUNET_break (0); json_decref (j_coins); return NULL; } if (0 == i) { total_fee = fee; total_amount = pc->amount_with_fee; } else { if ( (0 > TALER_amount_add (&total_fee, &total_fee, &fee)) || (0 > TALER_amount_add (&total_amount, &total_amount, &pc->amount_with_fee)) ) { /* integer overflow */ GNUNET_break (0); json_decref (j_coins); return NULL; } } GNUNET_CRYPTO_rsa_public_key_hash (pc->denom_pub.rsa_public_key, &denom_hash); /* create JSON for this coin */ j_coin = json_pack ( "{s:o, s:o," /* contribution/coin_pub */ " s:s, s:o," /* exchange_url / denom_pub */ " s:o, s:o}", /* ub_sig / coin_sig */ "contribution", TALER_JSON_from_amount (&pc->amount_with_fee), "coin_pub", GNUNET_JSON_from_data_auto (&pc->coin_pub), "exchange_url", pc->exchange_url, "h_denom", GNUNET_JSON_from_data_auto (&denom_hash), "ub_sig", GNUNET_JSON_from_rsa_signature (pc->denom_sig.rsa_signature), "coin_sig", GNUNET_JSON_from_data_auto (&pc->coin_sig)); if (0 != json_array_append_new (j_coins, j_coin)) { GNUNET_break (0); json_decref (j_coins); return NULL; } } pay_obj = json_pack ("{ s:o }", "coins", j_coins); if (NULL == pay_obj) { GNUNET_break (0); return NULL; } if (NULL != session_id) { if (0 != json_object_set (pay_obj, "session_id", json_string (session_id))) { GNUNET_break (0); json_decref (pay_obj); return NULL; } } oph = GNUNET_new (struct TALER_MERCHANT_OrderPayHandle); oph->ctx = ctx; oph->pay_cb = pay_cb; oph->pay_cb_cls = pay_cb_cls; { char *path; GNUNET_asprintf (&path, "orders/%s/pay", order_id); oph->url = TALER_url_join (merchant_url, path, NULL); GNUNET_free (path); } if (NULL == oph->url) { GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not construct request URL.\n"); json_decref (pay_obj); GNUNET_free (oph); return NULL; } oph->num_coins = num_coins; oph->coins = GNUNET_new_array (num_coins, struct TALER_MERCHANT_PaidCoin); memcpy (oph->coins, coins, num_coins * sizeof (struct TALER_MERCHANT_PaidCoin)); eh = curl_easy_init (); if (GNUNET_OK != TALER_curl_easy_post (&oph->post_ctx, eh, pay_obj)) { GNUNET_break (0); json_decref (pay_obj); GNUNET_free (oph); return NULL; } json_decref (pay_obj); GNUNET_assert (CURLE_OK == curl_easy_setopt (eh, CURLOPT_URL, oph->url)); oph->job = GNUNET_CURL_job_add2 (ctx, eh, oph->post_ctx.headers, &handle_pay_finished, oph); return oph; } /** * Pay a merchant. API for wallets that have the coin's private keys. * _NOTE_: this function does NOT calculate each coin amount in order * to match the contract total price. This calculation is to be made * by the logic using this library. * * @param ctx the execution loop context * @param merchant_url base URL of the merchant's backend * @param session_id session to pay for, or NULL for none * @param h_contract_terms hashcode of the proposal being paid * @param amount total value of the contract to be paid to the merchant * @param max_fee maximum fee covered by the merchant (according to the contract) * @param merchant_pub the public key of the merchant (used to identify the merchant for refund requests) * @param merchant_sig signature from the merchant over the original contract * @param timestamp timestamp when the contract was finalized, must match approximately the current time of the merchant * @param refund_deadline date until which the merchant can issue a refund to the customer via the merchant (can be zero if refunds are not allowed) * @param pay_deadline maximum time limit to pay for this contract * @param h_wire hash of the merchant’s account details * @param order_id order id of the proposal being paid * @param num_coins number of coins used to pay * @param coins array of coins we use to pay * @param pay_cb the callback to call when a reply for this request is available * @param pay_cb_cls closure for @a pay_cb * @return a handle for this request */ struct TALER_MERCHANT_OrderPayHandle * TALER_MERCHANT_order_pay (struct GNUNET_CURL_Context *ctx, const char *merchant_url, const char *session_id, const struct GNUNET_HashCode *h_contract_terms, const struct TALER_Amount *amount, const struct TALER_Amount *max_fee, const struct TALER_MerchantPublicKeyP *merchant_pub, const struct TALER_MerchantSignatureP *merchant_sig, struct GNUNET_TIME_Absolute timestamp, struct GNUNET_TIME_Absolute refund_deadline, struct GNUNET_TIME_Absolute pay_deadline, const struct GNUNET_HashCode *h_wire, const char *order_id, unsigned int num_coins, const struct TALER_MERCHANT_PayCoin coins[], TALER_MERCHANT_OrderPayCallback pay_cb, void *pay_cb_cls) { (void) GNUNET_TIME_round_abs (×tamp); (void) GNUNET_TIME_round_abs (&pay_deadline); (void) GNUNET_TIME_round_abs (&refund_deadline); if (GNUNET_YES != TALER_amount_cmp_currency (amount, max_fee)) { GNUNET_break (0); return NULL; } { struct TALER_MERCHANT_PaidCoin pc[num_coins]; struct TALER_DepositRequestPS dr = { .purpose.purpose = htonl (TALER_SIGNATURE_WALLET_COIN_DEPOSIT), .purpose.size = htonl (sizeof (dr)), .h_contract_terms = *h_contract_terms, .h_wire = *h_wire, .wallet_timestamp = GNUNET_TIME_absolute_hton (timestamp), .refund_deadline = GNUNET_TIME_absolute_hton (refund_deadline), .merchant = *merchant_pub }; for (unsigned int i = 0; icoin_priv.eddsa_priv, &dr.coin_pub.eddsa_pub); TALER_amount_hton (&dr.amount_with_fee, &coin->amount_with_fee); if (0 > TALER_amount_subtract (&fee, &coin->amount_with_fee, &coin->amount_without_fee)) { /* Integer underflow, fee larger than total amount? This should not happen (client violated API!) */ GNUNET_break (0); return NULL; } TALER_amount_hton (&dr.deposit_fee, &fee); GNUNET_CRYPTO_rsa_public_key_hash (coin->denom_pub.rsa_public_key, &dr.h_denom_pub); GNUNET_CRYPTO_eddsa_sign (&coin->coin_priv.eddsa_priv, &dr, &p->coin_sig.eddsa_signature); p->denom_pub = coin->denom_pub; p->denom_sig = coin->denom_sig; p->denom_value = coin->denom_value; p->coin_pub = dr.coin_pub; p->amount_with_fee = coin->amount_with_fee; p->amount_without_fee = coin->amount_without_fee; p->exchange_url = coin->exchange_url; } { struct TALER_MERCHANT_OrderPayHandle *oph; oph = TALER_MERCHANT_order_pay_frontend (ctx, merchant_url, order_id, session_id, num_coins, pc, pay_cb, pay_cb_cls); if (NULL == oph) return NULL; oph->h_contract_terms = *h_contract_terms; oph->merchant_pub = *merchant_pub; oph->am_wallet = true; return oph; } } } /** * Cancel a pay request. This function cannot be used on a request handle if * a response is already served for it. * * @param oph the pay request handle */ void TALER_MERCHANT_order_pay_cancel (struct TALER_MERCHANT_OrderPayHandle *oph) { if (NULL != oph->job) { GNUNET_CURL_job_cancel (oph->job); oph->job = NULL; } TALER_curl_easy_post_finished (&oph->post_ctx); GNUNET_free (oph->coins); GNUNET_free (oph->url); GNUNET_free (oph); } /* end of merchant_api_post_order_pay.c */